<commit_before>var app = app || {};

$(function () {
	'use strict';

	app.utils = {};

	app.utils.isTrue = function (x, callback) {
		if (typeof x !== 'boolean') {
			return x === 'true';
		} else {
			return x;
		}

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.normalizeValue = function (value) {
		var result = value;

		if (value === 'true') {
			result = true;
		} else  if (value === 'false') {
			result = false;
		} else  if (value === 'undefined') {
			result = undefined;
		} else  if (value === 'null') {
			result = null;
		} else  if (value === 'NaN') {
			result = NaN;
		} else  if (!isNaN(value)) {
			result = parseInt(value, 10);
		}

		return result;
	};

	app.utils.updateShareUrls = function (callback) {
		$('#share-modal').find('a.twitter').attr('href', 'http://twitter.com/home?status=' + app.session.settings.title + ' ' + window.location.href + ' from @code_Magic');
		$('#share-modal').find('a.facebook').attr('href', 'http://www.facebook.com/sharer.php?u=' + window.location.href);
		$('#share-modal').find('a.google-plus').attr('href', 'https://plus.google.com/share?url=' + window.location.href + '&title=' + app.session.settings.title);
		$('#share-modal').find('a.linkedin').attr('href', 'http://www.linkedin.com/shareArticle?mini=true&url=' + window.location.href + '&title=' + app.session.settings.title + '&summary=' + app.session.settings.description + '&source=http://codeMagic.gr');
		$('#share-modal').find('a.pinterest').attr('href', 'http://pinterest.com/pin/create/bookmarklet/?url=' + window.location.href + '&is_video=false&description=' + app.session.settings.title);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.resizeEditors = function (editors, callback) {
		editors.html.resize();
		editors.css.resize();
		editors.js.resize();

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.em2px = function () {
		var div = $('

').appendTo('body');
		var em = div.width();
		div.remove();

		return parseInt(em, 10);
	};

	app.utils.rem2px = function () {
		var div = $('

').appendTo('body');
		var rem = div.width();
		div.remove();

		return parseInt(rem, 10);
	};

	app.utils.setIframeHeight = function (iframe, callback) {
		// TODO: make this work properly
		var height = Math.max($('#editors').height(), $(iframe).height()) - (app.utils.rem2px() * 0.25);
		$(iframe).height(height);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.write2iframe = function (iframe, result, callback) {
		var iframeDocument = iframe.contentDocument;
		iframeDocument.open();
		iframeDocument.write(result);
		iframeDocument.close();

		app.utils.setIframeHeight(iframe);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.consoleClear = function (callback) {
		$('#console-editor').html('');

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.consoleLog = function (log, callback) {
		$('#console .editor-module').addClass('enabled');
		$('#console-editor').append('> ' + log + '');

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.getZippedProject = function (editors, callback) {
		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.generateResult = function () {
		var result = app.utils.generateHead() + app.utils.generateBody();

		return result;
	};

	app.utils.generateLogger = function () {
		// TODO: better error handling and object debugging
		// WHY: breaking down logger into many pieces to prevent proxies from chocking by passing the 500 character limit

		var result = '';
		return result;
	};

	app.utils.generateContent = function () {
		var result = '';
		if ($('#markupChoice').val() === 'Markdown') {
			result = marked(app.editors.html.getValue());
		} else if ($('#markupChoice').val() === 'HAML') {
			app.utils.consoleLog('HAML support is not ready to use yet.');
		} else if ($('#markupChoice').val() === 'Jade') {
			app.utils.consoleLog('Jade support is not ready to use yet.');
		} else {
			result = app.editors.html.getValue();
		}

		return result;
	};

	app.utils.generateStyle = function () {
		var result = '';

		if ($('#styleChoice').val() === 'Less') {
			var parser = new(less.Parser)();

			parser.parse(app.editors.css.getValue(), function (e, tree) {
				if (e) {
					// TODO: better error handling in console
					$('#console-editor').append('> ' + e.message + '
');
				}
				result = tree.toCSS();
			});
		} else if ($('#styleChoice').val() === 'SASS' || $('#styleChoice').val() === 'SCSS') {
			app.utils.consoleLog('SASS/SCSS support is not ready to use yet.');
		} else if ($('#styleChoice').val() === 'Stylus') {
			app.utils.consoleLog('Stylus support is not ready to use yet.');
		} else {
			result = app.editors.css.getValue();
		}

		return result;
	};

	app.utils.generateExternalStyle = function () {
		var items = $("select[name=csslibrary]").val();
		var result = '';

		for (var i = 0; i < items.length; i++) {
			result+= '<link href="'+ items[i] + '">';
		}

		return result;
	};

	app.utils.generateScript = function () {
		var result = '';

		if ($('#scriptChoice').val() === 'CoffeeScript') {
			app.utils.consoleLog('CoffeeScript support is not ready to use yet.');
		} else {
			result = app.editors.js.getValue();
		}

		return result;
	};

	app.utils.generateExternalScript = function () {
		var items = $("select[name=jslibrary]").val();
		var result = '';

		for (var i = 0; i < items.length; i++) {
			result+= '';
		}

		return result;
	};

	app.utils.generateHead = function () {
		var style = app.utils.generateStyle();
		var externalStyle = app.utils.generateExternalStyle();
		var logger = app.utils.generateLogger();
		var result = '<!doctype html>' + logger + '<meta charset="utf-8"><title>Title</title><meta name="description" content="Description"><meta name="author" content="Author">' + externalStyle +'';

		return result;
	};

	app.utils.generateBody = function () {
		var content = app.utils.generateContent();
		var script= app.utils.generateScript();
		var externalScript = app.utils.generateExternalScript();
		var result = '' + content + externalScript + '';

		return result;
	};

	app.utils.updateLayout = function (callback) {
		app.utils.resizeEditors(app.editors);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.setTheme = function (theme, callback) {
		_.each([app.editors.html, app.editors.css, app.editors.js], function(editor) {
			editor.setTheme('ace/theme/' + theme);
		});

		app.utils.setSettings('theme', theme);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.setEditorMode = function (target, mode, callback) {
		app.session.settings[target].mode = mode;

		app.utils.setSettings(target + '.mode', mode);

		if (mode === 'coffeescript') {
			mode = 'coffee';
		}

		app.editors[target + 'Session'].setMode('ace/mode/' + mode);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.setOption = function (option, value, callback) {
		var result = {};

		if (option !== 'csslibrary' && option !== 'jslibrary') {
			result[option] = value;

			_.each([app.editors.html, app.editors.css, app.editors.js], function(editor) {
				editor.setOptions(result);
			});

			app.utils.setSettings(option, value);
		}

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.getAllSettings = function () {
		var keys = Object.keys(localStorage);
		var result = {};
		var value;

		for (var i = 0; i < keys.length; i++) {
			value = localStorage.getItem(keys[i]);
			result[keys[i].replace('codemagic.settings.', '')] = app.utils.normalizeValue(value);
		}

		return result;
	};

	app.utils.getSettings = function (option) {
		var result;

		if (option !== 'csslibrary' && option !== 'jslibrary') {
			result = localStorage.getItem('codemagic.settings.' + option);
			result = app.utils.normalizeValue(result);

			app.session.settings[option] = result;
		}

		return result;
	};

	app.utils.setSettings = function (option, val, callback) {
		app.session.settings[option] = val;
		option = 'codemagic.settings.' + option;
		localStorage.setItem(option, val);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.toggleEditorState = function (target, callback) {
		var state = false;
		if ($('#' + target + '-editor-toggle').hasClass('enabled')) {
			state = true;
		}
		app.session.settings[target].state = state;

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.toggleFullscreenMode = function (target, callback) {
		if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
			if (target.requestFullscreen) {
				target.requestFullscreen();
			} else
			if (target.mozRequestFullScreen) {
				target.mozRequestFullScreen();
			} else
			if (target.webkitRequestFullscreen) {
				target.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
			}
		}
		else {
			if (document.cancelFullScreen) {
				document.cancelFullScreen();
			}
			else if (document.mozCancelFullScreen) {
				document.mozCancelFullScreen();
			}
			else if (document.webkitCancelFullScreen) {
				document.webkitCancelFullScreen();
			}
		}

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.toggleHideEditorsMode = function (target, callback) {
		var editors = $('#editors');
		var result = $('#result');

		var state1 = !editors.hasClass('hideEditors');
		var state2 = result.hasClass('hideResult');

		if (state1) {
			editors.addClass('hideEditors');

			if (state2) {
				app.utils.toggleHideResultMode();
			}

			window.setTimeout(function () {
				editors.hide();
				result.addClass('hideEditors');
			}, 250);
		} else {
			result.removeClass('hideEditors');

			window.setTimeout(function () {
				editors.show();
				editors.removeClass('hideEditors');
			}, 250);
		}

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.toggleHideResultMode = function (target, callback) {
		var editors = $('#editors');
		var result = $('#result');

		var state = !result.hasClass('hideResult');
		var state2 = result.hasClass('hideEditors');

		if (state) {
			result.addClass('hideResult');

			if (state2) {
				app.utils.toggleHideEditorsMode();
			}

			window.setTimeout(function () {
				result.hide();
				editors.addClass('hideResult');
			}, 250);
		} else {
			editors.removeClass('hideResult');

			window.setTimeout(function () {
				result.show();
				result.removeClass('hideResult');
			}, 250);
		}

		if (typeof callback == 'function') {
			callback();
		}
	};
});
<commit_msg>added rel='stylesheet' to external styles<commit_after>var app = app || {};

$(function () {
	'use strict';

	app.utils = {};

	app.utils.isTrue = function (x, callback) {
		if (typeof x !== 'boolean') {
			return x === 'true';
		} else {
			return x;
		}

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.normalizeValue = function (value) {
		var result = value;

		if (value === 'true') {
			result = true;
		} else  if (value === 'false') {
			result = false;
		} else  if (value === 'undefined') {
			result = undefined;
		} else  if (value === 'null') {
			result = null;
		} else  if (value === 'NaN') {
			result = NaN;
		} else  if (!isNaN(value)) {
			result = parseInt(value, 10);
		}

		return result;
	};

	app.utils.updateShareUrls = function (callback) {
		$('#share-modal').find('a.twitter').attr('href', 'http://twitter.com/home?status=' + app.session.settings.title + ' ' + window.location.href + ' from @code_Magic');
		$('#share-modal').find('a.facebook').attr('href', 'http://www.facebook.com/sharer.php?u=' + window.location.href);
		$('#share-modal').find('a.google-plus').attr('href', 'https://plus.google.com/share?url=' + window.location.href + '&title=' + app.session.settings.title);
		$('#share-modal').find('a.linkedin').attr('href', 'http://www.linkedin.com/shareArticle?mini=true&url=' + window.location.href + '&title=' + app.session.settings.title + '&summary=' + app.session.settings.description + '&source=http://codeMagic.gr');
		$('#share-modal').find('a.pinterest').attr('href', 'http://pinterest.com/pin/create/bookmarklet/?url=' + window.location.href + '&is_video=false&description=' + app.session.settings.title);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.resizeEditors = function (editors, callback) {
		editors.html.resize();
		editors.css.resize();
		editors.js.resize();

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.em2px = function () {
		var div = $('

').appendTo('body');
		var em = div.width();
		div.remove();

		return parseInt(em, 10);
	};

	app.utils.rem2px = function () {
		var div = $('

').appendTo('body');
		var rem = div.width();
		div.remove();

		return parseInt(rem, 10);
	};

	app.utils.setIframeHeight = function (iframe, callback) {
		// TODO: make this work properly
		var height = Math.max($('#editors').height(), $(iframe).height()) - (app.utils.rem2px() * 0.25);
		$(iframe).height(height);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.write2iframe = function (iframe, result, callback) {
		var iframeDocument = iframe.contentDocument;
		iframeDocument.open();
		iframeDocument.write(result);
		iframeDocument.close();

		app.utils.setIframeHeight(iframe);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.consoleClear = function (callback) {
		$('#console-editor').html('');

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.consoleLog = function (log, callback) {
		$('#console .editor-module').addClass('enabled');
		$('#console-editor').append('> ' + log + '');

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.getZippedProject = function (editors, callback) {
		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.generateResult = function () {
		var result = app.utils.generateHead() + app.utils.generateBody();

		return result;
	};

	app.utils.generateLogger = function () {
		// TODO: better error handling and object debugging
		// WHY: breaking down logger into many pieces to prevent proxies from chocking by passing the 500 character limit

		var result = '';
		return result;
	};

	app.utils.generateContent = function () {
		var result = '';
		if ($('#markupChoice').val() === 'Markdown') {
			result = marked(app.editors.html.getValue());
		} else if ($('#markupChoice').val() === 'HAML') {
			app.utils.consoleLog('HAML support is not ready to use yet.');
		} else if ($('#markupChoice').val() === 'Jade') {
			app.utils.consoleLog('Jade support is not ready to use yet.');
		} else {
			result = app.editors.html.getValue();
		}

		return result;
	};

	app.utils.generateStyle = function () {
		var result = '';

		if ($('#styleChoice').val() === 'Less') {
			var parser = new(less.Parser)();

			parser.parse(app.editors.css.getValue(), function (e, tree) {
				if (e) {
					// TODO: better error handling in console
					$('#console-editor').append('> ' + e.message + '
');
				}
				result = tree.toCSS();
			});
		} else if ($('#styleChoice').val() === 'SASS' || $('#styleChoice').val() === 'SCSS') {
			app.utils.consoleLog('SASS/SCSS support is not ready to use yet.');
		} else if ($('#styleChoice').val() === 'Stylus') {
			app.utils.consoleLog('Stylus support is not ready to use yet.');
		} else {
			result = app.editors.css.getValue();
		}

		return result;
	};

	app.utils.generateExternalStyle = function () {
		var items = $("select[name=csslibrary]").val();
		var result = '';

		for (var i = 0; i < items.length; i++) {
			result+= '<link rel="stylesheet" href="'+ items[i] + '">';
		}

		return result;
	};

	app.utils.generateScript = function () {
		var result = '';

		if ($('#scriptChoice').val() === 'CoffeeScript') {
			app.utils.consoleLog('CoffeeScript support is not ready to use yet.');
		} else {
			result = app.editors.js.getValue();
		}

		return result;
	};

	app.utils.generateExternalScript = function () {
		var items = $("select[name=jslibrary]").val();
		var result = '';

		for (var i = 0; i < items.length; i++) {
			result+= '';
		}

		return result;
	};

	app.utils.generateHead = function () {
		var style = app.utils.generateStyle();
		var externalStyle = app.utils.generateExternalStyle();
		var logger = app.utils.generateLogger();
		var result = '<!doctype html>' + logger + '<meta charset="utf-8"><title>Title</title><meta name="description" content="Description"><meta name="author" content="Author">' + externalStyle +'';

		return result;
	};

	app.utils.generateBody = function () {
		var content = app.utils.generateContent();
		var script= app.utils.generateScript();
		var externalScript = app.utils.generateExternalScript();
		var result = '' + content + externalScript + '';

		return result;
	};

	app.utils.updateLayout = function (callback) {
		app.utils.resizeEditors(app.editors);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.setTheme = function (theme, callback) {
		_.each([app.editors.html, app.editors.css, app.editors.js], function(editor) {
			editor.setTheme('ace/theme/' + theme);
		});

		app.utils.setSettings('theme', theme);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.setEditorMode = function (target, mode, callback) {
		app.session.settings[target].mode = mode;

		app.utils.setSettings(target + '.mode', mode);

		if (mode === 'coffeescript') {
			mode = 'coffee';
		}

		app.editors[target + 'Session'].setMode('ace/mode/' + mode);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.setOption = function (option, value, callback) {
		var result = {};

		if (option !== 'csslibrary' && option !== 'jslibrary') {
			result[option] = value;

			_.each([app.editors.html, app.editors.css, app.editors.js], function(editor) {
				editor.setOptions(result);
			});

			app.utils.setSettings(option, value);
		}

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.getAllSettings = function () {
		var keys = Object.keys(localStorage);
		var result = {};
		var value;

		for (var i = 0; i < keys.length; i++) {
			value = localStorage.getItem(keys[i]);
			result[keys[i].replace('codemagic.settings.', '')] = app.utils.normalizeValue(value);
		}

		return result;
	};

	app.utils.getSettings = function (option) {
		var result;

		if (option !== 'csslibrary' && option !== 'jslibrary') {
			result = localStorage.getItem('codemagic.settings.' + option);
			result = app.utils.normalizeValue(result);

			app.session.settings[option] = result;
		}

		return result;
	};

	app.utils.setSettings = function (option, val, callback) {
		app.session.settings[option] = val;
		option = 'codemagic.settings.' + option;
		localStorage.setItem(option, val);

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.toggleEditorState = function (target, callback) {
		var state = false;
		if ($('#' + target + '-editor-toggle').hasClass('enabled')) {
			state = true;
		}
		app.session.settings[target].state = state;

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.toggleFullscreenMode = function (target, callback) {
		if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
			if (target.requestFullscreen) {
				target.requestFullscreen();
			} else
			if (target.mozRequestFullScreen) {
				target.mozRequestFullScreen();
			} else
			if (target.webkitRequestFullscreen) {
				target.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
			}
		}
		else {
			if (document.cancelFullScreen) {
				document.cancelFullScreen();
			}
			else if (document.mozCancelFullScreen) {
				document.mozCancelFullScreen();
			}
			else if (document.webkitCancelFullScreen) {
				document.webkitCancelFullScreen();
			}
		}

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.toggleHideEditorsMode = function (target, callback) {
		var editors = $('#editors');
		var result = $('#result');

		var state1 = !editors.hasClass('hideEditors');
		var state2 = result.hasClass('hideResult');

		if (state1) {
			editors.addClass('hideEditors');

			if (state2) {
				app.utils.toggleHideResultMode();
			}

			window.setTimeout(function () {
				editors.hide();
				result.addClass('hideEditors');
			}, 250);
		} else {
			result.removeClass('hideEditors');

			window.setTimeout(function () {
				editors.show();
				editors.removeClass('hideEditors');
			}, 250);
		}

		if (typeof callback == 'function') {
			callback();
		}
	};

	app.utils.toggleHideResultMode = function (target, callback) {
		var editors = $('#editors');
		var result = $('#result');

		var state = !result.hasClass('hideResult');
		var state2 = result.hasClass('hideEditors');

		if (state) {
			result.addClass('hideResult');

			if (state2) {
				app.utils.toggleHideEditorsMode();
			}

			window.setTimeout(function () {
				result.hide();
				editors.addClass('hideResult');
			}, 250);
		} else {
			editors.removeClass('hideResult');

			window.setTimeout(function () {
				result.show();
				result.removeClass('hideResult');
			}, 250);
		}

		if (typeof callback == 'function') {
			callback();
		}
	};
});
<|endoftext|>


<commit_before>var latencyDetails = [];
function loadAnalysisPage(){
    VoltDbAnalysis.setDefaultAnalysisSettings();

    $("#tabProcedureBtn").trigger("click");
    $("#tabAnalysis li a").on("click", function(){
        VoltDbAnalysis.refreshChart();
    })

    $("#ulProcedure li a").on("click", function(){
        if($($(this)[0]).text() == "Frequency"){
            $(".spnAnalysisLegend").html(VoltDbAnalysis.partitionStatus == "both" ?"Frequency(" : "Frequency");
        } else if($($(this)[0]).text() == "Total Processing Time"){
            $(".spnAnalysisLegend").html(VoltDbAnalysis.partitionStatus == "both" ?"Total Processing Time(" : "Total Processing Time");
        } else {
            $(".spnAnalysisLegend").html(VoltDbAnalysis.partitionStatus == "both" ?"Average Execution Time(" : "Average Execution Time");
        }
        //this method is called twice to ensure graph reloads properly
        VoltDbAnalysis.refreshChart();
        VoltDbAnalysis.refreshChart();
    })

    function calculateCombinedValue(profileData){
        var totalValue = 0;
        for(var j = 0; j < profileData.length; j++){
            totalValue += (profileData[j].AVG/1000000) * profileData[j].INVOCATIONS;
        }
        return totalValue;
    }

    function checkObjForLongStatementName(profileData){
        for(var j = 0; j < profileData.length; j++){
            if(profileData[j].STATEMENT.length > 14){
                return true;
            }
        }
        return false;
    }

    function formatAnalysisLegend(isMP, isP){
        if(isMP && isP){
            $("#legendAnalysisMP").hide();
            $("#legendAnalysisP").hide();
            $("#legendAnalysisBoth").show();
            VoltDbAnalysis.partitionStatus = "both"
        } else if(isMP){
            $("#legendAnalysisMP").show();
            $("#legendAnalysisP").hide();
            $("#legendAnalysisBoth").hide();
            VoltDbAnalysis.partitionStatus = "MP"
        } else {
            $("#legendAnalysisMP").hide();
            $("#legendAnalysisP").show();
            $("#legendAnalysisBoth").hide();
            VoltDbAnalysis.partitionStatus = "SP"
        }
    }

    function fetchData (){
        $("#analysisLoader").show();
        $("#analysisRemarks").hide();
        $("#procedureWarning").html("");
        $("#tableWarning").html("");
        VoltDbAnalysis.refreshChart();
        voltDbRenderer.GetProcedureProfileInformation(function(profileData){
            voltDbRenderer.GetProcedureDetailInformation(function (procedureDetails){
                if(profileData != undefined){
                    if(!$.isEmptyObject(profileData["PROCEDURE_PROFILE"])){
                        $(".analyzeNowContent").hide();
                        $(".dataContent").show();
                        $(".noDataContent").hide();
                    } else {
                        $(".mainContentAnalysis").hide();
                        $(".dataContent").hide();
                        $(".noDataContent").show();

                    }
                    //For data section
                    //$("#tblAnalyzeNowContent").hide();
                    //$("#tblNoDataContent").show();
                }
                $("#analysisLoader").hide();
                VoltDbAnalysis.proceduresCount = profileData["PROCEDURE_PROFILE"].length;
                var dataLatencyProcedures = [];
                var dataLatencySysProcedures = [];
                var dataFrequencySysProcedures = [];
                var dataFrequencyProcedures = [];
                var dataTotalProcessingProcedures = [];
                var dataTotalProcessingSysProcedures = [];
                var timestamp;
                var sumOfAllProcedure = calculateCombinedValue(profileData["PROCEDURE_PROFILE"])
                var isMPPresent = false;
                var isPPresent = false;
                var totalProcessingTime = VoltDbUI.getFromLocalStorage("totalProcessingTime");
                var averageExecutionTime = VoltDbUI.getFromLocalStorage("averageExecutionTime");
                var showHideSysProcedures = VoltDbUI.getFromLocalStorage("showHideSysProcedures");
                for(var i = 0; i < profileData["PROCEDURE_PROFILE"].length; i++){
                    if(i == 0)
                        timestamp = profileData["PROCEDURE_PROFILE"][i].TIMESTAMP;
                    var calculatedProcessingTime = (profileData["PROCEDURE_PROFILE"][i].AVG/1000000) * profileData["PROCEDURE_PROFILE"][i].INVOCATIONS;
                    var procedureName = profileData["PROCEDURE_PROFILE"][i].PROCEDURE;
                    var avgExecTime = profileData["PROCEDURE_PROFILE"][i].AVG / 1000000;
                    var invocation = profileData["PROCEDURE_PROFILE"][i].INVOCATIONS;
                    var wtPercentage = profileData["PROCEDURE_PROFILE"][i].WEIGHTED_PERC;
                    //find procedure type
                    var type = "Single Partitioned";
                    procedureDetails["PROCEDURE_DETAIL"].forEach (function(item){
                        if(procedureName == item.PROCEDURE && item.PARTITION_ID == 16383){
                            type = "Multi Partitioned"
                            return false;
                        }
                    });

                    if(type == "Multi Partitioned")
                        isMPPresent = true;
                    else
                        isPPresent = true;

                    var warningString = '';
                    var warningToolTip = '';

                    if(calculatedProcessingTime > totalProcessingTime && totalProcessingTime != "") {
                        $("#analysisRemarks").show();
                        $("#procedureWarningSection").show();
                        warningString = "
" + procedureName + " has total processing time greater than "+ totalProcessingTime +"ms.
";
                        warningToolTip = procedureName + "
 has total processing time greater
 than "+ totalProcessingTime +"ms.";
                    }

                    if(averageExecutionTime != undefined && averageExecutionTime != ""){
                        if(avgExecTime > averageExecutionTime){
                            $("#analysisRemarks").show();
                            $("#procedureWarningSection").show();
                            warningString = warningString + "
" + procedureName + " has average execution time greater than "+ averageExecutionTime +"ms.
"
                            warningToolTip = warningToolTip + "
"+ procedureName + "
has average execution time greater
 than "+ averageExecutionTime +"ms.";
                        }
                    }

                    $("#procedureWarning").append(warningString);

                    VoltDbAnalysis.procedureValue[procedureName] =
                        {
                            AVG: avgExecTime,
                            INVOCATIONS: invocation,
                            TOTAL_PROCESSING_TIME: calculatedProcessingTime,
                            TYPE:type,
                            WEIGHTED_PERC: wtPercentage,
                            WARNING: warningToolTip
                        }
                    if(procedureName.indexOf("org.voltdb.sysprocs") > -1){
                        dataLatencySysProcedures.push({"label": procedureName , "value": avgExecTime, "index": i});
                        dataFrequencySysProcedures.push({"label": procedureName, "value": invocation, "index": i});
                        dataTotalProcessingSysProcedures.push({"label": procedureName, "value": calculatedProcessingTime, "index": i});
                    } else {
                        dataLatencyProcedures.push({"label": procedureName , "value": avgExecTime, "index": i});
                        dataFrequencyProcedures.push({"label": procedureName, "value": invocation, "index": i});
                        dataTotalProcessingProcedures.push({"label": procedureName, "value": calculatedProcessingTime, "index": i});
                    }
                }
                var formatDate = VoltDbAnalysis.formatDateTime(timestamp);
                $("#analysisDate").html(formatDate);
                formatAnalysisLegend(isMPPresent, isPPresent);
                MonitorGraphUI.initializeAnalysisGraph();
                if(showHideSysProcedures){
                    dataLatencyProcedures = $.merge(dataLatencyProcedures, dataLatencySysProcedures);
                    dataFrequencyProcedures = $.merge(dataFrequencyProcedures, dataFrequencySysProcedures);
                    dataTotalProcessingProcedures = $.merge(dataTotalProcessingProcedures, dataTotalProcessingSysProcedures);

                }
                ////order the procedure by  their (avg_exec_time * invocation) value
                dataLatencyProcedures.sort(function(a,b) {return ((a.index) > (b.index)) ? 1 : (((b.index) > (a.index)) ? -1 : 0);});
                dataFrequencyProcedures.sort(function(a,b) {return ((a.index) > (b.index)) ? 1 : (((b.index) > (a.index)) ? -1 : 0);});
                dataTotalProcessingProcedures.sort(function(a,b) {return ((a.index) > (b.index)) ? 1 : (((b.index) > (a.index)) ? -1 : 0);});

                MonitorGraphUI.RefreshAnalysisLatencyGraph(dataLatencyProcedures);
                MonitorGraphUI.RefreshAnalysisFrequencyGraph(dataFrequencyProcedures);
                MonitorGraphUI.RefreshAnalysisCombinedGraph(dataTotalProcessingProcedures);
            })
        })

        voltDbRenderer.GetProcedureDetailInformation(function (procedureDetails){
            var latencyDetails = [];
//            procedureDetails["PROCEDURE_DETAIL"].sort(function(a, b) {
//                return parseFloat(b.AVG_EXECUTION_TIME) - parseFloat(a.AVG_EXECUTION_TIME);
//            });

             //find procedure type

            procedureDetails["PROCEDURE_DETAIL"].forEach (function(item){
                var type = "Single Partitioned";
                if(procedureName == item.PROCEDURE && item.PARTITION_ID == 16383){
                    type = "Multi Partitioned"
                    return false;
                }

                if(VoltDbAnalysis.combinedDetail[item.PROCEDURE] == undefined){
                    VoltDbAnalysis.combinedDetail[item.PROCEDURE] = [];
                }

                if(item.STATEMENT != "<ALL>"){
                    VoltDbAnalysis.combinedDetail[item.PROCEDURE].push({
                        AVG: item.AVG_EXECUTION_TIME/1000000,
                        INVOCATIONS: item.INVOCATIONS,
                        PARTITION_ID : item.PARTITION_ID,
                        STATEMENT: item.STATEMENT,
                        TIMESTAMP: item.TIMESTAMP,
                        PROCEDURE: item.PROCEDURE,
                        TYPE: type
                    })
                }

                VoltDbAnalysis.latencyDetail[item.STATEMENT] =
                    {
                        AVG: item.AVG_EXECUTION_TIME/1000000,
                        MIN: item.MIN_EXECUTION_TIME/1000000,
                        MAX: item.MAX_EXECUTION_TIME/1000000,
                        PARTITION_ID: item.PARTITION_ID,
                        INVOCATIONS: item.INVOCATIONS
                    }

                if(item.STATEMENT != "<ALL>"){
                    VoltDbAnalysis.latencyDetailValue.push({"type": type,  "STATEMENT": item.STATEMENT , "value": item.AVG_EXECUTION_TIME/1000000, "PROCEDURE": item.PROCEDURE, "TIMESTAMP": item.TIMESTAMP, "INVOCATION": item.INVOCATIONS, "MIN": item.MIN_EXECUTION_TIME, "MAX": item.MAX_EXECUTION_TIME});
                }
            });

            MonitorGraphUI.initializeFrequencyDetailGraph();
            MonitorGraphUI.initializeProcedureDetailGraph();
            MonitorGraphUI.initializeCombinedDetailGraph();
        });

    }

    $("#btnAnalyzeNow").on("click", function(){
        fetchData();
    })
}

(function(window) {
    iVoltDbAnalysis = (function(){
        this.procedureValue = {};
        this.latencyDetailValue = [];
        this.latencyDetail = {};
        this.combinedDetail = {};
        this.partitionStatus = "SP"
        this.proceduresCount = 0;
        this.latencyDetailTest = {};
        this.formatDateTime = function(timestamp) {
            var dateTime = new Date(timestamp);
            //get date
            var days = dateTime.getDate();
            var months = dateTime.getMonth() + 1;
            var years = dateTime.getFullYear();

            days = days < 10 ? "0" + days : days;
            months = months < 10 ? "0" + months : months;

            //get time
            var timePeriod = "AM"
            var hours = dateTime.getHours();
            var minutes = dateTime.getMinutes();
            var seconds = dateTime.getSeconds();

            timePeriod = hours >= 12 ? 'PM' : 'AM';
            hours = hours % 12;
            hours = hours ? hours : 12;
            hours = hours < 10 ? "0" + hours : hours
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            //get final date time
            var date = months + "/" + days + "/" + years;
            var time = hours + ":" + minutes + ":" + seconds + " " + timePeriod;
            return date + " " + time;
        };

        this.refreshChart= function(){
            setTimeout(function(){
                window.dispatchEvent(new Event('resize'));
            },200)
        }

        this.setDefaultAnalysisSettings = function(){
            if(VoltDbUI.getFromLocalStorage("totalProcessingTime") == undefined){
               saveInLocalStorage("totalProcessingTime", 3000)
            }
            if(VoltDbUI.getFromLocalStorage("averageExecutionTime") == undefined){
                saveInLocalStorage("averageExecutionTime", 500)
            }
            if(VoltDbUI.getFromLocalStorage("showHideSysProcedures") == undefined){
                saveInLocalStorage("showHideSysProcedures", true)
            }
        }
    });

    window.VoltDbAnalysis = new iVoltDbAnalysis();
})(window);<commit_msg>VMC-358-modified-all: Modified code to replace data from procedure profile API with that from procedure detail API<commit_after>var latencyDetails = [];
function loadAnalysisPage(){
    VoltDbAnalysis.setDefaultAnalysisSettings();
    $("#tabProcedureBtn").trigger("click");
    $("#tabAnalysis li a").on("click", function(){
        VoltDbAnalysis.refreshChart();
    })

    $("#ulProcedure li a").on("click", function(){
        refreshLegend($($(this)[0]).text());
    })

    function refreshLegend(legendTitle){
        if(legendTitle == "Frequency"){
            $(".spnAnalysisLegend").html(VoltDbAnalysis.partitionStatus == "both" ?"Frequency(" : "Frequency");
            VoltDbAnalysis.currentTab =  "Frequency";
        } else if(legendTitle == "Total Processing Time"){
            $(".spnAnalysisLegend").html(VoltDbAnalysis.partitionStatus == "both" ?"Total Processing Time(" : "Total Processing Time");
            VoltDbAnalysis.currentTab = "Total Processing Time";
        } else {
            $(".spnAnalysisLegend").html(VoltDbAnalysis.partitionStatus == "both" ?"Average Execution Time(" : "Average Execution Time");
            VoltDbAnalysis.currentTab = "Average Execution Time";
        }
        //this method is called twice to ensure graph reloads properly
        VoltDbAnalysis.refreshChart();
        VoltDbAnalysis.refreshChart();
    }

    function calculateCombinedValue(profileData){
        var totalValue = 0;
        for(var j = 0; j < profileData.length; j++){
            totalValue += (profileData[j].AVG/1000000) * profileData[j].INVOCATIONS;
        }
        return totalValue;
    }

    function checkObjForLongStatementName(profileData){
        for(var j = 0; j < profileData.length; j++){
            if(profileData[j].STATEMENT.length > 14){
                return true;
            }
        }
        return false;
    }

    function formatAnalysisLegend(isMP, isP){
        if(isMP && isP){
            $("#legendAnalysisMP").hide();
            $("#legendAnalysisP").hide();
            $("#legendAnalysisBoth").show();
            VoltDbAnalysis.partitionStatus = "both"
        } else if(isMP){
            $("#legendAnalysisMP").show();
            $("#legendAnalysisP").hide();
            $("#legendAnalysisBoth").hide();
            VoltDbAnalysis.partitionStatus = "MP"
        } else {
            $("#legendAnalysisMP").hide();
            $("#legendAnalysisP").show();
            $("#legendAnalysisBoth").hide();
            VoltDbAnalysis.partitionStatus = "SP"
        }
        refreshLegend(VoltDbAnalysis.currentTab);
    }

    function fetchData (){
        $("#analysisLoader").show();
        $("#analysisRemarks").hide();
        $("#procedureWarning").html("");
        $("#tableWarning").html("");
        VoltDbAnalysis.refreshChart();

        voltDbRenderer.GetProcedureDetailInformation(function (procedureDetails){
            if(procedureDetails != undefined){
                if(!$.isEmptyObject(procedureDetails["PROCEDURE_DETAIL"])){
                    $(".analyzeNowContent").hide();
                    $(".dataContent").show();
                    $(".noDataContent").hide();
                } else {
                    $(".mainContentAnalysis").hide();
                    $(".dataContent").hide();
                    $(".noDataContent").show();

                }
                //For data section
                //$("#tblAnalyzeNowContent").hide();
                //$("#tblNoDataContent").show();
            }
            $("#analysisLoader").hide();
            //************need to determine count late****************//
            //VoltDbAnalysis.proceduresCount = profileData["PROCEDURE_PROFILE"].length;
            var dataLatencyProcedures = [];
            var dataLatencySysProcedures = [];
            var dataFrequencySysProcedures = [];
            var dataFrequencyProcedures = [];
            var dataTotalProcessingProcedures = [];
            var dataTotalProcessingSysProcedures = [];
            var timestamp;
            var isMPPresent = false;
            var isPPresent = false;
            var totalProcessingTime = VoltDbUI.getFromLocalStorage("totalProcessingTime");
            var averageExecutionTime = VoltDbUI.getFromLocalStorage("averageExecutionTime");
            var showHideSysProcedures = VoltDbUI.getFromLocalStorage("showHideSysProcedures");
            var procedureObj = {}
            var type = "Single Partitioned";
            for(var i = 0; i < procedureDetails["PROCEDURE_DETAIL"].length; i++ ){
                var statement = procedureDetails["PROCEDURE_DETAIL"][i].STATEMENT;
                var procedure = procedureDetails["PROCEDURE_DETAIL"][i].PROCEDURE;
                if(i == 0)
                    timestamp = procedureDetails["PROCEDURE_DETAIL"][i].TIMESTAMP;

                if(!procedureObj.hasOwnProperty(procedure)){
                    procedureObj[procedure] = {};
                    procedureObj[procedure]["COUNT"] = 0;
                    procedureObj[procedure]["AVG"] = 0;
                    procedureObj[procedure]["INVOCATION"] = 0;
                    procedureObj[procedure]["TYPE"] = "Single Partitioned"
                }

                if(statement == "<ALL>"){
                    procedureObj[procedure]["COUNT"]++;
                    procedureObj[procedure]["AVG"] += procedureDetails["PROCEDURE_DETAIL"][i].AVG_EXECUTION_TIME;
                    procedureObj[procedure]["INVOCATION"] += procedureDetails["PROCEDURE_DETAIL"][i].INVOCATIONS;
                }

                if(procedureObj[procedure]["TYPE"] != "Multi Partitioned"
                && procedureDetails["PROCEDURE_DETAIL"][i].PARTITION_ID == 16383){
                    procedureObj[procedure]["TYPE"] = "Multi Partitioned";
                }
            }

            var isSPresent = false;
            var isMPPresent = false;
            $.each(procedureObj, function(key, value){
                var avgExecTime = (value["AVG"] / value["COUNT"]) / 1000000;
                var calculatedProcessingTime = (avgExecTime * value["INVOCATION"]);
                var procedureName = key;
                var invocation = value["INVOCATION"];
                var type = value["TYPE"];
                var warningString = '';
                var warningToolTip = '';

                if((procedureName.indexOf("org.voltdb.sysprocs") > -1 && showHideSysProcedures)
                || procedureName.indexOf("org.voltdb.sysprocs") == -1){
                    if(type == "Single Partitioned"){
                        isSPresent = true;
                    } else {
                        isMPPresent = true;
                    }
                }

                if(calculatedProcessingTime > totalProcessingTime && totalProcessingTime != "") {
                    $("#analysisRemarks").show();
                    $("#procedureWarningSection").show();
                    warningString = "
" + procedureName + " has total processing time greater than "+ totalProcessingTime +"ms.
";
                    warningToolTip = procedureName + "
 has total processing time greater
 than "+ totalProcessingTime +"ms.";
                }

                if(averageExecutionTime != undefined && averageExecutionTime != ""){
                    if(avgExecTime > averageExecutionTime){
                        $("#analysisRemarks").show();
                        $("#procedureWarningSection").show();
                        warningString = warningString + "
" + procedureName + " has average execution time greater than "+ averageExecutionTime +"ms.
"
                        warningToolTip = warningToolTip + "
"+ procedureName + "
has average execution time greater
 than "+ averageExecutionTime +"ms.";
                    }
                }

                $("#procedureWarning").append(warningString);

                VoltDbAnalysis.procedureValue[procedureName] = {
                    AVG: avgExecTime,
                    INVOCATIONS: invocation,
                    TOTAL_PROCESSING_TIME: calculatedProcessingTime,
                    TYPE:type,
                    WARNING: warningToolTip
                }

                if(procedureName.indexOf("org.voltdb.sysprocs") > -1){
                    dataLatencySysProcedures.push({"label": procedureName , "value": avgExecTime, "index": calculatedProcessingTime});
                    dataFrequencySysProcedures.push({"label": procedureName, "value": invocation, "index": calculatedProcessingTime});
                    dataTotalProcessingSysProcedures.push({"label": procedureName, "value": calculatedProcessingTime, "index": calculatedProcessingTime});
                } else {
                    dataLatencyProcedures.push({"label": procedureName , "value": avgExecTime, "index": calculatedProcessingTime});
                    dataFrequencyProcedures.push({"label": procedureName, "value": invocation, "index": calculatedProcessingTime});
                    dataTotalProcessingProcedures.push({"label": procedureName, "value": calculatedProcessingTime, "index": calculatedProcessingTime});
                }
            });

            var formatDate = VoltDbAnalysis.formatDateTime(timestamp);
            $("#analysisDate").html(formatDate);
            formatAnalysisLegend(isMPPresent, isSPresent);
            MonitorGraphUI.initializeAnalysisGraph();

            if(showHideSysProcedures){
                dataLatencyProcedures = $.merge(dataLatencyProcedures, dataLatencySysProcedures);
                dataFrequencyProcedures = $.merge(dataFrequencyProcedures, dataFrequencySysProcedures);
                dataTotalProcessingProcedures = $.merge(dataTotalProcessingProcedures, dataTotalProcessingSysProcedures);
            }

            ////order the procedure by  their (avg_exec_time * invocation) value
            dataLatencyProcedures.sort(function(a,b) {return ((b.index) > (a.index)) ? 1 : (((a.index) > (b.index)) ? -1 : 0);});
            dataFrequencyProcedures.sort(function(a,b) {return ((b.index) > (a.index)) ? 1 : (((a.index) > (b.index)) ? -1 : 0);});
            dataTotalProcessingProcedures.sort(function(a,b) {return ((b.index) > (a.index)) ? 1 : (((a.index) > (b.index)) ? -1 : 0);});

            MonitorGraphUI.RefreshAnalysisLatencyGraph(dataLatencyProcedures);
            MonitorGraphUI.RefreshAnalysisFrequencyGraph(dataFrequencyProcedures);
            MonitorGraphUI.RefreshAnalysisCombinedGraph(dataTotalProcessingProcedures);
        });

        voltDbRenderer.GetProcedureDetailInformation(function (procedureDetails){
            var latencyDetails = [];
//            procedureDetails["PROCEDURE_DETAIL"].sort(function(a, b) {
//                return parseFloat(b.AVG_EXECUTION_TIME) - parseFloat(a.AVG_EXECUTION_TIME);
//            });

             //find procedure type

            procedureDetails["PROCEDURE_DETAIL"].forEach (function(item){
                var type = "Single Partitioned";
                if(procedureName == item.PROCEDURE && item.PARTITION_ID == 16383){
                    type = "Multi Partitioned"
                    return false;
                }

                if(VoltDbAnalysis.combinedDetail[item.PROCEDURE] == undefined){
                    VoltDbAnalysis.combinedDetail[item.PROCEDURE] = [];
                }

                if(item.STATEMENT != "<ALL>"){
                    VoltDbAnalysis.combinedDetail[item.PROCEDURE].push({
                        AVG: item.AVG_EXECUTION_TIME/1000000,
                        INVOCATIONS: item.INVOCATIONS,
                        PARTITION_ID : item.PARTITION_ID,
                        STATEMENT: item.STATEMENT,
                        TIMESTAMP: item.TIMESTAMP,
                        PROCEDURE: item.PROCEDURE,
                        TYPE: type
                    })
                }

                VoltDbAnalysis.latencyDetail[item.STATEMENT] =
                    {
                        AVG: item.AVG_EXECUTION_TIME/1000000,
                        MIN: item.MIN_EXECUTION_TIME/1000000,
                        MAX: item.MAX_EXECUTION_TIME/1000000,
                        PARTITION_ID: item.PARTITION_ID,
                        INVOCATIONS: item.INVOCATIONS
                    }

                if(item.STATEMENT != "<ALL>"){
                    VoltDbAnalysis.latencyDetailValue.push({"type": type,  "STATEMENT": item.STATEMENT , "value": item.AVG_EXECUTION_TIME/1000000, "PROCEDURE": item.PROCEDURE, "TIMESTAMP": item.TIMESTAMP, "INVOCATION": item.INVOCATIONS, "MIN": item.MIN_EXECUTION_TIME, "MAX": item.MAX_EXECUTION_TIME});
                }
            });

            MonitorGraphUI.initializeFrequencyDetailGraph();
            MonitorGraphUI.initializeProcedureDetailGraph();
            MonitorGraphUI.initializeCombinedDetailGraph();
        });

    }

    $("#btnAnalyzeNow").on("click", function(){
        fetchData();
    })
}

(function(window) {
    iVoltDbAnalysis = (function(){
        this.procedureValue = {};
        this.latencyDetailValue = [];
        this.latencyDetail = {};
        this.combinedDetail = {};
        this.partitionStatus = "SP"
        this.proceduresCount = 0;
        this.latencyDetailTest = {};
        this.currentTab = "Average Execution Time";
        this.formatDateTime = function(timestamp) {
            var dateTime = new Date(timestamp);
            //get date
            var days = dateTime.getDate();
            var months = dateTime.getMonth() + 1;
            var years = dateTime.getFullYear();

            days = days < 10 ? "0" + days : days;
            months = months < 10 ? "0" + months : months;

            //get time
            var timePeriod = "AM"
            var hours = dateTime.getHours();
            var minutes = dateTime.getMinutes();
            var seconds = dateTime.getSeconds();

            timePeriod = hours >= 12 ? 'PM' : 'AM';
            hours = hours % 12;
            hours = hours ? hours : 12;
            hours = hours < 10 ? "0" + hours : hours
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            //get final date time
            var date = months + "/" + days + "/" + years;
            var time = hours + ":" + minutes + ":" + seconds + " " + timePeriod;
            return date + " " + time;
        };

        this.refreshChart= function(){
            setTimeout(function(){
                window.dispatchEvent(new Event('resize'));
            },200)
        }

        this.setDefaultAnalysisSettings = function(){
            if(VoltDbUI.getFromLocalStorage("totalProcessingTime") == undefined){
               saveInLocalStorage("totalProcessingTime", 3000)
            }
            if(VoltDbUI.getFromLocalStorage("averageExecutionTime") == undefined){
                saveInLocalStorage("averageExecutionTime", 500)
            }
            if(VoltDbUI.getFromLocalStorage("showHideSysProcedures") == undefined){
                saveInLocalStorage("showHideSysProcedures", true)
            }
        }
    });

    window.VoltDbAnalysis = new iVoltDbAnalysis();
})(window);<|endoftext|>


<commit_before>/**
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Check whether the page uses the non-standard scrollTop and
 * scrollLeft properties.
 * @bug https://code.google.com/p/compatibility-detector/issues/detail?id=16
 *
 * The scrollTop and scrollLeft properties are not included in any public
 * standard, and have different behavior in different browsers.
 * In IE and Firefox, document.body.scrollTop/Left work in quirks mode but not
 * in standards mode, while document.documentElement.scrollTop/Left work
 * in standards mode but not quirks mode.
 * In Webkit, only document.body.scrollTop/Left work, both in quirks mode and
 * standars mode. And document.documentElement.scrollTop/Left always return 0,
 * according to https://bugs.webkit.org/show_bug.cgi?id=5991
 *
 * For detecting these, we define a new getter/setter to get
 * document.documentElement.scrollTop/Left. If the page try to use
 * scrollTop/Left on document.documentElement, we can catch it.
 */

addScriptToInject(function() {

// Only check when browser is in standards mode, since IE and Chrome are the
// same in quirks mode.
if (chrome_comp.inQuirksMode())
  return;

chrome_comp.CompDetect.declareDetector(

'scroll_top_left',

chrome_comp.CompDetect.NonScanDomBaseDetector,

function constructor(rootNode) {
  // Index into the array: 0: docElement.scrollLeft, 1: docElement.scrollTop,
  // 2: body.scrollLeft, 3: body.scrollTop.
  this.getterCallStacks_ = [];
  this.getterResults_ = [];
  this.lastCaller_ = null;

  this.onGetterCalled_ = function(id, result) {
    var caller = arguments.callee.caller.caller.caller;
    if (caller == this.lastCaller_) {
      // Only record the first occurrence in one function.
      if (this.getterCallStacks_[id])
        return;
    } else {
      this.checkUnpairedGetterCalls_();
      this.lastCaller_ = caller;
    }

    var callerSource = caller.toString();

    // TODO: Omit jQuery, because ...
    if (callerSource.indexOf('jQuery') != -1)
      return;

    switch (id) {
      case 0:
        if (callerSource.indexOf('pageXOffset') != -1 ||
            callerSource.indexOf('scrollX') != -1 ||
            callerSource.indexOf('body.scrollLeft') != -1)
          return;
        break;
      case 1:
        if (callerSource.indexOf('pageYOffset') != -1 ||
            callerSource.indexOf('scrollY') != -1 ||
            callerSource.indexOf('body.scrollTop') != -1)
          return;
        break;
      case 2:
        if (callerSource.indexOf('pageXOffset') != -1 ||
            callerSource.indexOf('scrollX') != -1 ||
            callerSource.indexOf('documentElement.scrollLeft') != -1)
          return;
        break;
      case 3:
        if (callerSource.indexOf('pageYOffset') != -1 ||
            callerSource.indexOf('scrollY') != -1 ||
            callerSource.indexOf('documentElement.scrollTop') != -1)
          return;
        break;
    }

    var stack = chrome_comp.dumpStack();
    if (!chrome_comp.isCalledFromExtension(stack)) {
      this.getterCallStacks_[id] = stack;
      this.getterResults_[id] = result;
    }
  };

  this.checkUnpairedGetterCalls_ = function() {

    if (this.getterCallStacks_[0] && !this.getterCallStacks_[2]) {
      // documentElement.scrollLeft without paired body.scrollLeft.
      this.addProblem('BX9008', {stack: this.getterCallStacks_[0]});

    } else if (!this.getterCallStacks_[0] && this.getterCallStacks_[2] &&
        !this.getterResults_[2]) {
      // body.scrollLeft without paired documentElement.scrollLeft.
      // Omit the case when body.scrollLeft is not zero, because in
      // 'body.scrollLeft || docElement.scrollLeft', 'docElement.scrollLeft'
      // won't be called.
      this.addProblem('BX9008', {stack: this.getterCallStacks_[2]});
    }

    if (this.getterCallStacks_[1] && !this.getterCallStacks_[3]) {
      // docElement.scrollTop without paired body.scrollTop
      this.addProblem('BX9008', {stack: this.getterCallStacks_[1]});

    } else if (!this.getterCallStacks_[1] && this.getterCallStacks_[3] &&
        !this.getterResults_[3]) {
      // body.scrollTop without paired docElement.scrollTop.
      // Omit the case when body.scrollTop is not zero, because in
      // 'body.scrollTop || docElement.scrollTop', 'docElement.scrollTop'
      // won't be called.
      this.addProblem('BX9008', {stack: this.getterCallStacks_[3]});
    }

    this.getterCallStacks_ = [];
    this.getterResults_ = [];
  };

  this.setUpDocumentElementHooks_ = function() {
    var docElement = document.documentElement;
    var This = this;
    chrome_comp.CompDetect.registerSimplePropertyHook(docElement, 'scrollLeft',
        function(oldValue, newValue, reason) {
          if (reason == 'get')
            This.onGetterCalled_(0, 0);
          return 0;
        }, false, true);
    chrome_comp.CompDetect.registerSimplePropertyHook(docElement, 'scrollTop',
        function(oldValue, newValue, reason) {
          if (reason == 'get')
            This.onGetterCalled_(1, 0);
          return 0;
        }, false, true);
  };

  this.bodyHooksReady_ = false;

  // Hook document.body.scrollTop/Left.
  this.setUpBodyHooks_ = function() {
    if (this.bodyHooksReady_)
      return;
    this.bodyHooksReady_ = true;

    var This = this;
    chrome_comp.CompDetect.registerSimplePropertyHook(
        document.body, 'scrollLeft',
        function(oldValue, newValue, reason) {
          if (reason == 'get') {
            var result = window.scrollX;
            This.onGetterCalled_(2, result);
            return result;
          } else {
            window.scrollTo(newValue, window.scrollY);
          }
        }, false, true);
    chrome_comp.CompDetect.registerSimplePropertyHook(
        document.body, 'scrollTop',
        function(oldValue, newValue, reason) {
          if (reason == 'get') {
            var result = window.scrollY;
            This.onGetterCalled_(3, result);
            return result;
          } else {
            window.scrollTo(window.scrollX, newValue);
          }
        }, false, true);
  };

},

function setUp() {
  this.setUpDocumentElementHooks_();

  if (document.body) {
    this.setUpBodyHooks_();
    return;
  }

  // The document.body may not be present here. If so, we create a
  // document.body property hook that returns the first element with tag name
  // 'body'.
  var originalGetter = document.__lookupGetter__('body');
  if (!originalGetter) {
    var body = null;
    originalGetter = function() {
      if (!body) {
        var bodies = document.getElementsByTagName('body');
        if (bodies)
          body = bodies[0];
      }
      return body;
    };
  }
  var This = this;
  chrome_comp.CompDetect.registerSimplePropertyHook(document, 'body',
      function(oldValue, newValue, reason) {
        if (reason == 'get') {
          var body = originalGetter.apply(document);
          if (body)
            This.setUpBodyHooks_();
        }
        return body;
      }, true, true);
},

function cleanUp() {
  // We can do nothing here, since we cannot remove the simple property hooks
  // and document.body hook.
  // Remove them will cause some standard page features broken.
},

function postAnalyze() {
  this.checkUnpairedGetterCalls_();
  this.lastCaller_ = null;
}

); // declareDetector

});
<commit_msg>[BX9008] Remove blank lines<commit_after>/**
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Check whether the page uses the non-standard scrollTop and
 * scrollLeft properties.
 * @bug https://code.google.com/p/compatibility-detector/issues/detail?id=16
 *
 * http://w3help.org/zh-cn/causes/BX9008
 * The scrollTop and scrollLeft properties are not included in any public
 * standard, and have different behavior in different browsers.
 * In IE and Firefox, document.body.scrollTop/Left work in quirks mode but not
 * in standards mode, while document.documentElement.scrollTop/Left work
 * in standards mode but not quirks mode.
 * In Webkit, only document.body.scrollTop/Left work, both in quirks mode and
 * standars mode. And document.documentElement.scrollTop/Left always return 0,
 * according to https://bugs.webkit.org/show_bug.cgi?id=5991
 *
 * To detect these, we define a new scrollTop/Left getter/setter for both
 * document.documentElement and document.body. If the page only uses
 * scrollTop/Left on document.documentElement but not on document.body,
 * we will report it.
 */

addScriptToInject(function() {

// Only check when browser is in standards mode, since IE and Chrome are the
// same in quirks mode.
if (chrome_comp.inQuirksMode())
  return;

chrome_comp.CompDetect.declareDetector(

'scroll_top_left',

chrome_comp.CompDetect.NonScanDomBaseDetector,

function constructor(rootNode) {
  // Index into the array: 0: docElement.scrollLeft, 1: docElement.scrollTop,
  // 2: body.scrollLeft, 3: body.scrollTop.
  this.getterCallStacks_ = [];
  this.getterResults_ = [];
  this.lastCaller_ = null;

  this.onGetterCalled_ = function(id, result) {
    // caller 1 is anonymous function parameter in registerSimplePropertyHook.
    // caller 2 is ExistingMethodHookObject.newMethodHandler_.
    // caller 3 is the original caller.
    var caller = arguments.callee.caller.caller.caller;
    if (caller == this.lastCaller_) {
      // Only record the first occurrence in one function.
      if (this.getterCallStacks_[id])
        return;
    } else {
      this.checkUnpairedGetterCalls_();
      this.lastCaller_ = caller;
    }

    var callerSource = caller.toString();

    switch (id) {
      case 0:
        if (callerSource.indexOf('pageXOffset') != -1 ||
            callerSource.indexOf('scrollX') != -1 ||
            callerSource.indexOf('body.scrollLeft') != -1)
          return;
        break;
      case 1:
        if (callerSource.indexOf('pageYOffset') != -1 ||
            callerSource.indexOf('scrollY') != -1 ||
            callerSource.indexOf('body.scrollTop') != -1)
          return;
        break;
      case 2:
        if (callerSource.indexOf('pageXOffset') != -1 ||
            callerSource.indexOf('scrollX') != -1 ||
            callerSource.indexOf('documentElement.scrollLeft') != -1)
          return;
        break;
      case 3:
        if (callerSource.indexOf('pageYOffset') != -1 ||
            callerSource.indexOf('scrollY') != -1 ||
            callerSource.indexOf('documentElement.scrollTop') != -1)
          return;
        break;
    }

    var stack = chrome_comp.dumpStack();
    if (!chrome_comp.isCalledFromExtension(stack)) {
      this.getterCallStacks_[id] = stack;
      this.getterResults_[id] = result;
    }
  };

  this.checkUnpairedGetterCalls_ = function() {

    if (this.getterCallStacks_[0] && !this.getterCallStacks_[2]) {
      // documentElement.scrollLeft without paired body.scrollLeft.
      this.addProblem('BX9008', {stack: this.getterCallStacks_[0]});
    } else if (!this.getterCallStacks_[0] && this.getterCallStacks_[2] &&
        !this.getterResults_[2]) {
      // body.scrollLeft without paired documentElement.scrollLeft.
      // Omit the case when body.scrollLeft is not zero, because in
      // 'body.scrollLeft || docElement.scrollLeft', 'docElement.scrollLeft'
      // won't be called.
      this.addProblem('BX9008', {stack: this.getterCallStacks_[2]});
    }

    if (this.getterCallStacks_[1] && !this.getterCallStacks_[3]) {
      // docElement.scrollTop without paired body.scrollTop
      this.addProblem('BX9008', {stack: this.getterCallStacks_[1]});
    } else if (!this.getterCallStacks_[1] && this.getterCallStacks_[3] &&
        !this.getterResults_[3]) {
      // body.scrollTop without paired docElement.scrollTop.
      // Omit the case when body.scrollTop is not zero, because in
      // 'body.scrollTop || docElement.scrollTop', 'docElement.scrollTop'
      // won't be called.
      this.addProblem('BX9008', {stack: this.getterCallStacks_[3]});
    }

    this.getterCallStacks_ = [];
    this.getterResults_ = [];
  };

  this.setUpDocumentElementHooks_ = function() {
    var docElement = document.documentElement;
    var This = this;
    chrome_comp.CompDetect.registerSimplePropertyHook(docElement, 'scrollLeft',
        function(oldValue, newValue, reason) {
          if (reason == 'get')
            This.onGetterCalled_(0, 0);
          return 0;
        }, false, true);
    chrome_comp.CompDetect.registerSimplePropertyHook(docElement, 'scrollTop',
        function(oldValue, newValue, reason) {
          if (reason == 'get')
            This.onGetterCalled_(1, 0);
          return 0;
        }, false, true);
  };

  this.bodyHooksReady_ = false;

  // Hook document.body.scrollTop/Left.
  this.setUpBodyHooks_ = function() {
    if (this.bodyHooksReady_)
      return;
    this.bodyHooksReady_ = true;
    var This = this;
    chrome_comp.CompDetect.registerSimplePropertyHook(
        document.body, 'scrollLeft',
        function(oldValue, newValue, reason) {
          if (reason == 'get') {
            var result = window.scrollX;
            This.onGetterCalled_(2, result);
            return result;
          } else {
            window.scrollTo(newValue, window.scrollY);
          }
        }, false, true);
    chrome_comp.CompDetect.registerSimplePropertyHook(
        document.body, 'scrollTop',
        function(oldValue, newValue, reason) {
          if (reason == 'get') {
            var result = window.scrollY;
            This.onGetterCalled_(3, result);
            return result;
          } else {
            window.scrollTo(window.scrollX, newValue);
          }
        }, false, true);
  };

},

function setUp() {
  this.setUpDocumentElementHooks_();

  if (document.body) {
    this.setUpBodyHooks_();
    return;
  }

  // The document.body may not be present here. If so, we create a
  // document.body property hook that returns the first element with tag name
  // 'body'.
  var originalGetter = document.__lookupGetter__('body');
  if (!originalGetter) {
    var body = null;
    originalGetter = function() {
      if (!body) {
        var bodies = document.getElementsByTagName('body');
        if (bodies)
          body = bodies[0];
      }
      return body;
    };
  }
  var This = this;
  chrome_comp.CompDetect.registerSimplePropertyHook(document, 'body',
      function(oldValue, newValue, reason) {
        if (reason == 'get') {
          var body = originalGetter.apply(document);
          if (body)
            This.setUpBodyHooks_();
        }
        return body;
      }, true, true);
},

function cleanUp() {
  // We can do nothing here, since we cannot remove the simple property hooks
  // and document.body hook.
  // Remove them will cause some standard page features broken.
},

function postAnalyze() {
  this.checkUnpairedGetterCalls_();
  this.lastCaller_ = null;
}

); // declareDetector

});
<|endoftext|>


<commit_before>function is_chinese(word) {
    return (/^[\u4e00-\u9fa5]+$/g).test(word);
}

function is_english(word) {
    return (/^[a-z\sA-Z]+$/g).test(word);
}

function valid_word(word) {
    if (word.length === 0 || word.length > 190) {
        return false;
    }
    if (is_chinese(word)) {
        return "Chinese";
    }
    if (is_english(word)) {
        return "English";
    }
    return "Mixed";
}

var haloword_opened = false;
var haloword_html = '
\

\
\
\
<audio id="haloword-audio"></audio>\

\
\
\
\
\

\

\

';
$("body").append(haloword_html);

// deal with Clearly
document.addEventListener("DOMNodeInserted", function(event) {
    var element = event.target;
    if ($(element).attr("id") == "readable_iframe") {
        // HACK: wait for iframe ready
        setTimeout(function() {
            $("body", element.contentDocument).mouseup(event_mouseup);
            $("body", element.contentDocument).click(event_click);
            if ($(element).css('z-index') >= 2147483647) {
                var style = $(element).attr('style') + ' z-index: 2147483646 !important';
                $(element).attr('style', style);
            }
        }, 1000);
    }
});

$("body").mouseup(event_mouseup);
$("body").click(event_click);

function event_click(event) {
    if (haloword_opened) {
        var target = $(event.target);
        if (target.attr("id") != "haloword-lookup" && !target.parents("#haloword-lookup")[0]) {
            $("#haloword-lookup").hide();
            $("#haloword-remove").hide();
            $("#haloword-add").show();
            haloword_opened = false;
        }
    }
}

var icon_url = chrome.extension.getURL("img/icon.svg");
var style_content = "";
if ($("head")[0]) {
    $($("head")[0]).append(style_content);
}
else {
    $($("body")[0]).prepend(style_content);
}

$("#haloword-lookup").draggable({ handle: "#haloword-title" });

$("#haloword-pron").click(function() {
    // HACK: fix Chrome won't play second time
    // unfortunately this doesn't work properly. more: crbug.com/129165.
    //$("#haloword-audio")[0].load();
    $("#haloword-audio")[0].play();
});

function pron_exist(word, is_upper) {
    /* two URLs:
    http://www.gstatic.com/dictionary/static/sounds/de/0/halo.mp3
    http://www.gstatic.com/dictionary/static/sounds/de/0/!Capella.mp3
    */
    var pron_url = "http://www.gstatic.com/dictionary/static/sounds/de/0/" + word + ".mp3";
    if (is_english(word) || is_upper) {
        $.ajax({
            url: pron_url,
            timeout: 3000,
            success: function() {
                var current_word = $("#haloword-word").html().toLowerCase();
                if (word == current_word || word.substring(1).toLowerCase() == current_word) {
                    $("#haloword-audio").attr("src", pron_url);
                    $("#haloword-pron").show();
                }
            },
            error: function(xhr, d, e) {
                if (!is_upper) {
                    pron_exist('!' + word[0].toUpperCase() + word.substring(1), true);
                }
            }
        });
    }
}

function get_selection() {
    var selection = $.trim(window.getSelection());
    if (!selection) {
        $("iframe").each(function() {
            if (this.contentDocument) {
                selection = $.trim(this.contentDocument.getSelection());
            }
            if (selection) {
                return false;
            }
        });
    }
    return selection;
}

$("#haloword-add").click(function() {
    $("#haloword-add").hide();
    $("#haloword-remove").show();
    var selection = get_selection();
    chrome.extension.sendMessage({method: "add", word: selection});
});
$("#haloword-remove").click(function() {
    $("#haloword-remove").hide();
    $("#haloword-add").show();
    var selection = get_selection();
    chrome.extension.sendMessage({method: "remove", word: selection});
});

function event_mouseup(e) {
    // chrome.storage.local.set({'disable_querybox': true})
    chrome.storage.local.get('disable_querybox', function(ret) {
        if (!ret.disable_querybox) {
            if (!e.ctrlKey && !e.metaKey) {
                return;
            }
            var selection = get_selection();
            var lang = valid_word(selection);
            if (!lang) {
                return;
            }

            $("#haloword-word").html(selection);
            $("#haloword-lookup").attr("style", "left: " + e.pageX + "px;" + "top: " + e.pageY + "px;");
            $("#haloword-open").attr("href", chrome.extension.getURL("main.html#" + selection));
            $("#haloword-close").click(function() {
                $("#haloword-lookup").hide();
                $("#haloword-remove").hide();
                $("#haloword-add").show();
                haloword_opened = false;
                return false;
            });

            $("#haloword-remove").hide();

            chrome.extension.sendMessage({method: "find", word: selection}, function(response) {
                if (response.exist) {
                    $("#haloword-add").hide();
                    $("#haloword-remove").show();
                }
                else {
                    $("#haloword-remove").hide();
                    $("#haloword-add").show();
                }
            });

            $("#haloword-pron").hide();
            $("#haloword-content").html("
Loading definitions...
");
            $("#haloword-lookup").show();

            $.ajax({
                url: youdao_url + selection,
                dataType: "json",
                success: function(data) {
                    var def = "", i;
                    if (data.errorCode === 0) {
                        if (data.basic) {
                            if (data.basic.phonetic) {
                                def += '
' + data.basic.phonetic + '
';
                            }

                            for (i in data.basic.explains) {
                                def += "
" + data.basic.explains[i] + "
";
                            }

                            $("#haloword-content").html(def);

                            pron_exist(selection.toLowerCase(), false);
                        }
                        else if (data.translation) {
                            for (i in data.translation) {
                                def += "
" + data.translation[i] + "
";
                            }
                            $("#haloword-content").html(def);
                        }
                        else {
                            // no definition and translation
                            $("#haloword-content").html("
I'm sorry, Dave.

I'm afraid I can't find that.
");
                        }
                    }
                    else {
                        $("#haloword-content").html("
I'm sorry, Dave.

I'm afraid I can't find that.
");
                    }
                },
                error: function(data) {
                    $("#extradef").hide();
                }
            });

            // HACK: fix dict window not openable
            setTimeout(function() {
                haloword_opened = true;
            }, 100);
        }
    })
}
<commit_msg>bug fix<commit_after>function is_chinese(word) {
    return (/^[\u4e00-\u9fa5]+$/g).test(word);
}

function is_english(word) {
    return (/^[a-z\sA-Z]+$/g).test(word);
}

function valid_word(word) {
    if (word.length === 0 || word.length > 190) {
        return false;
    }
    if (is_chinese(word)) {
        return "Chinese";
    }
    if (is_english(word)) {
        return "English";
    }
    return "Mixed";
}

var haloword_opened = false;
var haloword_html = '
\

\
\
\
<audio id="haloword-audio"></audio>\

\
\
\
\
\

\

\

';
$("body").append(haloword_html);

// deal with Clearly
document.addEventListener("DOMNodeInserted", function(event) {
    var element = event.target;
    if ($(element).attr("id") == "readable_iframe") {
        // HACK: wait for iframe ready
        setTimeout(function() {
            $("body", element.contentDocument).mouseup(event_mouseup);
            $("body", element.contentDocument).click(event_click);
            if ($(element).css('z-index') >= 2147483647) {
                var style = $(element).attr('style') + ' z-index: 2147483646 !important';
                $(element).attr('style', style);
            }
        }, 1000);
    }
});

$("body").mouseup(event_mouseup);
$("body").click(event_click);

function event_click(event) {
    if (haloword_opened) {
        var target = $(event.target);
        if (target.attr("id") != "haloword-lookup" && !target.parents("#haloword-lookup")[0]) {
            $("#haloword-lookup").hide();
            $("#haloword-remove").hide();
            $("#haloword-add").show();
            haloword_opened = false;
        }
    }
}

var icon_url = chrome.extension.getURL("img/icon.svg");
var style_content = "";
if ($("head")[0]) {
    $($("head")[0]).append(style_content);
}
else {
    $($("body")[0]).prepend(style_content);
}

$("#haloword-lookup").draggable({ handle: "#haloword-title" });

$("#haloword-pron").click(function() {
    // HACK: fix Chrome won't play second time
    // unfortunately this doesn't work properly. more: crbug.com/129165.
    //$("#haloword-audio")[0].load();
    $("#haloword-audio")[0].play();
});

function pron_exist(word, is_upper) {
    /* two URLs:
    http://www.gstatic.com/dictionary/static/sounds/de/0/halo.mp3
    http://www.gstatic.com/dictionary/static/sounds/de/0/!Capella.mp3
    */
    var pron_url = "http://www.gstatic.com/dictionary/static/sounds/de/0/" + word + ".mp3";
    if (is_english(word) || is_upper) {
        $.ajax({
            url: pron_url,
            timeout: 3000,
            success: function() {
                var current_word = $("#haloword-word").html().toLowerCase();
                if (word == current_word || word.substring(1).toLowerCase() == current_word) {
                    $("#haloword-audio").attr("src", pron_url);
                    $("#haloword-pron").show();
                }
            },
            error: function(xhr, d, e) {
                if (!is_upper) {
                    pron_exist('!' + word[0].toUpperCase() + word.substring(1), true);
                }
            }
        });
    }
}

function get_selection() {
    var selection = $.trim(window.getSelection());
    if (!selection) {
        $("iframe").each(function() {
            if (this.contentDocument) {
                selection = $.trim(this.contentDocument.getSelection());
            }
            if (selection) {
                return false;
            }
        });
    }
    return selection;
}

$("#haloword-add").click(function() {
    $("#haloword-add").hide();
    $("#haloword-remove").show();
    var selection = get_selection();
    chrome.extension.sendMessage({method: "add", word: selection});
});
$("#haloword-remove").click(function() {
    $("#haloword-remove").hide();
    $("#haloword-add").show();
    var selection = get_selection();
    chrome.extension.sendMessage({method: "remove", word: selection});
});

function event_mouseup(e) {
    // chrome.storage.local.set({'disable_querybox': true})
    chrome.storage.local.get('disable_querybox', function(ret) {
        if (!ret.disable_querybox) {
            if (!e.ctrlKey && !e.metaKey) {
                return;
            }
            var selection = get_selection();
            var lang = valid_word(selection);
            if (!lang) {
                return;
            }

            $("#haloword-word").html(selection);

            var windowWidth = $(window).outerWidth(),
                halowordWidth = $("#haloword-lookup").outerWidth(),
                left = Math.min(windowWidth + scrollX - halowordWidth, e.pageX);
            $("#haloword-lookup").attr("style", "left: " + left + "px;" + "top: " + e.pageY + "px;");
            $("#haloword-open").attr("href", chrome.extension.getURL("main.html#" + selection));
            $("#haloword-close").click(function() {
                $("#haloword-lookup").hide();
                $("#haloword-remove").hide();
                $("#haloword-add").show();
                haloword_opened = false;
                return false;
            });

            $("#haloword-remove").hide();

            chrome.extension.sendMessage({method: "find", word: selection}, function(response) {
                if (response.exist) {
                    $("#haloword-add").hide();
                    $("#haloword-remove").show();
                }
                else {
                    $("#haloword-remove").hide();
                    $("#haloword-add").show();
                }
            });

            $("#haloword-pron").hide();
            $("#haloword-content").html("
Loading definitions...
");
            $("#haloword-lookup").show();

            $.ajax({
                url: youdao_url + selection,
                dataType: "json",
                success: function(data) {
                    var def = "", i;
                    if (data.errorCode === 0) {
                        if (data.basic) {
                            if (data.basic.phonetic) {
                                def += '
' + data.basic.phonetic + '
';
                            }

                            for (i in data.basic.explains) {
                                def += "
" + data.basic.explains[i] + "
";
                            }

                            $("#haloword-content").html(def);

                            pron_exist(selection.toLowerCase(), false);
                        }
                        else if (data.translation) {
                            for (i in data.translation) {
                                def += "
" + data.translation[i] + "
";
                            }
                            $("#haloword-content").html(def);
                        }
                        else {
                            // no definition and translation
                            $("#haloword-content").html("
I'm sorry, Dave.

I'm afraid I can't find that.
");
                        }
                    }
                    else {
                        $("#haloword-content").html("
I'm sorry, Dave.

I'm afraid I can't find that.
");
                    }
                },
                error: function(data) {
                    $("#extradef").hide();
                }
            });

            // HACK: fix dict window not openable
            setTimeout(function() {
                haloword_opened = true;
            }, 100);
        }
    })
}
<|endoftext|>


<commit_before>angular.module('monad.templates', []).run(['$templateCache', function($templateCache) {
  'use strict';

  $templateCache.put('/monad/LICENSE.html',
    "
The MIT License (MIT)
\n" +
    "
\n" +
    "    Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n" +
    "    Marijn Ophorst <marijn@monomelodies.nl>\n" +
    "
\n" +
    "
\n" +
    "    Permission is hereby granted, free of charge, to any person obtaining a copy\n" +
    "    of this software and associated documentation files (the \"Software\"), to deal\n" +
    "    in the Software without restriction, including without limitation the rights\n" +
    "    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" +
    "    copies of the Software, and to permit persons to whom the Software is\n" +
    "    furnished to do so, subject to the following conditions:\n" +
    "
\n" +
    "
\n" +
    "    The above copyright notice and this permission notice shall be included in all\n" +
    "    copies or substantial portions of the Software.\n" +
    "
\n" +
    "
\n" +
    "    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" +
    "    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" +
    "    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" +
    "    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" +
    "    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" +
    "    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n" +
    "    SOFTWARE.\n" +
    "
"
  );

  $templateCache.put('/monad/components/Login/template.html',
    "

\n" +
    "
\n" +
    "
\n" +
    "        <form ng-submit=$ctrl.auth.attempt($ctrl.credentials) id=auth name=auth novalidate method=post>\n" +
    "            <fieldset>\n" +
    "                <legend translate>Please login</legend>\n" +
    "
\n" +
    "                    <input name=username ng-model=$ctrl.credentials.username class=form-control placeholder=\"{{ 'Username' | translate }}\">\n" +
    "
\n" +
    "
\n" +
    "                    <input type=password name=password ng-model=$ctrl.credentials.password class=form-control placeholder=\"{{ 'Password' | translate }}\">\n" +
    "
\n" +
    "                <button type=submit class=\"btn btn-default pull-right\" translate>Go!</button>\n" +
    "            </fieldset>\n" +
    "        </form>\n" +
    "
\n" +
    "
"
  );

  $templateCache.put('/monad/components/Update/template.html',
    "
\n" +
    "    \n" +
    "    Create new item in {{ $ctrl.type }}\n" +
    "    Edit <q>{{ $ctrl.data.item[$ctrl.title ? $ctrl.title : '$title'] }}</q> in {{ $ctrl.type }}\n" +
    "
\n" +
    "
\n" +
    "    <form ng-submit=$ctrl.save() id=mo_update_form name=mo_update_form novalidate method=post>\n" +
    "

\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "                <button type=submit class=\"btn btn-primary fixed\" ng-if=\"mo_update_form.$valid && $ctrl.$dirty\" translate>Save changes</button>\n" +
    "                \n" +
    "
\n" +
    "
\n" +
    "    </form>\n" +
    "
"
  );

  $templateCache.put('/monad/templates/home.html',
    "
\n" +
    "
\n" +
    "
{{ $root.title }} administrator
\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "
Welcome!
\n" +
    "
\n" +
    "                Hi there, you've reached the administrator for this site. Your options are listed here.\n" +
    "                You can also use the main menu at the top to navigate.\n" +
    "
\n" +
    "
\n" +
    "        \n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "                        {{ item.title | translate }}\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "        \n" +
    "
\n" +
    "
"
  );

  $templateCache.put('/monad/templates/license.html',
    "
\n" +
    "
License
\n" +
    "
\n" +
    "
\n" +
    "
Note: this applies to the Monad CMS framework, not (necessarily) the site it is used for :)
\n" +
    "

\n" +
    "
\n" +
    "
\n" +
    "    <button class=\"btn btn-primary\" ng-click=ok() translate>Got it!</button>\n" +
    "
"
  );

}]);
<commit_msg>rebuild<commit_after>console.log('ahoy');
angular.module('monad.templates').run(['$templateCache', function($templateCache) {
  'use strict';

  $templateCache.put('/monad/LICENSE.html',
    "
The MIT License (MIT)
\n" +
    "
\n" +
    "    Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016\n" +
    "    Marijn Ophorst <marijn@monomelodies.nl>\n" +
    "
\n" +
    "
\n" +
    "    Permission is hereby granted, free of charge, to any person obtaining a copy\n" +
    "    of this software and associated documentation files (the \"Software\"), to deal\n" +
    "    in the Software without restriction, including without limitation the rights\n" +
    "    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" +
    "    copies of the Software, and to permit persons to whom the Software is\n" +
    "    furnished to do so, subject to the following conditions:\n" +
    "
\n" +
    "
\n" +
    "    The above copyright notice and this permission notice shall be included in all\n" +
    "    copies or substantial portions of the Software.\n" +
    "
\n" +
    "
\n" +
    "    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" +
    "    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" +
    "    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" +
    "    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" +
    "    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" +
    "    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n" +
    "    SOFTWARE.\n" +
    "
"
  );

  $templateCache.put('/monad/components/Login/template.html',
    "

\n" +
    "
\n" +
    "
\n" +
    "        <form ng-submit=$ctrl.auth.attempt($ctrl.credentials) id=auth name=auth novalidate method=post>\n" +
    "            <fieldset>\n" +
    "                <legend translate>Please login</legend>\n" +
    "
\n" +
    "                    <input name=username ng-model=$ctrl.credentials.username class=form-control placeholder=\"{{ 'Username' | translate }}\">\n" +
    "
\n" +
    "
\n" +
    "                    <input type=password name=password ng-model=$ctrl.credentials.password class=form-control placeholder=\"{{ 'Password' | translate }}\">\n" +
    "
\n" +
    "                <button type=submit class=\"btn btn-default pull-right\" translate>Go!</button>\n" +
    "            </fieldset>\n" +
    "        </form>\n" +
    "
\n" +
    "
"
  );

  $templateCache.put('/monad/components/Update/template.html',
    "
\n" +
    "    \n" +
    "    Create new item in {{ $ctrl.type }}\n" +
    "    Edit <q>{{ $ctrl.data.item[$ctrl.title ? $ctrl.title : '$title'] }}</q> in {{ $ctrl.type }}\n" +
    "
\n" +
    "
\n" +
    "    <form ng-submit=$ctrl.save() id=mo_update_form name=mo_update_form novalidate method=post>\n" +
    "

\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "                <button type=submit class=\"btn btn-primary fixed\" ng-disabled=!mo_update_form.$valid ng-if=$ctrl.$dirty() translate>Save changes</button>\n" +
    "                \n" +
    "
\n" +
    "
\n" +
    "    </form>\n" +
    "
"
  );

  $templateCache.put('/monad/templates/home.html',
    "
\n" +
    "
\n" +
    "
{{ $root.title }} administrator
\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "
Welcome!
\n" +
    "
\n" +
    "                Hi there, you've reached the administrator for this site. Your options are listed here.\n" +
    "                You can also use the main menu at the top to navigate.\n" +
    "
\n" +
    "
\n" +
    "        \n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "                        {{ item.title | translate }}\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "        \n" +
    "
\n" +
    "
"
  );

  $templateCache.put('/monad/templates/license.html',
    "
\n" +
    "
License
\n" +
    "
\n" +
    "
\n" +
    "
Note: this applies to the Monad CMS framework, not (necessarily) the site it is used for :)
\n" +
    "

\n" +
    "
\n" +
    "
\n" +
    "    <button class=\"btn btn-primary\" ng-click=ok() translate>Got it!</button>\n" +
    "
"
  );

}]);
<|endoftext|>


<commit_before>(function(env) {
    env.ddg_spice_is_it_up = function(api_result) {
        "use strict";

        if(!api_result){
            return Spice.failed('is_it_up');
        }

        api_result['status_code'] = (api_result['status_code'] === 1);

        Spice.add({
            id: 'is_it_up',
            name: 'Domain status',
            data: api_result,
            signal: 'high',
            meta: {
                sourceUrl: 'http://isitup.org/' + api_result['domain'],
                sourceName: 'Is it up?',
                sourceIcon: true
            },
            template_group: 'info',
            templates: {
                group: 'info',
                options: {
                    content: Spice.is_it_up.detail
                }
            }
        });
    }
}(this));

<commit_msg>Is it up: Moved to the group 'base'.<commit_after>(function(env) {
    env.ddg_spice_is_it_up = function(api_result) {
        "use strict";

        if(!api_result){
            return Spice.failed('is_it_up');
        }

        api_result['status_code'] = (api_result['status_code'] === 1);

        Spice.add({
            id: 'is_it_up',
            name: 'Domain status',
            data: api_result,
            signal: 'high',
            meta: {
                sourceUrl: 'http://isitup.org/' + api_result['domain'],
                sourceName: 'Is it up?',
                sourceIcon: true
            },
            template_group: 'info',
            templates: {
                group: 'base',
                options: {
                    content: Spice.is_it_up.detail,
		    moreAt: true
                }
            }
        });
    }
}(this));

<|endoftext|>