<commit_before>/*
 * fixmystreet.js
 * FixMyStreet JavaScript
 */

/*
 * general height fixing function
 *
 * elem1: element to check against
 * elem2: target element
 * offset: this will be added (if present) to the final value, useful for height errors
 */
function heightFix(elem1, elem2, offset){
    var h1 = $(elem1).height(),
        h2 = $(elem2).height();
    if(offset === undefined){
        offset = 0;
    }
    if(h1 > h2){
        $(elem2).css({'min-height':h1+offset});
    }
}

/*
 * very simple tab function
 *
 * elem: trigger element, must have an href attribute (so probably needs to be an )
 */
function tabs(elem, indirect) {
    var href = elem.attr('href');
    //stupid IE sometimes adds the full uri into the href attr, so trim
    var start = href.indexOf('#'),
        target = href.slice(start, href.length);

    if (indirect) {
        elem = $(target + '_tab');
    }

    if(!$(target).hasClass('open'))
    {
        //toggle class on nav
        $('.tab-nav .active').removeClass('active');
        elem.addClass('active');

        //hide / show the right tab
        $('.tab.open').hide().removeClass('open');
        $(target).show().addClass('open');
    }
}

$(function(){
    var $html = $('html');

    var cobrand;
    if (window.location.href.indexOf('bromley') != -1) {
        cobrand = 'bromley';
    }

    // Deal with switching between mobile and desktop versions on resize
    var last_type;
    $(window).resize(function(){
        var type = $('#site-header').css('borderTopWidth');
        if (type == '4px') { type = 'mobile'; }
        else if (type == '0px') { type = 'desktop'; }
        else { return; }
        if (last_type == type) { return; }
        if (type == 'mobile') {
            $html.addClass('mobile');
            $('#map_box').prependTo('.content').css({
                zIndex: '', position: '',
                top: '', left: '', right: '', bottom: '',
                width: '', height: '10em',
                margin: ''
            });
            if (typeof fixmystreet !== 'undefined') {
                fixmystreet.state_map = ''; // XXX
            }
            if (typeof fixmystreet !== 'undefined' && fixmystreet.page == 'around') {
                // Immediately go full screen map if on around page
                if (cobrand != 'bromley') {
                    $('#site-header').hide();
                }
                $('#map_box').prependTo('.wrapper').css({
                    position: 'absolute',
                    top: 0, left: 0, right: 0, bottom: 0,
                    height: 'auto',
                    margin: 0
                });
                $('#fms_pan_zoom').css({ top: '2.75em !important' });
                $('.big-green-banner')
                    .addClass('mobile-map-banner')
                    .appendTo('#map_box')
                    .text('Place pin on map')
	            .prepend('home');
            }
            $('span.report-a-problem-btn').on('click.reportBtn', function(){
                $('html, body').animate({scrollTop:0}, 500);
            }).css({ cursor:'pointer' }).on('hover.reportBtn', function(){
                $(this).toggleClass('hover');
            });
        } else {
            // Make map full screen on non-mobile sizes.
            $html.removeClass('mobile');
            var map_pos = 'fixed', map_height = '100%';
            if (cobrand == 'bromley' || $html.hasClass('ie6')) {
                map_pos = 'absolute';
                map_height = $(window).height();
            }
            $('#map_box').prependTo('.wrapper').css({
                zIndex: 0, position: map_pos,
                top: 0, left: 0, right: 0, bottom: 0,
                width: '100%', height: map_height,
                margin: 0
            });
            if (cobrand == 'bromley') {
                $('#bromley-footer').hide();
            }
            if (typeof fixmystreet !== 'undefined') {
                fixmystreet.state_map = 'full';
            }
            if (typeof fixmystreet !== 'undefined' && fixmystreet.page == 'around') {
                // Remove full-screen-ness
                if (cobrand != 'bromley') {
                    $('#site-header').show();
                }
                $('#fms_pan_zoom').css({ top: '4.75em !important' });
                $('.big-green-banner')
                    .removeClass('mobile-map-banner')
                    .prependTo('#side')
                    .text('Click map to report a problem');
            }
            $('span.report-a-problem-btn').css({ cursor:'' }).off('.reportBtn');
        }
        last_type = type;
    }).resize();

    /*
     * Report a problem page
     */
    //desktop
    if ($('#report-a-problem-sidebar').is(':visible')) {
        heightFix('#report-a-problem-sidebar', '.content', 26);
    }

    //show/hide notes on mobile
    $('.mobile #report-a-problem-sidebar').after('How to send successful reports').hide();
    $('.rap-notes-trigger').click(function(e){
        e.preventDefault();
        //check if we've already moved the notes
        if($('.rap-notes').length > 0){
            //if we have, show and hide .content
            $('.content').hide();
            $('.rap-notes').show();
        }else{
            //if not, move them and show, hiding .content
            $('.content').after('

').hide();
            $('#report-a-problem-sidebar').appendTo('.rap-notes').show().after('Back');
        }
        $('html, body').scrollTop($('#report-a-problem-sidebar').offset().top);
        location.hash = 'rap-notes';
    });
    $('.mobile').on('click', '.rap-notes-close', function(e){
        e.preventDefault();
        //hide notes, show .content
        $('.content').show();
        $('.rap-notes').hide();
        $('html, body').scrollTop($('#mob_ok').offset().top);
        location.hash = 'report';
    });

    //move 'skip this step' link on mobile
    $('.mobile #skip-this-step').hide();
    $('.mobile #skip-this-step a').addClass('chevron').wrap('
').appendTo('#key-tools');

    /*
     * Tabs
     */
    //make initial tab active
    $('.tab-nav a').first().addClass('active');
    $('.tab').first().addClass('open');

    //hide other tabs
    $('.tab').not('.open').hide();

    //set up click event
    $(".tab-nav").on('click', 'a', function(e){
        e.preventDefault();
        tabs($(this));
    });
    $('.tab_link').click(function(e) {
        e.preventDefault();
        tabs($(this), 1);
    });

    /*
     * Skip to nav on mobile
     */
    $('.mobile').on('click', '#nav-link', function(e){
        e.preventDefault();
        var offset = $('#main-nav').offset().top;
        $('html, body').animate({scrollTop:offset}, 1000);
    });

    /*
     * Show stuff on input focus
     */
    $('.form-focus-hidden').hide();
    $('.form-focus-trigger').on('focus', function(){
        $('.form-focus-hidden').fadeIn(500);
    });

    /*
     * Show on click - pretty generic
     */
    $('.hideshow-trigger').on('click', function(e){
        e.preventDefault();
        var href = $(this).attr('href'),
            //stupid IE sometimes adds the full uri into the href attr, so trim
            start = href.indexOf('#'),
            target = href.slice(start, href.length);

        $(target).removeClass('hidden-js');

        $(this).hide();
    });

    /*
     * nicetable - on mobile shift 'name' col to be a row
     */
    $('.mobile .nicetable th.title').remove();
    $('.mobile .nicetable td.title').each(function(i){
        $(this).attr('colspan', 5).insertBefore($(this).parent('tr')).wrap('
');
    });
    // $('.mobile .nicetable tr.heading > td.title').css({'min-width':'300px'});
    // $('.mobile .nicetable tr > td.data').css({'max-width':'12%'});

    /*
     * Map controls prettiness
     */
    //add links container (if its not there)
    if($('#sub_map_links').length === 0){
        $('
').insertAfter($('#map'));
    }

// A sliding drawer from the bottom of the page, small version
// that doesn't change the main content at all.
$.fn.small_drawer = function(id) {
    this.toggle(function(){
        var $this = $(this), d = $('#' + id);
        if (!$this.addClass('hover').data('setup')) {
            d.hide().removeClass('hidden-js').css({
                padding: '1em',
                background: '#fff'
            });
            $this.data('setup', true);
        }
        d.slideDown();
    }, function(e){
        var $this = $(this), d = $('#' + id);
        $this.removeClass('hover');
        d.slideUp();
    });
};

// A sliding drawer from the bottom of the page, large version
$.fn.drawer = function(id, ajax) {
    // IE7 positions the fixed tool bar 1em to the left unless it comes after
    // the full-width section, ho-hum. Move it to where it would be after an
    // open/close anyway
    if ($('html.ie7').length) {
        var $sw = $('.shadow-wrap'), $content = $('.content[role="main"]');
        $sw.appendTo($content);
    }
    this.toggle(function(){
        var $this = $(this), d = $('#' + id), $content = $('.content[role="main"]');
        if (!$this.addClass('hover').data('setup')) {
            // make a drawer div with an innerDiv
            if (!d.length) {
                d = $('
');
            }
            var innerDiv = $('
');
            d.wrapInner(innerDiv);

            // if ajax, load it with a spinner
            if (ajax) {
                var href = $this.attr('href') + ';ajax=1';
                $this.prepend(' ');
                innerDiv.load(href, function(){
                    $('.spinner').remove();
                });
            }

            // Tall drawer - put after .content for scrolling to work okay.
            // position over the top of the main .content in precisely the right location
            d.insertAfter($content).addClass('content').css({
                position: 'absolute',
                zIndex: '1100',
                marginTop: $('html.ie6, html.ie7').length ? '-3em' : 0, // IE6/7 otherwise include the 3em padding and stay too low
                left: 0,
                top: $(window).height() - $content.offset().top
            }).removeClass('hidden-js').find('h2').css({ marginTop: 0 });
            $this.data('setup', true);
        }

        //do the animation
        $('.shadow-wrap').prependTo(d).addClass('static');
        d.show().animate({top:'3em'}, 1000, function(){
            $content.fadeOut(function() {
                d.css({ position: 'relative' });
            });
        });
    }, function(e){
        var $this = $(this), d = $('#' + id), $sw = $('.shadow-wrap'),
            $content = $('.content[role="main"]'),
            tot_height = $(window).height() - d.offset().top;
        $this.removeClass('hover');
        d.css({ position: 'absolute' }).animate({ top: tot_height }, 1000, function(){
            d.hide();
            $sw.appendTo($content).removeClass('static');
        });
        $content.show();
    });
};

    if ($('html.mobile').length) {
        $('#council_wards').hide().removeClass('hidden-js').find('h2').hide();
        $('#key-tool-wards').click(function(e){
            e.preventDefault();
            $('#council_wards').slideToggle('800', function(){
              $('#key-tool-wards').toggleClass('active');
            });
        });
    } else {
        $('#key-tool-wards').drawer('council_wards', false);
        $('#key-tool-around-updates').drawer('updates_ajax', true);
    }
    $('#key-tool-report-updates').small_drawer('report-updates-data');

    // Go directly to RSS feed if RSS button clicked on alert page
    // (due to not wanting around form to submit, though good thing anyway)
    $('.container').on('click', '#alert_rss_button', function(e){
        e.preventDefault();
        var feed = $('input[name=feed][type=radio]:checked').nextAll('a').attr('href');
        window.location.href = feed;
    });
    $('.container').on('click', '#alert_email_button', function(e){
        e.preventDefault();
        var form = $('<form/>').attr({ method:'post', action:"/alert/subscribe" });
        $('#alerts input[type=text], #alerts input[type=hidden], #alerts input[type=radio]:checked').each(function() {
            var $v = $(this);
            $('<input/>').attr({ name:$v.attr('name'), value:$v.val(), type:'hidden' }).appendTo(form);
        });
        form.submit();
    });

    //add permalink on desktop, force hide on mobile
    $('#sub_map_links').append('Permalink');
    if($('.mobile').length){
        $('#map_permalink').hide();
        $('#key-tools a.feed').appendTo('#sub_map_links');
        $('#key-tools li:empty').remove();
        $('#report-updates-data').insertAfter($('#map_box'));
    }
    //add open/close toggle button on desk
    $('#sub_map_links').prepend(' ');

    //set up map_links_toggle click event
    $('#map_links_toggle').on('click', function(){
        var maplinks_width = $('#sub_map_links').width();

        if($(this).hasClass('closed')){
            $(this).removeClass('closed');
            $('#sub_map_links').animate({'right':'0'}, 1200);
        }else{
            $(this).addClass('closed');
            $('#sub_map_links').animate({'right':-maplinks_width}, 1200);
        }
    });

    /*
     * Add close buttons for .promo's
     */
    if($('.promo').length){
        $('.promo').append('x');
    }
    //only close its own parent
    $('.promo').on('click', '.close-promo', function(e){
        e.preventDefault();
        $(this).parent('.promo').animate({
            'height':0,
            'margin-bottom':0,
            'padding-top':0,
            'padding-bottom':0
        },{
            duration:500,
            queue:false
        }).fadeOut(500);
    });

    /*
     * Fancybox fullscreen images
     */
    $('a[rel=fancy]').fancybox({
        'overlayColor': '#000000'
    });

    /*
     * heightfix the desktop .content div
     *
     * this must be kept near the end so that the
     * rendered height is used after any page manipulation (such as tabs)
     */
    if (!$('html.mobile').length) {
        if (!($('body').hasClass('frontpage'))){
            var offset = -176;
            if (cobrand == 'bromley') {
                offset = -110;
            }
            heightFix(window, '.content', offset);
        }
    }

});

/*
XXX Disabled because jerky on Android and makes map URL bar height too small on iPhone.
// Hide URL bar
$(window).load(function(){
    window.setTimeout(function(){
        var s = window.pageYOffset || document.compatMode === "CSS1Compat" && document.documentElement.scrollTop || document.body.scrollTop || 0;
        if (s < 20 && !location.hash) {
            window.scrollTo(0, 1);
        }
    }, 0);
});
*/

<commit_msg>Bromley map only on RHS.<commit_after>/*
 * fixmystreet.js
 * FixMyStreet JavaScript
 */

/*
 * general height fixing function
 *
 * elem1: element to check against
 * elem2: target element
 * offset: this will be added (if present) to the final value, useful for height errors
 */
function heightFix(elem1, elem2, offset){
    var h1 = $(elem1).height(),
        h2 = $(elem2).height();
    if(offset === undefined){
        offset = 0;
    }
    if(h1 > h2){
        $(elem2).css({'min-height':h1+offset});
    }
}

/*
 * very simple tab function
 *
 * elem: trigger element, must have an href attribute (so probably needs to be an )
 */
function tabs(elem, indirect) {
    var href = elem.attr('href');
    //stupid IE sometimes adds the full uri into the href attr, so trim
    var start = href.indexOf('#'),
        target = href.slice(start, href.length);

    if (indirect) {
        elem = $(target + '_tab');
    }

    if(!$(target).hasClass('open'))
    {
        //toggle class on nav
        $('.tab-nav .active').removeClass('active');
        elem.addClass('active');

        //hide / show the right tab
        $('.tab.open').hide().removeClass('open');
        $(target).show().addClass('open');
    }
}

$(function(){
    var $html = $('html');

    var cobrand;
    if (window.location.href.indexOf('bromley') != -1) {
        cobrand = 'bromley';
    }

    // Deal with switching between mobile and desktop versions on resize
    var last_type;
    $(window).resize(function(){
        var type = $('#site-header').css('borderTopWidth');
        if (type == '4px') { type = 'mobile'; }
        else if (type == '0px') { type = 'desktop'; }
        else { return; }
        if (last_type == type) { return; }
        if (type == 'mobile') {
            $html.addClass('mobile');
            $('#map_box').prependTo('.content').css({
                zIndex: '', position: '',
                top: '', left: '', right: '', bottom: '',
                width: '', height: '10em',
                margin: ''
            });
            if (typeof fixmystreet !== 'undefined') {
                fixmystreet.state_map = ''; // XXX
            }
            if (typeof fixmystreet !== 'undefined' && fixmystreet.page == 'around') {
                // Immediately go full screen map if on around page
                if (cobrand != 'bromley') {
                    $('#site-header').hide();
                }
                $('#map_box').prependTo('.wrapper').css({
                    position: 'absolute',
                    top: 0, left: 0, right: 0, bottom: 0,
                    height: 'auto',
                    margin: 0
                });
                $('#fms_pan_zoom').css({ top: '2.75em !important' });
                $('.big-green-banner')
                    .addClass('mobile-map-banner')
                    .appendTo('#map_box')
                    .text('Place pin on map')
	            .prepend('home');
            }
            $('span.report-a-problem-btn').on('click.reportBtn', function(){
                $('html, body').animate({scrollTop:0}, 500);
            }).css({ cursor:'pointer' }).on('hover.reportBtn', function(){
                $(this).toggleClass('hover');
            });
        } else {
            // Make map full screen on non-mobile sizes.
            $html.removeClass('mobile');
            if (cobrand == 'bromley') {
                if ($html.hasClass('ie6')) {
                    $('#map_box').prependTo('.wrapper').css({
                        zIndex: 0, position: 'absolute',
                        right: 0, top: '4em',// left: $('.content').offset().left + $('.content').width(),
                        width: $(window).width() - $('.content').offset().left - $('.content').width() - 32,
                        height: $(window).height() - $('.content').offset().top + 32,
                        margin: 0
                    });
                } else {
                    $('#map_box').prependTo('.wrapper').css({
                        zIndex: 0, position: 'fixed',
                        right: 0, top: $('.content').offset().top, bottom: 0,// left: $('.content').offset().left + $('.content').width(),
                        width: $(window).width() - $('.content').offset().left - $('.content').width() - 32,
                        height: $(window).height() - $('.content').offset().top,
                        margin: 0
                    });
                }
            } else if ($html.hasClass('ie6')) {
                $('#map_box').prependTo('.wrapper').css({
                    zIndex: 0, position: 'absolute',
                    top: 0, left: 0, right: 0, bottom: 0,
                    width: '100%', height: $(window).height(),
                    margin: 0
                });
            } else {
                $('#map_box').prependTo('.wrapper').css({
                    zIndex: 0, position: 'fixed',
                    top: 0, left: 0, right: 0, bottom: 0,
                    width: '100%', height: '100%',
                    margin: 0
                });
            }
            if (cobrand == 'bromley') {
                $('#bromley-footer').hide();
            }
            if (typeof fixmystreet !== 'undefined') {
                fixmystreet.state_map = 'full';
            }
            if (typeof fixmystreet !== 'undefined' && fixmystreet.page == 'around') {
                // Remove full-screen-ness
                if (cobrand != 'bromley') {
                    $('#site-header').show();
                }
                $('#fms_pan_zoom').css({ top: '4.75em !important' });
                $('.big-green-banner')
                    .removeClass('mobile-map-banner')
                    .prependTo('#side')
                    .text('Click map to report a problem');
            }
            $('span.report-a-problem-btn').css({ cursor:'' }).off('.reportBtn');
        }
        last_type = type;
    }).resize();

    /*
     * Report a problem page
     */
    //desktop
    if ($('#report-a-problem-sidebar').is(':visible')) {
        heightFix('#report-a-problem-sidebar', '.content', 26);
    }

    //show/hide notes on mobile
    $('.mobile #report-a-problem-sidebar').after('How to send successful reports').hide();
    $('.rap-notes-trigger').click(function(e){
        e.preventDefault();
        //check if we've already moved the notes
        if($('.rap-notes').length > 0){
            //if we have, show and hide .content
            $('.content').hide();
            $('.rap-notes').show();
        }else{
            //if not, move them and show, hiding .content
            $('.content').after('

').hide();
            $('#report-a-problem-sidebar').appendTo('.rap-notes').show().after('Back');
        }
        $('html, body').scrollTop($('#report-a-problem-sidebar').offset().top);
        location.hash = 'rap-notes';
    });
    $('.mobile').on('click', '.rap-notes-close', function(e){
        e.preventDefault();
        //hide notes, show .content
        $('.content').show();
        $('.rap-notes').hide();
        $('html, body').scrollTop($('#mob_ok').offset().top);
        location.hash = 'report';
    });

    //move 'skip this step' link on mobile
    $('.mobile #skip-this-step').hide();
    $('.mobile #skip-this-step a').addClass('chevron').wrap('
').appendTo('#key-tools');

    /*
     * Tabs
     */
    //make initial tab active
    $('.tab-nav a').first().addClass('active');
    $('.tab').first().addClass('open');

    //hide other tabs
    $('.tab').not('.open').hide();

    //set up click event
    $(".tab-nav").on('click', 'a', function(e){
        e.preventDefault();
        tabs($(this));
    });
    $('.tab_link').click(function(e) {
        e.preventDefault();
        tabs($(this), 1);
    });

    /*
     * Skip to nav on mobile
     */
    $('.mobile').on('click', '#nav-link', function(e){
        e.preventDefault();
        var offset = $('#main-nav').offset().top;
        $('html, body').animate({scrollTop:offset}, 1000);
    });

    /*
     * Show stuff on input focus
     */
    $('.form-focus-hidden').hide();
    $('.form-focus-trigger').on('focus', function(){
        $('.form-focus-hidden').fadeIn(500);
    });

    /*
     * Show on click - pretty generic
     */
    $('.hideshow-trigger').on('click', function(e){
        e.preventDefault();
        var href = $(this).attr('href'),
            //stupid IE sometimes adds the full uri into the href attr, so trim
            start = href.indexOf('#'),
            target = href.slice(start, href.length);

        $(target).removeClass('hidden-js');

        $(this).hide();
    });

    /*
     * nicetable - on mobile shift 'name' col to be a row
     */
    $('.mobile .nicetable th.title').remove();
    $('.mobile .nicetable td.title').each(function(i){
        $(this).attr('colspan', 5).insertBefore($(this).parent('tr')).wrap('
');
    });
    // $('.mobile .nicetable tr.heading > td.title').css({'min-width':'300px'});
    // $('.mobile .nicetable tr > td.data').css({'max-width':'12%'});

    /*
     * Map controls prettiness
     */
    //add links container (if its not there)
    if($('#sub_map_links').length === 0){
        $('
').insertAfter($('#map'));
    }

// A sliding drawer from the bottom of the page, small version
// that doesn't change the main content at all.
$.fn.small_drawer = function(id) {
    this.toggle(function(){
        var $this = $(this), d = $('#' + id);
        if (!$this.addClass('hover').data('setup')) {
            d.hide().removeClass('hidden-js').css({
                padding: '1em',
                background: '#fff'
            });
            $this.data('setup', true);
        }
        d.slideDown();
    }, function(e){
        var $this = $(this), d = $('#' + id);
        $this.removeClass('hover');
        d.slideUp();
    });
};

// A sliding drawer from the bottom of the page, large version
$.fn.drawer = function(id, ajax) {
    // IE7 positions the fixed tool bar 1em to the left unless it comes after
    // the full-width section, ho-hum. Move it to where it would be after an
    // open/close anyway
    if ($('html.ie7').length) {
        var $sw = $('.shadow-wrap'), $content = $('.content[role="main"]');
        $sw.appendTo($content);
    }
    this.toggle(function(){
        var $this = $(this), d = $('#' + id), $content = $('.content[role="main"]');
        if (!$this.addClass('hover').data('setup')) {
            // make a drawer div with an innerDiv
            if (!d.length) {
                d = $('
');
            }
            var innerDiv = $('
');
            d.wrapInner(innerDiv);

            // if ajax, load it with a spinner
            if (ajax) {
                var href = $this.attr('href') + ';ajax=1';
                $this.prepend(' ');
                innerDiv.load(href, function(){
                    $('.spinner').remove();
                });
            }

            // Tall drawer - put after .content for scrolling to work okay.
            // position over the top of the main .content in precisely the right location
            d.insertAfter($content).addClass('content').css({
                position: 'absolute',
                zIndex: '1100',
                marginTop: $('html.ie6, html.ie7').length ? '-3em' : 0, // IE6/7 otherwise include the 3em padding and stay too low
                left: 0,
                top: $(window).height() - $content.offset().top
            }).removeClass('hidden-js').find('h2').css({ marginTop: 0 });
            $this.data('setup', true);
        }

        //do the animation
        $('.shadow-wrap').prependTo(d).addClass('static');
        d.show().animate({top:'3em'}, 1000, function(){
            $content.fadeOut(function() {
                d.css({ position: 'relative' });
            });
        });
    }, function(e){
        var $this = $(this), d = $('#' + id), $sw = $('.shadow-wrap'),
            $content = $('.content[role="main"]'),
            tot_height = $(window).height() - d.offset().top;
        $this.removeClass('hover');
        d.css({ position: 'absolute' }).animate({ top: tot_height }, 1000, function(){
            d.hide();
            $sw.appendTo($content).removeClass('static');
        });
        $content.show();
    });
};

    if ($('html.mobile').length) {
        $('#council_wards').hide().removeClass('hidden-js').find('h2').hide();
        $('#key-tool-wards').click(function(e){
            e.preventDefault();
            $('#council_wards').slideToggle('800', function(){
              $('#key-tool-wards').toggleClass('active');
            });
        });
    } else {
        $('#key-tool-wards').drawer('council_wards', false);
        $('#key-tool-around-updates').drawer('updates_ajax', true);
    }
    $('#key-tool-report-updates').small_drawer('report-updates-data');

    // Go directly to RSS feed if RSS button clicked on alert page
    // (due to not wanting around form to submit, though good thing anyway)
    $('.container').on('click', '#alert_rss_button', function(e){
        e.preventDefault();
        var feed = $('input[name=feed][type=radio]:checked').nextAll('a').attr('href');
        window.location.href = feed;
    });
    $('.container').on('click', '#alert_email_button', function(e){
        e.preventDefault();
        var form = $('<form/>').attr({ method:'post', action:"/alert/subscribe" });
        $('#alerts input[type=text], #alerts input[type=hidden], #alerts input[type=radio]:checked').each(function() {
            var $v = $(this);
            $('<input/>').attr({ name:$v.attr('name'), value:$v.val(), type:'hidden' }).appendTo(form);
        });
        form.submit();
    });

    //add permalink on desktop, force hide on mobile
    $('#sub_map_links').append('Permalink');
    if($('.mobile').length){
        $('#map_permalink').hide();
        $('#key-tools a.feed').appendTo('#sub_map_links');
        $('#key-tools li:empty').remove();
        $('#report-updates-data').insertAfter($('#map_box'));
    }
    //add open/close toggle button on desk
    $('#sub_map_links').prepend(' ');

    //set up map_links_toggle click event
    $('#map_links_toggle').on('click', function(){
        var maplinks_width = $('#sub_map_links').width();

        if($(this).hasClass('closed')){
            $(this).removeClass('closed');
            $('#sub_map_links').animate({'right':'0'}, 1200);
        }else{
            $(this).addClass('closed');
            $('#sub_map_links').animate({'right':-maplinks_width}, 1200);
        }
    });

    /*
     * Add close buttons for .promo's
     */
    if($('.promo').length){
        $('.promo').append('x');
    }
    //only close its own parent
    $('.promo').on('click', '.close-promo', function(e){
        e.preventDefault();
        $(this).parent('.promo').animate({
            'height':0,
            'margin-bottom':0,
            'padding-top':0,
            'padding-bottom':0
        },{
            duration:500,
            queue:false
        }).fadeOut(500);
    });

    /*
     * Fancybox fullscreen images
     */
    $('a[rel=fancy]').fancybox({
        'overlayColor': '#000000'
    });

    /*
     * heightfix the desktop .content div
     *
     * this must be kept near the end so that the
     * rendered height is used after any page manipulation (such as tabs)
     */
    if (!$('html.mobile').length) {
        if (!($('body').hasClass('frontpage'))){
            var offset = -176;
            if (cobrand == 'bromley') {
                offset = -110;
            }
            heightFix(window, '.content', offset);
        }
    }

});

/*
XXX Disabled because jerky on Android and makes map URL bar height too small on iPhone.
// Hide URL bar
$(window).load(function(){
    window.setTimeout(function(){
        var s = window.pageYOffset || document.compatMode === "CSS1Compat" && document.documentElement.scrollTop || document.body.scrollTop || 0;
        if (s < 20 && !location.hash) {
            window.scrollTo(0, 1);
        }
    }, 0);
});
*/

<|endoftext|>


<commit_before>var vishull = require("../visibility")

var width = 500
var height = 500

var canvas = document.createElement("canvas")
canvas.width = width
canvas.height = height
document.body.appendChild(canvas)

var context = canvas.getContext("2d")

var lines = []
var dt = 0.1
var r = 100
var cx = width/2
var cy = height/2
for(var t=0.0; t+dt<2.0*Math.PI; t+=dt) {
  lines.push([
    [r*Math.cos(t)+cx, r*Math.sin(t)+cy],
    [r*Math.cos(t-dt/2)+cx, r*Math.sin(t-dt/2)+cy]
  ])
}

lines.push([[400,300], [300,400]])
lines.push([[400,300], [400,400]])
lines.push([[300,400], [400,400]])
var radius = 10;
function redraw(p) {
  context.fillStyle = "#234"
  context.fillRect(0, 0, width, height)

  var region = vishull(lines, p)

  context.fillStyle = "rgba(255, 255, 130, 0.5)"
  context.beginPath()
  context.moveTo(region[0][0], region[0][1])
  for(var i=1; i<region.length; ++i) {
    var r = region[i]
    context.lineTo(r[0], r[1])
  }
  context.lineTo(region[0][0], region[0][1])
  context.closePath()
  context.fill()

  context.strokeStyle = "rgba(128, 198, 100, 1.0)"
  for(var i=0; i<lines.length; ++i) {
    var s = lines[i]
    context.beginPath()
    context.moveTo(s[0][0], s[0][1])
    context.lineTo(s[1][0], s[1][1])
    context.closePath()
    context.stroke()
  }

  context.fillStyle = "rgba(255, 255, 0, 1)"
  context.beginPath()
  context.arc(p[0]-radius, p[1]-radius, 10, 0.0, 2.0*Math.PI)
  context.closePath()
  context.fill()
}

canvas.addEventListener("mousemove", function(e) {
  redraw([e.x, e.y])
})

redraw([width/2, height/2])<commit_msg>utilize radius in arc drawing<commit_after>var vishull = require("../visibility")

var width = 500
var height = 500

var canvas = document.createElement("canvas")
canvas.width = width
canvas.height = height
document.body.appendChild(canvas)

var context = canvas.getContext("2d")

var lines = []
var dt = 0.1
var r = 100
var cx = width/2
var cy = height/2
for(var t=0.0; t+dt<2.0*Math.PI; t+=dt) {
  lines.push([
    [r*Math.cos(t)+cx, r*Math.sin(t)+cy],
    [r*Math.cos(t-dt/2)+cx, r*Math.sin(t-dt/2)+cy]
  ])
}

lines.push([[400,300], [300,400]])
lines.push([[400,300], [400,400]])
lines.push([[300,400], [400,400]])
var radius = 10;
function redraw(p) {
  context.fillStyle = "#234"
  context.fillRect(0, 0, width, height)

  var region = vishull(lines, p)

  context.fillStyle = "rgba(255, 255, 130, 0.5)"
  context.beginPath()
  context.moveTo(region[0][0], region[0][1])
  for(var i=1; i<region.length; ++i) {
    var r = region[i]
    context.lineTo(r[0], r[1])
  }
  context.lineTo(region[0][0], region[0][1])
  context.closePath()
  context.fill()

  context.strokeStyle = "rgba(128, 198, 100, 1.0)"
  for(var i=0; i<lines.length; ++i) {
    var s = lines[i]
    context.beginPath()
    context.moveTo(s[0][0], s[0][1])
    context.lineTo(s[1][0], s[1][1])
    context.closePath()
    context.stroke()
  }

  context.fillStyle = "rgba(255, 255, 0, 1)"
  context.beginPath()
  context.arc(p[0]-radius, p[1]-radius, radius, 0.0, 2.0*Math.PI)
  context.closePath()
  context.fill()
}

canvas.addEventListener("mousemove", function(e) {
  redraw([e.x, e.y])
})

redraw([width/2, height/2])<|endoftext|>


<commit_before>"use strict";

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var DLModels = require("dl-models");
var map = DLModels.map;
var PurchaseRequest = DLModels.purchasing.PurchaseRequest;
var generateCode = require("../../utils/code-generator");
var BaseManager = require("module-toolkit").BaseManager;
var i18n = require("dl-i18n");
var UnitManager = require("../master/unit-manager");
var BudgetManager = require("../master/budget-manager");
var CategoryManager = require("../master/category-manager");
var ProductManager = require("../master/product-manager");

module.exports = class PurchaseRequestManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.moduleId = "PR";
        this.year = (new Date()).getFullYear().toString().substring(2, 4);
        this.collection = this.db.use(map.purchasing.collection.PurchaseRequest);

        this.unitManager = new UnitManager(db, user);
        this.budgetManager = new BudgetManager(db, user);
        this.categoryManager = new CategoryManager(db, user);
        this.productManager = new ProductManager(db, user);
    }

    _getQuery(paging) {
        var deletedFilter = {
                _deleted: false
            },
            keywordFilter = {};

        var query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterNo = {
                "no": {
                    "$regex": regex
                }
            };

            var filterUnitDivisionName = {
                "unit.division.name": {
                    "$regex": regex
                }
            };
            var filterUnitName = {
                "unit.name": {
                    "$regex": regex
                }
            };

            var filterCategory = {
                "category.name": {
                    "$regex": regex
                }
            };

            keywordFilter = {
                "$or": [filterNo, filterUnitDivisionName, filterUnitName, filterCategory]
            };
        }
        query = {
            "$and": [deletedFilter, paging.filter, keywordFilter]
        };
        return query;
    }

    _validate(purchaseRequest) {
        var errors = {};
        var valid = purchaseRequest;

        var getPurchaseRequestPromise = this.collection.singleOrDefault({
            _id: {
                '$ne': new ObjectId(valid._id)
            },
            no: valid.no
        });

        var getUnit = valid.unitId && valid.unitId.toString().trim() != "" ? this.unitManager.getSingleByIdOrDefault(valid.unitId) : Promise.resolve(null);
        var getCategory = valid.categoryId && valid.categoryId.toString().trim() != "" ? this.categoryManager.getSingleByIdOrDefault(valid.categoryId) : Promise.resolve(null);
        var getBudget = valid.budgetId && valid.budgetId.toString().trim() != "" ? this.budgetManager.getSingleByIdOrDefault(valid.budgetId) : Promise.resolve(null);
        var getProduct = [];

        valid.items = valid.items instanceof Array ? valid.items : [];
        for (var _item of valid.items)
            getProduct.push(_item.productId && _item.productId.toString().trim() != "" ? this.productManager.getSingleByIdOrDefault(_item.productId) : Promise.resolve(null));

        return Promise.all([getPurchaseRequestPromise, getUnit, getCategory, getBudget].concat(getProduct))
            .then(results => {
                var _purchaseRequest = results[0];
                var _unit = results[1];
                var _category = results[2];
                var _budget = results[3];
                var _products = results.slice(4, results.length);

                if (_purchaseRequest)
                    errors["no"] = i18n.__("PurchaseRequest.no.isExists:%s is exists", i18n.__("PurchaseRequest.product._:No"));

                if (!valid.date || valid.date == "" || valid.date == "undefined")
                    errors["date"] = i18n.__("PurchaseRequest.date.isRequired:%s is required", i18n.__("PurchaseRequest.date._:Date")); //"Tanggal PR tidak boleh kosong";

                if (!_unit)
                    errors["unit"] = i18n.__("PurchaseRequest.unit.isRequired:%s is not exists", i18n.__("PurchaseRequest.unit._:Unit")); //"Unit tidak boleh kosong";
                else if (!valid.unitId)
                    errors["unit"] = i18n.__("PurchaseRequest.unit.isRequired:%s is required", i18n.__("PurchaseRequest.unit._:Unit")); //"Unit tidak boleh kosong";

                if (!_category)
                    errors["category"] = i18n.__("PurchaseRequest.category.isRequired:%s is not exists", i18n.__("PurchaseRequest.category._:Category")); //"Category tidak boleh kosong";
                else if (!valid.categoryId)
                    errors["category"] = i18n.__("PurchaseRequest.category.isRequired:%s is required", i18n.__("PurchaseRequest.category._:Category")); //"Category tidak boleh kosong";

                if (!_budget)
                    errors["budget"] = i18n.__("PurchaseRequest.budget.name.isRequired:%s is not exists", i18n.__("PurchaseRequest.budget.name._:Budget")); //"Budget tidak boleh kosong";
                else if (!valid.budget._id)
                    errors["budget"] = i18n.__("PurchaseRequest.budget.name.isRequired:%s is required", i18n.__("PurchaseRequest.budget.name._:Budget")); //"Budget tidak boleh kosong";

                if (!valid.expectedDeliveryDate || valid.expectedDeliveryDate == "" || valid.expectedDeliveryDate == "undefined")
                    valid.expectedDeliveryDate = "";

                if (valid.items && valid.items.length <= 0) {
                    errors["items"] = i18n.__("PurchaseRequest.items.isRequired:%s is required", i18n.__("PurchaseRequest.items._:Item")); //"Harus ada minimal 1 barang";
                }
                else {
                    var itemErrors = [];
                    for (var item of valid.items) {
                        var itemError = {};
                        if (!item.product || !item.product._id)
                            itemError["product"] = i18n.__("PurchaseRequest.items.product.name.isRequired:%s is required", i18n.__("PurchaseRequest.items.product.name._:Name")); //"Nama barang tidak boleh kosong";
                        if (item.quantity <= 0)
                            itemError["quantity"] = i18n.__("PurchaseRequest.items.quantity.isRequired:%s is required", i18n.__("PurchaseRequest.items.quantity._:Quantity")); //Jumlah barang tidak boleh kosong";

                        if (Object.getOwnPropertyNames(itemError).length > 0)
                            itemErrors.push(itemError);
                    }
                    if (itemErrors.length > 0)
                        errors.items = itemErrors;
                }

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require("module-toolkit").ValidationError;
                    return Promise.reject(new ValidationError("data does not pass validation", errors));
                }

                valid.unitId = _unit._id;
                valid.unit = _unit;

                valid.categoryId = _category._id;
                valid.category = _category;

                valid.budgetId = _budget._id;
                valid.budget = _budget;

                for (var prItem of valid.items) {
                    for (var _product of _products) {
                        if (prItem.product._id.toString() == _product._id.toString()) {
                            prItem.product = _product;
                            prItem.uom = _product.uom;
                            break;
                        }
                    }
                }

                if (!valid.stamp)
                    valid = new PurchaseRequest(valid);

                valid.stamp(this.user.username, "manager");
                return Promise.resolve(valid);
            });
    }

    create(purchaseRequest) {
        return new Promise((resolve, reject) => {
            var dateFormat = "MMYY";
            var locale = "id-ID";
            var moment = require("moment");
            moment.locale(locale);
            this._validate(purchaseRequest)
                .then(validPurchaseRequest => {
                    validPurchaseRequest.no = generateCode();
                    if (validPurchaseRequest.expectedDeliveryDate == "undefined") {
                        validPurchaseRequest.expectedDeliveryDate = "";
                    }
                    this.collection.insert(validPurchaseRequest)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    post(listPurchaseRequest) {
        var purchaseRequests = [];
        var tasks = [];
        return new Promise((resolve, reject) => {
            for (var purchaseRequest of listPurchaseRequest) {
                purchaseRequests.push(this.getSingleByIdOrDefault(purchaseRequest._id));
            }
            Promise.all(purchaseRequests)
                .then(validPurchaseRequest => {
                    for (var pr of listPurchaseRequest) {
                        for (var _pr of validPurchaseRequest) {
                            if (_pr._id.equals(pr._id)) {
                                _pr.isPosted = true;
                                tasks.push(this.update(_pr));
                                break;
                            }
                        }

                    }
                    Promise.all(tasks)
                        .then(result => {
                            resolve(result);
                        })
                        .catch(e => {
                            reject(e);
                        });

                })
                .catch(e => {
                    reject(e);
                });
        });

    }

    pdf(id) {
        return new Promise((resolve, reject) => {

            this.getSingleById(id)
                .then(purchaseRequest => {
                    var getDefinition = require("../../pdf/definitions/purchase-request");
                    var definition = getDefinition(purchaseRequest);

                    var generatePdf = require("../../pdf/pdf-generator");
                    generatePdf(definition)
                        .then(binary => {
                            resolve(binary);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    getDataPRMonitoring(unitId, categoryId, budgetId, PRNo, dateFrom, dateTo) {
        return new Promise((resolve, reject) => {
            var sorting = {
                "date": -1,
                "no": 1
            };
            var query = {};
            if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && budgetId != "undefined" && budgetId != "" && PRNo != "undefined" && PRNo != "" && dateFrom != "undefined" && dateFrom != "" && dateFrom != "null" && dateTo != "undefined" && dateTo != "" && dateTo != "null") {
                query = {
                    unitId: new ObjectId(unitId),
                    categoryId: new ObjectId(categoryId),
                    "no": PRNo,
                    "budget._id": new ObjectId(budgetId),
                    date: {
                        $gte: dateFrom,
                        $lte: dateTo
                    }
                };
            }
            else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && budgetId != "undefined" && budgetId != "" && PRNo != "undefined" && PRNo != "") {
                query = {
                    unitId: new ObjectId(unitId),
                    categoryId: new ObjectId(categoryId),
                    "no": PRNo,
                    "budget._id": new ObjectId(budgetId)
                };
            }
            else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && budgetId != "undefined" && budgetId != "") {
                query = {
                    unitId: new ObjectId(unitId),
                    categoryId: new ObjectId(categoryId),
                    "budget._id": new ObjectId(budgetId)
                };
            }
            else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "") {
                query = {
                    unitId: new ObjectId(unitId),
                    categoryId: new ObjectId(categoryId)
                };
            }
            else if (unitId != "undefined" && unitId != "") {
                query = {
                    unitId: new ObjectId(unitId)
                };
            }
            else if (categoryId != "undefined" && categoryId != "") {
                query = {
                    categoryId: new ObjectId(categoryId)
                };
            }
            else if (budgetId != "undefined" && budgetId != "") {
                query = {
                    "budget._id": budgetId
                };
            }
            else if (PRNo != "undefined" && PRNo != "") {
                query = {
                    "no": PRNo
                };
                console.log(query);
            }
            else if (dateFrom != "undefined" && dateFrom != "" && dateFrom != "null" && dateTo != "undefined" && dateTo != "" && dateTo != "null") {
                query = {
                    date: {
                        $gte: dateFrom,
                        $lte: dateTo
                    }
                };
            }
            query = Object.assign(query, {
                _createdBy: this.user.username,
                _deleted: false,
                isPosted: true
            });
            this.collection.find(query).sort(sorting).toArray()
                .then(purchaseRequest => {
                    resolve(purchaseRequest);
                    console.log(purchaseRequest);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.purchasing.collection.PurchaseRequest}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        };

        var noIndex = {
            name: `ix_${map.purchasing.collection.PurchaseRequest}_no`,
            key: {
                no: 1
            },
            unique: true
        };

        return this.collection.createIndexes([dateIndex, noIndex]);
    }
};<commit_msg>delete console log<commit_after>"use strict";

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var DLModels = require("dl-models");
var map = DLModels.map;
var PurchaseRequest = DLModels.purchasing.PurchaseRequest;
var generateCode = require("../../utils/code-generator");
var BaseManager = require("module-toolkit").BaseManager;
var i18n = require("dl-i18n");
var UnitManager = require("../master/unit-manager");
var BudgetManager = require("../master/budget-manager");
var CategoryManager = require("../master/category-manager");
var ProductManager = require("../master/product-manager");

module.exports = class PurchaseRequestManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.moduleId = "PR";
        this.year = (new Date()).getFullYear().toString().substring(2, 4);
        this.collection = this.db.use(map.purchasing.collection.PurchaseRequest);

        this.unitManager = new UnitManager(db, user);
        this.budgetManager = new BudgetManager(db, user);
        this.categoryManager = new CategoryManager(db, user);
        this.productManager = new ProductManager(db, user);
    }

    _getQuery(paging) {
        var deletedFilter = {
            _deleted: false
        },
            keywordFilter = {};

        var query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterNo = {
                "no": {
                    "$regex": regex
                }
            };

            var filterUnitDivisionName = {
                "unit.division.name": {
                    "$regex": regex
                }
            };
            var filterUnitName = {
                "unit.name": {
                    "$regex": regex
                }
            };

            var filterCategory = {
                "category.name": {
                    "$regex": regex
                }
            };

            keywordFilter = {
                "$or": [filterNo, filterUnitDivisionName, filterUnitName, filterCategory]
            };
        }
        query = {
            "$and": [deletedFilter, paging.filter, keywordFilter]
        };
        return query;
    }

    _validate(purchaseRequest) {
        var errors = {};
        var valid = purchaseRequest;

        var getPurchaseRequestPromise = this.collection.singleOrDefault({
            _id: {
                '$ne': new ObjectId(valid._id)
            },
            no: valid.no
        });

        var getUnit = valid.unitId && valid.unitId.toString().trim() != "" ? this.unitManager.getSingleByIdOrDefault(valid.unitId) : Promise.resolve(null);
        var getCategory = valid.categoryId && valid.categoryId.toString().trim() != "" ? this.categoryManager.getSingleByIdOrDefault(valid.categoryId) : Promise.resolve(null);
        var getBudget = valid.budgetId && valid.budgetId.toString().trim() != "" ? this.budgetManager.getSingleByIdOrDefault(valid.budgetId) : Promise.resolve(null);
        var getProduct = [];

        valid.items = valid.items instanceof Array ? valid.items : [];
        for (var _item of valid.items)
            getProduct.push(_item.productId && _item.productId.toString().trim() != "" ? this.productManager.getSingleByIdOrDefault(_item.productId) : Promise.resolve(null));

        return Promise.all([getPurchaseRequestPromise, getUnit, getCategory, getBudget].concat(getProduct))
            .then(results => {
                var _purchaseRequest = results[0];
                var _unit = results[1];
                var _category = results[2];
                var _budget = results[3];
                var _products = results.slice(4, results.length);

                if (_purchaseRequest)
                    errors["no"] = i18n.__("PurchaseRequest.no.isExists:%s is exists", i18n.__("PurchaseRequest.product._:No"));

                if (!valid.date || valid.date == "" || valid.date == "undefined")
                    errors["date"] = i18n.__("PurchaseRequest.date.isRequired:%s is required", i18n.__("PurchaseRequest.date._:Date")); //"Tanggal PR tidak boleh kosong";

                if (!_unit)
                    errors["unit"] = i18n.__("PurchaseRequest.unit.isRequired:%s is not exists", i18n.__("PurchaseRequest.unit._:Unit")); //"Unit tidak boleh kosong";
                else if (!valid.unitId)
                    errors["unit"] = i18n.__("PurchaseRequest.unit.isRequired:%s is required", i18n.__("PurchaseRequest.unit._:Unit")); //"Unit tidak boleh kosong";

                if (!_category)
                    errors["category"] = i18n.__("PurchaseRequest.category.isRequired:%s is not exists", i18n.__("PurchaseRequest.category._:Category")); //"Category tidak boleh kosong";
                else if (!valid.categoryId)
                    errors["category"] = i18n.__("PurchaseRequest.category.isRequired:%s is required", i18n.__("PurchaseRequest.category._:Category")); //"Category tidak boleh kosong";

                if (!_budget)
                    errors["budget"] = i18n.__("PurchaseRequest.budget.name.isRequired:%s is not exists", i18n.__("PurchaseRequest.budget.name._:Budget")); //"Budget tidak boleh kosong";
                else if (!valid.budget._id)
                    errors["budget"] = i18n.__("PurchaseRequest.budget.name.isRequired:%s is required", i18n.__("PurchaseRequest.budget.name._:Budget")); //"Budget tidak boleh kosong";

                if (!valid.expectedDeliveryDate || valid.expectedDeliveryDate == "" || valid.expectedDeliveryDate == "undefined")
                    valid.expectedDeliveryDate = "";

                if (valid.items && valid.items.length <= 0) {
                    errors["items"] = i18n.__("PurchaseRequest.items.isRequired:%s is required", i18n.__("PurchaseRequest.items._:Item")); //"Harus ada minimal 1 barang";
                }
                else {
                    var itemErrors = [];
                    for (var item of valid.items) {
                        var itemError = {};
                        if (!item.product || !item.product._id)
                            itemError["product"] = i18n.__("PurchaseRequest.items.product.name.isRequired:%s is required", i18n.__("PurchaseRequest.items.product.name._:Name")); //"Nama barang tidak boleh kosong";
                        if (item.quantity <= 0)
                            itemError["quantity"] = i18n.__("PurchaseRequest.items.quantity.isRequired:%s is required", i18n.__("PurchaseRequest.items.quantity._:Quantity")); //Jumlah barang tidak boleh kosong";

                        if (Object.getOwnPropertyNames(itemError).length > 0)
                            itemErrors.push(itemError);
                    }
                    if (itemErrors.length > 0)
                        errors.items = itemErrors;
                }

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require("module-toolkit").ValidationError;
                    return Promise.reject(new ValidationError("data does not pass validation", errors));
                }

                valid.unitId = _unit._id;
                valid.unit = _unit;

                valid.categoryId = _category._id;
                valid.category = _category;

                valid.budgetId = _budget._id;
                valid.budget = _budget;

                for (var prItem of valid.items) {
                    for (var _product of _products) {
                        if (prItem.product._id.toString() == _product._id.toString()) {
                            prItem.product = _product;
                            prItem.uom = _product.uom;
                            break;
                        }
                    }
                }

                if (!valid.stamp)
                    valid = new PurchaseRequest(valid);

                valid.stamp(this.user.username, "manager");
                return Promise.resolve(valid);
            });
    }

    create(purchaseRequest) {
        return new Promise((resolve, reject) => {
            var dateFormat = "MMYY";
            var locale = "id-ID";
            var moment = require("moment");
            moment.locale(locale);
            this._validate(purchaseRequest)
                .then(validPurchaseRequest => {
                    validPurchaseRequest.no = generateCode();
                    if (validPurchaseRequest.expectedDeliveryDate == "undefined") {
                        validPurchaseRequest.expectedDeliveryDate = "";
                    }
                    this.collection.insert(validPurchaseRequest)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    post(listPurchaseRequest) {
        var purchaseRequests = [];
        var tasks = [];
        return new Promise((resolve, reject) => {
            for (var purchaseRequest of listPurchaseRequest) {
                purchaseRequests.push(this.getSingleByIdOrDefault(purchaseRequest._id));
            }
            Promise.all(purchaseRequests)
                .then(validPurchaseRequest => {
                    for (var pr of listPurchaseRequest) {
                        for (var _pr of validPurchaseRequest) {
                            if (_pr._id.equals(pr._id)) {
                                _pr.isPosted = true;
                                tasks.push(this.update(_pr));
                                break;
                            }
                        }

                    }
                    Promise.all(tasks)
                        .then(result => {
                            resolve(result);
                        })
                        .catch(e => {
                            reject(e);
                        });

                })
                .catch(e => {
                    reject(e);
                });
        });

    }

    pdf(id) {
        return new Promise((resolve, reject) => {

            this.getSingleById(id)
                .then(purchaseRequest => {
                    var getDefinition = require("../../pdf/definitions/purchase-request");
                    var definition = getDefinition(purchaseRequest);

                    var generatePdf = require("../../pdf/pdf-generator");
                    generatePdf(definition)
                        .then(binary => {
                            resolve(binary);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    getDataPRMonitoring(unitId, categoryId, budgetId, PRNo, dateFrom, dateTo) {
        return new Promise((resolve, reject) => {
            var sorting = {
                "date": -1,
                "no": 1
            };
            var query = {};
            if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && budgetId != "undefined" && budgetId != "" && PRNo != "undefined" && PRNo != "" && dateFrom != "undefined" && dateFrom != "" && dateFrom != "null" && dateTo != "undefined" && dateTo != "" && dateTo != "null") {
                query = {
                    unitId: new ObjectId(unitId),
                    categoryId: new ObjectId(categoryId),
                    "no": PRNo,
                    "budget._id": new ObjectId(budgetId),
                    date: {
                        $gte: dateFrom,
                        $lte: dateTo
                    }
                };
            }
            else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && budgetId != "undefined" && budgetId != "" && PRNo != "undefined" && PRNo != "") {
                query = {
                    unitId: new ObjectId(unitId),
                    categoryId: new ObjectId(categoryId),
                    "no": PRNo,
                    "budget._id": new ObjectId(budgetId)
                };
            }
            else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && budgetId != "undefined" && budgetId != "") {
                query = {
                    unitId: new ObjectId(unitId),
                    categoryId: new ObjectId(categoryId),
                    "budget._id": new ObjectId(budgetId)
                };
            }
            else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "") {
                query = {
                    unitId: new ObjectId(unitId),
                    categoryId: new ObjectId(categoryId)
                };
            }
            else if (unitId != "undefined" && unitId != "") {
                query = {
                    unitId: new ObjectId(unitId)
                };
            }
            else if (categoryId != "undefined" && categoryId != "") {
                query = {
                    categoryId: new ObjectId(categoryId)
                };
            }
            else if (budgetId != "undefined" && budgetId != "") {
                query = {
                    "budget._id": budgetId
                };
            }
            else if (PRNo != "undefined" && PRNo != "") {
                query = {
                    "no": PRNo
                };
            }
            else if (dateFrom != "undefined" && dateFrom != "" && dateFrom != "null" && dateTo != "undefined" && dateTo != "" && dateTo != "null") {
                query = {
                    date: {
                        $gte: dateFrom,
                        $lte: dateTo
                    }
                };
            }
            query = Object.assign(query, {
                _createdBy: this.user.username,
                _deleted: false,
                isPosted: true
            });
            this.collection.find(query).sort(sorting).toArray()
                .then((purchaseRequests) => {
                    resolve(purchaseRequests);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.purchasing.collection.PurchaseRequest}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        };

        var noIndex = {
            name: `ix_${map.purchasing.collection.PurchaseRequest}_no`,
            key: {
                no: 1
            },
            unique: true
        };

        return this.collection.createIndexes([dateIndex, noIndex]);
    }
};<|endoftext|>


<commit_before>var gulp = require('gulp');
var compass = require('gulp-compass');
var browserSync = require('browser-sync').create();
var minifyCss = require('gulp-minify-css');
var jade = require('gulp-jade');

gulp.task('serve', function() {
    browserSync.init({
        server: "./public"
    });

    gulp.src('fonts-fontface/*').pipe(gulp.dest('public/fonts'));
    gulp.src('img/*').pipe(gulp.dest('public/images'));
    gulp.watch("sass/**/*.scss", ['compass']);
    gulp.watch("templates/*.jade", ['templates']);
});
gulp.task('compass', function() {
    return gulp.src('sass/*.scss')
        .pipe(compass({
            config_file: 'config.rb',
            css: 'compiled/css',
            sass: 'sass/'
        }))
        .on('error', function(error) {
            console.log(error.message);
            this.emit('end');
        })
        .pipe(gulp.dest('compiled/css'))
        .pipe(minifyCss())
        .pipe(gulp.dest('public'))
        .pipe(browserSync.stream())
    ;
});

gulp.task('templates', function() {
    return gulp.src('templates/index.jade')
        .pipe(jade())
        .pipe(gulp.dest('public/'))
        .pipe(browserSync.reload({stream: true}))
    ;
});

gulp.task('default', ['templates', 'compass', 'serve']);
<commit_msg>fix gulpfile for fonts<commit_after>var gulp = require('gulp');
var compass = require('gulp-compass');
var browserSync = require('browser-sync').create();
var minifyCss = require('gulp-minify-css');
var jade = require('gulp-jade');

gulp.task('serve', function() {
    browserSync.init({
        server: "./public"
    });

    gulp.src('fonts/*').pipe(gulp.dest('public/fonts'));
    gulp.src('img/*').pipe(gulp.dest('public/images'));
    gulp.watch("sass/**/*.scss", ['compass']);
    gulp.watch("templates/*.jade", ['templates']);
});
gulp.task('compass', function() {
    return gulp.src('sass/*.scss')
        .pipe(compass({
            config_file: 'config.rb',
            css: 'compiled/css',
            sass: 'sass/'
        }))
        .on('error', function(error) {
            console.log(error.message);
            this.emit('end');
        })
        .pipe(gulp.dest('compiled/css'))
        .pipe(minifyCss())
        .pipe(gulp.dest('public'))
        .pipe(browserSync.stream())
    ;
});

gulp.task('templates', function() {
    return gulp.src('templates/index.jade')
        .pipe(jade())
        .pipe(gulp.dest('public/'))
        .pipe(browserSync.reload({stream: true}))
    ;
});

gulp.task('default', ['templates', 'compass', 'serve']);
<|endoftext|>


<commit_before>/*
 * fixmystreet.js
 * FixMyStreet JavaScript
 */

/*
 * general height fixing function
 *
 * elem1: element to check against
 * elem2: target element
 * offset: this will be added (if present) to the final value, useful for height errors
 */
function heightFix(elem1, elem2, offset){
    var h1 = $(elem1).height(),
        h2 = $(elem2).height();
    if(offset === undefined){
        offset = 0;
    }
    if(h1 > h2){
        $(elem2).css({'min-height':h1+offset});
    }
}

/*
 * very simple tab function
 *
 * elem: trigger element, must have an href attribute (so probably needs to be an )
 */
function tabs(elem, indirect) {
    var href = elem.attr('href');
    //stupid IE sometimes adds the full uri into the href attr, so trim
    var start = href.indexOf('#'),
        target = href.slice(start, href.length);

    if (indirect) {
        elem = $(target + '_tab');
    }

    if(!$(target).hasClass('open'))
    {
        //toggle class on nav
        $('.tab-nav .active').removeClass('active');
        elem.addClass('active');

        //hide / show the right tab
        $('.tab.open').hide().removeClass('open');
        $(target).show().addClass('open');
    }
}

$(function(){
    var $html = $('html');

    var cobrand;
    if (window.location.href.indexOf('bromley') != -1) {
        cobrand = 'bromley';
    }

    // Deal with switching between mobile and desktop versions on resize
    var last_type;
    $(window).resize(function(){
        var type = $('#site-header').css('borderTopWidth');
        if (type == '4px') { type = 'mobile'; }
        else if (type == '0px') { type = 'desktop'; }
        else { return; }
        if (last_type == type) { return; }
        if (type == 'mobile') {
            $html.addClass('mobile');
            $('#map_box').prependTo('.content').css({
                zIndex: '', position: '',
                top: '', left: '', right: '', bottom: '',
                width: '', height: '10em',
                margin: ''
            });
            if (typeof fixmystreet !== 'undefined') {
                fixmystreet.state_map = ''; // XXX
            }
            if (typeof fixmystreet !== 'undefined' && fixmystreet.page == 'around') {
                // Immediately go full screen map if on around page
                if (cobrand != 'bromley') {
                    $('#site-header').hide();
                }
                $('#map_box').prependTo('.wrapper').css({
                    position: 'absolute',
                    top: 0, left: 0, right: 0, bottom: 0,
                    height: 'auto',
                    margin: 0
                });
                $('#fms_pan_zoom').css({ top: '2.75em !important' });
                $('.big-green-banner')
                    .addClass('mobile-map-banner')
                    .appendTo('#map_box')
                    .text('Place pin on map')
	            .prepend('home');
            }
            $('span.report-a-problem-btn').on('click.reportBtn', function(){
                $('html, body').animate({scrollTop:0}, 500);
            }).css({ cursor:'pointer' }).on('hover.reportBtn', function(){
                $(this).toggleClass('hover');
            });
        } else {
            // Make map full screen on non-mobile sizes.
            $html.removeClass('mobile');
            position_map_box();
            if (typeof fixmystreet !== 'undefined') {
                if (cobrand == 'bromley') {
                    //$('#bromley-footer').hide();
                } else {
                    fixmystreet.state_map = 'full';
                }
            }
            if (typeof fixmystreet !== 'undefined' && fixmystreet.page == 'around') {
                // Remove full-screen-ness
                var banner_text;
                if (cobrand == 'bromley') {
                    banner_text = 'Click map to report a problemYellow pins show existing reports';
                } else {
                    $('#site-header').show();
                    banner_text = 'Click map to report a problem';
                }
                $('#fms_pan_zoom').css({ top: '4.75em !important' });
                $('.big-green-banner')
                    .removeClass('mobile-map-banner')
                    .prependTo('#side')
                    .html(banner_text);
            }
            $('span.report-a-problem-btn').css({ cursor:'' }).off('.reportBtn');
        }
        last_type = type;
    }).resize();

    /*
     * Report a problem page
     */
    //desktop
    if ($('#report-a-problem-sidebar').is(':visible')) {
        heightFix('#report-a-problem-sidebar', '.content', 26);
    }

    //show/hide notes on mobile
    $('.mobile #report-a-problem-sidebar').after('How to send successful reports').hide();
    $('.rap-notes-trigger').click(function(e){
        e.preventDefault();
        //check if we've already moved the notes
        if($('.rap-notes').length > 0){
            //if we have, show and hide .content
            $('.content').hide();
            $('.rap-notes').show();
        }else{
            //if not, move them and show, hiding .content
            $('.content').after('

').hide();
            $('#report-a-problem-sidebar').appendTo('.rap-notes').show().after('Back');
        }
        $('html, body').scrollTop($('#report-a-problem-sidebar').offset().top);
        location.hash = 'rap-notes';
    });
    $('.mobile').on('click', '.rap-notes-close', function(e){
        e.preventDefault();
        //hide notes, show .content
        $('.content').show();
        $('.rap-notes').hide();
        $('html, body').scrollTop($('#mob_ok').offset().top);
        location.hash = 'report';
    });

    //move 'skip this step' link on mobile
    $('.mobile #skip-this-step').hide();
    $('.mobile #skip-this-step a').addClass('chevron').wrap('
').appendTo('#key-tools');

    /*
     * Tabs
     */
    //make initial tab active
    $('.tab-nav a').first().addClass('active');
    $('.tab').first().addClass('open');

    //hide other tabs
    $('.tab').not('.open').hide();

    //set up click event
    $(".tab-nav").on('click', 'a', function(e){
        e.preventDefault();
        tabs($(this));
    });
    $('.tab_link').click(function(e) {
        e.preventDefault();
        tabs($(this), 1);
    });

    /*
     * Skip to nav on mobile
     */
    $('.mobile').on('click', '#nav-link', function(e){
        e.preventDefault();
        var offset = $('#main-nav').offset().top;
        $('html, body').animate({scrollTop:offset}, 1000);
    });

    /*
     * Show stuff on input focus
     */
    var form_focus_data = $('.form-focus-trigger').map(function() {
        return $(this).val();
    }).get().join('');
    if (!form_focus_data) {
        $('.form-focus-hidden').hide();
        $('.form-focus-trigger').on('focus', function(){
            $('.form-focus-hidden').fadeIn(500);
        });
    }

    /*
     * Show on click - pretty generic
     */
    $('.hideshow-trigger').on('click', function(e){
        e.preventDefault();
        var href = $(this).attr('href'),
            //stupid IE sometimes adds the full uri into the href attr, so trim
            start = href.indexOf('#'),
            target = href.slice(start, href.length);

        $(target).removeClass('hidden-js');

        $(this).hide();
    });

    /*
     * nicetable - on mobile shift 'name' col to be a row
     */
    $('.mobile .nicetable th.title').remove();
    $('.mobile .nicetable td.title').each(function(i){
        $(this).attr('colspan', 5).insertBefore($(this).parent('tr')).wrap('
');
    });
    // $('.mobile .nicetable tr.heading > td.title').css({'min-width':'300px'});
    // $('.mobile .nicetable tr > td.data').css({'max-width':'12%'});

    /*
     * Map controls prettiness
     */
    //add links container (if its not there)
    if($('#sub_map_links').length === 0){
        $('
').insertAfter($('#map'));
    }

// A sliding drawer from the bottom of the page, small version
// that doesn't change the main content at all.
$.fn.small_drawer = function(id) {
    this.toggle(function(){
        var $this = $(this), d = $('#' + id);
        if (!$this.addClass('hover').data('setup')) {
            d.hide().removeClass('hidden-js').css({
                padding: '1em',
                background: '#fff'
            });
            $this.data('setup', true);
        }
        d.slideDown();
    }, function(e){
        var $this = $(this), d = $('#' + id);
        $this.removeClass('hover');
        d.slideUp();
    });
};

// A sliding drawer from the bottom of the page, large version
$.fn.drawer = function(id, ajax) {
    // IE7 positions the fixed tool bar 1em to the left unless it comes after
    // the full-width section, ho-hum. Move it to where it would be after an
    // open/close anyway
    if ($('html.ie7').length) {
        var $sw = $('.shadow-wrap'), $content = $('.content[role="main"]');
        $sw.appendTo($content);
    }
    this.toggle(function(){
        var $this = $(this), d = $('#' + id), $content = $('.content[role="main"]');
        if (!$this.addClass('hover').data('setup')) {
            // make a drawer div with an innerDiv
            if (!d.length) {
                d = $('
');
            }
            var innerDiv = $('
');
            d.wrapInner(innerDiv);

            // if ajax, load it with a spinner
            if (ajax) {
                var href = $this.attr('href') + ';ajax=1';
                $this.prepend(' ');
                innerDiv.load(href, function(){
                    $('.spinner').remove();
                });
            }

            // Tall drawer - put after .content for scrolling to work okay.
            // position over the top of the main .content in precisely the right location
            d.insertAfter($content).addClass('content').css({
                position: 'absolute',
                zIndex: '1100',
                marginTop: $('html.ie6, html.ie7').length ? '-3em' : 0, // IE6/7 otherwise include the 3em padding and stay too low
                left: 0,
                top: $(window).height() - $content.offset().top
            }).removeClass('hidden-js').find('h2').css({ marginTop: 0 });
            $this.data('setup', true);
        }

        //do the animation
        $('.shadow-wrap').prependTo(d).addClass('static');
        d.show().animate({top:'3em'}, 1000, function(){
            $content.fadeOut(function() {
                d.css({ position: 'relative' });
            });
        });
    }, function(e){
        var $this = $(this), d = $('#' + id), $sw = $('.shadow-wrap'),
            $content = $('.content[role="main"]'),
            tot_height = $(window).height() - d.offset().top;
        $this.removeClass('hover');
        d.css({ position: 'absolute' }).animate({ top: tot_height }, 1000, function(){
            d.hide();
            $sw.appendTo($content).removeClass('static');
        });
        $content.show();
    });
};

    if ($('html.mobile').length || slide_wards_down ) {
        $('#council_wards').hide().removeClass('hidden-js').find('h2').hide();
        $('#key-tool-wards').click(function(e){
            e.preventDefault();
            $('#council_wards').slideToggle('800', function(){
              $('#key-tool-wards').toggleClass('hover');
            });
        });
    } else {
        $('#key-tool-wards').drawer('council_wards', false);
        $('#key-tool-around-updates').drawer('updates_ajax', true);
    }
    $('#key-tool-report-updates').small_drawer('report-updates-data');

    // Go directly to RSS feed if RSS button clicked on alert page
    // (due to not wanting around form to submit, though good thing anyway)
    $('.container').on('click', '#alert_rss_button', function(e){
        e.preventDefault();
        var feed = $('input[name=feed][type=radio]:checked').nextAll('a').attr('href');
        window.location.href = feed;
    });
    $('.container').on('click', '#alert_email_button', function(e){
        e.preventDefault();
        var form = $('<form/>').attr({ method:'post', action:"/alert/subscribe" });
        form.append($('<input name="alert" value="Subscribe me to an email alert" type="hidden" />'));
        $('#alerts input[type=text], #alerts input[type=hidden], #alerts input[type=radio]:checked').each(function() {
            var $v = $(this);
            $('<input/>').attr({ name:$v.attr('name'), value:$v.val(), type:'hidden' }).appendTo(form);
        });
        form.submit();
    });

    //add permalink on desktop, force hide on mobile
    $('#sub_map_links').append('Permalink');
    if($('.mobile').length){
        $('#map_permalink').hide();
        $('#key-tools a.feed').appendTo('#sub_map_links');
        $('#key-tools li:empty').remove();
        $('#report-updates-data').insertAfter($('#map_box'));
    }
    //add open/close toggle button on desk
    $('#sub_map_links').prepend(' ');

    //set up map_links_toggle click event
    $('#map_links_toggle').on('click', function(){
        var maplinks_width = $('#sub_map_links').width();

        if($(this).hasClass('closed')){
            $(this).removeClass('closed');
            $('#sub_map_links').animate({'right':'0'}, 1200);
        }else{
            $(this).addClass('closed');
            $('#sub_map_links').animate({'right':-maplinks_width}, 1200);
        }
    });

    /*
     * Add close buttons for .promo's
     */
    if($('.promo').length){
        $('.promo').append('x');
    }
    //only close its own parent
    $('.promo').on('click', '.close-promo', function(e){
        e.preventDefault();
        $(this).parent('.promo').animate({
            'height':0,
            'margin-bottom':0,
            'padding-top':0,
            'padding-bottom':0
        },{
            duration:500,
            queue:false
        }).fadeOut(500);
    });

    /*
     * Fancybox fullscreen images
     */
    if (typeof $.fancybox == 'function') {
        $('a[rel=fancy]').fancybox({
            'overlayColor': '#000000'
        });
    }

    /*
     * heightfix the desktop .content div
     *
     * this must be kept near the end so that the
     * rendered height is used after any page manipulation (such as tabs)
     */
    if (!$('html.mobile').length) {
        if (!($('body').hasClass('frontpage'))){
            var offset = -176;
            if (cobrand == 'bromley') {
                offset = -110;
            }
            heightFix(window, '.content', offset);
            // in case we have a map that isn't full screen
            map_fix();
        }
    }

});

/*
XXX Disabled because jerky on Android and makes map URL bar height too small on iPhone.
// Hide URL bar
$(window).load(function(){
    window.setTimeout(function(){
        var s = window.pageYOffset || document.compatMode === "CSS1Compat" && document.documentElement.scrollTop || document.body.scrollTop || 0;
        if (s < 20 && !location.hash) {
            window.scrollTo(0, 1);
        }
    }, 0);
});
*/

<commit_msg>Form needs to be in the body for IE8 to submit.<commit_after>/*
 * fixmystreet.js
 * FixMyStreet JavaScript
 */

/*
 * general height fixing function
 *
 * elem1: element to check against
 * elem2: target element
 * offset: this will be added (if present) to the final value, useful for height errors
 */
function heightFix(elem1, elem2, offset){
    var h1 = $(elem1).height(),
        h2 = $(elem2).height();
    if(offset === undefined){
        offset = 0;
    }
    if(h1 > h2){
        $(elem2).css({'min-height':h1+offset});
    }
}

/*
 * very simple tab function
 *
 * elem: trigger element, must have an href attribute (so probably needs to be an )
 */
function tabs(elem, indirect) {
    var href = elem.attr('href');
    //stupid IE sometimes adds the full uri into the href attr, so trim
    var start = href.indexOf('#'),
        target = href.slice(start, href.length);

    if (indirect) {
        elem = $(target + '_tab');
    }

    if(!$(target).hasClass('open'))
    {
        //toggle class on nav
        $('.tab-nav .active').removeClass('active');
        elem.addClass('active');

        //hide / show the right tab
        $('.tab.open').hide().removeClass('open');
        $(target).show().addClass('open');
    }
}

$(function(){
    var $html = $('html');

    var cobrand;
    if (window.location.href.indexOf('bromley') != -1) {
        cobrand = 'bromley';
    }

    // Deal with switching between mobile and desktop versions on resize
    var last_type;
    $(window).resize(function(){
        var type = $('#site-header').css('borderTopWidth');
        if (type == '4px') { type = 'mobile'; }
        else if (type == '0px') { type = 'desktop'; }
        else { return; }
        if (last_type == type) { return; }
        if (type == 'mobile') {
            $html.addClass('mobile');
            $('#map_box').prependTo('.content').css({
                zIndex: '', position: '',
                top: '', left: '', right: '', bottom: '',
                width: '', height: '10em',
                margin: ''
            });
            if (typeof fixmystreet !== 'undefined') {
                fixmystreet.state_map = ''; // XXX
            }
            if (typeof fixmystreet !== 'undefined' && fixmystreet.page == 'around') {
                // Immediately go full screen map if on around page
                if (cobrand != 'bromley') {
                    $('#site-header').hide();
                }
                $('#map_box').prependTo('.wrapper').css({
                    position: 'absolute',
                    top: 0, left: 0, right: 0, bottom: 0,
                    height: 'auto',
                    margin: 0
                });
                $('#fms_pan_zoom').css({ top: '2.75em !important' });
                $('.big-green-banner')
                    .addClass('mobile-map-banner')
                    .appendTo('#map_box')
                    .text('Place pin on map')
	            .prepend('home');
            }
            $('span.report-a-problem-btn').on('click.reportBtn', function(){
                $('html, body').animate({scrollTop:0}, 500);
            }).css({ cursor:'pointer' }).on('hover.reportBtn', function(){
                $(this).toggleClass('hover');
            });
        } else {
            // Make map full screen on non-mobile sizes.
            $html.removeClass('mobile');
            position_map_box();
            if (typeof fixmystreet !== 'undefined') {
                if (cobrand == 'bromley') {
                    //$('#bromley-footer').hide();
                } else {
                    fixmystreet.state_map = 'full';
                }
            }
            if (typeof fixmystreet !== 'undefined' && fixmystreet.page == 'around') {
                // Remove full-screen-ness
                var banner_text;
                if (cobrand == 'bromley') {
                    banner_text = 'Click map to report a problemYellow pins show existing reports';
                } else {
                    $('#site-header').show();
                    banner_text = 'Click map to report a problem';
                }
                $('#fms_pan_zoom').css({ top: '4.75em !important' });
                $('.big-green-banner')
                    .removeClass('mobile-map-banner')
                    .prependTo('#side')
                    .html(banner_text);
            }
            $('span.report-a-problem-btn').css({ cursor:'' }).off('.reportBtn');
        }
        last_type = type;
    }).resize();

    /*
     * Report a problem page
     */
    //desktop
    if ($('#report-a-problem-sidebar').is(':visible')) {
        heightFix('#report-a-problem-sidebar', '.content', 26);
    }

    //show/hide notes on mobile
    $('.mobile #report-a-problem-sidebar').after('How to send successful reports').hide();
    $('.rap-notes-trigger').click(function(e){
        e.preventDefault();
        //check if we've already moved the notes
        if($('.rap-notes').length > 0){
            //if we have, show and hide .content
            $('.content').hide();
            $('.rap-notes').show();
        }else{
            //if not, move them and show, hiding .content
            $('.content').after('

').hide();
            $('#report-a-problem-sidebar').appendTo('.rap-notes').show().after('Back');
        }
        $('html, body').scrollTop($('#report-a-problem-sidebar').offset().top);
        location.hash = 'rap-notes';
    });
    $('.mobile').on('click', '.rap-notes-close', function(e){
        e.preventDefault();
        //hide notes, show .content
        $('.content').show();
        $('.rap-notes').hide();
        $('html, body').scrollTop($('#mob_ok').offset().top);
        location.hash = 'report';
    });

    //move 'skip this step' link on mobile
    $('.mobile #skip-this-step').hide();
    $('.mobile #skip-this-step a').addClass('chevron').wrap('
').appendTo('#key-tools');

    /*
     * Tabs
     */
    //make initial tab active
    $('.tab-nav a').first().addClass('active');
    $('.tab').first().addClass('open');

    //hide other tabs
    $('.tab').not('.open').hide();

    //set up click event
    $(".tab-nav").on('click', 'a', function(e){
        e.preventDefault();
        tabs($(this));
    });
    $('.tab_link').click(function(e) {
        e.preventDefault();
        tabs($(this), 1);
    });

    /*
     * Skip to nav on mobile
     */
    $('.mobile').on('click', '#nav-link', function(e){
        e.preventDefault();
        var offset = $('#main-nav').offset().top;
        $('html, body').animate({scrollTop:offset}, 1000);
    });

    /*
     * Show stuff on input focus
     */
    var form_focus_data = $('.form-focus-trigger').map(function() {
        return $(this).val();
    }).get().join('');
    if (!form_focus_data) {
        $('.form-focus-hidden').hide();
        $('.form-focus-trigger').on('focus', function(){
            $('.form-focus-hidden').fadeIn(500);
        });
    }

    /*
     * Show on click - pretty generic
     */
    $('.hideshow-trigger').on('click', function(e){
        e.preventDefault();
        var href = $(this).attr('href'),
            //stupid IE sometimes adds the full uri into the href attr, so trim
            start = href.indexOf('#'),
            target = href.slice(start, href.length);

        $(target).removeClass('hidden-js');

        $(this).hide();
    });

    /*
     * nicetable - on mobile shift 'name' col to be a row
     */
    $('.mobile .nicetable th.title').remove();
    $('.mobile .nicetable td.title').each(function(i){
        $(this).attr('colspan', 5).insertBefore($(this).parent('tr')).wrap('
');
    });
    // $('.mobile .nicetable tr.heading > td.title').css({'min-width':'300px'});
    // $('.mobile .nicetable tr > td.data').css({'max-width':'12%'});

    /*
     * Map controls prettiness
     */
    //add links container (if its not there)
    if($('#sub_map_links').length === 0){
        $('
').insertAfter($('#map'));
    }

// A sliding drawer from the bottom of the page, small version
// that doesn't change the main content at all.
$.fn.small_drawer = function(id) {
    this.toggle(function(){
        var $this = $(this), d = $('#' + id);
        if (!$this.addClass('hover').data('setup')) {
            d.hide().removeClass('hidden-js').css({
                padding: '1em',
                background: '#fff'
            });
            $this.data('setup', true);
        }
        d.slideDown();
    }, function(e){
        var $this = $(this), d = $('#' + id);
        $this.removeClass('hover');
        d.slideUp();
    });
};

// A sliding drawer from the bottom of the page, large version
$.fn.drawer = function(id, ajax) {
    // IE7 positions the fixed tool bar 1em to the left unless it comes after
    // the full-width section, ho-hum. Move it to where it would be after an
    // open/close anyway
    if ($('html.ie7').length) {
        var $sw = $('.shadow-wrap'), $content = $('.content[role="main"]');
        $sw.appendTo($content);
    }
    this.toggle(function(){
        var $this = $(this), d = $('#' + id), $content = $('.content[role="main"]');
        if (!$this.addClass('hover').data('setup')) {
            // make a drawer div with an innerDiv
            if (!d.length) {
                d = $('
');
            }
            var innerDiv = $('
');
            d.wrapInner(innerDiv);

            // if ajax, load it with a spinner
            if (ajax) {
                var href = $this.attr('href') + ';ajax=1';
                $this.prepend(' ');
                innerDiv.load(href, function(){
                    $('.spinner').remove();
                });
            }

            // Tall drawer - put after .content for scrolling to work okay.
            // position over the top of the main .content in precisely the right location
            d.insertAfter($content).addClass('content').css({
                position: 'absolute',
                zIndex: '1100',
                marginTop: $('html.ie6, html.ie7').length ? '-3em' : 0, // IE6/7 otherwise include the 3em padding and stay too low
                left: 0,
                top: $(window).height() - $content.offset().top
            }).removeClass('hidden-js').find('h2').css({ marginTop: 0 });
            $this.data('setup', true);
        }

        //do the animation
        $('.shadow-wrap').prependTo(d).addClass('static');
        d.show().animate({top:'3em'}, 1000, function(){
            $content.fadeOut(function() {
                d.css({ position: 'relative' });
            });
        });
    }, function(e){
        var $this = $(this), d = $('#' + id), $sw = $('.shadow-wrap'),
            $content = $('.content[role="main"]'),
            tot_height = $(window).height() - d.offset().top;
        $this.removeClass('hover');
        d.css({ position: 'absolute' }).animate({ top: tot_height }, 1000, function(){
            d.hide();
            $sw.appendTo($content).removeClass('static');
        });
        $content.show();
    });
};

    if ($('html.mobile').length || slide_wards_down ) {
        $('#council_wards').hide().removeClass('hidden-js').find('h2').hide();
        $('#key-tool-wards').click(function(e){
            e.preventDefault();
            $('#council_wards').slideToggle('800', function(){
              $('#key-tool-wards').toggleClass('hover');
            });
        });
    } else {
        $('#key-tool-wards').drawer('council_wards', false);
        $('#key-tool-around-updates').drawer('updates_ajax', true);
    }
    $('#key-tool-report-updates').small_drawer('report-updates-data');

    // Go directly to RSS feed if RSS button clicked on alert page
    // (due to not wanting around form to submit, though good thing anyway)
    $('.container').on('click', '#alert_rss_button', function(e){
        e.preventDefault();
        var feed = $('input[name=feed][type=radio]:checked').nextAll('a').attr('href');
        window.location.href = feed;
    });
    $('.container').on('click', '#alert_email_button', function(e){
        e.preventDefault();
        var form = $('<form/>').attr({ method:'post', action:"/alert/subscribe" });
        form.append($('<input name="alert" value="Subscribe me to an email alert" type="hidden" />'));
        $('#alerts input[type=text], #alerts input[type=hidden], #alerts input[type=radio]:checked').each(function() {
            var $v = $(this);
            $('<input/>').attr({ name:$v.attr('name'), value:$v.val(), type:'hidden' }).appendTo(form);
        });
        $('body').append(form);
        form.submit();
    });

    //add permalink on desktop, force hide on mobile
    $('#sub_map_links').append('Permalink');
    if($('.mobile').length){
        $('#map_permalink').hide();
        $('#key-tools a.feed').appendTo('#sub_map_links');
        $('#key-tools li:empty').remove();
        $('#report-updates-data').insertAfter($('#map_box'));
    }
    //add open/close toggle button on desk
    $('#sub_map_links').prepend(' ');

    //set up map_links_toggle click event
    $('#map_links_toggle').on('click', function(){
        var maplinks_width = $('#sub_map_links').width();

        if($(this).hasClass('closed')){
            $(this).removeClass('closed');
            $('#sub_map_links').animate({'right':'0'}, 1200);
        }else{
            $(this).addClass('closed');
            $('#sub_map_links').animate({'right':-maplinks_width}, 1200);
        }
    });

    /*
     * Add close buttons for .promo's
     */
    if($('.promo').length){
        $('.promo').append('x');
    }
    //only close its own parent
    $('.promo').on('click', '.close-promo', function(e){
        e.preventDefault();
        $(this).parent('.promo').animate({
            'height':0,
            'margin-bottom':0,
            'padding-top':0,
            'padding-bottom':0
        },{
            duration:500,
            queue:false
        }).fadeOut(500);
    });

    /*
     * Fancybox fullscreen images
     */
    if (typeof $.fancybox == 'function') {
        $('a[rel=fancy]').fancybox({
            'overlayColor': '#000000'
        });
    }

    /*
     * heightfix the desktop .content div
     *
     * this must be kept near the end so that the
     * rendered height is used after any page manipulation (such as tabs)
     */
    if (!$('html.mobile').length) {
        if (!($('body').hasClass('frontpage'))){
            var offset = -176;
            if (cobrand == 'bromley') {
                offset = -110;
            }
            heightFix(window, '.content', offset);
            // in case we have a map that isn't full screen
            map_fix();
        }
    }

});

/*
XXX Disabled because jerky on Android and makes map URL bar height too small on iPhone.
// Hide URL bar
$(window).load(function(){
    window.setTimeout(function(){
        var s = window.pageYOffset || document.compatMode === "CSS1Compat" && document.documentElement.scrollTop || document.body.scrollTop || 0;
        if (s < 20 && !location.hash) {
            window.scrollTo(0, 1);
        }
    }, 0);
});
*/

<|endoftext|>