<commit_before>$(window).ready(function(){

	//main menu flyouts or mbmenu releacment
	//$( '#MenuView .parent, #HeaderLinksView .parent, #ShortcutsMenu .parent' ).hover(
	$( '.nav > .parent' ).hover(
		function(){
			if ( $(this).find('ul') ){
				$(this).find('ul').stop(true, true).delay(0).fadeIn(250);
			}
		},
		function(){
			if ( $(this).find('ul') ){
				$(this).find('ul').stop(true, true).fadeOut(250);
			}
		}
	);

	/*Resizes the app to fill the browser's window case smaller'*/
	var viewportHeight = $(window).height();
	var wrapperDivHeight = $('body > div').outerHeight(true)
	var appChromeHeight = 0;
	var bufferHeight = 0;
	var recentlyViewedHeight = 0;

	if ( $('#LoginPageView').length > 0 ) {
		appChromeHeight = 38 + $('#FooterView').outerHeight(true);
		if ( wrapperDivHeight < viewportHeight  ){
			bufferHeight = viewportHeight - appChromeHeight;
			$('#LoginView').height(  bufferHeight   );
		}
	} else {
		recentlyViewedHeight = $('#RecentlyViewedView').outerHeight(true);
		appChromeHeight = recentlyViewedHeight + $('#MenuView').outerHeight(true) + $('#HeaderView').outerHeight(true) + $('#FooterView').outerHeight(true);
		if ( wrapperDivHeight < viewportHeight  ){
			bufferHeight = viewportHeight - appChromeHeight;
			$('#RecentlyViewedView').height( $('#RecentlyViewedView').height() + bufferHeight   );
		}
	}

	/*Dropdowns - Dropkick*/

	$('#edit-form select, .search-view-1 select, #inline-edit-form select').dropkick();

	$('html').click(function(e) {
		$.each($('td > select'), function(index, value) {
			$(value).dropkick('close');
		});
	});

	/*Checkboxes
	 from: http://webdesign.maratz.com/lab/fancy-checkboxes-and-radio-buttons/jquery.html
	 * */

	function setupCheckboxes( $context ) {

		if ( $('input:checkbox', $context ).length ) {
			$('input:checkbox', $context ).each(function(){
				$(this).parent().removeClass('c_on');
			});
			$('label input:checked', $context ).each(function(){
				$(this).parent('label').addClass('c_on');
		    });
		}

		$('label', $context[0] ).
		    live( 'click', { $inputContext:$(this).content  },
				function( event ){
			        if ( $('input:checkbox', event.data.$inputContext ).length ) {
						$('input:checkbox', event.data.$inputContext ).each(function(){
							$(this).parent().removeClass('c_on');
						});
						$('label input:checked', event.data.$inputContext ).each(function(){
							$(this).parent('label').addClass('c_on');
					    });
					}
			});
	}

    //we're doing that because the multiselect widget isn't generated yet..
    window.setTimeout(
    	function setCheckboxes(){
    		setupCheckboxes( $('#search-form') );
    		setupCheckboxes( $('#app-search') );
    	},
    1000 );

	$(".overlay-label-field > input").live('focus', function(){
		$(this).prev().fadeOut(100);
	});

	$(".overlay-label-field > input").live('blur', function(){
		if($(this).val() == "") {
			$(this).prev().fadeIn(250);
		}
	});

});

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function f(){ log.history = log.history || []; log.history.push(arguments); if(this.console) { var args = arguments, newarr; args.callee = args.callee.caller; newarr = [].slice.call(args); if (typeof console.log === 'object') log.apply.call(console.log, console, newarr); else console.log.apply(console, newarr);}};

// make it safe to use console.log always
(function(a){function b(){}for(var c="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),d;!!(d=c.pop());){a[d]=a[d]||b;}})
(function(){try{console.log();return window.console;}catch(a){return (window.console={});}}());<commit_msg>query cleaning<commit_after>$(window).ready(function(){

	//main menu flyouts or mbmenu releacment
	//$( '#MenuView .parent, #HeaderLinksView .parent, #ShortcutsMenu .parent' ).hover(
	$( '.nav > .parent' ).hover(
		function(){
			if ( $(this).find('ul') ){
				$(this).find('ul').stop(true, true).delay(0).fadeIn(250);
			}
		},
		function(){
			if ( $(this).find('ul') ){
				$(this).find('ul').stop(true, true).fadeOut(250);
			}
		}
	);

	/*Resizes the app to fill the browser's window case smaller'*/
	var viewportHeight = $(window).height();
	var wrapperDivHeight = $('body > div').outerHeight(true)
	var appChromeHeight = 0;
	var bufferHeight = 0;
	var recentlyViewedHeight = 0;

	if ( $('#LoginPageView').length > 0 ) {
		appChromeHeight = 38 + $('#FooterView').outerHeight(true);
		if ( wrapperDivHeight < viewportHeight  ){
			bufferHeight = viewportHeight - appChromeHeight;
			$('#LoginView').height(  bufferHeight   );
		}
	} else {
		recentlyViewedHeight = $('#RecentlyViewedView').outerHeight(true);
		appChromeHeight = recentlyViewedHeight + $('#MenuView').outerHeight(true) + $('#HeaderView').outerHeight(true) + $('#FooterView').outerHeight(true);
		if ( wrapperDivHeight < viewportHeight  ){
			bufferHeight = viewportHeight - appChromeHeight;
			$('#RecentlyViewedView').height( $('#RecentlyViewedView').height() + bufferHeight   );
		}
	}

	/*Dropdowns - Dropkick*/

	$('#edit-form select, .search-view-1 select, #inline-edit-form select').dropkick();

	$('html').click(function(e) {
		$.each($('td > select'), function(index, value) {
			$(value).dropkick('close');
		});
	});

	/*Checkboxes
	 from: http://webdesign.maratz.com/lab/fancy-checkboxes-and-radio-buttons/jquery.html
	 * */

	function setupCheckboxes( $context ) {

		if ( $('input:checkbox', $context ).length ) {
			$('input:checkbox', $context ).each(function(){
				$(this).parent().removeClass('c_on');
			});
			$('label input:checked', $context ).each(function(){
				$(this).parent('label').addClass('c_on');
		    });
		}

		$('label', $context[0] ).
		    live( 'click', { $inputContext:$(this).content  },
				function( event ){
			        if ( $('input:checkbox', event.data.$inputContext ).length ) {
						$('input:checkbox', event.data.$inputContext ).each(function(){
							$(this).parent().removeClass('c_on');
						});
						$('label input:checked', event.data.$inputContext ).each(function(){
							$(this).parent('label').addClass('c_on');
					    });
					}
			});
	}

    //we're doing that because the multiselect widget isn't generated yet..
    window.setTimeout(
    	function setCheckboxes(){
    		setupCheckboxes( $('#search-form') );
    		setupCheckboxes( $('#app-search') );
    		setupCheckboxes( $('label.hasCheckBox') );
    	},
    1000 );

	$(".overlay-label-field > input").live('focus', function(){
		$(this).prev().fadeOut(100);
	});

	$(".overlay-label-field > input").live('blur', function(){
		if($(this).val() == "") {
			$(this).prev().fadeIn(250);
		}
	});

});

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function f(){ log.history = log.history || []; log.history.push(arguments); if(this.console) { var args = arguments, newarr; args.callee = args.callee.caller; newarr = [].slice.call(args); if (typeof console.log === 'object') log.apply.call(console.log, console, newarr); else console.log.apply(console, newarr);}};

// make it safe to use console.log always
(function(a){function b(){}for(var c="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),d;!!(d=c.pop());){a[d]=a[d]||b;}})
(function(){try{console.log();return window.console;}catch(a){return (window.console={});}}());<|endoftext|>


<commit_before>
const load_stylesheet = reflink => {
    let link = document.createElement( "link" );
    link.href = reflink;
    // link.type = "text/css";
    link.rel = "stylesheet";

    document.getElementsByTagName("head")[0].appendChild(link);
};

if ( !localStorage && localStorage.getItem('mode-direction') === 'rtl' ) {
    load_stylesheet('./css/framework7-rtl.css')
    document.body.classList.add('rtl');
} else {
    load_stylesheet('./css/framework7.css')
}

let obj = !localStorage ? {id: 'theme-light', type: 'light'} : JSON.parse(localStorage.getItem("ui-theme"));
if ( !obj ) {
    obj = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ?
        {id: 'theme-dark', type: 'dark'} : {id: 'theme-light', type: 'light'};
    localStorage && localStorage.setItem("ui-theme", JSON.stringify(obj));
}

document.body.classList.add(`theme-type-${obj.type}`);
<commit_msg>[mobile] fix "rtl" option getting<commit_after>
const load_stylesheet = reflink => {
    let link = document.createElement( "link" );
    link.href = reflink;
    // link.type = "text/css";
    link.rel = "stylesheet";

    document.getElementsByTagName("head")[0].appendChild(link);
};

if ( localStorage && localStorage.getItem('mobile-mode-direction') === 'rtl' ) {
    load_stylesheet('./css/framework7-rtl.css')
    document.body.classList.add('rtl');
} else {
    load_stylesheet('./css/framework7.css')
}

let obj = !localStorage ? {id: 'theme-light', type: 'light'} : JSON.parse(localStorage.getItem("ui-theme"));
if ( !obj ) {
    obj = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ?
        {id: 'theme-dark', type: 'dark'} : {id: 'theme-light', type: 'light'};
    localStorage && localStorage.setItem("ui-theme", JSON.stringify(obj));
}

document.body.classList.add(`theme-type-${obj.type}`);
<|endoftext|>


<commit_before>(function(){

    var $compare_flow,
        $dropdown_wrapper,
        $btn_comparison_cancel,
        $btn_comparison_submit,
        $comparison_option_left,
        $comparison_option_right,
        $comparison_default_right,
        $comparison_result_wrapper;

    var templates = {};

    var entityOne = null,
        entityTwo = null,
        entityOneXHR,
        entityTwoXHR;

    var getCompareOptionHTML = function(data) {
        data.type_name = data.type.id === 1 ? 'school' : 'preschool';
        return templates['compare-option'](data);
    };

    var fetchData = function(entity) {
        var schoolURL = '/schools/school/' + entity.id;
        var endpoints = [
            schoolURL + '/infrastructure',
            schoolURL + '/finance',
            schoolURL + '/demographics'
        ];
        var endpointsParamsString = _(endpoints).map(function(s) {
            return 'endpoints=' + s;
        }).join('&');
        var $deferred = $.Deferred();
        var apiURL = 'merge?' + endpointsParamsString;
        var apiXHR = klp.api.do(apiURL);
        apiXHR.done(function(data) {
            entity.infrastructure_data = data[endpoints[0]];
            entity.finance_data = data[endpoints[1]];
            entity.demographics_data = data[endpoints[2]];
            $deferred.resolve(entity);
        });
        apiXHR.fail(function(err) {
            alert("failed to load school data");
            $deferred.reject(err);
        });
        return $deferred;
    };

    var getContext = function(entity) {
        console.log("get context called with ", entity);
        var context = $.extend(entity, klp.utils.getBoyGirlPercents(entity.num_boys, entity.num_girls));
        var mt = klp.utils.getMTProfilePercents(entity.demographics_data.mt_profile);
        context.mt_profile_percents = mt.percents || {};
        context.total_mt = mt.total;
        context.hasFinanceData = entity.finance_data.sg_amount || entity.finance_data.smg_amount || entity.finance_data.tlm_amount;
        if (context.hasFinanceData) {
            context.finance_percents = klp.utils.getFinancePercents(entity.finance_data);
        }
        context.studentTeacherRatio = klp.utils.getStudentTeacherRatio(entity.infrastructure_data);
        context.hasStudents = entity.num_boys || entity.num_girls;
        return context;
    };

    var getMTProfiles = function(entity1, entity2) {
        var mt1 = entity1.mt_profile_percents || {};
        var mt2 = entity2.mt_profile_percents || {};
        console.log("mt1", mt1, "mt2", mt2);
        var allLanguages = _(_(mt1).keys().concat(_(mt2).keys())).unique();
        console.log("all languages", allLanguages);
        var mts = {};
        _(allLanguages).each(function(lang) {
            mts[lang] = {};
            mts[lang].school1 = {
                'percent': mt1.hasOwnProperty(lang) ? mt1[lang] : 0,
                'total': entity1.demographics_data.mt_profile.hasOwnProperty(lang) ? entity1.demographics_data.mt_profile[lang] : 0
            };
            mts[lang].school2 = {
                'percent': mt2.hasOwnProperty(lang) ? mt2[lang] : 0,
                'total': entity2.demographics_data.mt_profile.hasOwnProperty(lang) ? entity2.demographics_data.mt_profile[lang] : 0
            };
        });
        console.log("mts", mts);
        return mts;
    };

    var getInfrastructureComparison = function(entity1, entity2) {
        var data1 = entity1.infrastructure_data.facilities || {};
        var data2 = entity2.infrastructure_data.facilities || {};
        var topLevelKeys = _(_(data1).keys().concat(_(data2).keys())).unique();
        var allOptions = {};
        _(topLevelKeys).each(function(key) {
            if (key in data1 && key in data2) {
                var arr = _(_(data1[key]).keys().concat(_(data2[key]).keys())).unique();
            } else if (key in data1) {
                var arr = _(data1[key]).keys();
            } else {
                var arr = _(data2[key]).keys();
            }
            allOptions[key] = arr;
        });
        var data = {};
        _(allOptions).each(function(value, key) {
            data[key] = {};
            _(allOptions[key]).each(function(nestedKey) {
                data[key][nestedKey] = {
                    'entity1': getInfrastructureItem(data1, key, nestedKey),
                    'entity2': getInfrastructureItem(data2, key, nestedKey)
                }
            });
        });
        console.log("infrastructure compare data ", data);
        return data;
    };

    var getInfrastructureItem = function(entity, key, nestedKey) {
        if (!entity.hasOwnProperty(key) || !entity[key].hasOwnProperty(nestedKey)) {
            return 'grey';
        }
        var hasInfra = entity[key][nestedKey];
        if (hasInfra) {
            return 'green';
        } else {
            return 'red';
        }
    };

    var selectOptionRight = function(entity) {
        entityTwo = entity;
        entityTwoXHR = fetchData(entity);
        var html = getCompareOptionHTML(entity);
        //console.log("right html", html);
        $dropdown_wrapper.removeClass("show");
        $comparison_option_right.html(html);
        $comparison_default_right.hide();
        $comparison_option_right.removeClass('hide').show();
        show_submit_button();
    };

    var open = function(entity1){
        //e.preventDefault();
        console.log("compare open called with ", entity1);
        if(klp.map){
            klp.map.closePopup();
        }
        entityOne = entity1;
        entityOneXHR = fetchData(entity1);
        var html = getCompareOptionHTML(entity1);
        $comparison_option_left.html(html);
        //klp.place_info.close_place();
        $comparison_result_wrapper.removeClass('show');

        $compare_flow.removeClass("hide");

        setTimeout(function(){
            $compare_flow.removeClass("hide").addClass("show");
        },0);
    };

    var close = function(e){
        e.preventDefault();
        $compare_flow.removeClass("show");
        entityOne = entityTwo = entityOneXHR = entityTwoXHR = null;
        setTimeout(function(){
            $compare_flow.removeClass("show").addClass("hide");
            clear_option_left();
            clear_option_right();
        },300);
    };

    var reset_submit_button = function(){
        $btn_comparison_cancel.addClass("show");
        $btn_comparison_submit.removeClass("show");
        $comparison_result_wrapper.html("").removeClass('show');
    };
    var show_submit_button = function(){
        $btn_comparison_cancel.removeClass("show");
        $btn_comparison_submit.addClass("show");
    };
    var clear_option_left = function(){
        // to do
        reset_submit_button();
    };
    var clear_option_right = function(e){
        if(e){
            e.preventDefault();
        }
        $comparison_option_right.hide();
        $comparison_default_right.show();
        $dropdown_wrapper.removeClass("show");
        entityTwo = entityTwoXHR = null;
        reset_submit_button();
    };
    var show_options_dropdown_right = function(e){
        e.preventDefault();
        $dropdown_wrapper.addClass("show");
    };

    var init = function(){
        $compare_flow = $("#compare_flow");
        $dropdown_wrapper = $('#dropdown_wrapper');

        $btn_comparison_cancel = $compare_flow.find(".js-btn-cancel");
        $btn_comparison_submit = $compare_flow.find(".js-btn-compare");

        $comparison_option_left = $(".js-comparison-option-left");
        $comparison_option_right = $(".js-comparison-option-right");
        $comparison_default_right = $(".js-comparison-default-right");

        $comparison_result_wrapper = $(".js-comparison-result-wrapper");
        $comparison_search = $("#comparison-search-select");
        _(['compare-option', 'comparison-result']).each(function(templateName) {
            var html = $('#tpl-' + templateName).html();
            //console.log("html", templateName, html);
            templates[templateName] = swig.compile(html);
        });

        $comparison_search.select2({
            placeholder: 'Search for schools...',
            minimumInputLength: 3,
            quietMillis: 300,
            allowClear: true,
            ajax: {
                url: "/api/v1/schools/info",
                quietMillis: 300,
                allowClear: true,
                data: function (term, page) {
                    return {
                        search: term,
                        type: entityOne.type.id === 1 ? 'primaryschools' : 'preschools'
                    };
                },
                results: function (data, page) {
                    //console.log("data", data);
                    return {results: data.features};
                }
            },
            formatResult: function(item) {
                return item.name;
                // console.log("item", item);
                // return {
                //     id: item.id,
                //     text: item.name,
                //     data: item
                // }
            },
            formatSelection: function(item) {
                return item.name;
            }
        });

        $comparison_search.on("change", function(e) {
            //console.log("changed event ", e);
            var data = e.added;
            selectOptionRight(data);
        });

        //$(document).on('click', ".js-trigger-compare", open);
        $(document).on('click', ".js-comparison-close", close);
        $(document).on('click', ".js-comparison-clear-left", clear_option_left);
        $(document).on('click', ".js-comparison-clear-right", clear_option_right);
        $(document).on('click', ".js-comparison-show-options-right", show_options_dropdown_right);
        //$(document).on('click', ".js-dropdown-option-right", select_options_right);
        $(document).on('click', ".js-btn-compare", function(e){
            e.preventDefault();
            $.when(entityOneXHR, entityTwoXHR).done(function(data1, data2) {
                //console.log("compare xhrs done ", data1, data2);
                console.log("school1", data1, "school2", data2);
                var school1 = getContext(data1);
                var school2 = getContext(data2);

                var context = {
                    'school1': school1,
                    'school2': school2,
                    'mt_profiles': getMTProfiles(school1, school2),
                    'infrastructure': getInfrastructureComparison(school1, school2)
                };
                var html = templates['comparison-result'](context);
                //console.log('comparison result html', html);
                $comparison_result_wrapper.html(html);
                $comparison_result_wrapper.html(html).addClass('show');
                // setTimeout(function(){
                //     var $selects = $comparison_result_wrapper.find('select');
                //     $selects.easyDropDown();
                // },0);

                setTimeout(function(){
                    init_comparison_charts(context);
                },100);
                //var html = templates['comparison-result'](context);
            });
            $btn_comparison_submit.removeClass("show");
            //var html = klp._tpl.comparison_result();
            //$comparison_result_wrapper.html(html).addClass('show');

        });
    };

    klp.comparison = {
        init: init,
        open: open,
        close: close
    };

    function init_comparison_charts(context) {
        var chart_width = 300;
        var s1 = context.school1;
        var s2 = context.school2;
        console.log("charts init called with ", context);
        var chartOptions = {
            innerSize: '85%',
            width: chart_width,
            height: chart_width
        };

        $('#comparison_boygirlchart_1').boyGirlChart(s1, chartOptions);

        $('#comparison_boygirlchart_2').boyGirlChart(s2, chartOptions);

        if (s1.hasFinanceData) {
            $('#comparison_financechart_1').financeChart(s1.finance_percents, chartOptions);
        }

        if (s2.hasFinanceData) {
            $('#comparison_financechart_2').financeChart(s2.finance_percents, chartOptions);
        }

    }
})();<commit_msg>URL state for comparing two schools<commit_after>(function(){

    var $compare_flow,
        $dropdown_wrapper,
        $btn_comparison_cancel,
        $btn_comparison_submit,
        $comparison_option_left,
        $comparison_option_right,
        $comparison_default_right,
        $comparison_result_wrapper;

    var templates = {};

    var entityOne = null,
        entityTwo = null,
        entityOneXHR,
        entityTwoXHR;

    var getCompareOptionHTML = function(data) {
        data.type_name = data.type.id === 1 ? 'school' : 'preschool';
        return templates['compare-option'](data);
    };

    var fetchData = function(entity) {
        var schoolURL = '/schools/school/' + entity.id;
        var endpoints = [
            schoolURL + '/infrastructure',
            schoolURL + '/finance',
            schoolURL + '/demographics'
        ];
        var endpointsParamsString = _(endpoints).map(function(s) {
            return 'endpoints=' + s;
        }).join('&');
        var $deferred = $.Deferred();
        var apiURL = 'merge?' + endpointsParamsString;
        var apiXHR = klp.api.do(apiURL);
        apiXHR.done(function(data) {
            entity.infrastructure_data = data[endpoints[0]];
            entity.finance_data = data[endpoints[1]];
            entity.demographics_data = data[endpoints[2]];
            $deferred.resolve(entity);
        });
        apiXHR.fail(function(err) {
            alert("failed to load school data");
            $deferred.reject(err);
        });
        return $deferred;
    };

    var getContext = function(entity) {
        console.log("get context called with ", entity);
        var context = $.extend(entity, klp.utils.getBoyGirlPercents(entity.num_boys, entity.num_girls));
        var mt = klp.utils.getMTProfilePercents(entity.demographics_data.mt_profile);
        context.mt_profile_percents = mt.percents || {};
        context.total_mt = mt.total;
        context.hasFinanceData = entity.finance_data.sg_amount || entity.finance_data.smg_amount || entity.finance_data.tlm_amount;
        if (context.hasFinanceData) {
            context.finance_percents = klp.utils.getFinancePercents(entity.finance_data);
        }
        context.studentTeacherRatio = klp.utils.getStudentTeacherRatio(entity.infrastructure_data);
        context.hasStudents = entity.num_boys || entity.num_girls;
        return context;
    };

    var getMTProfiles = function(entity1, entity2) {
        var mt1 = entity1.mt_profile_percents || {};
        var mt2 = entity2.mt_profile_percents || {};
        console.log("mt1", mt1, "mt2", mt2);
        var allLanguages = _(_(mt1).keys().concat(_(mt2).keys())).unique();
        console.log("all languages", allLanguages);
        var mts = {};
        _(allLanguages).each(function(lang) {
            mts[lang] = {};
            mts[lang].school1 = {
                'percent': mt1.hasOwnProperty(lang) ? mt1[lang] : 0,
                'total': entity1.demographics_data.mt_profile.hasOwnProperty(lang) ? entity1.demographics_data.mt_profile[lang] : 0
            };
            mts[lang].school2 = {
                'percent': mt2.hasOwnProperty(lang) ? mt2[lang] : 0,
                'total': entity2.demographics_data.mt_profile.hasOwnProperty(lang) ? entity2.demographics_data.mt_profile[lang] : 0
            };
        });
        console.log("mts", mts);
        return mts;
    };

    var getInfrastructureComparison = function(entity1, entity2) {
        var data1 = entity1.infrastructure_data.facilities || {};
        var data2 = entity2.infrastructure_data.facilities || {};
        var topLevelKeys = _(_(data1).keys().concat(_(data2).keys())).unique();
        var allOptions = {};
        _(topLevelKeys).each(function(key) {
            if (key in data1 && key in data2) {
                var arr = _(_(data1[key]).keys().concat(_(data2[key]).keys())).unique();
            } else if (key in data1) {
                var arr = _(data1[key]).keys();
            } else {
                var arr = _(data2[key]).keys();
            }
            allOptions[key] = arr;
        });
        var data = {};
        _(allOptions).each(function(value, key) {
            data[key] = {};
            _(allOptions[key]).each(function(nestedKey) {
                data[key][nestedKey] = {
                    'entity1': getInfrastructureItem(data1, key, nestedKey),
                    'entity2': getInfrastructureItem(data2, key, nestedKey)
                }
            });
        });
        console.log("infrastructure compare data ", data);
        return data;
    };

    var getInfrastructureItem = function(entity, key, nestedKey) {
        if (!entity.hasOwnProperty(key) || !entity[key].hasOwnProperty(nestedKey)) {
            return 'grey';
        }
        var hasInfra = entity[key][nestedKey];
        if (hasInfra) {
            return 'green';
        } else {
            return 'red';
        }
    };

    var selectOptionRight = function(entity) {
        entityTwo = entity;
        entityTwoXHR = fetchData(entity);
        var html = getCompareOptionHTML(entity);
        //console.log("right html", html);
        $dropdown_wrapper.removeClass("show");
        $comparison_option_right.html(html);
        $comparison_default_right.hide();
        $comparison_option_right.removeClass('hide').show();
        show_submit_button();
    };

    var open = function(entity1){
        //e.preventDefault();
        console.log("compare open called with ", entity1);
        if(klp.map){
            klp.map.closePopup();
        }
        entityOne = entity1;
        entityOneXHR = fetchData(entity1);
        var html = getCompareOptionHTML(entity1);
        $comparison_option_left.html(html);
        //klp.place_info.close_place();
        $comparison_result_wrapper.removeClass('show');

        $compare_flow.removeClass("hide");

        setTimeout(function(){
            $compare_flow.removeClass("hide").addClass("show");
        },0);
    };

    var openFromURL = function(compareString) {
        var entities = compareString.split(",")
        if (entities.length !== 2) {
            //invalid URL Hash, must be like "3537,4219"
            return;
        }
        var $xhr1 = klp.api.do("schools/school/" + entities[0]);
        var $xhr2 = klp.api.do("schools/school/" + entities[1]);
        $.when($xhr1, $xhr2).done(function(school1, school2) {
            open(school1);
            selectOptionRight(school2);
            $btn_comparison_submit.click();
        });
    };

    var close = function(e){
        e.preventDefault();
        $compare_flow.removeClass("show");
        entityOne = entityTwo = entityOneXHR = entityTwoXHR = null;
        setTimeout(function(){
            $compare_flow.removeClass("show").addClass("hide");
            clear_option_left();
            clear_option_right();
        },300);
        klp.router.setHash(null, {compare: null}, {trigger: false});
    };

    var reset_submit_button = function(){
        $btn_comparison_cancel.addClass("show");
        $btn_comparison_submit.removeClass("show");
        $comparison_result_wrapper.html("").removeClass('show');
    };
    var show_submit_button = function(){
        $btn_comparison_cancel.removeClass("show");
        $btn_comparison_submit.addClass("show");
    };
    var clear_option_left = function(){
        // to do
        reset_submit_button();
    };
    var clear_option_right = function(e){
        if(e){
            e.preventDefault();
        }
        $comparison_option_right.hide();
        $comparison_default_right.show();
        $dropdown_wrapper.removeClass("show");
        entityTwo = entityTwoXHR = null;
        reset_submit_button();
    };
    var show_options_dropdown_right = function(e){
        e.preventDefault();
        $dropdown_wrapper.addClass("show");
    };

    var init = function(){
        $compare_flow = $("#compare_flow");
        $dropdown_wrapper = $('#dropdown_wrapper');

        $btn_comparison_cancel = $compare_flow.find(".js-btn-cancel");
        $btn_comparison_submit = $compare_flow.find(".js-btn-compare");

        $comparison_option_left = $(".js-comparison-option-left");
        $comparison_option_right = $(".js-comparison-option-right");
        $comparison_default_right = $(".js-comparison-default-right");

        $comparison_result_wrapper = $(".js-comparison-result-wrapper");
        $comparison_search = $("#comparison-search-select");
        _(['compare-option', 'comparison-result']).each(function(templateName) {
            var html = $('#tpl-' + templateName).html();
            //console.log("html", templateName, html);
            templates[templateName] = swig.compile(html);
        });

        $comparison_search.select2({
            placeholder: 'Search for schools...',
            minimumInputLength: 3,
            quietMillis: 300,
            allowClear: true,
            ajax: {
                url: "/api/v1/schools/info",
                quietMillis: 300,
                allowClear: true,
                data: function (term, page) {
                    return {
                        search: term,
                        type: entityOne.type.id === 1 ? 'primaryschools' : 'preschools'
                    };
                },
                results: function (data, page) {
                    //console.log("data", data);
                    return {results: data.features};
                }
            },
            formatResult: function(item) {
                return item.name;
                // console.log("item", item);
                // return {
                //     id: item.id,
                //     text: item.name,
                //     data: item
                // }
            },
            formatSelection: function(item) {
                return item.name;
            }
        });

        $comparison_search.on("change", function(e) {
            //console.log("changed event ", e);
            var data = e.added;
            selectOptionRight(data);
        });

        //$(document).on('click', ".js-trigger-compare", open);
        $(document).on('click', ".js-comparison-close", close);
        $(document).on('click', ".js-comparison-clear-left", clear_option_left);
        $(document).on('click', ".js-comparison-clear-right", clear_option_right);
        $(document).on('click', ".js-comparison-show-options-right", show_options_dropdown_right);
        //$(document).on('click', ".js-dropdown-option-right", select_options_right);
        $(document).on('click', ".js-btn-compare", function(e){
            e.preventDefault();
            $.when(entityOneXHR, entityTwoXHR).done(function(data1, data2) {
                //console.log("compare xhrs done ", data1, data2);
                console.log("school1", data1, "school2", data2);
                var school1 = getContext(data1);
                var school2 = getContext(data2);

                var context = {
                    'school1': school1,
                    'school2': school2,
                    'mt_profiles': getMTProfiles(school1, school2),
                    'infrastructure': getInfrastructureComparison(school1, school2)
                };
                var html = templates['comparison-result'](context);
                //console.log('comparison result html', html);
                $comparison_result_wrapper.html(html);
                $comparison_result_wrapper.html(html).addClass('show');
                // setTimeout(function(){
                //     var $selects = $comparison_result_wrapper.find('select');
                //     $selects.easyDropDown();
                // },0);
                var urlString = [school1.id, school2.id].join(",")
                //console.log("url string", urlString);
                klp.router.setHash(null, {'compare': urlString}, {trigger: false});
                setTimeout(function(){
                    init_comparison_charts(context);
                },100);
                //var html = templates['comparison-result'](context);
            });
            $btn_comparison_submit.removeClass("show");
            //var html = klp._tpl.comparison_result();
            //$comparison_result_wrapper.html(html).addClass('show');

        });
        klp.router.events.on('hashchange:compare', function(e, params) {
            console.log("change params", params);
            var changedCompare = params.changed.compare;
            if (changedCompare.newVal) {
                openFromURL(changedCompare.newVal);
            } else {
                close();
            }
        });
    };

    klp.comparison = {
        init: init,
        open: open,
        close: close
    };

    function init_comparison_charts(context) {
        var chart_width = 300;
        var s1 = context.school1;
        var s2 = context.school2;
        console.log("charts init called with ", context);
        var chartOptions = {
            innerSize: '85%',
            width: chart_width,
            height: chart_width
        };

        $('#comparison_boygirlchart_1').boyGirlChart(s1, chartOptions);

        $('#comparison_boygirlchart_2').boyGirlChart(s2, chartOptions);

        if (s1.hasFinanceData) {
            $('#comparison_financechart_1').financeChart(s1.finance_percents, chartOptions);
        }

        if (s2.hasFinanceData) {
            $('#comparison_financechart_2').financeChart(s2.finance_percents, chartOptions);
        }

    }
})();<|endoftext|>


<commit_before>module.exports = function (processes, schema) {
    'use strict';
    const ec = require('./error-code');
    const parse = require('co-body');
    const httpStatus = require('http-status');

    return {
        update: update,
        create: create
    };

    /////////////////////////

    function* update(next) {
        let process = yield parse(this);
        let rv = yield processes.update(this.params.process_id, process);
        if (rv.error) {
            this.throw(httpStatus.BAD_REQUEST, rv.error);
        }
        this.body = rv.val;
        yield next;

    }

    // create creates a new process and associated dependencies.
    // It validates the submitted entry and enters in default
    // values for optional missing attributes.
    function *create(next) {
        try {
            let process = yield parse(this);
            process.project_id = this.params.project_id;
            process.owner = this.reqctx.user.id;
            //process = prepareProcess(process);
            //yield validateProcess(process);
            let inserted = yield processes.create(process);
            this.status = 200;
            this.body = inserted;
            yield next;
        } catch (err) {
            console.log(err, err.stack.split("\n"));
            let e = ec(err);
            this.status = e.status();
            this.body = e.error();
        }

        //////////////////////

        /**
         * validateProcess validates the process, settings, files, samples
         * measurements. Aborts if any one of these items doesn't validate.
         *
         * @param {Process} process - The process as defined by the Process schema.
         */
        function *validateProcess(process) {
            yield schema.processes.validateAsync(process);
            yield *validateSettings(process.setup.settings);
            yield *validateFiles(process.project_id, process.files_created, process.setup.files);
            yield *validateSamples(process.samples_created, process.samples_transformed);
            yield *validateMeasurements(process.measurements_taken);
        }

        /**
         * validateSettings validates the settings in a process. The settings
         * is validated against the Settings schema.
         *
         * @param {Array} settings - The settings as defined the by Settings schema.
         */
        function *validateSettings(settings) {
            for (let i = 0; i < settings.length; i++) {
                yield schema.settings.validateAsync(settings[i]);
            }
        }

        /**
         * validateFiles validates the files in a process. Each file is
         * is an object defined by the Files schema.
         * @param {String} projectID - project files belong to.
         * @param{Array} files_created - Files created by this process.
         * @param{Array} files_used = Files used (input into) by this process.
         */
        function *validateFiles(projectID, files_created, files_used) {
            let filesList = "";
            let reason = {
                rule: 'validateFiles',
                what: '',
                expected: `all files in ${filesList} to be in project`
            };

            let count = yield schema.model.files.countInProject(files_created, projectID);
            if (count != files_created.length) {
                filesList = files_created;
                throw new Error(reason);
            }

            count = yield schema.model.files.countInProject(files_used, projectID);
            if (count != files_used.length) {
                filesList = files_used;
                throw new Error(reason);
            }
        }

        /**
         * Validates the samples for a process.
         *
         * @param{Array} samplesCreated - The samples created by this process
         * @param{Array} samplesTransformed = The samples transformed by this process
         */
        function *validateSamples(samplesCreated, samplesTransformed) {
            for (let i = 0; i < samplesCreated.length; i++) {
                yield schema.samples.validateAsync(samplesCreated[i]);
            }

            let model = schema.model.samples;
            for (let i = 0; i < samplesTransformed.length; i++) {
                yield schema.transformedSamples.validateAsync(samplesTransformed[i]);

                // validate the attribute ids for the transformed samples
                let shares = samplesTransformed[i].shares;
                let uses = samplesTransformed[i].uses;
                let asetID = samplesTransformed[i].attribute_set_id;

                let count = yield model.countAttributesInSample(asetID, shares);
                if (count !== shares.length) {
                    throw new Error('unknown attributes in shares');
                }

                count = yield model.countAttributesInSample(asetID, uses);
                if (count !== uses.length) {
                    throw new Error('unknown attributes in uses');
                }
            }
        }

        /**
         * Validates the measurements as defined by the Measurements schema.
         *
         * @param{Array} measurements - A measurements taken by this process.
         */
        function *validateMeasurements(measurements) {
            for (let i = 0; i < measurements.length; i++) {
                yield schema.measurements.validateAsync(measurements[i]);
            }
        }

    }

    function prepareProcess(process) {
        schema.processes.stripNonSchemaAttrs(process);
        schema.processes.addDefaultsToTarget(process);

        // Add owner and project to created samples
        process.samples_created.forEach(function (s) {
            s.owner = process.owner;
            s.project_id = process.project_id;
        });
        return process;
    }
};
<commit_msg>stub out the get call for processes.<commit_after>module.exports = function (processes, schema) {
    'use strict';
    const ec = require('./error-code');
    const parse = require('co-body');
    const httpStatus = require('http-status');

    return {
        update: update,
        create: create,
        get: get
    };

    /////////////////////////

    function* update(next) {
        let process = yield parse(this);
        let rv = yield processes.update(this.params.process_id, process);
        if (rv.error) {
            this.throw(httpStatus.BAD_REQUEST, rv.error);
        }
        this.body = rv.val;
        yield next;

    }

    function* get(next) {
        yield next;
    }

    // create creates a new process and associated dependencies.
    // It validates the submitted entry and enters in default
    // values for optional missing attributes.
    function *create(next) {
        try {
            let process = yield parse(this);
            process.project_id = this.params.project_id;
            process.owner = this.reqctx.user.id;
            //process = prepareProcess(process);
            //yield validateProcess(process);
            let inserted = yield processes.create(process);
            this.status = 200;
            this.body = inserted;
            yield next;
        } catch (err) {
            console.log(err, err.stack.split("\n"));
            let e = ec(err);
            this.status = e.status();
            this.body = e.error();
        }

        //////////////////////

        /**
         * validateProcess validates the process, settings, files, samples
         * measurements. Aborts if any one of these items doesn't validate.
         *
         * @param {Process} process - The process as defined by the Process schema.
         */
        function *validateProcess(process) {
            yield schema.processes.validateAsync(process);
            yield *validateSettings(process.setup.settings);
            yield *validateFiles(process.project_id, process.files_created, process.setup.files);
            yield *validateSamples(process.samples_created, process.samples_transformed);
            yield *validateMeasurements(process.measurements_taken);
        }

        /**
         * validateSettings validates the settings in a process. The settings
         * is validated against the Settings schema.
         *
         * @param {Array} settings - The settings as defined the by Settings schema.
         */
        function *validateSettings(settings) {
            for (let i = 0; i < settings.length; i++) {
                yield schema.settings.validateAsync(settings[i]);
            }
        }

        /**
         * validateFiles validates the files in a process. Each file is
         * is an object defined by the Files schema.
         * @param {String} projectID - project files belong to.
         * @param{Array} files_created - Files created by this process.
         * @param{Array} files_used = Files used (input into) by this process.
         */
        function *validateFiles(projectID, files_created, files_used) {
            let filesList = "";
            let reason = {
                rule: 'validateFiles',
                what: '',
                expected: `all files in ${filesList} to be in project`
            };

            let count = yield schema.model.files.countInProject(files_created, projectID);
            if (count != files_created.length) {
                filesList = files_created;
                throw new Error(reason);
            }

            count = yield schema.model.files.countInProject(files_used, projectID);
            if (count != files_used.length) {
                filesList = files_used;
                throw new Error(reason);
            }
        }

        /**
         * Validates the samples for a process.
         *
         * @param{Array} samplesCreated - The samples created by this process
         * @param{Array} samplesTransformed = The samples transformed by this process
         */
        function *validateSamples(samplesCreated, samplesTransformed) {
            for (let i = 0; i < samplesCreated.length; i++) {
                yield schema.samples.validateAsync(samplesCreated[i]);
            }

            let model = schema.model.samples;
            for (let i = 0; i < samplesTransformed.length; i++) {
                yield schema.transformedSamples.validateAsync(samplesTransformed[i]);

                // validate the attribute ids for the transformed samples
                let shares = samplesTransformed[i].shares;
                let uses = samplesTransformed[i].uses;
                let asetID = samplesTransformed[i].attribute_set_id;

                let count = yield model.countAttributesInSample(asetID, shares);
                if (count !== shares.length) {
                    throw new Error('unknown attributes in shares');
                }

                count = yield model.countAttributesInSample(asetID, uses);
                if (count !== uses.length) {
                    throw new Error('unknown attributes in uses');
                }
            }
        }

        /**
         * Validates the measurements as defined by the Measurements schema.
         *
         * @param{Array} measurements - A measurements taken by this process.
         */
        function *validateMeasurements(measurements) {
            for (let i = 0; i < measurements.length; i++) {
                yield schema.measurements.validateAsync(measurements[i]);
            }
        }

    }

    function prepareProcess(process) {
        schema.processes.stripNonSchemaAttrs(process);
        schema.processes.addDefaultsToTarget(process);

        // Add owner and project to created samples
        process.samples_created.forEach(function (s) {
            s.owner = process.owner;
            s.project_id = process.project_id;
        });
        return process;
    }
};
<|endoftext|>


<commit_before>/*
 * This file is part of the hyyan/woo-poly-integration plugin.
 * (c) Hyyan Abo Fakher <hyyanaf@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

(function ($, document, HYYAN_WPI_VARIABLES) {

    /**
     * Construct variables
     *
     * @param {jQuery} $
     * @param {document} document
     * @param {object} data
     *
     * @returns {Variables}
     */
    var Variables = function ($, document, data) {
        this.$ = $;
        this.document = document;
        this.data = data;
        this._dialog = this._createDialog();
    };

    Variables.prototype = {
        /** Constructor */
        constructor: Variables,
        init: function () {

            var self = this;
            $('#post_lang_choice').change(function () {
                self.shouldAlert();
            });
            $('#product-type').change(function () {
                self.shouldAlert();
            });

        }
        /**
         * Check if we should alert the user
         *
         * @returns {Boolean}
         */
        , shouldAlert: function () {
            var type = this.getCurrentProduct();
            var lang = this.getCurrentLanguage();
            if (type === 'variable' && lang !== this.data['defaultLang']) {
                this._dialog.dialog('open');
                /* Disable Saving */
                this._changeSaveBoxState(true);
                return true;
            }
            this._changeSaveBoxState(false);
            return false;
        }
        /**
         * Get current product language
         *
         * @returns {String}
         */
        , getCurrentLanguage: function () {
            return this.$('#post_lang_choice').val();
        }
        /**
         * Get current product type
         *
         * @returns {string}
         */
        , getCurrentProduct: function () {
            return this.$('#product-type').val();
        }
        /**
         * Change the state of save box from disable to enable and vs
         *
         * @param {boolean} enable
         */
        , _changeSaveBoxState: function (enable) {
            this.$('#submitdiv *').prop('disabled', enable);
        }
        /**
         * Create dialog
         *
         * @returns {objet}
         */
        , _createDialog: function () {

            /* This variable */
            var self = this;

            /* Fix the z-index */
            this.$('')
                    .appendTo($('head'));

            /* Create dialog */
            var dialog = this.$("
")
                    .html('
' + self.data['content'] + '
')
                    .attr('title', self.data['title'])
                    .appendTo("body");

            dialog.dialog({
                dialogClass: "wp-dialog",
                autoOpen: false,
                modal: true,
                width: 400,
                height: 250,
                position: {
                    my: "center",
                    at: "center"
                },
                buttons: [
                    {
                        text: 'Got It',
                        click: function () {
                            $(this).dialog('close');
                        }
                    }
                ]
            });

            return dialog;
        }
    };

    // bootstrap
    $(document).ready(function ($) {
        new Variables($, document, HYYAN_WPI_VARIABLES).init();
    });

})(jQuery, document, HYYAN_WPI_VARIABLES);
<commit_msg>Update Variables.js<commit_after>/*
 * This file is part of the hyyan/woo-poly-integration plugin.
 * (c) Hyyan Abo Fakher <hyyanaf@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

(function ($, document, HYYAN_WPI_VARIABLES) {

    /**
     * Construct variables
     *
     * @param {jQuery} $
     * @param {document} document
     * @param {object} data
     *
     * @returns {Variables}
     */
    var Variables = function ($, document, data) {
        this.$ = $;
        this.document = document;
        this.data = data;
        this._dialog = this._createDialog();
    };

    Variables.prototype = {
        /** Constructor */
        constructor: Variables,
        init: function () {

            var self = this;
            $('#post_lang_choice').on('change', function () {
                self.shouldAlert();
            });
            $('#product-type').on('change', function () {
                self.shouldAlert();
            });

        }
        /**
         * Check if we should alert the user
         *
         * @returns {Boolean}
         */
        , shouldAlert: function () {
            var type = this.getCurrentProduct();
            var lang = this.getCurrentLanguage();
            if (type === 'variable' && lang !== this.data['defaultLang']) {
                this._dialog.dialog('open');
                /* Disable Saving */
                this._changeSaveBoxState(true);
                return true;
            }
            this._changeSaveBoxState(false);
            return false;
        }
        /**
         * Get current product language
         *
         * @returns {String}
         */
        , getCurrentLanguage: function () {
            return this.$('#post_lang_choice').val();
        }
        /**
         * Get current product type
         *
         * @returns {string}
         */
        , getCurrentProduct: function () {
            return this.$('#product-type').val();
        }
        /**
         * Change the state of save box from disable to enable and vs
         *
         * @param {boolean} enable
         */
        , _changeSaveBoxState: function (enable) {
            this.$('#submitdiv *').prop('disabled', enable);
        }
        /**
         * Create dialog
         *
         * @returns {objet}
         */
        , _createDialog: function () {

            /* This variable */
            var self = this;

            /* Fix the z-index */
            this.$('')
                    .appendTo($('head'));

            /* Create dialog */
            var dialog = this.$("
")
                    .html('
' + self.data['content'] + '
')
                    .attr('title', self.data['title'])
                    .appendTo("body");

            dialog.dialog({
                dialogClass: "wp-dialog",
                autoOpen: false,
                modal: true,
                width: 400,
                height: 250,
                position: {
                    my: "center",
                    at: "center"
                },
                buttons: [
                    {
                        text: 'Got It',
                        click: function () {
                            $(this).dialog('close');
                        }
                    }
                ]
            });

            return dialog;
        }
    };

    // bootstrap
    $(function() {
        new Variables($, document, HYYAN_WPI_VARIABLES).init();
    });

})(jQuery, document, HYYAN_WPI_VARIABLES);
<|endoftext|>


<commit_before>module.exports = function(model) {
    return {
        mustExist: mustExist,
        mustNotExist: mustNotExist
    };

    function mustExist(what, modelName, done) {
        'use strict';
        model[modelName].get(what).then(function(value) {
            let error = null;
            if (!value) {
                error = {
                    rule: 'mustExist',
                    actual: what,
                    expected: 'did not find ' + what + ' in model'
                };
            }
            done(error);
        });
    }

    function mustNotExist(what, spec, done) {
        'use strict';

        let pieces = spec.split(':'),
            modelName = pieces[0],
            modelIndex = pieces[1];
        model[modelName].get(what, modelIndex).then(function(value) {
            let error = null;
            if (value) {
                // found a match, when we shouldn't have
                error = {
                    rule: 'mustNotExist',
                    actual: what,
                    expected: `found ${what} in model`
                };
            }
            done(error);
        });
    }
};
<commit_msg>Add rules for validating property schema _type and units.<commit_after>var _ = require('lodash');
module.exports = function(model) {
    'use strict';

    let propertyTypes = [
        'number',
        'string',
        'histogram',
        'composition'
    ];

    let propertyUnits = [
        'mm',
        'm',
        'c',
        'f'
    ];

    return {
        mustExist: mustExist,
        mustNotExist: mustNotExist,
        isValidPropertyType: isValidPropertyType,
        isValidUnit: isValidUnit
    };

    // mustExist looks up an entry in the named table by id. If
    // the entry doesn't exist it returns an error.
    function mustExist(what, modelName, done) {
        model[modelName].get(what).then(function(value) {
            let error = null;
            if (!value) {
                error = {
                    rule: 'mustExist',
                    actual: what,
                    expected: 'did not find ' + what + ' in model'
                };
            }
            done(error);
        });
    }

    // mustNotExist looks up an entry in the named table by the named
    // index. If the entry exists it returns an error.
    function mustNotExist(what, spec, done) {
        let pieces = spec.split(':'),
            modelName = pieces[0],
            modelIndex = pieces[1];
        model[modelName].get(what, modelIndex).then(function(value) {
            let error = null;
            if (value) {
                // found a match, when we shouldn't have
                error = {
                    rule: 'mustNotExist',
                    actual: what,
                    expected: `found ${what} in model`
                };
            }
            done(error);
        });
    }

    function isValidPropertyType(what, _ignore) {
        let invalid = {
            rule: 'isValidPropertyType',
            actual: what,
            expected: `type to be one of ${propertyTypes}`
        };
        return _.indexOf(propertyTypes, what) === -1 ? invalid : null;
    }

    function isValidUnit(what, _ignore) {
        let invalid = {
            rule: 'isValidUnit',
            actual: what,
            expected: `units to be one of ${propertyUnits}`
        };
        return _.indexOf(propertyUnits, what) === -1 ? invalid : null;
    }
};
<|endoftext|>


<commit_before>/* global ga */
/* eslint no-underscore-dangle: off, no-var: off, vars-on-top: off */

function loadAnalytics() {
  var idaScript = document.createElement('script');
  idaScript.src = '//www.ibm.com/common/stats/ida_stats.js';
  document.head.appendChild(idaScript);
}

window.addEventListener('load', loadAnalytics);
<commit_msg>Update analytics.js<commit_after>/* eslint no-underscore-dangle: off, no-var: off, vars-on-top: off */

function loadAnalytics() {
  var idaScript = document.createElement('script');
  idaScript.src = '//www.ibm.com/common/stats/ida_stats.js';
  document.head.appendChild(idaScript);
}

window.addEventListener('load', loadAnalytics);
<|endoftext|>


<commit_before>var constantModule = angular.module('uchiwa.constants', []);

// Settings
constantModule.constant('settings', {
  date: 'yyyy-MM-dd HH:mm:ss',
  hideSilenced: false,
  theme: 'default'
});

// Version
constantModule.constant('version', {
  uchiwa: '0.3.4'
});
<commit_msg>Release 0.4.0.beta<commit_after>var constantModule = angular.module('uchiwa.constants', []);

// Settings
constantModule.constant('settings', {
  date: 'yyyy-MM-dd HH:mm:ss',
  hideSilenced: false,
  theme: 'default'
});

// Version
constantModule.constant('version', {
  uchiwa: '0.4.0.beta'
});
<|endoftext|>


<commit_before>(function ($, _, Backbone, app) {
    "use strict";

    app.container = app.container || {};
    app.container.anchor = app.container.anchor || "body";
    app.initializers.push(function (next) {
        /**
         * Allow users to add their own routable views. When creating view
         * the options are passed to the constructor, which contain the
         * arguments object passed to the callback function.
         *
         * @param route the route (passed to backbone.js)
         * @param name the name of the route
         * @param creator the method to be called to create the view
         */
        app.container.route = function(route, name, creator){
            app.router.route(route, name, function() {
                var childSelector = app.container.anchor + ' > *',
                    headerSelector = app.container.anchor + ' > header',
                    $children = $(childSelector),
                    args = Array.prototype.slice.call(arguments);

                if (app.currentView) {
                    if (app.currentView.close) {
                        app.currentView.close();
                    }

                    delete app.currentView;
                }

                $children.each(function(idx, child) {
                    var $child = $(child),
                        name = $child.prop("tagName");

                    if ('HEADER' !== name && 'FOOTER' !== name && 'SCRIPT' !== name) {
                        $child.remove();
                    }
                });

                args.push(function(err, view) {
                    if (err) {
                        return app.error(err);
                    }

                    var rendered = view.render();

                    app.currentView = view;

                    $(headerSelector).after(rendered.el);

                });

                creator.apply(this, args);

                return false;
            });
        };

        return next();
        // app.router.navigate("order/0", {trigger:true});
    });
})($, _, Backbone, window["jolira-app"]);
<commit_msg>add a parameter to the container that allows passing and additional parameter.<commit_after>(function ($, _, Backbone, app) {
    "use strict";

    app.container = app.container || {};
    app.container.anchor = app.container.anchor || "body";
    app.initializers.push(function (next) {
        /**
         * Allow users to add their own routable views. When creating view
         * the options are passed to the constructor, which contain the
         * arguments object passed to the callback function.
         *
         * @param route the route (passed to backbone.js)
         * @param name the name of the route
         * @param creator the method to be called to create the view
         * @param router this parameter allows us to override the router function
         *        to be called. If this method is not passed, app.router.route
         *        is called.
         */
        app.container.route = function(route, name, creator, router){
            router = router || app.router.route;

            router(route, name, function() {
                var childSelector = app.container.anchor + ' > *',
                    headerSelector = app.container.anchor + ' > header',
                    $children = $(childSelector),
                    args = Array.prototype.slice.call(arguments);

                if (app.currentView) {
                    if (app.currentView.close) {
                        app.currentView.close();
                    }

                    delete app.currentView;
                }

                $children.each(function(idx, child) {
                    var $child = $(child),
                        name = $child.prop("tagName");

                    if ('HEADER' !== name && 'FOOTER' !== name && 'SCRIPT' !== name) {
                        $child.remove();
                    }
                });

                args.push(function(err, view) {
                    if (err) {
                        return app.error(err);
                    }

                    var rendered = view.render();

                    app.currentView = view;

                    $(headerSelector).after(rendered.el);

                });

                creator.apply(this, args);

                return false;
            });
        };

        return next();
        // app.router.navigate("order/0", {trigger:true});
    });
})($, _, Backbone, window["jolira-app"]);
<|endoftext|>


<commit_before>
var mySpeed = 8;
var SHEEP_SPEED = 8;
var WOLF_SPEED = 4;
var MOVE_FRAME_COUNT_LIMIT = 3;
var pixel = 64;
var DIRS = ['up', 'right', 'down', 'left'];
var DX   = [0, 1, 0, -1];
var DY   = [-1, 0, 1, 0];
var sheepId;
var isInvincible;
var isEnded;
var isTimeLimit;
var wolfImageIndex = 0;

function initPlayScene(userObj, mapObj, normalItemObj, powerItemObj, timeLimit, initScore, game) {
    isInvincible = false;
    isEnded = false;
    isTimeLimit = false;

    //start the music
	game.assets[startSe].play();
    bgmController.stop();
    bgmController.play(gameBgm);

	var scene = new Scene();
	//add scene environment
	var bg = new Sprite(1920, 1080);
	bg.image = game.assets[gameImg];
	scene.addChild(bg);

	//left side
	var hightScoreTxt = new Label("Highest score :");
	hightScoreTxt.font = `36px ${normalFont}`;
	hightScoreTxt.moveTo(60,170);
	scene.addChild(hightScoreTxt);
	var currentScoreTxt = new Label("current score : " + ('00000' + initScore).slice(-5));
	currentScoreTxt.font = `36px ${normalFont}`;
	currentScoreTxt.moveTo(60,350);
	scene.addChild(currentScoreTxt);

	var timeTxt = new Label("time : " + timeLimit / 1000);
	timeTxt.font = `36px ${normalFont}`;
	timeTxt.moveTo(60,530);
	scene.addChild(timeTxt);
    var timeIntervalId = setInterval(() => {
        if (isEnded) {
            clearInterval(timeIntervalId);
        }

        if (isTimeLimit) {
            timeLimit = 0;
        } else if (!isEnded) {
            timeLimit = Math.max(0, timeLimit - 1000);
        }

        timeTxt.text = "time : " + timeLimit / 1000;
    }, 1000);

	var map = initDynamicMap(game,mapObj);
	scene.addChild(map);

    //init all item before character
    var normalItemList = {};
    for(let i=0;i<normalItemObj.length;i++){
        //init item obj and assign to list for checking when sheep hit
        const item = initNormalItem(game,normalItemObj[i]);
        normalItemList[normalItemObj[i].id] = item;
        scene.addChild(item);
    }

    var powerItemList = {};
    for(let i=0;i<powerItemObj.length;i++){
        //init item obj and assign to list for checking when sheep hit
        const item = initPowerItem(game,powerItemObj[i]);
        powerItemList[powerItemObj[i].id] = item;
        scene.addChild(item);
    }

	//set right side screen position
	var fixPosition = [[1515,90], [1515,275],[1515,455],[1515,640],[1515,825]];

	//init all character
	var character = {};
	for(let i=0;i<userObj.length;i++){
		var objId = userObj[i].id;
		if(myId == objId){
			//set speed every move
            mySpeed = userObj[i].isEnemy ? WOLF_SPEED : SHEEP_SPEED;
		}
		character[objId] = initPlayer(game,map,socket,userObj[i]);
        if(myId == objId) {
            initPlayerMove(game, map, socket, character, userObj, mapObj, normalItemObj, normalItemList, powerItemObj, powerItemList);
        }
		// Add elements to scene.
    	scene.addChild(character[objId]);

    	//set sheep id for killing
    	if(!userObj[i].isEnemy){
			sheepId = objId;
		}
	}

	wolfImageIndex = 0;
	var cProfile = {};
	var deathFrame = {};
	for(let i=0;i<userObj.length;i++){
		var objId = userObj[i].id;
		//set right side profile
		var player = new Sprite(pixel, pixel);
	    player.image = game.assets[charImg];
        player.frame = userObj[i].imageIndex * 3;

	    deathFrame[objId] = userObj[i].imageIndex * 3 + 2;

	    //starting point
	    player.scale(3);
	    player.x = fixPosition[i][0] + 52;
	    player.y = fixPosition[i][1] + 25;

	    cProfile[objId] = player;

	    scene.addChild(cProfile[objId]);

	    var nameTag = "AI";
	    if(null!=userObj[i].user){
	    	nameTag = userObj[i].user.username;
	    }
	    var usernameTag = new Label(nameTag);
	    usernameTag.font = `36px ${normalFont}`;
	    usernameTag.moveTo(fixPosition[i][0] + 50 ,fixPosition[i][1] + 120);
	    scene.addChild(usernameTag);
	    //end right side profile
	}

    socket.on('movePlayer', (req) => {
    	game.assets[footStepsSe].play();

        const {x, y} = req.player.coordinate;
        var targetUser = userObj.find(x => x.id === req.player.id);
        var objId = req.player.id;

        //rotate head before change position
        //rotate character
        if(character[objId].x<x){ //right
        	character[objId].scaleX  = -1;
        	character[objId].rotation = 0;
        }else if(character[objId].x>x){ // left
        	character[objId].scaleX  = 1;
        	character[objId].rotation = 0;
        }else if(character[objId].y<y){ // down
        	character[objId].scaleX  = -1;
        	character[objId].rotation = 90;
        }else if(character[objId].y>y){ // up
        	character[objId].scaleX  = -1;
        	character[objId].rotation = 270;
        }

        const idx = targetUser.imageIndex * 3;

        if (targetUser.isAI) {
            character[objId].frame = character[objId].frame === idx ? idx + 1 : idx;
        } else {
            if (++targetUser.moveFrameCount > MOVE_FRAME_COUNT_LIMIT) {
                targetUser.moveFrameCount = 0;
                character[objId].frame = character[objId].frame === idx ? idx + 1 : idx;
            }
        }

        //change position
        character[objId].x = x;
        character[objId].y = y;
    });

    socket.on('killSheep', (req) => {
        const sheep = userObj.find(x => !x.isEnemy);
        sheep.isAlive = false;
        scene.removeChild(character[sheep.id]);

    	game.assets[sheepDeathSe].play();

    	addDeathOnProfile(game,scene,cProfile,sheep.id,deathFrame);
    });

    socket.on('killWolf', (req) => {
        const wolf = userObj.find(x => x.id === req.player.id);
        wolf.isAlive = false;
        scene.removeChild(character[wolf.id]);
        game.assets[wolfDeathSe].play();

        //gray profile by sprite overlay
        //170 x 160
        addDeathOnProfile(game,scene,cProfile,wolf.id,deathFrame);
    });

    socket.on('respawnWolf', (req) => {
        const wolf = userObj.find(x => x.id === req.player.id);
        wolf.isAlive = true;
        wolf.coordinate = req.player.coordinate;
        character[wolf.id].x = wolf.coordinate.x;
        character[wolf.id].y = wolf.coordinate.y;
        scene.addChild(character[wolf.id]);
    });

    socket.on('takeNormalItem', (req) => {
        const targetItemObj = normalItemObj.find(x => x.id === req.normalItem.id);
        targetItemObj.enabled = false;

        const item = normalItemList[targetItemObj.id];
        scene.removeChild(item);
        game.assets[foodSe].play();
    });

    socket.on('takePowerItem', (req) => {
        const targetItemObj = powerItemObj.find(x => x.id === req.powerItem.id);
        targetItemObj.enabled = false;

        const item = powerItemList[targetItemObj.id];
        scene.removeChild(item);
        game.assets[powerUpSe].play();
    });

    socket.on('startInvincible', () => {
        if (isEnded) { return; }

        isInvincible = true;
        // TODO: enable super mode image

        bgmController.stop();
        bgmController.play(powerup1Bgm);
    });

    socket.on('endInvincible', () => {
        if (isEnded) { return; }

        isInvincible = false;
        // TODO: disable super mode image

        bgmController.stop();
        bgmController.play(gameBgm);
    });

    socket.on('endGame', (req) => {
        isEnded = true;
        isTimeLimit = req.isTimeLimit;
        game.assets[gameBgm].stop();
        game.assets[endSe].play();

        goToResultScene(game, req.game.score);
    });

    socket.on('updateScore', (scores) => {
        currentScoreTxt.text = "current score : " + ('00000' + scores.score).slice(-5);
    });

    game.replaceScene(scene);
}

function initPlayer(game,map,socket,userObj){
	 // Player for now will be a pixel x pixel.
    var player = new Sprite(pixel, pixel);
    player.image = game.assets[charImg];

    //count for change frame
    userObj.moveFrameCount = 0;

    //starting point
    player.x = userObj.coordinate.x;
    player.y = userObj.coordinate.y;

    //if enemy = wolf
    if(userObj.isEnemy){
        // wolf
        userObj.imageIndex = wolfImageIndex % 4 + 1;
        ++wolfImageIndex;
    }else{
        // sheep
        userObj.imageIndex = 0;
    }

    player.frame = userObj.imageIndex * 3;

    return player;
}

function initPlayerMove(game, map, socket, character, userObj, mapObj, normalItemObj, normalItemList, powerItemObj, powerItemList)  {
    const myUserObj = userObj.find(x => x.id === myId);
    const myCharacter = character[myId];

    // Let player move within bounds.
    myCharacter.addEventListener(Event.ENTER_FRAME, function () {
        // First move the player. If the player's new location has resulted
        // in the player being in a "hit" zone, then back the player up to
        // its original location. Tweak "hits" by "offset" pixels.

        let {x, y} = myCharacter;
        DIRS.forEach((dir, i) => {
            if (!game.input[dir]) { return; }
            x += DX[i] * mySpeed;
            y += DY[i] * mySpeed;

            //check the wall
            if (!myHitTest(map, x, y)) {
            	//check for warp portal at the border of map
            	warpPortal(x, y, mapObj);
            }else{
            	//smooth turn
            	var autoMovePixcel = mySpeed;
            	var xGhost = x-gameOffSetX;
            	var yGhost = y-gameOffSetY;
            	for(var j=(pixel/(-2*autoMovePixcel));(j*autoMovePixcel)<(pixel/2);j++){
            		if(j!=0){
            			if(DX[i] != 0){ //user go right or left
            				yGhost = y + (autoMovePixcel*j) - gameOffSetY; //DX not zero change Y
            			}else{//user go up and down DY not zero change X
            				xGhost = x + (autoMovePixcel*j) - gameOffSetX;
            			}
	            		if(!(map.hitTest(xGhost, yGhost) ||
	    	                    map.hitTest(xGhost + pixel - 1, yGhost) ||
	    	                    map.hitTest(xGhost, yGhost + pixel - 1) ||
	    	                    map.hitTest(xGhost + pixel - 1, yGhost + pixel - 1))){

	            			if(DX[i] != 0){
	            				x -= DX[i] * mySpeed; //return to x old position
	            				(j<0)?y -= 1 * mySpeed:y += 1 * mySpeed;
	            			}else{
	            				y -= DY[i] * mySpeed;
	            				(j<0)?x -= 1 * mySpeed:x += 1 * mySpeed;
	            			}
	            			j = 5;
		                	warpPortal(x, y, mapObj);
	            		}
            		}
            	}
            	//end smooth turn
            }
        });

        // kill by sheepId
        if (myId === sheepId && myUserObj.isAlive) {
            for (let i = 0; i < userObj.length; i++) {
                if (userObj[i] === myUserObj) { continue; }
                if (!userObj[i].isAlive) { continue; }
                if (character[userObj[i].id].intersect(myCharacter)) {
                    if (isInvincible) {
                        socket.killWolf({wolfId: userObj[i].id});
                        userObj[i].isAlive = false;
                    } else {
                    	//sheep invincible for test
                        /*socket.killSheep();
                        myUserObj.isAlive = false;
                        break;*/
                    }
                }
            }

            //check sheep intersect with item
            for(let i=0;i<normalItemObj.length;i++){
                if (!normalItemObj[i].enabled) { continue; }

                const item = normalItemList[normalItemObj[i].id];
                if(myCharacter.intersect(item)){
                    normalItemObj[i].enabled = false;
                    socket.takeNormalItem({itemId: normalItemObj[i].id});
                }
            }

            for(let i=0;i<powerItemObj.length;i++){
                if (!powerItemObj[i].enabled) { continue; }

                const item = powerItemList[powerItemObj[i].id];
                if(myCharacter.intersect(item)){
                    powerItemObj[i].enabled = false;
                    socket.takePowerItem({itemId: powerItemObj[i].id});
                }
            }
        }
    });
}

function myHitTest (map, x, y) {
	x -= gameOffSetX;
	y -= gameOffSetY;
    return map.hitTest(x, y) ||
        map.hitTest(x + pixel - 1, y) ||
        map.hitTest(x, y + pixel - 1) ||
        map.hitTest(x + pixel - 1, y + pixel - 1);
}

function warpPortal(x, y, mapObj){
	var mapXLimit = (mapObj.width * pixel)-(pixel/2) + gameOffSetX;
	var mapYLimit = (mapObj.height * pixel)-(pixel/2) + gameOffSetY;
	if(x>mapXLimit){
		x = pixel/2 + gameOffSetX;
	}else if(x<pixel/2 + gameOffSetX){
		x = mapXLimit;
	}else if(y>mapYLimit){
		y = pixel/2 + gameOffSetY;
	}else if(y<pixel/2 + gameOffSetY){
		y = mapYLimit;
	}
	socket.movePlayer({x, y});
}

function addDeathOnProfile(game,scene,cProfile,id,deathFrame){
	var blackBox = new Sprite(180, 170);
    blackBox.image = game.assets[blackImg];
    cProfile[id].frame = deathFrame[id]; //profile position
    blackBox.moveTo(cProfile[id].x-60,cProfile[id].y-30);
    blackBox.opacity = 0.5;
    scene.addChild(blackBox);
}
<commit_msg>remove comment<commit_after>
var mySpeed = 8;
var SHEEP_SPEED = 8;
var WOLF_SPEED = 4;
var MOVE_FRAME_COUNT_LIMIT = 3;
var pixel = 64;
var DIRS = ['up', 'right', 'down', 'left'];
var DX   = [0, 1, 0, -1];
var DY   = [-1, 0, 1, 0];
var sheepId;
var isInvincible;
var isEnded;
var isTimeLimit;
var wolfImageIndex = 0;

function initPlayScene(userObj, mapObj, normalItemObj, powerItemObj, timeLimit, initScore, game) {
    isInvincible = false;
    isEnded = false;
    isTimeLimit = false;

    //start the music
	game.assets[startSe].play();
    bgmController.stop();
    bgmController.play(gameBgm);

	var scene = new Scene();
	//add scene environment
	var bg = new Sprite(1920, 1080);
	bg.image = game.assets[gameImg];
	scene.addChild(bg);

	//left side
	var hightScoreTxt = new Label("Highest score :");
	hightScoreTxt.font = `36px ${normalFont}`;
	hightScoreTxt.moveTo(60,170);
	scene.addChild(hightScoreTxt);
	var currentScoreTxt = new Label("current score : " + ('00000' + initScore).slice(-5));
	currentScoreTxt.font = `36px ${normalFont}`;
	currentScoreTxt.moveTo(60,350);
	scene.addChild(currentScoreTxt);

	var timeTxt = new Label("time : " + timeLimit / 1000);
	timeTxt.font = `36px ${normalFont}`;
	timeTxt.moveTo(60,530);
	scene.addChild(timeTxt);
    var timeIntervalId = setInterval(() => {
        if (isEnded) {
            clearInterval(timeIntervalId);
        }

        if (isTimeLimit) {
            timeLimit = 0;
        } else if (!isEnded) {
            timeLimit = Math.max(0, timeLimit - 1000);
        }

        timeTxt.text = "time : " + timeLimit / 1000;
    }, 1000);

	var map = initDynamicMap(game,mapObj);
	scene.addChild(map);

    //init all item before character
    var normalItemList = {};
    for(let i=0;i<normalItemObj.length;i++){
        //init item obj and assign to list for checking when sheep hit
        const item = initNormalItem(game,normalItemObj[i]);
        normalItemList[normalItemObj[i].id] = item;
        scene.addChild(item);
    }

    var powerItemList = {};
    for(let i=0;i<powerItemObj.length;i++){
        //init item obj and assign to list for checking when sheep hit
        const item = initPowerItem(game,powerItemObj[i]);
        powerItemList[powerItemObj[i].id] = item;
        scene.addChild(item);
    }

	//set right side screen position
	var fixPosition = [[1515,90], [1515,275],[1515,455],[1515,640],[1515,825]];

	//init all character
	var character = {};
	for(let i=0;i<userObj.length;i++){
		var objId = userObj[i].id;
		if(myId == objId){
			//set speed every move
            mySpeed = userObj[i].isEnemy ? WOLF_SPEED : SHEEP_SPEED;
		}
		character[objId] = initPlayer(game,map,socket,userObj[i]);
        if(myId == objId) {
            initPlayerMove(game, map, socket, character, userObj, mapObj, normalItemObj, normalItemList, powerItemObj, powerItemList);
        }
		// Add elements to scene.
    	scene.addChild(character[objId]);

    	//set sheep id for killing
    	if(!userObj[i].isEnemy){
			sheepId = objId;
		}
	}

	wolfImageIndex = 0;
	var cProfile = {};
	var deathFrame = {};
	for(let i=0;i<userObj.length;i++){
		var objId = userObj[i].id;
		//set right side profile
		var player = new Sprite(pixel, pixel);
	    player.image = game.assets[charImg];
        player.frame = userObj[i].imageIndex * 3;

	    deathFrame[objId] = userObj[i].imageIndex * 3 + 2;

	    //starting point
	    player.scale(3);
	    player.x = fixPosition[i][0] + 52;
	    player.y = fixPosition[i][1] + 25;

	    cProfile[objId] = player;

	    scene.addChild(cProfile[objId]);

	    var nameTag = "AI";
	    if(null!=userObj[i].user){
	    	nameTag = userObj[i].user.username;
	    }
	    var usernameTag = new Label(nameTag);
	    usernameTag.font = `36px ${normalFont}`;
	    usernameTag.moveTo(fixPosition[i][0] + 50 ,fixPosition[i][1] + 120);
	    scene.addChild(usernameTag);
	    //end right side profile
	}

    socket.on('movePlayer', (req) => {
    	game.assets[footStepsSe].play();

        const {x, y} = req.player.coordinate;
        var targetUser = userObj.find(x => x.id === req.player.id);
        var objId = req.player.id;

        //rotate head before change position
        //rotate character
        if(character[objId].x<x){ //right
        	character[objId].scaleX  = -1;
        	character[objId].rotation = 0;
        }else if(character[objId].x>x){ // left
        	character[objId].scaleX  = 1;
        	character[objId].rotation = 0;
        }else if(character[objId].y<y){ // down
        	character[objId].scaleX  = -1;
        	character[objId].rotation = 90;
        }else if(character[objId].y>y){ // up
        	character[objId].scaleX  = -1;
        	character[objId].rotation = 270;
        }

        const idx = targetUser.imageIndex * 3;

        if (targetUser.isAI) {
            character[objId].frame = character[objId].frame === idx ? idx + 1 : idx;
        } else {
            if (++targetUser.moveFrameCount > MOVE_FRAME_COUNT_LIMIT) {
                targetUser.moveFrameCount = 0;
                character[objId].frame = character[objId].frame === idx ? idx + 1 : idx;
            }
        }

        //change position
        character[objId].x = x;
        character[objId].y = y;
    });

    socket.on('killSheep', (req) => {
        const sheep = userObj.find(x => !x.isEnemy);
        sheep.isAlive = false;
        scene.removeChild(character[sheep.id]);

    	game.assets[sheepDeathSe].play();

    	addDeathOnProfile(game,scene,cProfile,sheep.id,deathFrame);
    });

    socket.on('killWolf', (req) => {
        const wolf = userObj.find(x => x.id === req.player.id);
        wolf.isAlive = false;
        scene.removeChild(character[wolf.id]);
        game.assets[wolfDeathSe].play();

        //gray profile by sprite overlay
        //170 x 160
        addDeathOnProfile(game,scene,cProfile,wolf.id,deathFrame);
    });

    socket.on('respawnWolf', (req) => {
        const wolf = userObj.find(x => x.id === req.player.id);
        wolf.isAlive = true;
        wolf.coordinate = req.player.coordinate;
        character[wolf.id].x = wolf.coordinate.x;
        character[wolf.id].y = wolf.coordinate.y;
        scene.addChild(character[wolf.id]);
    });

    socket.on('takeNormalItem', (req) => {
        const targetItemObj = normalItemObj.find(x => x.id === req.normalItem.id);
        targetItemObj.enabled = false;

        const item = normalItemList[targetItemObj.id];
        scene.removeChild(item);
        game.assets[foodSe].play();
    });

    socket.on('takePowerItem', (req) => {
        const targetItemObj = powerItemObj.find(x => x.id === req.powerItem.id);
        targetItemObj.enabled = false;

        const item = powerItemList[targetItemObj.id];
        scene.removeChild(item);
        game.assets[powerUpSe].play();
    });

    socket.on('startInvincible', () => {
        if (isEnded) { return; }

        isInvincible = true;
        // TODO: enable super mode image

        bgmController.stop();
        bgmController.play(powerup1Bgm);
    });

    socket.on('endInvincible', () => {
        if (isEnded) { return; }

        isInvincible = false;
        // TODO: disable super mode image

        bgmController.stop();
        bgmController.play(gameBgm);
    });

    socket.on('endGame', (req) => {
        isEnded = true;
        isTimeLimit = req.isTimeLimit;
        game.assets[gameBgm].stop();
        game.assets[endSe].play();

        goToResultScene(game, req.game.score);
    });

    socket.on('updateScore', (scores) => {
        currentScoreTxt.text = "current score : " + ('00000' + scores.score).slice(-5);
    });

    game.replaceScene(scene);
}

function initPlayer(game,map,socket,userObj){
	 // Player for now will be a pixel x pixel.
    var player = new Sprite(pixel, pixel);
    player.image = game.assets[charImg];

    //count for change frame
    userObj.moveFrameCount = 0;

    //starting point
    player.x = userObj.coordinate.x;
    player.y = userObj.coordinate.y;

    //if enemy = wolf
    if(userObj.isEnemy){
        // wolf
        userObj.imageIndex = wolfImageIndex % 4 + 1;
        ++wolfImageIndex;
    }else{
        // sheep
        userObj.imageIndex = 0;
    }

    player.frame = userObj.imageIndex * 3;

    return player;
}

function initPlayerMove(game, map, socket, character, userObj, mapObj, normalItemObj, normalItemList, powerItemObj, powerItemList)  {
    const myUserObj = userObj.find(x => x.id === myId);
    const myCharacter = character[myId];

    // Let player move within bounds.
    myCharacter.addEventListener(Event.ENTER_FRAME, function () {
        // First move the player. If the player's new location has resulted
        // in the player being in a "hit" zone, then back the player up to
        // its original location. Tweak "hits" by "offset" pixels.

        let {x, y} = myCharacter;
        DIRS.forEach((dir, i) => {
            if (!game.input[dir]) { return; }
            x += DX[i] * mySpeed;
            y += DY[i] * mySpeed;

            //check the wall
            if (!myHitTest(map, x, y)) {
            	//check for warp portal at the border of map
            	warpPortal(x, y, mapObj);
            }else{
            	//smooth turn
            	var autoMovePixcel = mySpeed;
            	var xGhost = x-gameOffSetX;
            	var yGhost = y-gameOffSetY;
            	for(var j=(pixel/(-2*autoMovePixcel));(j*autoMovePixcel)<(pixel/2);j++){
            		if(j!=0){
            			if(DX[i] != 0){ //user go right or left
            				yGhost = y + (autoMovePixcel*j) - gameOffSetY; //DX not zero change Y
            			}else{//user go up and down DY not zero change X
            				xGhost = x + (autoMovePixcel*j) - gameOffSetX;
            			}
	            		if(!(map.hitTest(xGhost, yGhost) ||
	    	                    map.hitTest(xGhost + pixel - 1, yGhost) ||
	    	                    map.hitTest(xGhost, yGhost + pixel - 1) ||
	    	                    map.hitTest(xGhost + pixel - 1, yGhost + pixel - 1))){

	            			if(DX[i] != 0){
	            				x -= DX[i] * mySpeed; //return to x old position
	            				(j<0)?y -= 1 * mySpeed:y += 1 * mySpeed;
	            			}else{
	            				y -= DY[i] * mySpeed;
	            				(j<0)?x -= 1 * mySpeed:x += 1 * mySpeed;
	            			}
	            			j = 5;
		                	warpPortal(x, y, mapObj);
	            		}
            		}
            	}
            	//end smooth turn
            }
        });

        // kill by sheepId
        if (myId === sheepId && myUserObj.isAlive) {
            for (let i = 0; i < userObj.length; i++) {
                if (userObj[i] === myUserObj) { continue; }
                if (!userObj[i].isAlive) { continue; }
                if (character[userObj[i].id].intersect(myCharacter)) {
                    if (isInvincible) {
                        socket.killWolf({wolfId: userObj[i].id});
                        userObj[i].isAlive = false;
                    } else {
                    	//sheep invincible for test
                        socket.killSheep();
                        myUserObj.isAlive = false;
                        break;
                    }
                }
            }

            //check sheep intersect with item
            for(let i=0;i<normalItemObj.length;i++){
                if (!normalItemObj[i].enabled) { continue; }

                const item = normalItemList[normalItemObj[i].id];
                if(myCharacter.intersect(item)){
                    normalItemObj[i].enabled = false;
                    socket.takeNormalItem({itemId: normalItemObj[i].id});
                }
            }

            for(let i=0;i<powerItemObj.length;i++){
                if (!powerItemObj[i].enabled) { continue; }

                const item = powerItemList[powerItemObj[i].id];
                if(myCharacter.intersect(item)){
                    powerItemObj[i].enabled = false;
                    socket.takePowerItem({itemId: powerItemObj[i].id});
                }
            }
        }
    });
}

function myHitTest (map, x, y) {
	x -= gameOffSetX;
	y -= gameOffSetY;
    return map.hitTest(x, y) ||
        map.hitTest(x + pixel - 1, y) ||
        map.hitTest(x, y + pixel - 1) ||
        map.hitTest(x + pixel - 1, y + pixel - 1);
}

function warpPortal(x, y, mapObj){
	var mapXLimit = (mapObj.width * pixel)-(pixel/2) + gameOffSetX;
	var mapYLimit = (mapObj.height * pixel)-(pixel/2) + gameOffSetY;
	if(x>mapXLimit){
		x = pixel/2 + gameOffSetX;
	}else if(x<pixel/2 + gameOffSetX){
		x = mapXLimit;
	}else if(y>mapYLimit){
		y = pixel/2 + gameOffSetY;
	}else if(y<pixel/2 + gameOffSetY){
		y = mapYLimit;
	}
	socket.movePlayer({x, y});
}

function addDeathOnProfile(game,scene,cProfile,id,deathFrame){
	var blackBox = new Sprite(180, 170);
    blackBox.image = game.assets[blackImg];
    cProfile[id].frame = deathFrame[id]; //profile position
    blackBox.moveTo(cProfile[id].x-60,cProfile[id].y-30);
    blackBox.opacity = 0.5;
    scene.addChild(blackBox);
}
<|endoftext|>


<commit_before>define(['zepto', 'pixi', 'box2d', 'helpers/math', 'socketio'], function ($, PIXI, Box2D, MathUtil, io) {

	var game = {
		state: {
			stage: null,
			renderer: null,
			world: null,
			bodies: [], // instances of b2Body (from Box2D)
			actors: []
		},

		STAGE_WIDTH: window.innerWidth,
		STAGE_HEIGHT: window.innerHeight,
		METER: 100,
		init: function () {
			var _g = this;

			// create a connection to the server
			var address = location.host; //window.prompt("Server address", "0.0.0.0");
			this.socket = io.connect('http://' + address); // + ':5000');

			const container = document.createElement("div");
			document.body.appendChild(container);

			_g.state.stage = new PIXI.Stage(0xDDDDDD, true);
			_g.state.renderer = PIXI.autoDetectRenderer(_g.STAGE_WIDTH, _g.STAGE_HEIGHT, undefined, false);
			document.body.appendChild(_g.state.renderer.view);

			const loader = new PIXI.AssetLoader(["assets/ball.png",
				"assets/box.jpg"]);
			loader.onComplete = _g.onLoadAssets.bind(_g);
			loader.load();
		},
		onLoadAssets: function () {
			var _g = this,
					gravity = new Box2D.Common.Math.b2Vec2(0, 10);

			_g.sync();

			world = new Box2D.Dynamics.b2World(gravity,  true);

			const polyFixture = new Box2D.Dynamics.b2FixtureDef();
			polyFixture.shape = new Box2D.Collision.Shapes.b2PolygonShape();
			polyFixture.density = 1;

			const circleFixture = new Box2D.Dynamics.b2FixtureDef();
			circleFixture.shape = new Box2D.Collision.Shapes.b2CircleShape();
			circleFixture.density = 1;
			circleFixture.restitution = 0.7;

			const bodyDef = new Box2D.Dynamics.b2BodyDef();
			bodyDef.type = Box2D.Dynamics.b2Body.b2_kinematicBody;

			for (var i = 0; i < 40; i++) {
				bodyDef.position.Set(MathUtil.rndRange(0, _g.STAGE_WIDTH) / _g.METER, -MathUtil.rndRange(50, 5000) / _g.METER);
				var body = world.CreateBody(bodyDef);
				var s;
				if (i/40 > 0.5) {
					s = i/40*50+50;
					circleFixture.shape.SetRadius(s / 2 / _g.METER);
					body.CreateFixture(circleFixture);
					_g.state.bodies.push(body);

					var ball = new PIXI.Sprite(PIXI.Texture.fromFrame("assets/ball.png"));
					_g.state.stage.addChild(ball);
					ball.i = i;
					ball.anchor.x = ball.anchor.y = 0.5;
					ball.scale.x = ball.scale.y = s / 100;

					_g.state.actors[_g.state.actors.length] = ball;
				}
				else {
					s = i/40*50+50;
					polyFixture.shape.SetAsBox(s / 2 / _g.METER, s / 2 / _g.METER);
					body.CreateFixture(polyFixture);
					_g.state.bodies.push(body);

					var box = new PIXI.Sprite(PIXI.Texture.fromFrame("assets/box.jpg"));
					_g.state.stage.addChild(box);
					box.i = i;
					box.anchor.x = box.anchor.y = 0.5;
					box.scale.x = s / 100;
					box.scale.y = s / 100;

					_g.state.actors[_g.state.actors.length] = box;
				}
			}
			_g.update();
		},
		update: function () {
			var _g = this;
			requestAnimationFrame(_g.update.bind(_g));
			world.Step(1 / 60,  3,  3);
			world.ClearForces();

			const n = _g.state.actors.length;
			for (var i = 0; i < n; i++) {
				var body  = _g.state.bodies[i];
				var actor = _g.state.actors[i];
				var position = body.GetPosition();
				actor.position.x = position.x * 100;
				actor.position.y = position.y * 100;
				actor.rotation = body.GetAngle();
			}
			_g.socket.emit('my other event', { my: 'data' });

			_g.state.renderer.render(_g.state.stage);

		},
		sync: function() {
			var _g = this;
			// _g.socket.on('news', function (data) {
			// 	console.log(data);
			// 	_g.socket.emit('my other event', { my: 'data' });
			// });
			_g.socket.on('update', function (data) {
				// console.log(data);
				const n = data.length;
				for (var i = 0; i < n; i++) {
					var body = _g.state.bodies[i],
							d = data[i],
							x = d.x,
							y = d.y,
							x_vel = d.x_vel,
							y_vel = d.y_vel,
							rot = d.rot,
							pos = new Box2D.Common.Math.b2Vec2(x, y)
							vel = new Box2D.Common.Math.b2Vec2(x_vel, y_vel);

					body.SetPosition(pos);
					body.SetLinearVelocity(vel);
					body.SetAngle(rot);
				}
			});
		}
	};

	window.game = game;
	return game;
});<commit_msg>only bind socket.on once, in init function<commit_after>define(['zepto', 'pixi', 'box2d', 'helpers/math', 'socketio'], function ($, PIXI, Box2D, MathUtil, io) {

	var game = {
		state: {
			stage: null,
			renderer: null,
			world: null,
			bodies: [], // instances of b2Body (from Box2D)
			actors: []
		},

		STAGE_WIDTH: window.innerWidth,
		STAGE_HEIGHT: window.innerHeight,
		METER: 100,
		init: function () {
			var _g = this;

			// create a connection to the server
			var address = location.host;
			_g.socket = io.connect('http://' + address);
			_g.socket.on('update', _g.sync.bind(_g));

			const container = document.createElement("div");
			document.body.appendChild(container);

			_g.state.stage = new PIXI.Stage(0xDDDDDD, true);
			_g.state.renderer = PIXI.autoDetectRenderer(_g.STAGE_WIDTH, _g.STAGE_HEIGHT, undefined, false);
			document.body.appendChild(_g.state.renderer.view);

			const loader = new PIXI.AssetLoader(["assets/ball.png",
				"assets/box.jpg"]);
			loader.onComplete = _g.onLoadAssets.bind(_g);
			loader.load();
		},
		onLoadAssets: function () {
			var _g = this,
					gravity = new Box2D.Common.Math.b2Vec2(0, 10);

			_g.sync();

			world = new Box2D.Dynamics.b2World(gravity,  true);

			const polyFixture = new Box2D.Dynamics.b2FixtureDef();
			polyFixture.shape = new Box2D.Collision.Shapes.b2PolygonShape();
			polyFixture.density = 1;

			const circleFixture = new Box2D.Dynamics.b2FixtureDef();
			circleFixture.shape = new Box2D.Collision.Shapes.b2CircleShape();
			circleFixture.density = 1;
			circleFixture.restitution = 0.7;

			const bodyDef = new Box2D.Dynamics.b2BodyDef();
			bodyDef.type = Box2D.Dynamics.b2Body.b2_kinematicBody;

			for (var i = 0; i < 40; i++) {
				bodyDef.position.Set(MathUtil.rndRange(0, _g.STAGE_WIDTH) / _g.METER, -MathUtil.rndRange(50, 5000) / _g.METER);
				var body = world.CreateBody(bodyDef);
				var s;
				if (i/40 > 0.5) {
					s = i/40*50+50;
					circleFixture.shape.SetRadius(s / 2 / _g.METER);
					body.CreateFixture(circleFixture);
					_g.state.bodies.push(body);

					var ball = new PIXI.Sprite(PIXI.Texture.fromFrame("assets/ball.png"));
					_g.state.stage.addChild(ball);
					ball.i = i;
					ball.anchor.x = ball.anchor.y = 0.5;
					ball.scale.x = ball.scale.y = s / 100;

					_g.state.actors[_g.state.actors.length] = ball;
				}
				else {
					s = i/40*50+50;
					polyFixture.shape.SetAsBox(s / 2 / _g.METER, s / 2 / _g.METER);
					body.CreateFixture(polyFixture);
					_g.state.bodies.push(body);

					var box = new PIXI.Sprite(PIXI.Texture.fromFrame("assets/box.jpg"));
					_g.state.stage.addChild(box);
					box.i = i;
					box.anchor.x = box.anchor.y = 0.5;
					box.scale.x = s / 100;
					box.scale.y = s / 100;

					_g.state.actors[_g.state.actors.length] = box;
				}
			}
			_g.update();
		},
		update: function () {
			var _g = this;
			requestAnimationFrame(_g.update.bind(_g));
			world.Step(1 / 60,  3,  3);
			world.ClearForces();

			const n = _g.state.actors.length;
			for (var i = 0; i < n; i++) {
				var body  = _g.state.bodies[i];
				var actor = _g.state.actors[i];
				var position = body.GetPosition();
				actor.position.x = position.x * 100;
				actor.position.y = position.y * 100;
				actor.rotation = body.GetAngle();
			}
			_g.state.renderer.render(_g.state.stage);
		},
		sync: function(data) {
			var _g = this;
			if (!data) {
				return;
			}
			var n = data.length;
			for (var i = 0; i < n; i++) {
				var body = _g.state.bodies[i],
						d = data[i],
						x = d.x,
						y = d.y,
						x_vel = d.x_vel,
						y_vel = d.y_vel,
						rot = d.rot,
						pos = new Box2D.Common.Math.b2Vec2(x, y)
						vel = new Box2D.Common.Math.b2Vec2(x_vel, y_vel);

				body.SetPosition(pos);
				body.SetLinearVelocity(vel);
				body.SetAngle(rot);
			}
		}
	};

	window.game = game;
	return game;
});<|endoftext|>