<commit_before>var dateArray = [];
$(function () {
    if ($('.month').length > 0) {
        $('.month').prev('h1').hide();
    }
    var d = new Date();
    $('#start_date').datepicker({
        dateFormat: "yy-mm-dd",
        minDate: d,
        onSelect: function () {
            var endDate = $('#end_date');
            var date = $(this).datepicker('getDate');
            endDate.datepicker('setDate', date);
            endDate.datepicker('option', 'minDate', date);
        },
        beforeShowDay: function (date) {
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            return [$.inArray(string, dateArray) == -1];
        }
    });
    $('#end_date').datepicker({
        dateFormat: "yy-mm-dd",
        minDate: d,
        beforeShowDay: function (date) {
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            return [$.inArray(string, dateArray) == -1];
        }
    });
    //Calendar Table
    $('.calendar').on('click', 'td.free, td.booked', function () {
        var apartmentId = $(this).parents('tr').attr('data-attr-apartment_id'),
            date = $(this).attr('data-attr-date');
        if ($(this).hasClass('free')) {
            location.href = '/bookings/create/' + apartmentId + '/' + date;
        } else {
            var bookingId = $(this).attr('data-attr-booking_id');
            location.href = '/bookings/edit/' + bookingId;
        }
    });
    //Bookings Table
    $('.bookings').on('click', 'tr', function (e) {
        if ($(e.target).hasClass('payed_confirm')) {
            return;
        }
        var bookingId = $(this).attr('data-attr-booking_id');
        if (!bookingId) {
            return;
        }
        location.href = '/bookings/edit/' + bookingId;
    });
    $('.bookings').on('click', '.payed_confirm', function () {
        var data = $(this).data();
        if (typeof data['id'] == 'undefined') {
            return;
        }
        var el = $(this).parent(),
            to_pay = $(el).siblings('.to_pay'),
            payed = $(el).siblings('.payed'),
            diff = $(el).siblings('.diff');
        if (confirm('Do you want to confirm payment?')) {
            $(document).trigger('show-loading');
            $(payed).html($(to_pay).html());
            $(diff).html("0");
            $.post(
                '/bookings/confirmPayment',
                data,
                function() {
                    $(document).trigger('hide-loading');
                    location.reload();
                },
                'json'
            );
        }
    });
    //Apartments Table
    $('.apartments').on('click', '.delete', function () {
        var apartmentId = $(this).attr('data-attr-apartment_id');
        if (apartmentId) {
            if (confirm("Do you want to delete this apartment?")) {
                location.href = '/apartments/delete/' + apartmentId;
            }
        }
    });
    //Fairs Table
    $('.fairs').on('click', '.delete', function () {
        var fairId = $(this).attr('data-attr-fair_id');
        if (fairId) {
            if (confirm("Do you want to delete this fair?")) {
                location.href = '/fairs/delete/' + fairId;
            }
        }
    });
    //Fairs Table
    $('.create-booking').on('click', '#delete', function () {
        var bookingId = $('[name="id"]').val();
        if (bookingId) {
            if (confirm("Do you want to delete this booking?")) {
                location.href = '/bookings/delete/' + bookingId;
            }
        }
    });
    //fair create form
    var fairCreateForm = $('.create-fair');
    if (fairCreateForm.length) {

    }
    //booking create form
    var bookingCreateForm = $('.create-booking');
    if (bookingCreateForm.length) {
        $(bookingCreateForm).ready(function () {
            if ($('[name="id"]').length == 0) {
                $(document).trigger('apartments-get-price');
            }
            $(document).trigger('apartments-get-booked-dates', [$('#apartment').val(), $('[name="id"]').val()]);
        });
        $('#apartment, #start_date, #end_date').on('change', function () {
            var data = {
                'apartment_id': $('#apartment').val(),
                'start_date': $('#start_date').val(),
                'end_date': $('#end_date').val(),
                'people_count': parseInt($('[name="people_count"]:checked').val())
            };
            if (typeof window.totalPeopleCount[data.apartment_id] != 'undefined') {
                var newCount = parseInt(window.totalPeopleCount[data.apartment_id]),
                    oldCount = $('[name="people_count"]').length,
                    newPeopleCount = newCount >= data.people_count ? data.people_count : 1;
                newCount = newCount > 1 ? newCount : 1;
                if (newCount < oldCount) {
                    for (var i = newCount + 1; i <= oldCount; i++) {
                        $('span.people_count' + i).remove();
                    }
                } else if (newCount > oldCount) {
                    var original = $('span.people_count1');
                    for (var i = oldCount + 1; i <= newCount; i++) {
                        var clone = $(original).clone();
                        $(clone).attr('class', 'people_count' + i);
                        $(clone).find('input').attr('id', 'people_count' + i);
                        $(clone).find('input').val(i);
                        $(clone).find('label').attr('for', 'people_count' + i);
                        $(clone).find('label').html(i);
                        $(original).parent().append(clone);
                    }
                }
                $('#people_count' + newPeopleCount).click();
            }
            $(document).trigger('apartments-get-price');
            if ($(this).attr('id') == 'apartment') {
                $(document).trigger('apartments-get-booked-dates', [$(this).val(), $('[name="id"]').val()]);
            }
        });
        // $(bookingCreateForm).on('click', '[name="people_count"]', function () {
        //     $(document).trigger('apartments-get-price');
        // });
        $(bookingCreateForm).on('click', '#payed_confirm', function () {
            var toPay = parseFloat($('#to_pay').val()),
                alreadyPayed = parseFloat($('#payed').val()),
                newAlreadyPayed = 0;
            if (toPay > alreadyPayed) {
                newAlreadyPayed = toPay - alreadyPayed;
                $('#payed').val(newAlreadyPayed);
                if (confirm('Do you want to confirm payment?')) {
                    $('#submit').click();
                } else {
                    $('#payed').val(alreadyPayed);
                }
            }
        });
    }
    $(document).on('apartments-get-booked-dates', function (ev, apartmentId, bookingId) {
        $(document).trigger('show-loading');
        $.get(
            '/apartments/getBookedDates',
            {"apartmentId": apartmentId, "bookingId": bookingId},
            function (response) {
                $(document).trigger('hide-loading');
                if (response.success) {
                    window.dateArray = response.dateArray;
                }
            },
            'json'
        );
    });
    $(document).on('apartments-get-price', function () {
        $(document).trigger('show-loading');
        var data = {
            'apartment_id': $('#apartment').val(),
            'start_date': $('#start_date').val(),
            'end_date': $('#end_date').val(),
            'people_count': parseInt($('[name="people_count"]:checked').val())
        };
        $.post(
            '/apartments/getPrice',
            data,
            function (response) {
                $(document).trigger('hide-loading');
                if (response.success) {
                    $('#calculated_price').html(response.price);
                    $('#calc_text').html(response.priceText);
                    $('#to_pay').val(response.price);
                    $('#to_pay_show').val(response.price);
                } else {
                    alert(response.error);
                }
            },
            'json'
        );
    });

    $('.search').on('click', '#search', function () {
        $(document).trigger('search');
    });

    $('.search').on('keyup', '[name="search"]', function (ev) {
        if (ev.keyCode == '13') {
            $(document).trigger('search');
        }
    });
    $('.buttons').on('click', '#cancel', function () {
        history.back();
    });
    $(document).on('search', function () {
        var search = $('[name="search"]').val().trim();
        if (!search) {
            return;
        }
        location.href = '/bookings/search/?search=' + search;
    });
    $(document).on('show-loading', function () {
        if (!$("#loading").length) {
            $('body').append('

');
        }
    });
    $(document).on('hide-loading', function () {
        if ($("#loading").length) {
            $("#loading").remove();
        }
    });

    //Скрывам дропдауны по клику вне списков
    $('body').click(function () {
        $('#menu-trigger').prop('checked', false);
    });
    $(".menu,#menu-trigger-label,#menu-trigger").click(function (e) {
        e.stopPropagation();
    });

    $('.month').on('click', 'a', function () {
        var href = $(this).attr('data-attr-href');
        if (href) {
            location.href = href;
        }
    });

    $('body').on('click', '.calendar th.date', function () {
        var cellIndex = $(this).index() + 1;
        $('.calendar th.date').removeClass('marked');
        $(this).closest('.calendar-wrap').find('tfoot th:nth-child(' + cellIndex + ')').addClass('marked');
    });

    function detectswipe(el,func) {
        swipe_det = new Object();
        swipe_det.sX = 0;
        swipe_det.sY = 0;
        swipe_det.eX = 0;
        swipe_det.eY = 0;
        var min_x = 250;  //min x swipe for horizontal swipe
        var max_x = 40;  //max x difference for vertical swipe
        var min_y = 40;  //min y swipe for vertical swipe
        var max_y = 50;  //max y difference for horizontal swipe
        var direc = "";
        var ele = document.getElementById(el);
        ele.addEventListener('touchstart',function(e){
            //console.log(e);return;
            var t = e.touches[0];
            swipe_det.sX = t.screenX;
            swipe_det.sY = t.screenY;
        },false);
        //ele.addEventListener('touchmove',function(e){
        //    // e.preventDefault();
        //},false);
        ele.addEventListener('touchend',function(e){
            //console.log(e);return;
            var t = e.changedTouches[0];
            swipe_det.eX = t.screenX;
            swipe_det.eY = t.screenY;
            //horizontal detection
            if ((((swipe_det.eX - min_x > swipe_det.sX) || (swipe_det.eX + min_x < swipe_det.sX)) && ((swipe_det.eY < swipe_det.sY + max_y) && (swipe_det.sY > swipe_det.eY - max_y)))) {
                if(swipe_det.eX > swipe_det.sX) direc = "r";
                else direc = "l";
            }

            if (direc != "") {
                if(typeof func == 'function') func(el,direc);
            }
            direc = "";
        },false);
    }

    detectswipe('body',function (el,d) {
        var href = '';
        if(d === 'l'){
            href = $('#next_month').attr('data-attr-href');
        } else if(d === 'r'){
            href = $('#prev_month').attr('data-attr-href');
        }
        if (href)  {
            location.href = href;
        }
    });

    var calendarTable = $('table.calendar');
    if ($(calendarTable).length) {
        //var td = $(calendarTable).find('td[data-info]');
        //var currentId = 0,
        //    currentText = '';
        //for (var i = 0; i < td.length; i++) {
        //    if ($(td[i]).hasClass('first-day') || $(td[i]).hasClass('last-day')) {
        //        continue;
        //    }
        //    var bId = $(td[i]).attr('data-attr-booking_id');
        //}
        if (typeof bookingsInfo != undefined) {
            for (var bookingId in bookingsInfo) {
                if (!bookingsInfo.hasOwnProperty(bookingId)) {
                    continue;
                }
                var text = bookingsInfo[bookingId].trim();
                if (text == '') {
                    continue;
                }
                var td = $(calendarTable).find('td[data-attr-booking_id=' + bookingId + ']'),
                    firstPosition = false,
                    tdIndexToDelte = [];
                for (var i = 0; i < td.length; i++) {
                    if ($(td[i]).hasClass('first-day') || $(td[i]).hasClass('last-day')) {
                        continue;
                    }
                    if (firstPosition === false) {
                        firstPosition = i;
                    } else {
                        tdIndexToDelte.push(i);
                    }
                }
                var cnt = tdIndexToDelte.length,
                    width = $(td[0]).width();
                for (var k in tdIndexToDelte) {
                    if (!tdIndexToDelte.hasOwnProperty(k)) {
                        continue;
                    }
                    $(td[tdIndexToDelte[k]]).remove();
                }
                $(td[firstPosition]).attr('colspan', cnt + 1);
                //text.substr(0, 4*(cnt + 1));
                $(td[firstPosition]).html("
" + text + "
");
                $(td[firstPosition]).find('.booking_info').width(width * (cnt + 1));
            }
        }
        if (typeof fairs != undefined) {
            for (var fairId in fairs) {
                if (!fairs.hasOwnProperty(fairId)) {
                    continue;
                }
                var text = fairs[fairId].trim();
                if (text == '') {
                    continue;
                }
                var td = $(calendarTable).find('td[data-fair-id=' + fairId + ']'),
                    firstPosition = false,
                    tdIndexToDelte = [];
                for (var i = 0; i < td.length; i++) {
                    if (firstPosition === false) {
                        firstPosition = i;
                    } else {
                        tdIndexToDelte.push(i);
                    }
                }
                var cnt = tdIndexToDelte.length,
                    width = $(td[0]).width();
                for (var k in tdIndexToDelte) {
                    if (!tdIndexToDelte.hasOwnProperty(k)) {
                        continue;
                    }
                    $(td[tdIndexToDelte[k]]).remove();
                }
                $(td[firstPosition]).attr('colspan', cnt + 1);
                //text.substr(0, 4*(cnt + 1));
                $(td[firstPosition]).html("
" + text + "
");
                $(td[firstPosition]).find('.fair_info').width(width * (cnt + 1));
            }
        }
    }

    var $table = $('table.calendar');
    $table.floatThead({
        top: 66,
        scrollContainer: function ($table) {
            return $table.closest('.inner');
        },
        position: 'absolute'
    });
});<commit_msg>apartments<commit_after>var dateArray = [];
$(function () {
    if ($('.month').length > 0) {
        $('.month').prev('h1').hide();
    }
    var d = new Date();
    $('#start_date').datepicker({
        dateFormat: "yy-mm-dd",
        minDate: d,
        onSelect: function () {
            var endDate = $('#end_date');
            var date = $(this).datepicker('getDate');
            endDate.datepicker('setDate', date);
            endDate.datepicker('option', 'minDate', date);
        },
        beforeShowDay: function (date) {
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            return [$.inArray(string, dateArray) == -1];
        }
    });
    $('#end_date').datepicker({
        dateFormat: "yy-mm-dd",
        minDate: d,
        beforeShowDay: function (date) {
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            return [$.inArray(string, dateArray) == -1];
        }
    });
    //Calendar Table
    $('.calendar').on('click', 'td.free, td.booked', function () {
        var apartmentId = $(this).parents('tr').attr('data-attr-apartment_id'),
            date = $(this).attr('data-attr-date');
        if ($(this).hasClass('free')) {
            location.href = '/bookings/create/' + apartmentId + '/' + date;
        } else {
            var bookingId = $(this).attr('data-attr-booking_id');
            location.href = '/bookings/edit/' + bookingId;
        }
    });
    //Bookings Table
    $('.bookings').on('click', 'tr', function (e) {
        if ($(e.target).hasClass('payed_confirm')) {
            return;
        }
        var bookingId = $(this).attr('data-attr-booking_id');
        if (!bookingId) {
            return;
        }
        location.href = '/bookings/edit/' + bookingId;
    });
    $('.bookings').on('click', '.payed_confirm', function () {
        var data = $(this).data();
        if (typeof data['id'] == 'undefined') {
            return;
        }
        var el = $(this).parent(),
            to_pay = $(el).siblings('.to_pay'),
            payed = $(el).siblings('.payed'),
            diff = $(el).siblings('.diff');
        if (confirm('Do you want to confirm payment?')) {
            $(document).trigger('show-loading');
            $(payed).html($(to_pay).html());
            $(diff).html("0");
            $.post(
                '/bookings/confirmPayment',
                data,
                function() {
                    $(document).trigger('hide-loading');
                    location.reload();
                },
                'json'
            );
        }
    });
    //Apartments Table
    $('.apartments').on('click', '.delete', function () {
        var apartmentId = $(this).attr('data-attr-apartment_id');
        if (apartmentId) {
            if (confirm("Do you want to delete this apartment?")) {
                location.href = '/apartments/delete/' + apartmentId;
            }
        }
    });
    //Fairs Table
    $('.fairs').on('click', '.delete', function () {
        var fairId = $(this).attr('data-attr-fair_id');
        if (fairId) {
            if (confirm("Do you want to delete this fair?")) {
                location.href = '/fairs/delete/' + fairId;
            }
        }
    });
    //Fairs Table
    $('.create-booking').on('click', '#delete', function () {
        var bookingId = $('[name="id"]').val();
        if (bookingId) {
            if (confirm("Do you want to delete this booking?")) {
                location.href = '/bookings/delete/' + bookingId;
            }
        }
    });
    //fair create form
    var fairCreateForm = $('.create-fair');
    if (fairCreateForm.length) {

    }
    //booking create form
    var bookingCreateForm = $('.create-booking');
    if (bookingCreateForm.length) {
        $(bookingCreateForm).ready(function () {
            if ($('[name="id"]').length == 0) {
                $(document).trigger('apartments-get-price');
            }
            $(document).trigger('apartments-get-booked-dates', [$('#apartment').val(), $('[name="id"]').val()]);
        });
        $('#apartment, #start_date, #end_date').on('change', function () {
            var data = {
                'apartment_id': $('#apartment').val(),
                'start_date': $('#start_date').val(),
                'end_date': $('#end_date').val(),
                'people_count': parseInt($('[name="people_count"]:checked').val())
            };
            if (typeof window.totalPeopleCount[data.apartment_id] != 'undefined') {
                var newCount = parseInt(window.totalPeopleCount[data.apartment_id]),
                    oldCount = $('[name="people_count"]').length,
                    newPeopleCount = newCount >= data.people_count ? data.people_count : newCount;
                newCount = newCount > 1 ? newCount : 1;
                if (newCount < oldCount) {
                    for (var i = newCount + 1; i <= oldCount; i++) {
                        $('span.people_count' + i).remove();
                    }
                } else if (newCount > oldCount) {
                    var original = $('span.people_count1');
                    for (var i = oldCount + 1; i <= newCount; i++) {
                        var clone = $(original).clone();
                        $(clone).attr('class', 'people_count' + i);
                        $(clone).find('input').attr('id', 'people_count' + i);
                        $(clone).find('input').val(i);
                        $(clone).find('label').attr('for', 'people_count' + i);
                        $(clone).find('label').html(i);
                        $(original).parent().append(clone);
                    }
                }
                $('#people_count' + newPeopleCount).click();
            }
            $(document).trigger('apartments-get-price');
            if ($(this).attr('id') == 'apartment') {
                $(document).trigger('apartments-get-booked-dates', [$(this).val(), $('[name="id"]').val()]);
            }
        });
        // $(bookingCreateForm).on('click', '[name="people_count"]', function () {
        //     $(document).trigger('apartments-get-price');
        // });
        $(bookingCreateForm).on('click', '#payed_confirm', function () {
            var toPay = parseFloat($('#to_pay').val()),
                alreadyPayed = parseFloat($('#payed').val()),
                newAlreadyPayed = 0;
            if (toPay > alreadyPayed) {
                newAlreadyPayed = toPay - alreadyPayed;
                $('#payed').val(newAlreadyPayed);
                if (confirm('Do you want to confirm payment?')) {
                    $('#submit').click();
                } else {
                    $('#payed').val(alreadyPayed);
                }
            }
        });
    }
    $(document).on('apartments-get-booked-dates', function (ev, apartmentId, bookingId) {
        $(document).trigger('show-loading');
        $.get(
            '/apartments/getBookedDates',
            {"apartmentId": apartmentId, "bookingId": bookingId},
            function (response) {
                $(document).trigger('hide-loading');
                if (response.success) {
                    window.dateArray = response.dateArray;
                }
            },
            'json'
        );
    });
    $(document).on('apartments-get-price', function () {
        $(document).trigger('show-loading');
        var data = {
            'apartment_id': $('#apartment').val(),
            'start_date': $('#start_date').val(),
            'end_date': $('#end_date').val(),
            'people_count': parseInt($('[name="people_count"]:checked').val())
        };
        $.post(
            '/apartments/getPrice',
            data,
            function (response) {
                $(document).trigger('hide-loading');
                if (response.success) {
                    $('#calculated_price').html(response.price);
                    $('#calc_text').html(response.priceText);
                    $('#to_pay').val(response.price);
                    $('#to_pay_show').val(response.price);
                } else {
                    alert(response.error);
                }
            },
            'json'
        );
    });

    $('.search').on('click', '#search', function () {
        $(document).trigger('search');
    });

    $('.search').on('keyup', '[name="search"]', function (ev) {
        if (ev.keyCode == '13') {
            $(document).trigger('search');
        }
    });
    $('.buttons').on('click', '#cancel', function () {
        history.back();
    });
    $(document).on('search', function () {
        var search = $('[name="search"]').val().trim();
        if (!search) {
            return;
        }
        location.href = '/bookings/search/?search=' + search;
    });
    $(document).on('show-loading', function () {
        if (!$("#loading").length) {
            $('body').append('

');
        }
    });
    $(document).on('hide-loading', function () {
        if ($("#loading").length) {
            $("#loading").remove();
        }
    });

    //Скрывам дропдауны по клику вне списков
    $('body').click(function () {
        $('#menu-trigger').prop('checked', false);
    });
    $(".menu,#menu-trigger-label,#menu-trigger").click(function (e) {
        e.stopPropagation();
    });

    $('.month').on('click', 'a', function () {
        var href = $(this).attr('data-attr-href');
        if (href) {
            location.href = href;
        }
    });

    $('body').on('click', '.calendar th.date', function () {
        var cellIndex = $(this).index() + 1;
        $('.calendar th.date').removeClass('marked');
        $(this).closest('.calendar-wrap').find('tfoot th:nth-child(' + cellIndex + ')').addClass('marked');
    });

    function detectswipe(el,func) {
        swipe_det = new Object();
        swipe_det.sX = 0;
        swipe_det.sY = 0;
        swipe_det.eX = 0;
        swipe_det.eY = 0;
        var min_x = 250;  //min x swipe for horizontal swipe
        var max_x = 40;  //max x difference for vertical swipe
        var min_y = 40;  //min y swipe for vertical swipe
        var max_y = 50;  //max y difference for horizontal swipe
        var direc = "";
        var ele = document.getElementById(el);
        ele.addEventListener('touchstart',function(e){
            //console.log(e);return;
            var t = e.touches[0];
            swipe_det.sX = t.screenX;
            swipe_det.sY = t.screenY;
        },false);
        //ele.addEventListener('touchmove',function(e){
        //    // e.preventDefault();
        //},false);
        ele.addEventListener('touchend',function(e){
            //console.log(e);return;
            var t = e.changedTouches[0];
            swipe_det.eX = t.screenX;
            swipe_det.eY = t.screenY;
            //horizontal detection
            if ((((swipe_det.eX - min_x > swipe_det.sX) || (swipe_det.eX + min_x < swipe_det.sX)) && ((swipe_det.eY < swipe_det.sY + max_y) && (swipe_det.sY > swipe_det.eY - max_y)))) {
                if(swipe_det.eX > swipe_det.sX) direc = "r";
                else direc = "l";
            }

            if (direc != "") {
                if(typeof func == 'function') func(el,direc);
            }
            direc = "";
        },false);
    }

    detectswipe('body',function (el,d) {
        var href = '';
        if(d === 'l'){
            href = $('#next_month').attr('data-attr-href');
        } else if(d === 'r'){
            href = $('#prev_month').attr('data-attr-href');
        }
        if (href)  {
            location.href = href;
        }
    });

    var calendarTable = $('table.calendar');
    if ($(calendarTable).length) {
        //var td = $(calendarTable).find('td[data-info]');
        //var currentId = 0,
        //    currentText = '';
        //for (var i = 0; i < td.length; i++) {
        //    if ($(td[i]).hasClass('first-day') || $(td[i]).hasClass('last-day')) {
        //        continue;
        //    }
        //    var bId = $(td[i]).attr('data-attr-booking_id');
        //}
        if (typeof bookingsInfo != undefined) {
            for (var bookingId in bookingsInfo) {
                if (!bookingsInfo.hasOwnProperty(bookingId)) {
                    continue;
                }
                var text = bookingsInfo[bookingId].trim();
                if (text == '') {
                    continue;
                }
                var td = $(calendarTable).find('td[data-attr-booking_id=' + bookingId + ']'),
                    firstPosition = false,
                    tdIndexToDelte = [];
                for (var i = 0; i < td.length; i++) {
                    if ($(td[i]).hasClass('first-day') || $(td[i]).hasClass('last-day')) {
                        continue;
                    }
                    if (firstPosition === false) {
                        firstPosition = i;
                    } else {
                        tdIndexToDelte.push(i);
                    }
                }
                var cnt = tdIndexToDelte.length,
                    width = $(td[0]).width();
                for (var k in tdIndexToDelte) {
                    if (!tdIndexToDelte.hasOwnProperty(k)) {
                        continue;
                    }
                    $(td[tdIndexToDelte[k]]).remove();
                }
                $(td[firstPosition]).attr('colspan', cnt + 1);
                //text.substr(0, 4*(cnt + 1));
                $(td[firstPosition]).html("
" + text + "
");
                $(td[firstPosition]).find('.booking_info').width(width * (cnt + 1));
            }
        }
        if (typeof fairs != undefined) {
            for (var fairId in fairs) {
                if (!fairs.hasOwnProperty(fairId)) {
                    continue;
                }
                var text = fairs[fairId].trim();
                if (text == '') {
                    continue;
                }
                var td = $(calendarTable).find('td[data-fair-id=' + fairId + ']'),
                    firstPosition = false,
                    tdIndexToDelte = [];
                for (var i = 0; i < td.length; i++) {
                    if (firstPosition === false) {
                        firstPosition = i;
                    } else {
                        tdIndexToDelte.push(i);
                    }
                }
                var cnt = tdIndexToDelte.length,
                    width = $(td[0]).width();
                for (var k in tdIndexToDelte) {
                    if (!tdIndexToDelte.hasOwnProperty(k)) {
                        continue;
                    }
                    $(td[tdIndexToDelte[k]]).remove();
                }
                $(td[firstPosition]).attr('colspan', cnt + 1);
                //text.substr(0, 4*(cnt + 1));
                $(td[firstPosition]).html("
" + text + "
");
                $(td[firstPosition]).find('.fair_info').width(width * (cnt + 1));
            }
        }
    }

    var $table = $('table.calendar');
    $table.floatThead({
        top: 66,
        scrollContainer: function ($table) {
            return $table.closest('.inner');
        },
        position: 'absolute'
    });
});<|endoftext|>


<commit_before>// Remove no-js class
document.querySelector('html').classList.remove('no-js');

// Require and initialize FastClick
import FastClick from '../../../node_modules/fastclick/lib/fastclick';
FastClick.attach(document.body);

// Require and initialize Application Cache Handler
// import * as appcacheHandler from './_modules/_appcache-handler';
// appcacheHandler.init();
<commit_msg>Removed deprecated code<commit_after>// Remove no-js class
document.querySelector('html').classList.remove('no-js');

// Require and initialize FastClick
import FastClick from '../../../node_modules/fastclick/lib/fastclick';
FastClick.attach(document.body);
<|endoftext|>


<commit_before>;(function(d3) {
	"use strict";
	owid.namespace("owid.view.header");

	owid.view.header = function() {
		var header = owid.dataflow();

		header.needs('containerNode', 'bounds', 'titleStr');

		header.defaults({
			titleLink: "",
			subtitleStr: "",
			logosSVG: []
		});

		header.initial('titleSizeScale', function() {
			return d3.scaleLinear().domain([30, 150]).range([1.5, 0.75]).clamp(true);
		});

		header.flow('g : containerNode', function(containerNode) {
			return d3.select(containerNode).append('g').attr('class', 'header');
		});

		// Render the logos first as they affect the positioning of the text

		header.flow('boundsForText, logoHeight : g, logosSVG, bounds', function(g, logosSVG, bounds) {
			var logoUpdate = g.selectAll('.logo').data(logosSVG||[]);
			var logos = logoUpdate.enter().append('g').attr('class', 'logo').merge(logoUpdate);

			// Go through and position/scale the logos as needed
			var targetHeight = 50;
			var offsetX = bounds.width;
            var logoHeight = 0;
			logos.each(function(d) {
				this.innerSVG = d.match(/<svg>(.*)<\/svg>/)[1]||d;

				var bbox = this.getBBox();
				var scale = targetHeight/bbox.height;
                offsetX -= bbox.width*scale;

				d3.select(this).attr('transform', 'translate(' + offsetX + ',' + 0 + ') scale(' + scale + ')');
                logoHeight = bbox.height*scale;
			});

			return [owid.bounds(0, 0, offsetX-10, bounds.height), logoHeight];
		});

		header.flow('titleLinkEl : g', function(g) {
			return g.append('a').attr('class', 'title').attr('target', '_blank');
		});

		header.flow('titleLinkEl, titleLink', function(titleLinkEl, titleLink) {
			titleLinkEl.attr('xlink:href', titleLink);
		});

		header.flow('title : titleLinkEl', function(titleLinkEl) {
			return titleLinkEl.append('text')
				.attr('dy', '1em');
		});

		header.flow('title, boundsForText', function(title, boundsForText) {
			title.attr('x', boundsForText.left)
				.attr('y', boundsForText.top);
		});

		header.flow('title, titleStr, titleSizeScale', function(title, titleStr, titleSizeScale) {
			title.style('font-size', titleSizeScale(s.stripTags(titleStr).length) + 'em');
		});

		header.flow('titleBox, titleFontSize : title, titleStr, boundsForText', function(title, titleStr, boundsForText) {
			// Try to fit the title into a single line if possible-- but not if it would make the text super small

			function resizeTitle(fontSize) {
				title.style('font-size', fontSize + 'em');
				owid.svgSetWrappedText(title, titleStr, boundsForText.width, { lineHeight: 1.1 });
			}

			var fontSize = 1.5;
			resizeTitle(fontSize);
			while (fontSize > 1.0 && title.selectAll('tspan').size() > 1) {
				resizeTitle(fontSize);
				fontSize -= 0.05;
			}

			if (fontSize <= 1.0)
				resizeTitle(1.1);

			title.attr('y', boundsForText.top);
			title.attr('y', boundsForText.top-title.node().getBBox().y);

			return [owid.bounds(title.node().getBBox()), fontSize];
		});

		header.flow('subtitle : g', function(g) {
			return g.append('text')
				.attr('class', 'subtitle')
				.attr('dy', '1em');
		});

		header.flow('subtitle, titleBox, titleFontSize, subtitleStr, boundsForText, logoHeight, bounds, g', function(subtitle, titleBox, titleFontSize, subtitleStr, boundsForText, logoHeight, bounds, g) {
            var width = boundsForText.width;
            if (titleBox.height > logoHeight)
                width = bounds.width;

			subtitle.attr('x', boundsForText.left+1).attr('y', boundsForText.top + titleBox.height);

			// Subtitle text must always be smaller than title text.
			var fontSize = Math.min(0.8, titleFontSize-0.3);
			subtitle.style('font-size', fontSize+'em');
			owid.svgSetWrappedText(subtitle, subtitleStr, width, { lineHeight: 1.2 });

			// Make it a little bit smaller if it still goes across many lines
			if (subtitle.selectAll('tspan').size() > 2) {
				fontSize = Math.min(0.65, fontSize);
				subtitle.style('font-size', fontSize+'em');
				owid.svgSetWrappedText(subtitle, subtitleStr, width, { lineHeight: 1.2 });
			}
		});

        header.flow('bbox : g, titleStr, subtitleStr, boundsForText', function(g) {
            g.selectAll('.bgRect').remove();
            var bbox = g.node().getBBox();
            g.insert('rect', '*').attr('class', 'bgRect').attr('x', 0).attr('y', 0).style('fill', 'white')
                    .attr('width', bbox.width+1).attr('height', bbox.height+10);
            return g.node().getBBox();
        });

		header.flow('g, bounds', function(g, bounds) {
			g.attr('transform', 'translate(' + bounds.left + ',' + bounds.top + ')');
		});

		return header;
	};

	owid.namespace("owid.control.header");

	owid.control.header = function(chart) {
		var headerControl = owid.dataflow();

		headerControl.needs('containerNode', 'bounds');

		headerControl.inputs({
			titleTemplate: "",
			titleLink: "",
			subtitleTemplate: "",
			logosSVG: [],
			entities: [],
			entityType: "",
			minYear: null,
			maxYear: null,
		});

		var header = owid.view.header();

		// Replaces things like *time* and *country* with the actual time and
		// country displayed by the current chart context
		headerControl.flow("fillTemplate : minYear, maxYear, entities, entityType", function(minYear, maxYear, entities, entityType) {
			return function(text) {
				if (s.contains(text, "*country*")) {
					var entityStr = _.pluck(entities, "name").join(', ');
					text = text.replace("*country*", entityStr || ("in selected " + entityType));
				}

				if (s.contains(text, "*time")) {
					if (!_.isFinite(minYear)) {
						text = text.replace("*time*", "over time");
					} else {
						var timeFrom = owid.displayYear(minYear),
							timeTo = owid.displayYear(maxYear),
							time = timeFrom === timeTo ? timeFrom : timeFrom + " to " + timeTo;

						text = text.replace("*time*", time);
						text = text.replace("*timeFrom*", timeFrom);
						text = text.replace("*timeTo*", timeTo);
					}
				}

				return text;
			};
		});

		headerControl.flow("titleStr : titleTemplate, fillTemplate", function(titleTemplate, fillTemplate) {
			return fillTemplate(titleTemplate);
		});

		headerControl.flow("subtitleStr : subtitleTemplate, fillTemplate", function(subtitleTemplate, fillTemplate) {
			return fillTemplate(subtitleTemplate);
		});

		headerControl.flow('containerNode, bounds, logosSVG, titleStr, titleLink, subtitleStr', function(containerNode, bounds, logosSVG, titleStr, titleLink, subtitleStr) {
			header.update({
				containerNode: containerNode,
				bounds: bounds,
				logosSVG: logosSVG,
				titleStr: titleStr,
				titleLink: titleLink,
				subtitleStr: subtitleStr,
			}, function() {
                document.title = header.title.text();
            });
		});

		headerControl.render = function(bounds, done) {
			var minYear, maxYear, disclaimer="";
			if (chart.activeTabName == "map") {
				chart.mapdata.update();

				var mapConfig = chart.map.attributes,
					timeFrom = chart.mapdata.minToleranceYear || mapConfig.targetYear,
					timeTo = chart.mapdata.maxToleranceYear || mapConfig.targetYear,
					year = mapConfig.targetYear,
					hasTargetYear = _.find(chart.mapdata.currentValues, function(d) { return d.year == year; }),
					d = owid.displayYear,
					timeline = chart.tabs.map.timeline;

				if (timeline && (timeline.isPlaying || timeline.isDragging))
					disclaimer = "";
				else if (hasTargetYear && timeFrom != timeTo) {
					// The target year is in the data but we're displaying a range, meaning not available for all countries
					disclaimer = " Since some observations for " + d(year) + " are not available the map displays the closest available data (" + d(timeFrom) + " to " + d(timeTo) + ").";
				} else if (!hasTargetYear && timeFrom != timeTo) {
					// The target year isn't in the data at all and we're displaying a range of other nearby values
					disclaimer = " Since observations for " + d(year) + " are not available the map displays the closest available data (" + d(timeFrom) + " to " + d(timeTo) + ").";
				} else if (!hasTargetYear && timeFrom == timeTo && timeFrom != year) {
					// The target year isn't in the data and we're displaying some other single year
					disclaimer = " Since observations for " + d(year) + " are not available the map displays the closest available data (from " + d(timeFrom) + ").";
				} else if (!hasTargetYear) {
					disclaimer = " No observations are available for this year.";
				} else {
	//				disclaimer = "A rather long placeholder to ensure that the text flow remains the same when changing between various years.";
					disclaimer = "";
				}

				minYear = year;
				maxYear = year;
			} else if (chart.model.get('chart-type') == App.ChartType.ScatterPlot) {
				minYear = (chart.model.get('chart-time')||[])[0];
				maxYear = (chart.model.get('chart-time')||[])[1];
			} else {
				minYear = chart.data.get('minYear');
				maxYear = chart.data.get('maxYear');
			}

			var baseUrl = Global.rootUrl + "/" + chart.model.get("chart-slug"),
				queryParams = owid.getQueryParams(),
				queryStr = owid.queryParamsToStr(queryParams),
				canonicalUrl = baseUrl + queryStr;

			headerControl.update({
				containerNode: chart.svg.node(),
				bounds: bounds,
				titleTemplate: chart.model.get('chart-name'),
				titleLink: canonicalUrl,
				subtitleTemplate: chart.model.get('chart-subname') + disclaimer,
				logosSVG: chart.model.get('logosSVG'),
				entities: chart.model.getSelectedEntities(),
				entityType: chart.model.get('entity-type'),
				minYear: minYear,
				maxYear: maxYear
			}, done);
		};

		headerControl.view = header;

		return headerControl;
	};
})(d3v4);<commit_msg>Header tweak<commit_after>;(function(d3) {
	"use strict";
	owid.namespace("owid.view.header");

	owid.view.header = function() {
		var header = owid.dataflow();

		header.needs('containerNode', 'bounds', 'titleStr');

		header.defaults({
			titleLink: "",
			subtitleStr: "",
			logosSVG: []
		});

		header.initial('titleSizeScale', function() {
			return d3.scaleLinear().domain([30, 150]).range([1.5, 0.75]).clamp(true);
		});

		header.flow('g : containerNode', function(containerNode) {
			return d3.select(containerNode).append('g').attr('class', 'header');
		});

		// Render the logos first as they affect the positioning of the text

		header.flow('boundsForText, logoHeight : g, logosSVG, bounds', function(g, logosSVG, bounds) {
			var logoUpdate = g.selectAll('.logo').data(logosSVG||[]);
			var logos = logoUpdate.enter().append('g').attr('class', 'logo').merge(logoUpdate);

			// Go through and position/scale the logos as needed
			var targetHeight = 50;
			var offsetX = bounds.width;
            var logoHeight = 0;
			logos.each(function(d) {
				this.innerSVG = d.match(/<svg>(.*)<\/svg>/)[1]||d;

				var bbox = this.getBBox();
				var scale = targetHeight/bbox.height;
                offsetX -= bbox.width*scale;

				d3.select(this).attr('transform', 'translate(' + offsetX + ',' + 0 + ') scale(' + scale + ')');
                logoHeight = bbox.height*scale;
			});

			return [owid.bounds(0, 0, offsetX-10, bounds.height), logoHeight];
		});

		header.flow('titleLinkEl : g', function(g) {
			return g.append('a').attr('class', 'title').attr('target', '_blank');
		});

		header.flow('titleLinkEl, titleLink', function(titleLinkEl, titleLink) {
			titleLinkEl.attr('xlink:href', titleLink);
		});

		header.flow('title : titleLinkEl', function(titleLinkEl) {
			return titleLinkEl.append('text')
				.attr('dy', '1em');
		});

		header.flow('title, boundsForText', function(title, boundsForText) {
			title.attr('x', boundsForText.left)
				.attr('y', boundsForText.top);
		});

		header.flow('title, titleStr, titleSizeScale', function(title, titleStr, titleSizeScale) {
			title.style('font-size', titleSizeScale(s.stripTags(titleStr).length) + 'em');
		});

		header.flow('titleBox, titleFontSize : title, titleStr, boundsForText', function(title, titleStr, boundsForText) {
			// Try to fit the title into a single line if possible-- but not if it would make the text super small

			function resizeTitle(fontSize) {
				title.style('font-size', fontSize + 'em');
				owid.svgSetWrappedText(title, titleStr, boundsForText.width, { lineHeight: 1.1 });
			}

			var fontSize = 1.5;
			resizeTitle(fontSize);
			while (fontSize > 1.0 && title.selectAll('tspan').size() > 1) {
				resizeTitle(fontSize);
				fontSize -= 0.05;
			}

			if (fontSize <= 1.0)
				resizeTitle(1.2);

			title.attr('y', boundsForText.top);
			title.attr('y', boundsForText.top-title.node().getBBox().y);

			return [owid.bounds(title.node().getBBox()), fontSize];
		});

		header.flow('subtitle : g', function(g) {
			return g.append('text')
				.attr('class', 'subtitle')
				.attr('dy', '1em');
		});

		header.flow('subtitle, titleBox, titleFontSize, subtitleStr, boundsForText, logoHeight, bounds, g', function(subtitle, titleBox, titleFontSize, subtitleStr, boundsForText, logoHeight, bounds, g) {
            var width = boundsForText.width;
            if (titleBox.height > logoHeight)
                width = bounds.width;

			subtitle.attr('x', boundsForText.left+1).attr('y', boundsForText.top + titleBox.height);

			// Subtitle text must always be smaller than title text.
			var fontSize = Math.min(0.8, titleFontSize-0.3);
			subtitle.style('font-size', fontSize+'em');
			owid.svgSetWrappedText(subtitle, subtitleStr, width, { lineHeight: 1.2 });

			// Make it a little bit smaller if it still goes across many lines
			if (subtitle.selectAll('tspan').size() > 2) {
				fontSize = Math.min(0.65, fontSize);
				subtitle.style('font-size', fontSize+'em');
				owid.svgSetWrappedText(subtitle, subtitleStr, width, { lineHeight: 1.2 });
			}
		});

        header.flow('bbox : g, titleStr, subtitleStr, boundsForText', function(g) {
            g.selectAll('.bgRect').remove();
            var bbox = g.node().getBBox();
            g.insert('rect', '*').attr('class', 'bgRect').attr('x', 0).attr('y', 0).style('fill', 'white')
                    .attr('width', bbox.width+1).attr('height', bbox.height+10);
            return g.node().getBBox();
        });

		header.flow('g, bounds', function(g, bounds) {
			g.attr('transform', 'translate(' + bounds.left + ',' + bounds.top + ')');
		});

		return header;
	};

	owid.namespace("owid.control.header");

	owid.control.header = function(chart) {
		var headerControl = owid.dataflow();

		headerControl.needs('containerNode', 'bounds');

		headerControl.inputs({
			titleTemplate: "",
			titleLink: "",
			subtitleTemplate: "",
			logosSVG: [],
			entities: [],
			entityType: "",
			minYear: null,
			maxYear: null,
		});

		var header = owid.view.header();

		// Replaces things like *time* and *country* with the actual time and
		// country displayed by the current chart context
		headerControl.flow("fillTemplate : minYear, maxYear, entities, entityType", function(minYear, maxYear, entities, entityType) {
			return function(text) {
				if (s.contains(text, "*country*")) {
					var entityStr = _.pluck(entities, "name").join(', ');
					text = text.replace("*country*", entityStr || ("in selected " + entityType));
				}

				if (s.contains(text, "*time")) {
					if (!_.isFinite(minYear)) {
						text = text.replace("*time*", "over time");
					} else {
						var timeFrom = owid.displayYear(minYear),
							timeTo = owid.displayYear(maxYear),
							time = timeFrom === timeTo ? timeFrom : timeFrom + " to " + timeTo;

						text = text.replace("*time*", time);
						text = text.replace("*timeFrom*", timeFrom);
						text = text.replace("*timeTo*", timeTo);
					}
				}

				return text;
			};
		});

		headerControl.flow("titleStr : titleTemplate, fillTemplate", function(titleTemplate, fillTemplate) {
			return fillTemplate(titleTemplate);
		});

		headerControl.flow("subtitleStr : subtitleTemplate, fillTemplate", function(subtitleTemplate, fillTemplate) {
			return fillTemplate(subtitleTemplate);
		});

		headerControl.flow('containerNode, bounds, logosSVG, titleStr, titleLink, subtitleStr', function(containerNode, bounds, logosSVG, titleStr, titleLink, subtitleStr) {
			header.update({
				containerNode: containerNode,
				bounds: bounds,
				logosSVG: logosSVG,
				titleStr: titleStr,
				titleLink: titleLink,
				subtitleStr: subtitleStr,
			}, function() {
                document.title = header.title.text();
            });
		});

		headerControl.render = function(bounds, done) {
			var minYear, maxYear, disclaimer="";
			if (chart.activeTabName == "map") {
				chart.mapdata.update();

				var mapConfig = chart.map.attributes,
					timeFrom = chart.mapdata.minToleranceYear || mapConfig.targetYear,
					timeTo = chart.mapdata.maxToleranceYear || mapConfig.targetYear,
					year = mapConfig.targetYear,
					hasTargetYear = _.find(chart.mapdata.currentValues, function(d) { return d.year == year; }),
					d = owid.displayYear,
					timeline = chart.tabs.map.timeline;

				if (timeline && (timeline.isPlaying || timeline.isDragging))
					disclaimer = "";
				else if (hasTargetYear && timeFrom != timeTo) {
					// The target year is in the data but we're displaying a range, meaning not available for all countries
					disclaimer = " Since some observations for " + d(year) + " are not available the map displays the closest available data (" + d(timeFrom) + " to " + d(timeTo) + ").";
				} else if (!hasTargetYear && timeFrom != timeTo) {
					// The target year isn't in the data at all and we're displaying a range of other nearby values
					disclaimer = " Since observations for " + d(year) + " are not available the map displays the closest available data (" + d(timeFrom) + " to " + d(timeTo) + ").";
				} else if (!hasTargetYear && timeFrom == timeTo && timeFrom != year) {
					// The target year isn't in the data and we're displaying some other single year
					disclaimer = " Since observations for " + d(year) + " are not available the map displays the closest available data (from " + d(timeFrom) + ").";
				} else if (!hasTargetYear) {
					disclaimer = " No observations are available for this year.";
				} else {
	//				disclaimer = "A rather long placeholder to ensure that the text flow remains the same when changing between various years.";
					disclaimer = "";
				}

				minYear = year;
				maxYear = year;
			} else if (chart.model.get('chart-type') == App.ChartType.ScatterPlot) {
				minYear = (chart.model.get('chart-time')||[])[0];
				maxYear = (chart.model.get('chart-time')||[])[1];
			} else {
				minYear = chart.data.get('minYear');
				maxYear = chart.data.get('maxYear');
			}

			var baseUrl = Global.rootUrl + "/" + chart.model.get("chart-slug"),
				queryParams = owid.getQueryParams(),
				queryStr = owid.queryParamsToStr(queryParams),
				canonicalUrl = baseUrl + queryStr;

			headerControl.update({
				containerNode: chart.svg.node(),
				bounds: bounds,
				titleTemplate: chart.model.get('chart-name'),
				titleLink: canonicalUrl,
				subtitleTemplate: chart.model.get('chart-subname') + disclaimer,
				logosSVG: chart.model.get('logosSVG'),
				entities: chart.model.getSelectedEntities(),
				entityType: chart.model.get('entity-type'),
				minYear: minYear,
				maxYear: maxYear
			}, done);
		};

		headerControl.view = header;

		return headerControl;
	};
})(d3v4);<|endoftext|>


<commit_before>
/*!--------------------------------*\
   3-Jekyll Theme
   @author Peiwen Lu (P233)
   https://github.com/P233/3-Jekyll
\*---------------------------------*/

// Detect window size, if less than 1280px add class 'mobile' to sidebar therefore it will be auto hide when trigger the pjax request in small screen devices.
if ($(window).width() <= 1280) {
  $('#sidebar').addClass('mobile')
}

// Variables
    tag1       = $('.p1_all'),
    tag2       = $('.one'),
    tag3       = $('.two'),
    tag4       = $('.thr'),
    tag5       = $('.fou'),
    tag6       = $('.fiv');
var sidebar    = $('#sidebar'),
    container  = $('#post'),
    content    = $('#pjax'),
    button     = $('#icon-arrow');

// Tags switcher
var clickHandler = function(k) {
  return function() {
    $(this).addClass('active').siblings().removeClass('active');
    tag1.hide();
    window['tag'+k].delay(50).fadeIn(350);
  }
};
for (var i = 1; i <= 6; i++) {
  $('#js-label' + i).on('click', clickHandler(i));
}

// If sidebar has class 'mobile', hide it after clicking.
tag1.on('click', function() {
  $(this).addClass('active').siblings().removeClass('active');
  if (sidebar.hasClass('mobile')) {
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }
});

// Enable fullscreen.
$('#js-fullscreen').on('click', function() {
  if (button.hasClass('fullscreen')) {
    sidebar.removeClass('fullscreen');
    button.removeClass('fullscreen');
    content.delay(300).queue(function(){
      $(this).removeClass('fullscreen').dequeue();
    });
  } else {
    sidebar.addClass('fullscreen');
    button.addClass('fullscreen');
    content.delay(200).queue(function(){
      $(this).addClass('fullscreen').dequeue();
    });
  }
});

$('#mobile-avatar').on('click', function(){
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
});

// Pjax
$(document).pjax('#avatar, #mobile-avatar, .pl__all', '#pjax', { fragment: '#pjax', timeout: 10000 });
$(document).on({
  'pjax:click': function() {
    content.removeClass('fadeIn').addClass('fadeOut');
    NProgress.start();
  },
  'pjax:start': function() {
    content.css({'opacity':0});
  },
  'pjax:end': function() {
    NProgress.done();
    container.scrollTop(0);
    content.css({'opacity':1}).removeClass('fadeOut').addClass('fadeIn');
    afterPjax();
  }
});

// Codepen embed js
// http://codepen.io/assets/embed/ei.js
// Added on 17 Nov 2013
var CodePenEmbed={width:"100%",init:function(){this.showCodePenEmbeds(),this.listenToParentPostMessages()},showCodePenEmbeds:function(){var e=document.getElementsByClassName("codepen");for(var t=e.length-1;t>-1;t--){var n=this._getParamsFromAttributes(e[t]);n=this._convertOldDataAttributesToNewDataAttributes(n);var r=this._buildURL(n),i=this._buildIFrame(n,r);this._addIFrameToPage(e[t],i)}},_getParamsFromAttributes:function(e){var t={},n=e.attributes;for(var r=0,i=n.length;r<i;r++)name=n[r].name,name.indexOf("data-")===0&&(t[name.replace("data-","")]=n[r].value);return t},_convertOldDataAttributesToNewDataAttributes:function(e){return e.href&&(e["slug-hash"]=e.href),e.type&&(e["default-tab"]=e.type),e.safe&&(e["safe"]=="true"?e.animations="run":e.animations="stop-after-5"),e},_buildURL:function(e){var t=this._getHost(e),n=e.user?e.user:"anon",r="?"+this._getGetParams(e),i=[t,n,"embed",e["slug-hash"]+r].join("/");return i.replace(/\/\//g,"//")},_getHost:function(e){return e.host?e.host:document.location.protocol=="file:"?"http://codepen.io":"//codepen.io"},_getGetParams:function(e){var t="",n=0;for(var r in e)t!==""&&(t+="&"),t+=r+"="+encodeURIComponent(e[r]);return t},_buildIFrame:function(e,t){var n={id:"cp_embed_"+e["slug-hash"].replace("/","_"),src:t,scrolling:"no",frameborder:"0",height:this._getHeight(e),allowTransparency:"true","class":"cp_embed_iframe",style:"width: "+this.width+"; overflow: hidden;"},r="",r},_getHeight:function(e){return e.height?e["height"]=="auto"?300:e.height:300},_addIFrameToPage:function(e,t){if(e.parentNode){var n=document.createElement("div");n.innerHTML=t,e.parentNode.replaceChild(n,e)}else e.innerHTML=t},listenToParentPostMessages:function(){var eventMethod=window.addEventListener?"addEventListener":"attachEvent",eventListener=window[eventMethod],messageEvent=eventMethod=="attachEvent"?"onmessage":"message";eventListener(messageEvent,function(e){try{var dataObj=eval("("+e.data+")"),iframe=document.getElementById("cp_embed_"+dataObj.hash);iframe&&(iframe.height=dataObj.height)}catch(err){}},!1)}};

// Re-run scripts for post content after pjax
function afterPjax() {
  // Open links in new tab
  $('#post__content a').attr('target','_blank');

  // Embed codepen after pjax
  CodePenEmbed.init();

  // Generate post TOC for h1 h2 and h3
  var toc = $('#post__toc-ul');
  // Empty TOC and generate an entry for h1
  toc.empty().append('
' + $('#post__title').text() + '
');

  // Generate entries for h2 and h3
  $('#post__content').children('h2,h3').each(function() {
    // Generate random ID for each heading
    $(this).attr('id', function() {
      var ID = "",
          alphabet = "abcdefghijklmnopqrstuvwxyz";

      for(var i=0; i < 5; i++) {
        ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
      }
      return ID;
    });

    if ($(this).prop("tagName") == 'H2') {
      toc.append('
' + $(this).text() + '
');
    } else {
      toc.append('
' + $(this).text() + '
');
    }
  });

  // Smooth scrolling
  $('.js-anchor-link').on('click', function() {
    var target = $(this.hash);
    container.animate({scrollTop: target.offset().top + container.scrollTop() - 70}, 500, function() {
      target.addClass('flash').delay(700).queue(function() {
        $(this).removeClass('flash').dequeue();
      });
    });
  });

  // Lazy Loading Disqus
  // http://jsfiddle.net/dragoncrew/SHGwe/1/
  var ds_loaded = false,
      top = $('#disqus_thread').offset().top;
      identifier = $('#post__title').data('identifier');
  window.disqus_shortname = '';
  window.disqus_identifier = identifier;

  function check() {
    if ( !ds_loaded && container.scrollTop() + container.height() > top ) {
      $.ajax({
        type: 'GET',
        url: 'http://' + disqus_shortname + '.disqus.com/embed.js',
        dataType: 'script',
        cache: true
      });
      ds_loaded = true;
    }
  }check();
  container.scroll(check);
}afterPjax();

<commit_msg>change content test html<commit_after>
/*!--------------------------------*\
   3-Jekyll Theme
   @author Peiwen Lu (P233)
   https://github.com/P233/3-Jekyll
\*---------------------------------*/

// Detect window size, if less than 1280px add class 'mobile' to sidebar therefore it will be auto hide when trigger the pjax request in small screen devices.
if ($(window).width() <= 1280) {
  $('#sidebar').addClass('mobile')
}

// Variables
    tag1       = $('.pl_all'),
    tag2       = $('.one'),
    tag3       = $('.two'),
    tag4       = $('.thr'),
    tag5       = $('.fou'),
    tag6       = $('.fiv');
var sidebar    = $('#sidebar'),
    container  = $('#post'),
    content    = $('#pjax'),
    button     = $('#icon-arrow');

// Tags switcher
var clickHandler = function(k) {
  return function() {
    $(this).addClass('active').siblings().removeClass('active');
    tag1.hide();
    window['tag'+k].delay(50).fadeIn(350);
  }
};
for (var i = 1; i <= 6; i++) {
  $('#js-label' + i).on('click', clickHandler(i));
}

// If sidebar has class 'mobile', hide it after clicking.
tag1.on('click', function() {
  $(this).addClass('active').siblings().removeClass('active');
  if (sidebar.hasClass('mobile')) {
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }
});

// Enable fullscreen.
$('#js-fullscreen').on('click', function() {
  if (button.hasClass('fullscreen')) {
    sidebar.removeClass('fullscreen');
    button.removeClass('fullscreen');
    content.delay(300).queue(function(){
      $(this).removeClass('fullscreen').dequeue();
    });
  } else {
    sidebar.addClass('fullscreen');
    button.addClass('fullscreen');
    content.delay(200).queue(function(){
      $(this).addClass('fullscreen').dequeue();
    });
  }
});

$('#mobile-avatar').on('click', function(){
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
});

// Pjax
$(document).pjax('#avatar, #mobile-avatar, .pl__all', '#pjax', { fragment: '#pjax', timeout: 10000 });
$(document).on({
  'pjax:click': function() {
    content.removeClass('fadeIn').addClass('fadeOut');
    NProgress.start();
  },
  'pjax:start': function() {
    content.css({'opacity':0});
  },
  'pjax:end': function() {
    NProgress.done();
    container.scrollTop(0);
    content.css({'opacity':1}).removeClass('fadeOut').addClass('fadeIn');
    afterPjax();
  }
});

// Codepen embed js
// http://codepen.io/assets/embed/ei.js
// Added on 17 Nov 2013
var CodePenEmbed={width:"100%",init:function(){this.showCodePenEmbeds(),this.listenToParentPostMessages()},showCodePenEmbeds:function(){var e=document.getElementsByClassName("codepen");for(var t=e.length-1;t>-1;t--){var n=this._getParamsFromAttributes(e[t]);n=this._convertOldDataAttributesToNewDataAttributes(n);var r=this._buildURL(n),i=this._buildIFrame(n,r);this._addIFrameToPage(e[t],i)}},_getParamsFromAttributes:function(e){var t={},n=e.attributes;for(var r=0,i=n.length;r<i;r++)name=n[r].name,name.indexOf("data-")===0&&(t[name.replace("data-","")]=n[r].value);return t},_convertOldDataAttributesToNewDataAttributes:function(e){return e.href&&(e["slug-hash"]=e.href),e.type&&(e["default-tab"]=e.type),e.safe&&(e["safe"]=="true"?e.animations="run":e.animations="stop-after-5"),e},_buildURL:function(e){var t=this._getHost(e),n=e.user?e.user:"anon",r="?"+this._getGetParams(e),i=[t,n,"embed",e["slug-hash"]+r].join("/");return i.replace(/\/\//g,"//")},_getHost:function(e){return e.host?e.host:document.location.protocol=="file:"?"http://codepen.io":"//codepen.io"},_getGetParams:function(e){var t="",n=0;for(var r in e)t!==""&&(t+="&"),t+=r+"="+encodeURIComponent(e[r]);return t},_buildIFrame:function(e,t){var n={id:"cp_embed_"+e["slug-hash"].replace("/","_"),src:t,scrolling:"no",frameborder:"0",height:this._getHeight(e),allowTransparency:"true","class":"cp_embed_iframe",style:"width: "+this.width+"; overflow: hidden;"},r="",r},_getHeight:function(e){return e.height?e["height"]=="auto"?300:e.height:300},_addIFrameToPage:function(e,t){if(e.parentNode){var n=document.createElement("div");n.innerHTML=t,e.parentNode.replaceChild(n,e)}else e.innerHTML=t},listenToParentPostMessages:function(){var eventMethod=window.addEventListener?"addEventListener":"attachEvent",eventListener=window[eventMethod],messageEvent=eventMethod=="attachEvent"?"onmessage":"message";eventListener(messageEvent,function(e){try{var dataObj=eval("("+e.data+")"),iframe=document.getElementById("cp_embed_"+dataObj.hash);iframe&&(iframe.height=dataObj.height)}catch(err){}},!1)}};

// Re-run scripts for post content after pjax
function afterPjax() {
  // Open links in new tab
  $('#post__content a').attr('target','_blank');

  // Embed codepen after pjax
  CodePenEmbed.init();

  // Generate post TOC for h1 h2 and h3
  var toc = $('#post__toc-ul');
  // Empty TOC and generate an entry for h1
  toc.empty().append('
' + $('#post__title').text() + '
');

  // Generate entries for h2 and h3
  $('#post__content').children('h2,h3').each(function() {
    // Generate random ID for each heading
    $(this).attr('id', function() {
      var ID = "",
          alphabet = "abcdefghijklmnopqrstuvwxyz";

      for(var i=0; i < 5; i++) {
        ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
      }
      return ID;
    });

    if ($(this).prop("tagName") == 'H2') {
      toc.append('
' + $(this).text() + '
');
    } else {
      toc.append('
' + $(this).text() + '
');
    }
  });

  // Smooth scrolling
  $('.js-anchor-link').on('click', function() {
    var target = $(this.hash);
    container.animate({scrollTop: target.offset().top + container.scrollTop() - 70}, 500, function() {
      target.addClass('flash').delay(700).queue(function() {
        $(this).removeClass('flash').dequeue();
      });
    });
  });

  // Lazy Loading Disqus
  // http://jsfiddle.net/dragoncrew/SHGwe/1/
  var ds_loaded = false,
      top = $('#disqus_thread').offset().top;
      identifier = $('#post__title').data('identifier');
  window.disqus_shortname = '';
  window.disqus_identifier = identifier;

  function check() {
    if ( !ds_loaded && container.scrollTop() + container.height() > top ) {
      $.ajax({
        type: 'GET',
        url: 'http://' + disqus_shortname + '.disqus.com/embed.js',
        dataType: 'script',
        cache: true
      });
      ds_loaded = true;
    }
  }check();
  container.scroll(check);
}afterPjax();

<|endoftext|>


<commit_before>athens.search = (function () {

    var searchDiv = $(".search-div");

    /**
     * Fades in the table search div.
     */
    function fadeInSearch()
    {
        athens.fadeInMask();
        $(".search-div").fadeTo(1, 1);
    }

    /**
     * Fades out the table search div.
     */
    function fadeOutSearch()
    {
        searchDiv.fadeTo(
            150,
            0,
            function () {
                $(this).css("display", "none");
            }
        );

    }

    var searchSubmitOnclick = function () {
        var handle = $(this).closest("div.search-table-content").data("handle-for");
        var ajaxSectionName = $("div.search-container[data-handle-for=" + handle + "]").closest(".filter-controls").data('table-for');

        var i = 0;

        var getVar = athens.ajax_section.getVar;

        $(this).parent().find('tr').each(
            function () {
                var fieldname = $(this).find('td.fieldname select option:selected').val();
                var operation = $(this).find('td.operation select option:selected').text();
                var value = $(this).find('td.value input').val();
                if (fieldname && operation && value) {
                    athens.ajax_section.registerGetVar(getVar(ajaxSectionName, handle, 'fieldname' + i, fieldname));
                    athens.ajax_section.registerGetVar(getVar(ajaxSectionName, handle, 'operation' + i, operation));
                    athens.ajax_section.registerGetVar(getVar(ajaxSectionName, handle, 'value' + i, value));
                } else {
                    athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'fieldname' + i));
                    athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'operation' + i));
                    athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'value' + i));
                }
                i++;
            }
        );
        athens.ajax_section.registerGetVar(getVar(ajaxSectionName, 'pagination', 'page', 1));
        athens.ajax_section.loadSection(ajaxSectionName);
        athens.fadeOutMask();
        fadeOutSearch();
    };

    var searchIconOnclick = function () {
        var handle = $(this).data("handle-for");
        var ajaxSectionName = $("div.search-container[data-handle-for=" + handle + "]").closest(".filter-controls").data('table-for');

        athens.fadeInMask();
        fadeInSearch();

        // Pre-select the existing search criteria
        $("#search-criteria-area").find('tr').each(
            function () {
                var rowNumber = $(this).attr("data-row");
                var fieldName = athens.ajax_section.getGetVarValue(ajaxSectionName, handle, 'fieldname' + rowNumber);
                $(this).find("td.fieldname select").val(fieldName);
                var operation = athens.ajax_section.getGetVarValue(ajaxSectionName, handle, 'operation' + rowNumber);
                $(this).find("td.operation select").val(operation);
                var value = athens.ajax_section.getGetVarValue(ajaxSectionName, handle, 'value' + rowNumber);
                $(this).find("td.value input").val(value);
            }
        );
    };

    var setupSearchFilter = function (handle) {
        // Move the search icon to the label
        var searchContainer = $("div.search-container[data-handle-for=" + handle + "]");
        var label = searchContainer.closest("div.table-container").prev("div.section-label");
        var searchIcon = $("div.search-icon[data-handle-for=" + handle + "]");

        $("#search-criteria-area").empty();
        $("div.search-table-content[data-handle-for=" + handle + "]").prependTo("#search-criteria-area");
        $("input.search-submit." + handle).click(searchSubmitOnclick);

        if (label.find("div.search-icon[data-handle-for=" + handle + "]").length === 0) {
            searchIcon.prependTo(label);
            searchIcon.click(searchIconOnclick);
        }

        // If this search filter has feedback, add a clear search link:
        $("p.filter-feedback[data-handle-for=" + handle + "]")
            .append(" Clear Search");

    };

    var clearSearch = function (handle) {
        var getVar = athens.ajax_section.getVar;
        var ajaxSectionName = $("div.search-container[data-handle-for=" + handle + "]").closest(".filter-controls").data('table-for');

        for (var i = 0; i <= 5; i++) {
            athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'fieldname' + i));
            athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'operation' + i));
            athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'value' + i));
        }

        athens.ajax_section.bareLoadSection(ajaxSectionName);
    };

    return {
        setupSearchFilter: setupSearchFilter,
        clearSearch: clearSearch
    };
}());

<commit_msg>Don't update search if there are no results.<commit_after>athens.search = (function () {

    var searchDiv = $(".search-div");

    /**
     * Fades in the table search div.
     */
    function fadeInSearch()
    {
        athens.fadeInMask();
        $(".search-div").fadeTo(1, 1);
    }

    /**
     * Fades out the table search div.
     */
    function fadeOutSearch()
    {
        searchDiv.fadeTo(
            150,
            0,
            function () {
                $(this).css("display", "none");
            }
        );

    }

    var searchSubmitOnclick = function () {
        var handle = $(this).closest("div.search-table-content").data("handle-for");
        var ajaxSectionName = $("div.search-container[data-handle-for=" + handle + "]").closest(".filter-controls").data('table-for');

        var i = 0;

        var getVar = athens.ajax_section.getVar;

        $(this).parent().find('tr').each(
            function () {
                var fieldname = $(this).find('td.fieldname select option:selected').val();
                var operation = $(this).find('td.operation select option:selected').text();
                var value = $(this).find('td.value input').val();
                if (fieldname && operation && value) {
                    athens.ajax_section.registerGetVar(getVar(ajaxSectionName, handle, 'fieldname' + i, fieldname));
                    athens.ajax_section.registerGetVar(getVar(ajaxSectionName, handle, 'operation' + i, operation));
                    athens.ajax_section.registerGetVar(getVar(ajaxSectionName, handle, 'value' + i, value));
                } else {
                    athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'fieldname' + i));
                    athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'operation' + i));
                    athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'value' + i));
                }
                i++;
            }
        );
        athens.ajax_section.registerGetVar(getVar(ajaxSectionName, 'pagination', 'page', 1));
        athens.ajax_section.loadSection(ajaxSectionName);
        athens.fadeOutMask();
        fadeOutSearch();
    };

    var searchIconOnclick = function () {
        var handle = $(this).data("handle-for");
        var ajaxSectionName = $("div.search-container[data-handle-for=" + handle + "]").closest(".filter-controls").data('table-for');

        athens.fadeInMask();
        fadeInSearch();

        // Pre-select the existing search criteria
        $("#search-criteria-area").find('tr').each(
            function () {
                var rowNumber = $(this).attr("data-row");
                var fieldName = athens.ajax_section.getGetVarValue(ajaxSectionName, handle, 'fieldname' + rowNumber);
                $(this).find("td.fieldname select").val(fieldName);
                var operation = athens.ajax_section.getGetVarValue(ajaxSectionName, handle, 'operation' + rowNumber);
                $(this).find("td.operation select").val(operation);
                var value = athens.ajax_section.getGetVarValue(ajaxSectionName, handle, 'value' + rowNumber);
                $(this).find("td.value input").val(value);
            }
        );
    };

    var setupSearchFilter = function (handle) {
        // Move the search icon to the label
        var searchContainer = $("div.search-container[data-handle-for=" + handle + "]");
        var label = searchContainer.closest("div.table-container").prev("div.section-label");
        var searchIcon = $("div.search-icon[data-handle-for=" + handle + "]");
        var searchCriteriaArea = $("#search-criteria-area");
        var newCriteriaHasRows = $("div.search-table-content[data-handle-for=" + handle + "]:not(.moved) tr[data-row=0] td.fieldname option").length > 2;
        var oldCriteriaHasRows = searchCriteriaArea.find('tr[data-row=0] td.fieldname option').length > 2;

        if (newCriteriaHasRows || !oldCriteriaHasRows) {
            searchCriteriaArea.empty();
            $("div.search-table-content[data-handle-for=" + handle + "]").prependTo(searchCriteriaArea).addClass('moved');
            $("input.search-submit." + handle).click(searchSubmitOnclick);
        }

        if (label.find("div.search-icon[data-handle-for=" + handle + "]").length === 0) {
            searchIcon.prependTo(label);
            searchIcon.click(searchIconOnclick);
        }

        // If this search filter has feedback, add a clear search link:
        $("p.filter-feedback[data-handle-for=" + handle + "]")
            .append(" Clear Search");

    };

    var clearSearch = function (handle) {
        var getVar = athens.ajax_section.getVar;
        var ajaxSectionName = $("div.search-container[data-handle-for=" + handle + "]").closest(".filter-controls").data('table-for');

        for (var i = 0; i <= 5; i++) {
            athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'fieldname' + i));
            athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'operation' + i));
            athens.ajax_section.unsetGetVar(getVar(ajaxSectionName, handle, 'value' + i));
        }

        athens.ajax_section.bareLoadSection(ajaxSectionName);
    };

    return {
        setupSearchFilter: setupSearchFilter,
        clearSearch: clearSearch
    };
}());

<|endoftext|>


<commit_before>/****************************************************
 *
 * CKEditor Extension
 *
 * Written by Larix Kortbeek for Grrr
 *
 *****************************************************/
Ext.form.CKEditor = function(config) {
    this.config = config;

    config.CKEditor = window.WYSIWYG_CKEDITOR_CONFIG || {
        // Allow only these tags (=true for all of them)
        allowedContent: true,
		customConfig: '',
        format_tags: 'p;h2;h3',

        // Available buttons
        toolbar: [
            ['Bold', 'Italic', '-', 'RemoveFormat'],
            ['Link', 'Unlink'],
            ['NumberedList', 'BulletedList', 'Blockquote', 'Format'],
            ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo', '-', 'Source', '-', 'CharCount']
        ],

        // Disable CKEditor's own image plugin
        removePlugins: 'image'
    };

    // Load the site's own styling
    if (window.WYSIWYG_CSS_URL) {
        config.CKEditor.contentsCss = window.WYSIWYG_CSS_URL;
    }

    config.CKEditor.height = "400px";
	config.CKEditor.maxLength = config.maxLength || 0;

	var extraPlugins = 'charcount,garpctrlenter';

    // Load the garp content plugins for richwyswig editor types
    if (config.rich) {
        // Always load the images picker
        extraPlugins += ",garpimages";
        var richButtons = ["Garpimage"];

        // Only load the video picker when a VIDEO_WIDTH template is defined
        if (typeof VIDEO_WIDTH !== 'undefined') {
            extraPlugins += ",garpvideos";
            richButtons.push("Garpvideo");
        }

        // Let the editor know
        config.CKEditor.toolbar.push(richButtons);
    }

    config.CKEditor.extraPlugins = extraPlugins;

    // Attach to Ext
    Ext.form.CKEditor.superclass.constructor.call(this, config);
};

Ext.extend(Ext.form.CKEditor, Ext.form.TextArea, {
    onRender: function(ct, position) {
        Ext.form.CKEditor.superclass.onRender.call(this, ct, position);

		var ckLoaded = function() {
        	this.editor = CKEDITOR.replace(this.id, this.config.CKEditor);

        	// Closure for quick access in the event listener
        	var that = this;
        	this.editor.on('dataReady', function() {
            	this.resetDirty();
            	that.waitingForSetData = false;
        	});
        	this.setValue(this.orgValue);
        };
		if (typeof CKEDITOR === 'undefined') {
			Ext.Loader.load([ASSET_URL + 'js/garp/ckeditor/ckeditor.js'], ckLoaded, this);
			return;
		}
		ckLoaded.call(this);
    },

	isValid: function(value) {
        var charCount = this.getCharCount();
		if (!this.editor) {
			return true;
		}

        if (!this.allowBlank && !charCount) {
            if (this.wasBlank) {
                return false;
            }
            this.wasBlank = true;
            this.editor.element.addClass('invalid');
            this.markInvalid(this.blankText);
            return false;
        }
        this.wasBlank = false;

		if (this.maxLength && charCount >= this.maxLength) {
            if (this.wasTooLong) {
                return false;
            }
            this.wasTooLong = true;
            this.editor.element.addClass('invalid');
            this.markInvalid(this.maxLengthText);
			return false;
		}
        this.wasTooLong = false;

        this.clearInvalid();
        return true;
	},

	// Get char count, stripped of HTML tags
	getCharCount: function() {
        var contentString = "";
		try {
            contentString = this.editor.document.getBody().getText();
		} catch(e) {
            contentString = this.getValue().replace(/(<([^>]+)>)/ig,"");
		}
        // Trim newlines and count
        return contentString.replace(/^\s+|\s+$/g, '').length;
	},

    setValue: function(value) {
        // Save the value as the elements original value
        this.orgValue = value;

        // Wait for an editor (the setValue function will be called on render)
        if (!this.editor) {
            return;
        }
        // Convert undefineds and nulls to empty string
        value = value || "";

        // Working around CKEditor's crazy-assync setData
        // (When setting data twice in short succession only the first data gets set)
        var that = this;

        function retrySetValue(event) {
            that.setValue(that.orgValue);
            that.waitingForSetData = false;
            event.removeListener();
        }
        if (this.waitingForSetData) {
            this.editor.on('dataReady', retrySetValue);
        }
        this.waitingForSetData = true;

        // Set CKEditor's content
        this.editor.setData(value);
    },

    getValue: function() {
        var val = this.orgValue;

        // If an editor is available and content has changed
        if (this.editor && this.editor.checkDirty()) {
            val = this.editor.getData();
        }

        // Convert falsy values to the empty string
        return val || "";
    },

    getRawValue: function() {
        return this.getValue();
    }
});

// Define "Rich CKEditor" (which allows for some more options such as image and video embeds)
Ext.form.RichCKEditor = function(config) {
    config.rich = true;
    Ext.form.RichCKEditor.superclass.constructor.call(this, config);
};
Ext.extend(Ext.form.RichCKEditor, Ext.form.CKEditor);

// Enable the CKEditor as default richtexteditor
Ext.reg('wysiwygeditor', Ext.form.CKEditor);
Ext.reg('richwysiwygeditor', Ext.form.RichCKEditor);
<commit_msg>Fix: CKEditor rendered too wide issue resolved<commit_after>/****************************************************
 *
 * CKEditor Extension
 *
 * Written by Larix Kortbeek for Grrr
 *
 *****************************************************/
Ext.form.CKEditor = function(config) {
    this.config = config;

    config.CKEditor = window.WYSIWYG_CKEDITOR_CONFIG || {
        // Allow only these tags (=true for all of them)
        allowedContent: true,
        customConfig: '',
        format_tags: 'p;h2;h3',

        // Available buttons
        toolbar: [
            ['Bold', 'Italic', '-', 'RemoveFormat'],
            ['Link', 'Unlink'],
            ['NumberedList', 'BulletedList', 'Blockquote', 'Format'],
            ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo', '-', 'Source', '-', 'CharCount']
        ],

        // Disable CKEditor's own image plugin
        removePlugins: 'image'
    };

    // Load the site's own styling
    if (window.WYSIWYG_CSS_URL) {
        config.CKEditor.contentsCss = window.WYSIWYG_CSS_URL;
    }

    config.CKEditor.height = "400px";
    config.CKEditor.maxLength = config.maxLength || 0;

    var extraPlugins = 'charcount,garpctrlenter';

    // Load the garp content plugins for richwyswig editor types
    if (config.rich) {
        // Always load the images picker
        extraPlugins += ",garpimages";
        var richButtons = ["Garpimage"];

        // Only load the video picker when a VIDEO_WIDTH template is defined
        if (typeof VIDEO_WIDTH !== 'undefined') {
            extraPlugins += ",garpvideos";
            richButtons.push("Garpvideo");
        }

        // Let the editor know
        config.CKEditor.toolbar.push(richButtons);
    }

    config.CKEditor.extraPlugins = extraPlugins;

    // Attach to Ext
    Ext.form.CKEditor.superclass.constructor.call(this, config);
};

Ext.extend(Ext.form.CKEditor, Ext.form.TextArea, {

    adjustEditorSize: function() {
        if (!this.editor || this.waitingForSetData) {
            return;
        }
        var w = this.itemCt.getWidth() - 125 - 30; // 125px padding and 30px margin
        this.editor.resize(w, parseInt(this.config.CKEditor.height, 10));
    },

    onRender: function(ct, position) {
        Ext.form.CKEditor.superclass.onRender.call(this, ct, position);
        var ckLoaded = function() {
            this.editor = CKEDITOR.replace(this.id, this.config.CKEditor);
            // Closure for quick access in the event listener
            var scope = this;
            this.editor.on('dataReady', function() {
                this.resetDirty();
                scope.waitingForSetData = false;
                scope.on('resize', scope.adjustEditorSize);
                scope.adjustEditorSize(this);
            });
            this.setValue(this.orgValue);
        };
        if (typeof CKEDITOR === 'undefined') {
            Ext.Loader.load([ASSET_URL + 'js/garp/ckeditor/ckeditor.js'], ckLoaded, this);
            return;
        }
        ckLoaded.call(this);
    },

    isValid: function(value) {
        var charCount = this.getCharCount();
        if (!this.editor) {
            return true;
        }

        if (!this.allowBlank && !charCount) {
            if (this.wasBlank) {
                return false;
            }
            this.wasBlank = true;
            this.editor.element.addClass('invalid');
            this.markInvalid(this.blankText);
            return false;
        }
        this.wasBlank = false;

        if (this.maxLength && charCount >= this.maxLength) {
            if (this.wasTooLong) {
                return false;
            }
            this.wasTooLong = true;
            this.editor.element.addClass('invalid');
            this.markInvalid(this.maxLengthText);
            return false;
        }
        this.wasTooLong = false;

        this.clearInvalid();
        return true;
    },

    // Get char count, stripped of HTML tags
    getCharCount: function() {
        var contentString = "";
        try {
            contentString = this.editor.document.getBody().getText();
        } catch(e) {
            contentString = this.getValue().replace(/(<([^>]+)>)/ig,"");
        }
        // Trim newlines and count
        return contentString.replace(/^\s+|\s+$/g, '').length;
    },

    setValue: function(value) {
        // Save the value as the elements original value
        this.orgValue = value;

        // Wait for an editor (the setValue function will be called on render)
        if (!this.editor) {
            return;
        }
        // Convert undefineds and nulls to empty string
        value = value || "";

        // Working around CKEditor's crazy-assync setData
        // (When setting data twice in short succession only the first data gets set)
        var that = this;

        function retrySetValue(event) {
            that.setValue(that.orgValue);
            that.waitingForSetData = false;
            event.removeListener();
        }
        if (this.waitingForSetData) {
            this.editor.on('dataReady', retrySetValue);
        }
        this.waitingForSetData = true;

        // Set CKEditor's content
        this.editor.setData(value);
    },

    getValue: function() {
        var val = this.orgValue;

        // If an editor is available and content has changed
        if (this.editor && this.editor.checkDirty()) {
            val = this.editor.getData();
        }

        // Convert falsy values to the empty string
        return val || "";
    },

    getRawValue: function() {
        return this.getValue();
    }
});

// Define "Rich CKEditor" (which allows for some more options such as image and video embeds)
Ext.form.RichCKEditor = function(config) {
    config.rich = true;
    Ext.form.RichCKEditor.superclass.constructor.call(this, config);
};
Ext.extend(Ext.form.RichCKEditor, Ext.form.CKEditor);

// Enable the CKEditor as default richtexteditor
Ext.reg('wysiwygeditor', Ext.form.CKEditor);
Ext.reg('richwysiwygeditor', Ext.form.RichCKEditor);
<|endoftext|>


<commit_before>define([
    'jquery',
    'underscore',
    'backbone',
    'app',
    'simplemde',
    'models/project/ProjectModel',
    'text!templates/projects/projectTemplate.html'
], function($, _, Backbone, app, SimpleMDE, ProjectModel, projectTemplate) {

    var ProjectView = Backbone.View.extend({
        el: $("#page"),

        events: {
            'submit form': 'save'
        },

        initialize: function(options) {
            this.model = new ProjectModel();
            _.bindAll(this, 'render', 'save');
        },

        render: function() {
            $('.menu a').removeClass('active');
            $('.menu a[href="#/projects"]').addClass('active');
            var self = this;
            this.model.fetch({
                success: function(project) {
                    var data = {
                        project: project,
                        _: _
                    }
                    var compiledTemplate = _.template(projectTemplate, data);
                    self.$el.html(compiledTemplate);
                    var simplemde = new SimpleMDE({
                        autoDownloadFontAwesome: true,
                        autofocus: false,
                        autosave: {
                            enabled: false
                        },
                        element: $('#project-description-input')[0],
                        indentWithTabs: false,
                        spellChecker: false,
                        tabSize: 4
                    });
                },
                error: function() {
                    throw new Error("Failed to fetch project");
                }
            });
        },

        save: function(event) {
            event.preventDefault();
            event.stopPropagation();

            if (this.$("#project-form").parsley().validate()) {
                var self = this;
                this.model.save({
                    name: this.$("#project-name-input").val(),
                    description: this.$("#project-description-input").val(),
                }, {
                    wait: true,
                    success: function(mod, res) {
                        app.showAlert('Success!', 'Project ' + this.$("#project-name-input").val() + ' updated!', 'success')
                            //Backbone.history.navigate("#/projects/" + self.model.id, { trigger: false });
                        Backbone.history.history.back();
                    },
                    error: function(model, response, options) {
                        var message = _.has(response, 'statusText') ? response.statusText : 'Unknown error!';
                        if (
                            _.has(response, 'responseJSON') &&
                            _.has(response.responseJSON, 'name') &&
                            _.has(response.responseJSON.name, 'length') &&
                            response.responseJSON.name.length > 0
                        ) {
                            message = response.responseJSON.name[0];
                        }
                        app.showAlert('Failed to update Project', message, 'error');
                    }
                });
            } else {
                if (typeof DEBUG != 'undefined' && DEBUG) console.log("Did not pass clientside validation");
            }
        }

    });

    return ProjectView;

});<commit_msg>Active class for project view<commit_after>define([
    'jquery',
    'underscore',
    'backbone',
    'app',
    'simplemde',
    'models/project/ProjectModel',
    'text!templates/projects/projectTemplate.html'
], function($, _, Backbone, app, SimpleMDE, ProjectModel, projectTemplate) {

    var ProjectView = Backbone.View.extend({
        el: $("#page"),

        events: {
            'submit form': 'save'
        },

        initialize: function(options) {
            this.model = new ProjectModel();
            _.bindAll(this, 'render', 'save');
        },

        render: function() {
            $('.item').removeClass('active');
            $('.item a[href="#/projects"]').parent().addClass('active');
            var self = this;
            this.model.fetch({
                success: function(project) {
                    var data = {
                        project: project,
                        _: _
                    }
                    var compiledTemplate = _.template(projectTemplate, data);
                    self.$el.html(compiledTemplate);
                    var simplemde = new SimpleMDE({
                        autoDownloadFontAwesome: true,
                        autofocus: false,
                        autosave: {
                            enabled: false
                        },
                        element: $('#project-description-input')[0],
                        indentWithTabs: false,
                        spellChecker: false,
                        tabSize: 4
                    });
                },
                error: function() {
                    throw new Error("Failed to fetch project");
                }
            });
        },

        save: function(event) {
            event.preventDefault();
            event.stopPropagation();

            if (this.$("#project-form").parsley().validate()) {
                var self = this;
                this.model.save({
                    name: this.$("#project-name-input").val(),
                    description: this.$("#project-description-input").val(),
                }, {
                    wait: true,
                    success: function(mod, res) {
                        app.showAlert('Success!', 'Project ' + this.$("#project-name-input").val() + ' updated!', 'success')
                            //Backbone.history.navigate("#/projects/" + self.model.id, { trigger: false });
                        Backbone.history.history.back();
                    },
                    error: function(model, response, options) {
                        var message = _.has(response, 'statusText') ? response.statusText : 'Unknown error!';
                        if (
                            _.has(response, 'responseJSON') &&
                            _.has(response.responseJSON, 'name') &&
                            _.has(response.responseJSON.name, 'length') &&
                            response.responseJSON.name.length > 0
                        ) {
                            message = response.responseJSON.name[0];
                        }
                        app.showAlert('Failed to update Project', message, 'error');
                    }
                });
            } else {
                if (typeof DEBUG != 'undefined' && DEBUG) console.log("Did not pass clientside validation");
            }
        }

    });

    return ProjectView;

});<|endoftext|>