<commit_before>// when hostnames or ip addresses are seen in channels or private messages
// lookup dns information about them

var dns = require('dns'),
    hostnameRe = /([a-z\d]([a-z\d\-]{0,61}[a-z\d])?\.)+[a-z]+/gi,
    ipRe = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/g;

function formatA(recs) {
    return 'A:' + recs.join(', ');
}

function formatCnames(cnames) {
    cnames.sort();

    return 'CNAME: ' + cnames.join(', ');
}

function formatMx(mx) {
    var result = [];

    mx.forEach(function (rec) {
        result.push(rec.exchange);
    });

    result.sort();

    return 'MX:' + result.join(', ');
}

function formatNs(nameservers) {
    nameservers.sort();

    return 'NS:' + nameservers.join(', ');
}

function formatReverse(ip, hostnames) {
    hostnames.sort();

    return ip + '->[' + hostnames.join(', ') + ']';
}

function infoHostnames(s, callback) {
    (s.match(hostnameRe) || []).forEach(function (hostname) {
        var doneCount = 0,
            results = [],
            numParts = 4;

        dns.resolve4(hostname, function (err, ips) {
            var ipsDoneCount = 0,
                ipResults = [];

            if (err) {
                console.log(err);
            } else {
                ips.forEach(function (ip) {
                    dns.reverse(ip, function (err, hostnames) {
                        ipsDoneCount += 1;

                        if (err) {
                            console.log(err);
                            ipResults.push(ip);
                        } else {
                            if (hostnames.length > 0) {
                                ipResults.push(formatReverse(ip, hostnames));
                            } else {
                                ipResults.push(ip);
                            }
                        }
                        if (ipsDoneCount === ips.length) {
                            results.push(formatA(ipResults));
                            doneCount += 1;
                            if (doneCount === numParts) {
                                callback(hostname + ' ' + results.join(' ; '));
                            }
                        }
                    });
                });
            }
        });

        dns.resolveCname(hostname, function (err, cnames) {
            doneCount += 1;
            if (err) {
                console.log(err);
            } else {
                if (cnames.length > 0) {
                    results.push(formatCnames(cnames));
                }
            }
            if (doneCount === numParts) {
                callback(hostname + ' ' + results.join(' ; '));
            }
        });

        dns.resolveMx(hostname, function (err, mx) {
            doneCount += 1;
            if (err) {
                console.log(err);
            } else {
                if (mx.length > 0) {
                    results.push(formatMx(mx));
                }
            }
            if (doneCount === numParts) {
                callback(hostname + ' ' + results.join(' ; '));
            }
        });

        dns.resolveNs(hostname, function (err, ns) {
            doneCount += 1;
            if (err) {
                console.log(err);
            } else {
                if (ns.length > 0) {
                    results.push(formatNs(ns));
                }
            }
            if (doneCount === numParts) {
                callback(hostname + ' ' + results.join(' ; '));
            }
        });
    });
}

function infoIps(s, callback) {
    (s.match(ipRe) || []).forEach(function (ip) {
        dns.reverse(ip, function (err, hostnames) {
            if (err) {
                console.log(err);
            } else {
                if (hostnames.length > 0) {
                    callback(formatReverse(ip, hostnames));
                }
            }
        });
    });
}

exports.privateMessage = function (m) {
    var conn = this;

    infoHostnames(m.text, function (resp) {
        conn.privmsg(m.from.nick, resp);
    });

    infoIps(m.text, function (resp) {
        conn.privmsg(m.from.nick, resp);
    });
};

exports.channelMessage = function (m) {
    var conn = this;

    infoHostnames(m.text, function (resp) {
        conn.privmsg(m.to, resp);
    });

    infoIps(m.text, function (resp) {
        conn.privmsg(m.to, resp);
    });
};
<commit_msg>sort mx records by priority<commit_after>// when hostnames or ip addresses are seen in channels or private messages
// lookup dns information about them

var dns = require('dns'),
    hostnameRe = /([a-z\d]([a-z\d\-]{0,61}[a-z\d])?\.)+[a-z]+/gi,
    ipRe = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/g;

function cmp(a, b) {
    return a > b ? 1 : a < b ? -1 : 0;
}

function formatA(recs) {
    return 'A:' + recs.join(', ');
}

function formatCnames(cnames) {
    cnames.sort();

    return 'CNAME: ' + cnames.join(', ');
}

function formatMx(mx) {
    var result = [];

    mx.sort(function (a, b) {
        var result = cmp(a.priority, b.priority);
        if (result === 0) {
            result = cmp(a.exchange, b.exchange);
        }

        return result;
    });
    mx.forEach(function (rec) {
        result.push(rec.exchange);
    });

    return 'MX:' + result.join(', ');
}

function formatNs(nameservers) {
    nameservers.sort();

    return 'NS:' + nameservers.join(', ');
}

function formatReverse(ip, hostnames) {
    hostnames.sort();

    return ip + '->[' + hostnames.join(', ') + ']';
}

function infoHostnames(s, callback) {
    (s.match(hostnameRe) || []).forEach(function (hostname) {
        var doneCount = 0,
            results = [],
            numParts = 4;

        dns.resolve4(hostname, function (err, ips) {
            var ipsDoneCount = 0,
                ipResults = [];

            if (err) {
                console.log(err);
            } else {
                ips.forEach(function (ip) {
                    dns.reverse(ip, function (err, hostnames) {
                        ipsDoneCount += 1;

                        if (err) {
                            console.log(err);
                            ipResults.push(ip);
                        } else {
                            if (hostnames.length > 0) {
                                ipResults.push(formatReverse(ip, hostnames));
                            } else {
                                ipResults.push(ip);
                            }
                        }
                        if (ipsDoneCount === ips.length) {
                            results.push(formatA(ipResults));
                            doneCount += 1;
                            if (doneCount === numParts) {
                                callback(hostname + ' ' + results.join(' ; '));
                            }
                        }
                    });
                });
            }
        });

        dns.resolveCname(hostname, function (err, cnames) {
            doneCount += 1;
            if (err) {
                console.log(err);
            } else {
                if (cnames.length > 0) {
                    results.push(formatCnames(cnames));
                }
            }
            if (doneCount === numParts) {
                callback(hostname + ' ' + results.join(' ; '));
            }
        });

        dns.resolveMx(hostname, function (err, mx) {
            doneCount += 1;
            if (err) {
                console.log(err);
            } else {
                if (mx.length > 0) {
                    results.push(formatMx(mx));
                }
            }
            if (doneCount === numParts) {
                callback(hostname + ' ' + results.join(' ; '));
            }
        });

        dns.resolveNs(hostname, function (err, ns) {
            doneCount += 1;
            if (err) {
                console.log(err);
            } else {
                if (ns.length > 0) {
                    results.push(formatNs(ns));
                }
            }
            if (doneCount === numParts) {
                callback(hostname + ' ' + results.join(' ; '));
            }
        });
    });
}

function infoIps(s, callback) {
    (s.match(ipRe) || []).forEach(function (ip) {
        dns.reverse(ip, function (err, hostnames) {
            if (err) {
                console.log(err);
            } else {
                if (hostnames.length > 0) {
                    callback(formatReverse(ip, hostnames));
                }
            }
        });
    });
}

exports.privateMessage = function (m) {
    var conn = this;

    infoHostnames(m.text, function (resp) {
        conn.privmsg(m.from.nick, resp);
    });

    infoIps(m.text, function (resp) {
        conn.privmsg(m.from.nick, resp);
    });
};

exports.channelMessage = function (m) {
    var conn = this;

    infoHostnames(m.text, function (resp) {
        conn.privmsg(m.to, resp);
    });

    infoIps(m.text, function (resp) {
        conn.privmsg(m.to, resp);
    });
};
<|endoftext|>


<commit_before>
/**
 * Licensed to The Apereo Foundation under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.

 * The Apereo Foundation licenses this file to you 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.
 */
	/**
	 *
	 * folderproperties, javascript for the folder properties tab
	 *
	 * @author Patrick Lockley
	 * @version 1.0
	 * @package
	 */

	 /**
	 *
	 * Function folders ajax send prepare
 	 * This function sorts out the URL for most of the queries in the folder properties window
	 * @param string url = the extra part of the url for this ajax query
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folders_ajax_send_prepare(url){

   	xmlHttp.open("post","website_code/php/folderproperties/" + url,true);
	xmlHttp.onreadystatechange=folder_properties_stateChanged;
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

}

 	/**
	 *
	 * Function folders properties state changed
 	 * This function handles all of the responses from the ajax queries
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folder_properties_stateChanged(){

	if (xmlHttp.readyState==4){

		if(xmlHttp.responseText!=""){

			document.getElementById('dynamic_area').innerHTML = xmlHttp.responseText;

		}
	}
}

 	/**
	 *
	 * Function folder name state changed
 	 * This function handles ajax responses for the folder rename query as this requires extra bits of work
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folder_rename_stateChanged(){

	if (xmlHttp.readyState==4){

		if(xmlHttp.responseText!=""){

			/*
			* the response contains the new html and the new file name, so split them
			*/

			array_response = xmlHttp.responseText.split("~*~");

			/*
			* set the html
			*/

			document.getElementById('dynamic_area').innerHTML = array_response[0];

			/*
			* prepare and change the folder name in the main window
			*/

			id = "folder_" + window.name.substr(0,window.name.indexOf("_"));

			current_innerHTML = window_reference.document.getElementById(id).childNodes[0].innerHTML;

			future_innerHTML = current_innerHTML.substr(0,current_innerHTML.lastIndexOf(">")+1) + array_response[1];

			window_reference.document.getElementById(id).childNodes[0].innerHTML = future_innerHTML;

		}
	}

}

 /**
	 *
	 * Function folders rss template
 	 * This function displays the RSS features for this folder
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folder_rss_template(){

	if(setup_ajax()!=false){

		var url="folder_rss_template.php";

		folders_ajax_send_prepare(url);

		xmlHttp.send('folder_id=' + window.name);

	}

}

 /**
	 *
	 * Function folders properties
 	 * This function displays the basic properties panel for this folder
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folderproperties_template(){

	if(setup_ajax()!=false){

		var url="folderproperties_template.php";

		folders_ajax_send_prepare(url);

		xmlHttp.send('folder_id=' + String(window.name).substr(0,String(window.name).indexOf("_")));

	}

}

 /**
	 *
	 * Function folder content template
 	 * This function shows the content of this folder for the folder content tab
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folder_content_template(){

	if(setup_ajax()!=false){

		var url="folder_content_template.php";

		folders_ajax_send_prepare(url);

		xmlHttp.send('folder_id=' + String(window.name).substr(0,String(window.name).indexOf("_")));

	}

}

 /**  CHECK THIS - OBSOLETE?
	 *
	 * Function folders ajax send prepare
 	 * This function sorts out the URL for most of the queries in the folder properties window
	 * @param string url = the extra part of the url for this ajax query
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folder_name_template_a(){

	if(setup_ajax()!=false){

		var url="folder_name_template.php";

		folders_ajax_send_prepare(url);

		xmlHttp.send('folder_id=' + window.name);

	}

}

 	/**
	 *
	 * Function rename folder
 	 * This function renames the folder
	 * @param string folder_id = the id of this folder
 	 * @param string form_tag = the the id of the form
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function rename_folder(folder_id,form_tag){

	new_name = document.getElementById(form_tag).childNodes[0].value;

	if(is_ok_name(new_name)){

		if(setup_ajax()!=false){

			var url="rename_folder_template.php";

			xmlHttp.open("post","website_code/php/folderproperties/" + url,true);
			xmlHttp.onreadystatechange=folder_rename_stateChanged;
			xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

			xmlHttp.send('folder_id=' + folder_id +'&folder_name=' + new_name);

		}

	}else{

		alert(NAME_FAIL_FOLDER_PROPERTIES);

	}

}<commit_msg>Fix: update workspace after rename<commit_after>
/**
 * Licensed to The Apereo Foundation under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.

 * The Apereo Foundation licenses this file to you 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.
 */
	/**
	 *
	 * folderproperties, javascript for the folder properties tab
	 *
	 * @author Patrick Lockley
	 * @version 1.0
	 * @package
	 */

	 /**
	 *
	 * Function folders ajax send prepare
 	 * This function sorts out the URL for most of the queries in the folder properties window
	 * @param string url = the extra part of the url for this ajax query
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folders_ajax_send_prepare(url){

   	xmlHttp.open("post","website_code/php/folderproperties/" + url,true);
	xmlHttp.onreadystatechange=folder_properties_stateChanged;
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

}

 	/**
	 *
	 * Function folders properties state changed
 	 * This function handles all of the responses from the ajax queries
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folder_properties_stateChanged(){

	if (xmlHttp.readyState==4){

		if(xmlHttp.responseText!=""){

			document.getElementById('dynamic_area').innerHTML = xmlHttp.responseText;

		}
	}
}

 	/**
	 *
	 * Function folder name state changed
 	 * This function handles ajax responses for the folder rename query as this requires extra bits of work
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folder_rename_stateChanged(){

	if (xmlHttp.readyState==4){

		if(xmlHttp.responseText!=""){

			/*
			* the response contains the new html and the new file name, so split them
			*/

			array_response = xmlHttp.responseText.split("~*~");

			/*
			* set the html
			*/

			document.getElementById('dynamic_area').innerHTML = array_response[0];

			/*
			 * set the file name in the file_area
			 */
			if(typeof window_reference==="undefined"){
				window.opener.refresh_workspace();
			}
			else {
				window_reference.refresh_workspace();
			}
		}
	}

}

 /**
	 *
	 * Function folders rss template
 	 * This function displays the RSS features for this folder
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folder_rss_template(){

	if(setup_ajax()!=false){

		var url="folder_rss_template.php";

		folders_ajax_send_prepare(url);

		xmlHttp.send('folder_id=' + window.name);

	}

}

 /**
	 *
	 * Function folders properties
 	 * This function displays the basic properties panel for this folder
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folderproperties_template(){

	if(setup_ajax()!=false){

		var url="folderproperties_template.php";

		folders_ajax_send_prepare(url);

		xmlHttp.send('folder_id=' + String(window.name).substr(0,String(window.name).indexOf("_")));

	}

}

 /**
	 *
	 * Function folder content template
 	 * This function shows the content of this folder for the folder content tab
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folder_content_template(){

	if(setup_ajax()!=false){

		var url="folder_content_template.php";

		folders_ajax_send_prepare(url);

		xmlHttp.send('folder_id=' + String(window.name).substr(0,String(window.name).indexOf("_")));

	}

}

 /**  CHECK THIS - OBSOLETE?
	 *
	 * Function folders ajax send prepare
 	 * This function sorts out the URL for most of the queries in the folder properties window
	 * @param string url = the extra part of the url for this ajax query
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function folder_name_template_a(){

	if(setup_ajax()!=false){

		var url="folder_name_template.php";

		folders_ajax_send_prepare(url);

		xmlHttp.send('folder_id=' + window.name);

	}

}

 	/**
	 *
	 * Function rename folder
 	 * This function renames the folder
	 * @param string folder_id = the id of this folder
 	 * @param string form_tag = the the id of the form
	 * @version 1.0
	 * @author Patrick Lockley
	 */

function rename_folder(folder_id,form_tag){

	new_name = document.getElementById(form_tag).childNodes[0].value;

	if(is_ok_name(new_name)){

		if(setup_ajax()!=false){

			var url="rename_folder_template.php";

			xmlHttp.open("post","website_code/php/folderproperties/" + url,true);
			xmlHttp.onreadystatechange=folder_rename_stateChanged;
			xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

			xmlHttp.send('folder_id=' + folder_id +'&folder_name=' + new_name);

		}

	}else{

		alert(NAME_FAIL_FOLDER_PROPERTIES);

	}

}<|endoftext|>


<commit_before>// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

$(function() {	// wrapping

// drag & drop ones first
var dragZonesSelector = ".modules";
$(dragZonesSelector).droppable({ hoverClass: "ui-state-active" });
$(".module:not(.box-zone)", dragZonesSelector).each(function() {
	if ($(this).css("position") === "absolute") {
		var el = this;
		$(this).draggable({
			connectToSortable: ".modules",
			revert: "invalid",
			stop: function (event, ui) {
				$("#save_modules").show("fast").attr("dragged", $(el).attr("id"));
			}
		}).mouseover(function(event, ui) {	// sortable gets muddled when dragging so disable it
				$(dragZonesSelector).sortable("option", "disabled", true);
		}).mouseout(function(event, ui) {
				$(dragZonesSelector).sortable("option", "disabled", false);
		});
	}
});

var modAdminDirty = false;
$(document).ready(function() {
	$(window).bind("beforeunload", function( e ) {
		if (modAdminDirty) {
			var m = tr("You have unsaved changes to your modules, are you sure you want to leave the page without saving?");
			var e = e || window.event;
			if (e && !($.browser.safari || $.browser.webkit)) {
				e.returnValue = m;
			}
			return m;
		}
	});
});

$(".modules").sortable( {
	connectWith: ".modules",
	items: ".module:not('.ui-draggable')",
	placeholder: "module-placeholder",
	revert: 200,
	tolerance: 'pointer',
	stop: function (event, ui) {
		if ($("#save_modules:visible").length === 0) {
			$("#save_modules").show("fast").attr("sortable", $(this).attr("id"))
					.parent().show("fast");
			modAdminDirty = true;
		}
		$(this).removeClass("ui-state-active");
	},
	start: function (event, ui) {
		$(this).addClass("ui-state-active");
	},
	receive: function(event, ui) {

		// check for list items arriving
		var dropped = $("> li", this);
		if (dropped.length) {
			var zone = $(this);	//dropped.parents(".modules:first");	// odd? more than one?
			if (zone && zone.attr("id") && zone.attr("id").match(/modules/)) {
				var ord = $.inArray(dropped[0], zone.children());
				var zoneStr = zone.attr("id").substring(0, zone.attr("id").indexOf("_"));
				var name = $.trim($("input:first", dropped).val());
				var options = {
					modName: name,
					modPos: zoneStr,
					modOrd: ord,
					dropped: dropped
				};
				if (zoneStr === "top" || zoneStr === "bottom") {
					options.nobox = true;
				}
				dropped.addClass("module-placeholder");
				showModuleEditForm(false, options);
			}

		}
	}
});
$("span.moduleflip").each( function() {
	var $edit = $('')
		.click( function() {
			$(this).parents(".module:first").dblclick();
		});
	var $unassign = $('')
		.click( function() {
			var id = $(this).parents(".module:first").attr("id").match(/\d+$/);
			if (id) {
				moduleUnassign( id );
			}
		});
	$(this).prepend($edit, $unassign);
});

// disable all links in modules apart from app menu
$(".module:not(.cssmenubox,.box-Application_Menu, .box-quickadmin)").find("a, input").click( function (event) {
	if (!$(this).parent().hasClass("moduleflip")) {
		event.stopImmediatePropagation();
		return false;
	} else {
		return true;
	}
});

// set dbl click form action
$(".module:not(.box-zone), #assigned_modules tr").dblclick(function () {showModuleEditForm(this);});

// source list of all modules
$("#module_list li").draggable({
	connectToSortable: ".modules",
	helper: "clone",
	revert: "invalid",
	start: function (event, ui) {	// stop flashing while dragging
		$(document.body).css("user-select", "none");
		$(document.body).css("-webkit-user-select", "none");
		$(document.body).css("-moz-user-select", "none");
		$(".description", ui.helper).hide();
	},
	stop: function (event, ui) {
		$(document.body).css("user-select", "");
		$(document.body).css("-webkit-user-select", "");
		$(document.body).css("-moz-user-select", "");
	}
});

$("#save_modules").click(function(evt) {
	if ($(this).attr("sortable")) {
		// save module order
		modAdminDirty = false;
		var ser = {};
		$(".modules").each(function() { /* do this on everything of class "modules" */
			ser[$(this).attr("id")] = $(this).find("> div.module").map(function() { /* do this on each child module */
				return $(this).attr("id").match(/\d+$/)[0];	// dare to do it in one go
			}).get();
		});
		$("#module-order").val($.toJSON(ser)).parents("form")[0].submit();
	} else if ($(this).attr("dragged")) {
		$("#" + $(this).attr("dragged")).dblclick();
		$(this).attr("dragged", "");
	}
	return false;
}).hide();

// module select action when in main page
$("#assign_name", "#tiki-center").change( function () {
	needToConfirm=false;
	//this.form.submit();
	$("input[name=preview]", this.form).click();
});

// show edit form dialogue
var showModuleEditForm = function(item, options) {
	var modId = 0, modName, modPos = "", modOrd = 0, modStyle = "", dropped = null;
	if (item) {
		if ($(item).is("tr")) {		// assigned_modules row dblclicked
			modName = $("td:first", item).text();
			modId = $("a:last", item).attr("href").match(/\d+$/);
			if (modId) {
				modId = modId[0];
				modOrd = $("td:eq(2)", item).text();
				modPos = $(item).parents("table:first").attr("id").match(/_(\w)$/);
				if (modPos) {
					modPos = modPos[1];
				}
			}
		} else {					// .module div dblclicked
			modName = $(item).attr("class").match(/box-[\S_-]+/);
			if (modName) {
				modName = modName[0].substring(4);
			}
			modId = $(item).attr("id").match(/\d+$/);
			if (modId) {
				modId = modId[0];
				var id = $("div:first", item).attr("id");
				if (id) {
					modPos = id.match(/(top|topbar|pagetop|left|right|pagebottom|bottom)(\d+)$/);
					if (modPos) {
						modOrd = modPos[2];
						modPos = modPos[1];
					}
				}
				modStyle = $(item).attr("style");
				if (modStyle && !modStyle.match("absolute")) {
					modStyle = "";	// use style from object if draggable
				}
			}
		}
	} else { // new module assignment
		modName = options.modName;
		modPos = options.modPos;
		modOrd = options.modOrd;
		dropped = options.dropped;
		if (typeof options.modId !== "undefined") {
			modId = options.modId;
		}
	}

	if ($("#module_edit_div").length === 0) {
		$("body").append($("
<form action='#' method='post'></form>
"));
		$("#module_edit_div form").append($("<input type='hidden' name='assign' value='popup' />" +
											"<input type='hidden' name='assign_name' value='' />" +
											"<input type='hidden' name='moduleId' value='' />"));
	}
	$("#module_edit_div input[name=assign_name]").val(modName);
	$("#module_edit_div input[name=moduleId]").val(modId);

	var postData = {
		edit_module: true,
		assign_name: modName,
		moduleId: modId,
		assign_position: modPos,
		assign_order: modOrd
		//preview: true
	};
	if (item) {
		postData.edit_assign = modId;
		//postData.assign_params = { style: modStyle };
	} else {
		if (typeof options.formVals !== "undefined") {
			var v = options.formVals;
			$.extend(v, postData);
			postData = v;
		}
		postData.preview = true;
	}

	$.post("tiki-admin_modules.php", postData, function(data) {
			$('#module_edit_div form').html(data);
			$("#module_edit_div form").append($("<input type='hidden' name='assign' value='popup' />" +
											"<input type='hidden' name='assign_name' value='"+modName+"' />" +
											"<input type='hidden' name='moduleId' value='"+modId+"' />"));
			$('#module_edit_div').dialog("option", "width", 580)
					.dialog("option", "height", 500)
					.dialog( "option", "position", 'center' )
					.find("input[type='submit']").hide();
			if (options && options.nobox) {
				$('input[name*=nobox]').val("y");
			}
			$(this).applyChosen();
			$("#module_params").tabs();
			$('.pagename').tiki("autocomplete", "pagename", {multiple: true, multipleSeparator: ";"});
			if (modStyle) {
				// preload style field with style if position:absolute (unnecessary spaces removed)
				$('input[name*=style]').val(modStyle.replace(/\:\s*/g, ":").replace(/\;\s*/g, ";"));
			}
			$("#assign_name", "#module_edit_div").change( function () {
				var formVals = {};
				$(this).parents("form").find("input[name!=assign], select, textarea").each( function () {
					formVals[$(this).attr("name")] = $(this).val();
				});
				showModuleEditForm (null, {
					modName: $(this).val(),
					modPos: modPos,
					modOrd: modOrd,
					dropped: dropped,
					modId: modId,
					formVals: formVals
				});
			});
			ajaxLoadingHide();
		},
	"html");

	var CancelLabel = tr("Cancel");
	var SaveLabel = tr("Save");
	var DeleteLabel = tr("Remove");
	var navbuttons = {};

	navbuttons[ CancelLabel ] = function () {
        $(this).dialog('close');
        if (dropped) {
          dropped.remove();
        }
      };
	navbuttons[ DeleteLabel ] = function () {
        moduleUnassign( modId );
        $(this).dialog('close');
      };
	navbuttons[ SaveLabel ] = function() {
        var bValid = true;
        $(this).find('input[type=text]').removeClass('ui-state-error');

        if (bValid) {
          modAdminDirty = false;
          $("#module_edit_div form").submit();
          $(this).dialog('close');
        }
      };

	$('#module_edit_div').dialog({
		bgiframe: true,
		width: 580,
		height: 500,
		modal: true,
		title: tr("Edit module:") + " " + unescape(modName).replace("+"," "),
		buttons: navbuttons,
		close: function () {
			$(this).find('input[type=text]').val('').removeClass('ui-state-error');
		}
	});
	 ajaxLoadingShow('module_edit_div');
};

var moduleUnassign = function(modId) {
	var modName = $("#module_" + modId).attr("class").match(/box-[\S_-]+/);	// TODO REFACTOR
	if (modName) {
		modName = modName[0].substring(4);
	}
	if (confirm(tr("Are you sure you want to unassign this module?") + " (" + modName + ")")) {
		window.location.replace("tiki-admin_modules.php?unassign=" + modId);
	}
};

});	// close closure
<commit_msg>[FIX] modules: Default to nobox for modules dropped in a zone module<commit_after>// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

$(function() {	// wrapping

// drag & drop ones first
var dragZonesSelector = ".modules";
$(dragZonesSelector).droppable({ hoverClass: "ui-state-active" });
$(".module:not(.box-zone)", dragZonesSelector).each(function() {
	if ($(this).css("position") === "absolute") {
		var el = this;
		$(this).draggable({
			connectToSortable: ".modules",
			revert: "invalid",
			stop: function (event, ui) {
				$("#save_modules").show("fast").attr("dragged", $(el).attr("id"));
			}
		}).mouseover(function(event, ui) {	// sortable gets muddled when dragging so disable it
				$(dragZonesSelector).sortable("option", "disabled", true);
		}).mouseout(function(event, ui) {
				$(dragZonesSelector).sortable("option", "disabled", false);
		});
	}
});

var modAdminDirty = false;
$(document).ready(function() {
	$(window).bind("beforeunload", function( e ) {
		if (modAdminDirty) {
			var m = tr("You have unsaved changes to your modules, are you sure you want to leave the page without saving?");
			var e = e || window.event;
			if (e && !($.browser.safari || $.browser.webkit)) {
				e.returnValue = m;
			}
			return m;
		}
	});
});

$(".modules").sortable( {
	connectWith: ".modules",
	items: ".module:not('.ui-draggable')",
	placeholder: "module-placeholder",
	revert: 200,
	tolerance: 'pointer',
	stop: function (event, ui) {
		if ($("#save_modules:visible").length === 0) {
			$("#save_modules").show("fast").attr("sortable", $(this).attr("id"))
					.parent().show("fast");
			modAdminDirty = true;
		}
		$(this).removeClass("ui-state-active");
	},
	start: function (event, ui) {
		$(this).addClass("ui-state-active");
	},
	receive: function(event, ui) {

		// check for list items arriving
		var dropped = $("> li", this);
		if (dropped.length) {
			var zone = $(this);	//dropped.parents(".modules:first");	// odd? more than one?
			if (zone && zone.attr("id") && zone.attr("id").match(/modules/)) {
				var ord = $.inArray(dropped[0], zone.children());
				var zoneStr = zone.attr("id").substring(0, zone.attr("id").indexOf("_"));
				var name = $.trim($("input:first", dropped).val());
				var options = {
					modName: name,
					modPos: zoneStr,
					modOrd: ord,
					dropped: dropped
				};
				if (zoneStr === "top" || zoneStr === "bottom" || zone.parent().parent().hasClass("box-zone")) {
					options.nobox = true;
				}
				dropped.addClass("module-placeholder");
				showModuleEditForm(false, options);
			}

		}
	}
});
$("span.moduleflip").each( function() {
	var $edit = $('')
		.click( function() {
			$(this).parents(".module:first").dblclick();
		});
	var $unassign = $('')
		.click( function() {
			var id = $(this).parents(".module:first").attr("id").match(/\d+$/);
			if (id) {
				moduleUnassign( id );
			}
		});
	$(this).prepend($edit, $unassign);
});

// disable all links in modules apart from app menu
$(".module:not(.cssmenubox,.box-Application_Menu, .box-quickadmin)").find("a, input").click( function (event) {
	if (!$(this).parent().hasClass("moduleflip")) {
		event.stopImmediatePropagation();
		return false;
	} else {
		return true;
	}
});

// set dbl click form action
$(".module:not(.box-zone), #assigned_modules tr").dblclick(function () {showModuleEditForm(this);});

// source list of all modules
$("#module_list li").draggable({
	connectToSortable: ".modules",
	helper: "clone",
	revert: "invalid",
	start: function (event, ui) {	// stop flashing while dragging
		$(document.body).css("user-select", "none");
		$(document.body).css("-webkit-user-select", "none");
		$(document.body).css("-moz-user-select", "none");
		$(".description", ui.helper).hide();
	},
	stop: function (event, ui) {
		$(document.body).css("user-select", "");
		$(document.body).css("-webkit-user-select", "");
		$(document.body).css("-moz-user-select", "");
	}
});

$("#save_modules").click(function(evt) {
	if ($(this).attr("sortable")) {
		// save module order
		modAdminDirty = false;
		var ser = {};
		$(".modules").each(function() { /* do this on everything of class "modules" */
			ser[$(this).attr("id")] = $(this).find("> div.module").map(function() { /* do this on each child module */
				return $(this).attr("id").match(/\d+$/)[0];	// dare to do it in one go
			}).get();
		});
		$("#module-order").val($.toJSON(ser)).parents("form")[0].submit();
	} else if ($(this).attr("dragged")) {
		$("#" + $(this).attr("dragged")).dblclick();
		$(this).attr("dragged", "");
	}
	return false;
}).hide();

// module select action when in main page
$("#assign_name", "#tiki-center").change( function () {
	needToConfirm=false;
	//this.form.submit();
	$("input[name=preview]", this.form).click();
});

// show edit form dialogue
var showModuleEditForm = function(item, options) {
	var modId = 0, modName, modPos = "", modOrd = 0, modStyle = "", dropped = null;
	if (item) {
		if ($(item).is("tr")) {		// assigned_modules row dblclicked
			modName = $("td:first", item).text();
			modId = $("a:last", item).attr("href").match(/\d+$/);
			if (modId) {
				modId = modId[0];
				modOrd = $("td:eq(2)", item).text();
				modPos = $(item).parents("table:first").attr("id").match(/_(\w)$/);
				if (modPos) {
					modPos = modPos[1];
				}
			}
		} else {					// .module div dblclicked
			modName = $(item).attr("class").match(/box-[\S_-]+/);
			if (modName) {
				modName = modName[0].substring(4);
			}
			modId = $(item).attr("id").match(/\d+$/);
			if (modId) {
				modId = modId[0];
				var id = $("div:first", item).attr("id");
				if (id) {
					modPos = id.match(/(top|topbar|pagetop|left|right|pagebottom|bottom)(\d+)$/);
					if (modPos) {
						modOrd = modPos[2];
						modPos = modPos[1];
					}
				}
				modStyle = $(item).attr("style");
				if (modStyle && !modStyle.match("absolute")) {
					modStyle = "";	// use style from object if draggable
				}
			}
		}
	} else { // new module assignment
		modName = options.modName;
		modPos = options.modPos;
		modOrd = options.modOrd;
		dropped = options.dropped;
		if (typeof options.modId !== "undefined") {
			modId = options.modId;
		}
	}

	if ($("#module_edit_div").length === 0) {
		$("body").append($("
<form action='#' method='post'></form>
"));
		$("#module_edit_div form").append($("<input type='hidden' name='assign' value='popup' />" +
											"<input type='hidden' name='assign_name' value='' />" +
											"<input type='hidden' name='moduleId' value='' />"));
	}
	$("#module_edit_div input[name=assign_name]").val(modName);
	$("#module_edit_div input[name=moduleId]").val(modId);

	var postData = {
		edit_module: true,
		assign_name: modName,
		moduleId: modId,
		assign_position: modPos,
		assign_order: modOrd
		//preview: true
	};
	if (item) {
		postData.edit_assign = modId;
		//postData.assign_params = { style: modStyle };
	} else {
		if (typeof options.formVals !== "undefined") {
			var v = options.formVals;
			$.extend(v, postData);
			postData = v;
		}
		postData.preview = true;
	}

	$.post("tiki-admin_modules.php", postData, function(data) {
			$('#module_edit_div form').html(data);
			$("#module_edit_div form").append($("<input type='hidden' name='assign' value='popup' />" +
											"<input type='hidden' name='assign_name' value='"+modName+"' />" +
											"<input type='hidden' name='moduleId' value='"+modId+"' />"));
			$('#module_edit_div').dialog("option", "width", 580)
					.dialog("option", "height", 500)
					.dialog( "option", "position", 'center' )
					.find("input[type='submit']").hide();
			if (options && options.nobox) {
				$('input[name*=nobox]').val("y");
			}
			$(this).applyChosen();
			$("#module_params").tabs();
			$('.pagename').tiki("autocomplete", "pagename", {multiple: true, multipleSeparator: ";"});
			if (modStyle) {
				// preload style field with style if position:absolute (unnecessary spaces removed)
				$('input[name*=style]').val(modStyle.replace(/\:\s*/g, ":").replace(/\;\s*/g, ";"));
			}
			$("#assign_name", "#module_edit_div").change( function () {
				var formVals = {};
				$(this).parents("form").find("input[name!=assign], select, textarea").each( function () {
					formVals[$(this).attr("name")] = $(this).val();
				});
				showModuleEditForm (null, {
					modName: $(this).val(),
					modPos: modPos,
					modOrd: modOrd,
					dropped: dropped,
					modId: modId,
					formVals: formVals
				});
			});
			ajaxLoadingHide();
		},
	"html");

	var CancelLabel = tr("Cancel");
	var SaveLabel = tr("Save");
	var DeleteLabel = tr("Remove");
	var navbuttons = {};

	navbuttons[ CancelLabel ] = function () {
        $(this).dialog('close');
        if (dropped) {
          dropped.remove();
        }
      };
	navbuttons[ DeleteLabel ] = function () {
        moduleUnassign( modId );
        $(this).dialog('close');
      };
	navbuttons[ SaveLabel ] = function() {
        var bValid = true;
        $(this).find('input[type=text]').removeClass('ui-state-error');

        if (bValid) {
          modAdminDirty = false;
          $("#module_edit_div form").submit();
          $(this).dialog('close');
        }
      };

	$('#module_edit_div').dialog({
		bgiframe: true,
		width: 580,
		height: 500,
		modal: true,
		title: tr("Edit module:") + " " + unescape(modName).replace("+"," "),
		buttons: navbuttons,
		close: function () {
			$(this).find('input[type=text]').val('').removeClass('ui-state-error');
		}
	});
	 ajaxLoadingShow('module_edit_div');
};

var moduleUnassign = function(modId) {
	var modName = $("#module_" + modId).attr("class").match(/box-[\S_-]+/);	// TODO REFACTOR
	if (modName) {
		modName = modName[0].substring(4);
	}
	if (confirm(tr("Are you sure you want to unassign this module?") + " (" + modName + ")")) {
		window.location.replace("tiki-admin_modules.php?unassign=" + modId);
	}
};

});	// close closure
<|endoftext|>


<commit_before>// Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

module.exports = function (config) {
    config.set({

        autoWatch: false,
        concurrency: Infinity,

        browsers: ["PhantomJS"],
        frameworks: ["jasmine"],
        reporters: ["progress", "htmlDetailed"],

        files: [
            "wwwroot/lib/**/dist/*.js",
            "Assets/Scripts/js/martinCostello/martinCostello.js",
            "Assets/Scripts/js/martinCostello/website/website.js",
            "Assets/Scripts/js/martinCostello/website/debug.js",
            "Assets/Scripts/js/martinCostello/website/track.js",
            "Assets/Scripts/js/martinCostello/website/tools/tools.js",
            "Assets/Scripts/js/martinCostello/website/tools/guidGenerator.js",
            "Assets/Scripts/js/martinCostello/website/tools/hashGenerator.js",
            "Assets/Scripts/js/martinCostello/website/tools/machineKeyGenerator.js",
            "Assets/Scripts/**/*.spec.js"
        ],

        htmlDetailed: {
            splitResults: false
        },

        plugins: [
            "karma-appveyor-reporter",
            "karma-chrome-launcher",
            "karma-html-detailed-reporter",
            "karma-jasmine",
            "karma-phantomjs-launcher"
        ],

        reporters: [
            "progress",
            "appveyor"
        ]
    })
}
<commit_msg>Fix duplicate Karma configuration property<commit_after>// Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

module.exports = function (config) {
    config.set({

        autoWatch: false,
        concurrency: Infinity,

        browsers: ["PhantomJS"],
        frameworks: ["jasmine"],

        files: [
            "wwwroot/lib/**/dist/*.js",
            "Assets/Scripts/js/martinCostello/martinCostello.js",
            "Assets/Scripts/js/martinCostello/website/website.js",
            "Assets/Scripts/js/martinCostello/website/debug.js",
            "Assets/Scripts/js/martinCostello/website/track.js",
            "Assets/Scripts/js/martinCostello/website/tools/tools.js",
            "Assets/Scripts/js/martinCostello/website/tools/guidGenerator.js",
            "Assets/Scripts/js/martinCostello/website/tools/hashGenerator.js",
            "Assets/Scripts/js/martinCostello/website/tools/machineKeyGenerator.js",
            "Assets/Scripts/**/*.spec.js"
        ],

        htmlDetailed: {
            splitResults: false
        },

        plugins: [
            "karma-appveyor-reporter",
            "karma-chrome-launcher",
            "karma-html-detailed-reporter",
            "karma-jasmine",
            "karma-phantomjs-launcher"
        ],

        reporters: [
            "progress",
            "appveyor"
        ]
    })
}
<|endoftext|>


<commit_before>// Enables TLS. This is built into the server anyway, but enabling this plugin
// just advertises it.

var utils = require('./utils');

// To create a key:
// openssl req -x509 -nodes -days 2190 -newkey rsa:1024 \
//         -keyout config/tls_key.pem -out config/tls_cert.pem

exports.hook_capabilities = function (next, connection) {
    /* Caution: We cannot advertise STARTTLS if the upgrade has already been done. */
    if (connection.notes.tls_enabled !== 1) {
        var key = this.config.get('tls_key.pem', 'binary');
        if (key) {
            connection.capabilities.push('STARTTLS');
            connection.notes.tls_enabled = 1;
        }
        else {
            connection.logcrit("TLS plugin enabled but no key found. Please see plugin docs.");
        }
    }
    /* Let the plugin chain continue. */
    next();
};

exports.hook_unrecognized_command = function (next, connection, params) {
    /* Watch for STARTTLS directive from client. */
    if (connection.notes.tls_enabled && params[0] === 'STARTTLS') {
        var key = this.config.get('tls_key.pem', 'binary');
        var cert = this.config.get('tls_cert.pem', 'binary');
        var options = { key: key, cert: cert, requestCert: true };

        /* Respond to STARTTLS command. */
        connection.respond(220, "Go ahead.");
        /* Upgrade the connection to TLS. */
        var self = this;
        connection.client.upgrade(options, function (authorized, verifyError, cert, cipher) {
            connection.reset_transaction();
            connection.hello_host = undefined;
            connection.using_tls = true;
            connection.notes.tls = {
                authorized: authorized,
                authorizationError: verifyError,
                peerCertificate: cert,
                cipher: cipher
            };
            connection.loginfo(self, 'secured:' +
                ((cipher) ? ' cipher=' + cipher.name + ' version=' + cipher.version : '') +
                ' verified=' + authorized +
                ((verifyError) ? ' error="' + verifyError + '"' : '' ) +
                ((cert && cert.subject) ? ' cn="' + cert.subject.CN + '"' +
                ' organization="' + cert.subject.O + '"' : '') +
                ((cert && cert.issuer) ? ' issuer="' + cert.issuer.O + '"' : '') +
                ((cert && cert.valid_to) ? ' expires="' + cert.valid_to + '"' : '') +
                ((cert && cert.fingerprint) ? ' fingerprint=' + cert.fingerprint : ''));
            return next(OK);  // Return OK as we responded to the client
        });
    }
    else {
        return next();
    }
};
<commit_msg>Fix STARTTLS capabilities if multiple EHLOs sent<commit_after>// Enables TLS. This is built into the server anyway, but enabling this plugin
// just advertises it.

var utils = require('./utils');

// To create a key:
// openssl req -x509 -nodes -days 2190 -newkey rsa:1024 \
//         -keyout config/tls_key.pem -out config/tls_cert.pem

exports.hook_capabilities = function (next, connection) {
    /* Caution: We cannot advertise STARTTLS if the upgrade has already been done. */
    if (!connection.using_tls) {
        var key = this.config.get('tls_key.pem', 'binary');
        if (key) {
            connection.capabilities.push('STARTTLS');
            connection.notes.tls_enabled = 1;
        }
        else {
            connection.logcrit("TLS plugin enabled but no key found. Please see plugin docs.");
        }
    }
    /* Let the plugin chain continue. */
    next();
};

exports.hook_unrecognized_command = function (next, connection, params) {
    /* Watch for STARTTLS directive from client. */
    if (connection.notes.tls_enabled && params[0] === 'STARTTLS') {
        var key = this.config.get('tls_key.pem', 'binary');
        var cert = this.config.get('tls_cert.pem', 'binary');
        var options = { key: key, cert: cert, requestCert: true };

        /* Respond to STARTTLS command. */
        connection.respond(220, "Go ahead.");
        /* Upgrade the connection to TLS. */
        var self = this;
        connection.client.upgrade(options, function (authorized, verifyError, cert, cipher) {
            connection.reset_transaction(function () {
                connection.hello_host = undefined;
                connection.using_tls = true;
                connection.notes.tls = {
                    authorized: authorized,
                    authorizationError: verifyError,
                    peerCertificate: cert,
                    cipher: cipher
                };
                connection.loginfo(self, 'secured:' +
                    ((cipher) ? ' cipher=' + cipher.name + ' version=' + cipher.version : '') +
                    ' verified=' + authorized +
                    ((verifyError) ? ' error="' + verifyError + '"' : '' ) +
                    ((cert && cert.subject) ? ' cn="' + cert.subject.CN + '"' +
                    ' organization="' + cert.subject.O + '"' : '') +
                    ((cert && cert.issuer) ? ' issuer="' + cert.issuer.O + '"' : '') +
                    ((cert && cert.valid_to) ? ' expires="' + cert.valid_to + '"' : '') +
                    ((cert && cert.fingerprint) ? ' fingerprint=' + cert.fingerprint : ''));
                return next(OK);  // Return OK as we responded to the client
            });
        });
    }
    else {
        return next();
    }
};
<|endoftext|>


<commit_before>'use strict';

(function (angular) {
    angular
        .module('fixedTimerPluginWidget')
        .controller('WidgetHomeCtrl', ['$scope', '$rootScope', 'Buildfire', 'DataStore', 'TAG_NAMES', 'STATUS_CODE', '$sce', '$timeout',
            function ($scope, $rootScope, Buildfire, DataStore, TAG_NAMES, STATUS_CODE, $sce, $timeout) {
                var WidgetHome = this;
                WidgetHome.data = null;
                WidgetHome.busy = false;
                WidgetHome.allItems = {};
                WidgetHome.isCounterNegative = false;
                WidgetHome.timerRunning = "stop";
                WidgetHome.counter = 5;
                WidgetHome.isPlay = false;
                WidgetHome.stopped = false;
                WidgetHome.stoppedPlus = false;
                WidgetHome.selectedTimerIndex =0;
                WidgetHome.countdown = function () {
                    WidgetHome.timerRunning = "start";
                    if (!WidgetHome.isCounterNegative) {
                        WidgetHome.countdownNeg();
                    }
                    else {
                        WidgetHome.countdownPlus();
                    }
                };

                WidgetHome.countdownNeg = function () {
                    WidgetHome.stopped = $timeout(function () {
                        console.log($scope.counter);
                        WidgetHome.counter--;
                        if (WidgetHome.counter == 0) {
                            WidgetHome.isPlay = true;
                            WidgetHome.timerRunning = '';
                            WidgetHome.isCounterNegative = true;
                            WidgetHome.countdownPlus();
                            return;
                        }
                        WidgetHome.countdownNeg();
                    }, 1000);
                };

                WidgetHome.countdownPlus = function () {
                    WidgetHome.stoppedPlus = $timeout(function () {
                        console.log(WidgetHome.counter);
                        WidgetHome.counter++;
                        WidgetHome.countdownPlus();
                    }, 1000);
                };

                WidgetHome.silenceReset = function () {
                    WidgetHome.isPlay = false;
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    WidgetHome.counter = WidgetHome.counterSetTime;
                };

                WidgetHome.stop = function () {
                    WidgetHome.timerRunning = "pause";
                    WidgetHome.isPlay = false;
                    if (WidgetHome.isCounterNegative)
                        $timeout.cancel(WidgetHome.stoppedPlus);
                    else
                        $timeout.cancel(WidgetHome.stopped);
                };

                WidgetHome.resetTimer = function () {
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    WidgetHome.counter = WidgetHome.counterSetTime;
                };

                var getTimerItems = function () {
                    Buildfire.spinner.show();
                    var success = function (result) {
                            WidgetHome.allItems = result;
                            console.log("----------------", WidgetHome.allItems);
                            WidgetHome.selectTimer(WidgetHome.allItems[0].data.data, 1);
                            Buildfire.spinner.hide();
                        },
                        error = function () {
                            Buildfire.spinner.hide();
                            console.log("Error fetching events");
                        };

                    DataStore.search({}, TAG_NAMES.TIMER_ITEMS).then(success, error);
                };

                WidgetHome.loadMore = function () {
                    if (WidgetHome.busy) return;
                    WidgetHome.busy = true;
                    getTimerItems();
                };

                WidgetHome.safeHtml = function (html) {
                    if (html)
                        return $sce.trustAsHtml(html);
                };

                /**
                 * init() function invocation to fetch previously saved user's data from datastore.
                 */
                var init = function () {

                    /*declare the device width heights*/
                    $rootScope.deviceHeight = window.innerHeight;
                    $rootScope.deviceWidth = window.innerWidth;
                    $rootScope.backgroundImage = "";

                    var success = function (result) {
                            WidgetHome.data = result.data;
                            if (!WidgetHome.data.content)
                                WidgetHome.data.content = {};
                            if (!WidgetHome.data.design)
                                WidgetHome.data.design = {};
                            $rootScope.backgroundImage = WidgetHome.data.design.backgroundImage ? WidgetHome.data.design.backgroundImage : "";
                        }
                        , error = function (err) {
                            if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                                console.error('Error while getting data', err);
                            }
                        };
                    getTimerItems();
                    DataStore.get(TAG_NAMES.TIMER_INFO).then(success, error);
                };

                var onUpdateCallback = function (event) {

                    setTimeout(function () {
                        if (event) {
                            switch (event.tag) {
                                case TAG_NAMES.TIMER_INFO:
                                    WidgetHome.data = event.data;
                                    if (!WidgetHome.data.design)
                                        WidgetHome.data.design = {};
                                    if (!WidgetHome.data.content)
                                        WidgetHome.data.content = {};
                                    if (!event.data.design.backgroundImage) {
                                        $rootScope.backgroundImage = "";
                                    } else {
                                        $rootScope.backgroundImage = event.data.design.backgroundImage;
                                    }
                                    break;
                                case TAG_NAMES.TIMER_ITEMS:
                                    if (event.id && !event.data) {
                                        WidgetHome.allItems = $.grep(WidgetHome.allItems, function (e, i) {
                                            return e.id !== event.id;
                                        });
                                    }
                                    console.log("---------------", event);
                                    //if(event.data) {
                                    //    WidgetHome.selectTimer(event.data.data);
                                    //}
                                    //else
                                    // if(WidgetHome.allItems.length){
                                    //   WidgetHome.selectTimer(WidgetHome.allItems.data);
                                    //}
                                    $scope.$apply();
                                    break;
                            }
                            $rootScope.$digest();
                        }
                    }, 0);
                };

                $rootScope.$on('TIMER_ADDED', function (e, item) {
                    console.log("============= inside timer added", WidgetHome.allItems, item);
                    WidgetHome.allItems.unshift(item);
                    WidgetHome.description = item.data && item.data.data && item.data.data.description;
                    WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    console.log("=============", WidgetHome.allItems, item);
                    $scope.$digest();
                });
                $rootScope.$on('TIMER_UPDATED', function (e, item) {
                    console.log("============= inside timer updated", WidgetHome.allItems, item);
                    WidgetHome.allItems.forEach(function (itemData, index) {
                        if (itemData.id == item.id) {
                            WidgetHome.allItems[index] = item;
                            WidgetHome.description = item.data && item.data.data && item.data.data.description;
                            WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            return false;
                        }
                    });
//              $rootScope.$digest();
                    console.log("=============", WidgetHome.allItems, item);
                });

                WidgetHome.covertToMS = function (data) {

                    if (!data.hrs) {
                        data.hrs = 0;
                    }
                    else {
                        data.hrs = Number(data.hrs);
                    }
                    if (!data.min) {
                        data.min = 0;
                    }
                    else {
                        data.min = Number(data.min);
                    }
                    if (!data.sec) {
                        data.sec = 0;
                    }
                    else {
                        data.sec = Number(data.sec);
                    }
                    console.log(data);
                    var timeInMS = data.hrs * 3600 + data.min * 60 + data.sec;
                    return timeInMS;
                };
                WidgetHome.selectTimer = function (data, elementId) {
                    WidgetHome.selectedTimerIndex = elementId;
                    console.log(WidgetHome.counter);
                    WidgetHome.description = data.description;
                    WidgetHome.counterSetTime = WidgetHome.covertToMS(data.timer);
                    WidgetHome.counter = WidgetHome.covertToMS(data.timer);
                };
                /**
                 * DataStore.onUpdate() is bound to listen any changes in datastore
                 */
                DataStore.onUpdate().then(null, null, onUpdateCallback);

                init();
            }]);
})(window.angular);<commit_msg>Added localStorage functionality for timer<commit_after>'use strict';

(function (angular) {
    angular
        .module('fixedTimerPluginWidget')
        .controller('WidgetHomeCtrl', ['$scope', '$rootScope', 'Buildfire', 'DataStore', 'TAG_NAMES', 'STATUS_CODE', '$sce', '$timeout',
            function ($scope, $rootScope, Buildfire, DataStore, TAG_NAMES, STATUS_CODE, $sce, $timeout) {
                var WidgetHome = this;
                WidgetHome.data = null;
                WidgetHome.busy = false;
                WidgetHome.allItems = {};
                WidgetHome.isCounterNegative = false;
                WidgetHome.timerRunning = "stop";
                WidgetHome.counter = 5;
                WidgetHome.isPlay = false;
                WidgetHome.stopped = false;
                WidgetHome.stoppedPlus = false;
                WidgetHome.selectedTimerIndex =0;
                WidgetHome.timerObj = {'timerTime': 0, 'lastUpdatedTime': 0, 'isPause': false};
                WidgetHome.countdown = function () {
                    WidgetHome.timerRunning = "start";
                    if (!WidgetHome.isCounterNegative) {
                        WidgetHome.countdownNeg();
                    }
                    else {
                        WidgetHome.countdownPlus();
                    }
                };

                WidgetHome.countdownNeg = function () {
                    WidgetHome.stopped = $timeout(function () {
                        console.log($scope.counter);
                        var localStorageData = localStorage.getItem('timerObject');
                        localStorageData = localStorageData && JSON.parse(localStorageData);
                        var elapsedTimeInSec;
                        if(localStorageData && !localStorageData.isPause) {
                            elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime)/1000;
                            WidgetHome.counter = localStorageData.timerTime - elapsedTimeInSec;
                            WidgetHome.timerObj = {'timerTime': WidgetHome.counter, 'lastUpdatedTime': new Date().getTime(), 'isPause': false};
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                        } else {
                            WidgetHome.timerObj.timerTime = (WidgetHome.counter = WidgetHome.counter - 1);
                            WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                            WidgetHome.timerObj.isPause = false;
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                        }
                        if (WidgetHome.counter <= 0) {
                            WidgetHome.isPlay = true;
                            WidgetHome.timerRunning = '';
                            console.log('timer time is ++++++++++++++', WidgetHome.counter);
                            WidgetHome.timerObj.timerTime = (WidgetHome.counter = WidgetHome.counter + 1);
                            WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                            WidgetHome.timerObj.isPause = false;
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            console.log('timer time is ++++++++++++++', WidgetHome.counter);
                            WidgetHome.isCounterNegative = true;
                            WidgetHome.countdownPlus();
                            return;
                        }
                        WidgetHome.countdownNeg();
                    }, 1000);
                };

                WidgetHome.countdownPlus = function () {
                    WidgetHome.stoppedPlus = $timeout(function () {
                        console.log(WidgetHome.counter);
                        var localStorageData = localStorage.getItem('timerObject');
                        localStorageData = localStorageData && JSON.parse(localStorageData);
                        var elapsedTimeInSec;
                        if(localStorageData) {
                            if(localStorageData.timerTime == 0 && localStorageData.isPause) {
                                WidgetHome.timerObj.timerTime = (WidgetHome.counter = WidgetHome.counter + 1);
                                WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                                WidgetHome.timerObj.isPause = false;
                                localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            } else {
                                elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime) / 1000;
                                WidgetHome.counter = Math.abs(localStorageData.timerTime) + elapsedTimeInSec;
                                WidgetHome.timerObj = {'timerTime': WidgetHome.counter, 'lastUpdatedTime': new Date().getTime(), 'isPause': false};
                                localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            }
                        }
//                        WidgetHome.counter++;
                        WidgetHome.countdownPlus();
                    }, 1000);
                };

                WidgetHome.silenceReset = function () {
                    WidgetHome.isPlay = false;
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    WidgetHome.counter = WidgetHome.counterSetTime;
                    localStorage.removeItem('timerObject');
                };

                WidgetHome.stop = function () {
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    localStorageData.isPause = true;
                    localStorage.setItem('timerObject', JSON.stringify(localStorageData));
                    WidgetHome.timerRunning = "pause";
                    WidgetHome.isPlay = false;
                    if (WidgetHome.isCounterNegative)
                        $timeout.cancel(WidgetHome.stoppedPlus);
                    else
                        $timeout.cancel(WidgetHome.stopped);
                };

                WidgetHome.resetTimer = function () {
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    WidgetHome.counter = WidgetHome.counterSetTime;
                    localStorage.removeItem('timerObject');
                };

                var getTimerItems = function () {
                    Buildfire.spinner.show();
                    var success = function (result) {
                            WidgetHome.allItems = result;
                            console.log("----------------", WidgetHome.allItems);
                            WidgetHome.selectTimer(WidgetHome.allItems[0].data.data, 1);
                            Buildfire.spinner.hide();
                        },
                        error = function () {
                            Buildfire.spinner.hide();
                            console.log("Error fetching events");
                        };

                    DataStore.search({}, TAG_NAMES.TIMER_ITEMS).then(success, error);
                };

                WidgetHome.loadMore = function () {
                    if (WidgetHome.busy) return;
                    WidgetHome.busy = true;
                    getTimerItems();
                };

                WidgetHome.safeHtml = function (html) {
                    if (html)
                        return $sce.trustAsHtml(html);
                };

                /**
                 * init() function invocation to fetch previously saved user's data from datastore.
                 */
                var init = function () {

                    /*declare the device width heights*/
                    $rootScope.deviceHeight = window.innerHeight;
                    $rootScope.deviceWidth = window.innerWidth;
                    $rootScope.backgroundImage = "";

                    var success = function (result) {
                            WidgetHome.data = result.data;
                            if (!WidgetHome.data.content)
                                WidgetHome.data.content = {};
                            if (!WidgetHome.data.design)
                                WidgetHome.data.design = {};
                            $rootScope.backgroundImage = WidgetHome.data.design.backgroundImage ? WidgetHome.data.design.backgroundImage : "";
                        }
                        , error = function (err) {
                            if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                                console.error('Error while getting data', err);
                            }
                        };
                    getTimerItems();
                    DataStore.get(TAG_NAMES.TIMER_INFO).then(success, error);
                };

                var onUpdateCallback = function (event) {

                    setTimeout(function () {
                        if (event) {
                            switch (event.tag) {
                                case TAG_NAMES.TIMER_INFO:
                                    WidgetHome.data = event.data;
                                    if (!WidgetHome.data.design)
                                        WidgetHome.data.design = {};
                                    if (!WidgetHome.data.content)
                                        WidgetHome.data.content = {};
                                    if (!event.data.design.backgroundImage) {
                                        $rootScope.backgroundImage = "";
                                    } else {
                                        $rootScope.backgroundImage = event.data.design.backgroundImage;
                                    }
                                    break;
                                case TAG_NAMES.TIMER_ITEMS:
                                    if (event.id && !event.data) {
                                        WidgetHome.allItems = $.grep(WidgetHome.allItems, function (e, i) {
                                            return e.id !== event.id;
                                        });
                                    }
                                    console.log("---------------", event);
                                    //if(event.data) {
                                    //    WidgetHome.selectTimer(event.data.data);
                                    //}
                                    //else
                                    // if(WidgetHome.allItems.length){
                                    //   WidgetHome.selectTimer(WidgetHome.allItems.data);
                                    //}
                                    $scope.$apply();
                                    break;
                            }
                            $rootScope.$digest();
                        }
                    }, 0);
                };

                $rootScope.$on('TIMER_ADDED', function (e, item) {
                    console.log("============= inside timer added", WidgetHome.allItems, item);
                    WidgetHome.allItems.unshift(item);
                    WidgetHome.description = item.data && item.data.data && item.data.data.description;
                    WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    console.log("=============", WidgetHome.allItems, item);
                    $scope.$digest();
                });
                $rootScope.$on('TIMER_UPDATED', function (e, item) {
                    console.log("============= inside timer updated", WidgetHome.allItems, item);
                    WidgetHome.allItems.forEach(function (itemData, index) {
                        if (itemData.id == item.id) {
                            WidgetHome.allItems[index] = item;
                            WidgetHome.description = item.data && item.data.data && item.data.data.description;
                            WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            return false;
                        }
                    });
//              $rootScope.$digest();
                    console.log("=============", WidgetHome.allItems, item);
                });

                WidgetHome.covertToMS = function (data) {

                    if (!data.hrs) {
                        data.hrs = 0;
                    }
                    else {
                        data.hrs = Number(data.hrs);
                    }
                    if (!data.min) {
                        data.min = 0;
                    }
                    else {
                        data.min = Number(data.min);
                    }
                    if (!data.sec) {
                        data.sec = 0;
                    }
                    else {
                        data.sec = Number(data.sec);
                    }
                    console.log(data);
                    var timeInMS = data.hrs * 3600 + data.min * 60 + data.sec;
                    return timeInMS;
                };
                WidgetHome.selectTimer = function (data, elementId) {
                    WidgetHome.selectedTimerIndex = elementId;
                    console.log(WidgetHome.counter);
                    WidgetHome.description = data.description;
                    WidgetHome.counterSetTime = WidgetHome.covertToMS(data.timer);
                    WidgetHome.counter = WidgetHome.covertToMS(data.timer);
                };
                /**
                 * DataStore.onUpdate() is bound to listen any changes in datastore
                 */
                DataStore.onUpdate().then(null, null, onUpdateCallback);

                init();
            }]);
})(window.angular);<|endoftext|>


<commit_before>'use strict';

(function (angular) {
    angular
        .module('wooCommercePluginWidget')
        .controller('WidgetHomeCtrl', ['$scope', 'DataStore', 'WooCommerceSDK', 'TAG_NAMES', '$sce', 'LAYOUTS', '$rootScope', 'PAGINATION', 'Buildfire', 'ViewStack',
            function ($scope, DataStore, WooCommerceSDK, TAG_NAMES, $sce, LAYOUTS, $rootScope, PAGINATION, Buildfire, ViewStack) {
                var WidgetHome = this;
                WidgetHome.data = null;
                WidgetHome.sections = [];
                WidgetHome.busy = true;
                WidgetHome.pageNumber = 1;
                //create new instance of buildfire carousel viewer
                WidgetHome.view = null;
                WidgetHome.safeHtml = function (html) {
                    if (html) {
                        var $html = $('
', {html: html});
                        $html.find('iframe').each(function (index, element) {
                            var src = element.src;
                            console.log('element is: ', src, src.indexOf('http'));
                            src = src && src.indexOf('file://') != -1 ? src.replace('file://', 'http://') : src;
                            element.src = src && src.indexOf('http') != -1 ? src : 'http:' + src;
                        });
                        return $sce.trustAsHtml($html.html());
                    }
                };

                WidgetHome.showDescription = function (description) {
                    return !((description == '

') || (description == '

'));
                };
                $rootScope.deviceHeight = window.innerHeight;
                $rootScope.deviceWidth = window.innerWidth;
                $rootScope.backgroundImage = "";
                WidgetHome.loadMore = function () {
                    console.log('>>>>>>>>>>>>>> inside load more widget home controller');
                    if (WidgetHome.busy) return;
                    WidgetHome.busy = true;
                    if (WidgetHome.data.content.storeURL && WidgetHome.data.content.consumerKey && WidgetHome.data.content.consumerSecret)
                        getSections(WidgetHome.data.content.storeURL, WidgetHome.data.content.consumerKey, WidgetHome.data.content.consumerSecret);
                    else
                        WidgetHome.sections = [];
                };

                WidgetHome.showItems = function (slug) {
                    if (WidgetHome.data.design.itemListLayout)
                        ViewStack.push({
                            template: WidgetHome.data.design.itemListLayout,
                            params: {
                                slug: slug,
                                controller: "WidgetItemsCtrl as WidgetItems",
                                shouldUpdateTemplate : true
                            }
                        });
                };

                WidgetHome.goToCart = function () {
                    ViewStack.push({
                        template: 'Checkout',
                        params: {
                            url: WidgetHome.data.content.storeURL + '/cart'
                        }
                    });
                };

                var currentStoreUrl = "";

                var getSections = function (storeURL, consumerKey, consumerSecret) {
                    console.log('<<<<<<<<<<<<<<<<<< inside get section of widget home controller');
                    Buildfire.spinner.show();
                    var success = function (result) {
                            Buildfire.spinner.hide();
                            console.log("********************************", result.data);
                            WidgetHome.sections = WidgetHome.sections.length ? WidgetHome.sections.concat(result.data.product_categories) : result.data.product_categories;
                            WidgetHome.pageNumber = WidgetHome.pageNumber + 1;
                            if (result.data.product_categories.length == PAGINATION.sectionsCount) {
                                WidgetHome.busy = false;
                            }
                        }
                        , error = function (err) {
                            Buildfire.spinner.hide();
                            console.error('Error In Fetching category list', err);
                        };
                    WooCommerceSDK.getSections(storeURL, consumerKey, consumerSecret, WidgetHome.pageNumber).then(success, error);
                };

                /*
                 * Fetch user's data from datastore
                 */

                var init = function () {
                    var success = function (result) {
                            WidgetHome.data = result.data;
                            if (!WidgetHome.data.design)
                                WidgetHome.data.design = {};
                            if (!WidgetHome.data.content)
                                WidgetHome.data.content = {};
                            if (!WidgetHome.data.settings)
                                WidgetHome.data.settings = {};
                            if (WidgetHome.data.content.storeURL) {
                                currentStoreUrl = WidgetHome.data.content.storeURL;
                            }
                            if (!WidgetHome.data.design.sectionListLayout) {
                                WidgetHome.data.design.sectionListLayout = LAYOUTS.sectionListLayout[0].name;
                            }
                            if (!WidgetHome.data.design.itemListLayout) {
                                WidgetHome.data.design.itemListLayout = LAYOUTS.itemListLayout[0].name;
                            }
                            console.log("WidgetHome.data.design.backgroundImage", WidgetHome.data.design.itemDetailsBgImage)
                            if (!WidgetHome.data.design.itemDetailsBgImage) {
                                $rootScope.backgroundImage = "";
                            } else {
                                $rootScope.backgroundImage = WidgetHome.data.design.itemDetailsBgImage;
                            }
                            if (WidgetHome.data.content.storeURL && WidgetHome.data.content.consumerKey && WidgetHome.data.content.consumerSecret)
                                getSections(WidgetHome.data.content.storeURL, WidgetHome.data.content.consumerKey, WidgetHome.data.content.consumerSecret);
                            else
                                WidgetHome.sections = [];
                        }
                        , error = function (err) {
                            console.error('Error while getting data', err);
                        };
                    DataStore.get(TAG_NAMES.WOOCOMMERCE_INFO).then(success, error);
                };

                var onUpdateCallback = function (event) {
                    setTimeout(function () {
                        if (event && event.tag) {
                            switch (event.tag) {
                                case TAG_NAMES.WOOCOMMERCE_INFO:
                                    WidgetHome.data = event.data;
                                    if (!WidgetHome.data.design)
                                        WidgetHome.data.design = {};
                                    if (!WidgetHome.data.design.sectionListLayout) {
                                        WidgetHome.data.design.sectionListLayout = LAYOUTS.sectionListLayout[0].name;
                                    }
                                    if (!WidgetHome.data.design.itemListLayout) {
                                        WidgetHome.data.design.itemListLayout = LAYOUTS.itemListLayout[0].name;
                                    }
                                    if (!WidgetHome.data.content.storeURL) {
                                        WidgetHome.sections = [];
                                        currentStoreUrl = "";
                                        WidgetHome.busy = false;
                                    }
                                    if (!WidgetHome.data.design.itemDetailsBgImage) {
                                        $rootScope.backgroundImage = "";
                                    } else {
                                        $rootScope.backgroundImage = WidgetHome.data.design.itemDetailsBgImage;
                                    }
                                    if (WidgetHome.data.content.storeURL && currentStoreUrl != WidgetHome.data.content.storeURL) {
                                        WidgetHome.sections = [];
                                        WidgetHome.busy = false;
                                        WidgetHome.pageNumber = 1;
                                        WidgetHome.loadMore();
                                    }
                                    if (WidgetHome.view) {
                                        WidgetHome.view.loadItems(WidgetHome.data.content.carouselImages);
                                    }

                                    break;
                            }
                            $scope.$digest();
                            $rootScope.$digest();
                        }
                    }, 0);
                };

                /**
                 * DataStore.onUpdate() is bound to listen any changes in datastore
                 */
                DataStore.onUpdate().then(null, null, onUpdateCallback);

                $rootScope.$on("Carousel:LOADED", function () {
                    WidgetHome.view = null;
                    if (!WidgetHome.view) {
                        WidgetHome.view = new buildfire.components.carousel.view("#carousel", [], "WideScreen");
                    }
                    if (WidgetHome.data && WidgetHome.data.content.carouselImages) {
                        WidgetHome.view.loadItems(WidgetHome.data.content.carouselImages, null, "WideScreen");
                    } else {
                        WidgetHome.view.loadItems([]);
                    }
                });

                /*crop image on the basis of width heights*/
                WidgetHome.cropImage = function (url, settings) {
                    var options = {};
                    if (!url) {
                        return "";
                    }
                    else {
                        if (settings.height) {
                            options.height = settings.height;
                        }
                        if (settings.width) {
                            options.width = settings.width;
                        }
                        return buildfire.imageLib.cropImage(url, options);
                    }
                };
                $scope.$on("$destroy", function () {
                    DataStore.clearListener();
                });

                $rootScope.$on('VIEW_CHANGED', function (e, type, view) {
                    if (type === 'POPALL') {
                        WidgetHome.data.content.storeURL = null;
                        WidgetHome.sections = [];
                        WidgetHome.busy = false;
                        WidgetHome.pageNumber = 1;
                        $scope.$digest();
                    }
                    if (type === 'POP') {
                        DataStore.onUpdate().then(null, null, onUpdateCallback);
                    }
                });

                init();
            }]);
})(window.angular);
<commit_msg>Added check before matching array length<commit_after>'use strict';

(function (angular) {
    angular
        .module('wooCommercePluginWidget')
        .controller('WidgetHomeCtrl', ['$scope', 'DataStore', 'WooCommerceSDK', 'TAG_NAMES', '$sce', 'LAYOUTS', '$rootScope', 'PAGINATION', 'Buildfire', 'ViewStack',
            function ($scope, DataStore, WooCommerceSDK, TAG_NAMES, $sce, LAYOUTS, $rootScope, PAGINATION, Buildfire, ViewStack) {
                var WidgetHome = this;
                WidgetHome.data = null;
                WidgetHome.sections = [];
                WidgetHome.busy = true;
                WidgetHome.pageNumber = 1;
                //create new instance of buildfire carousel viewer
                WidgetHome.view = null;
                WidgetHome.safeHtml = function (html) {
                    if (html) {
                        var $html = $('
', {html: html});
                        $html.find('iframe').each(function (index, element) {
                            var src = element.src;
                            console.log('element is: ', src, src.indexOf('http'));
                            src = src && src.indexOf('file://') != -1 ? src.replace('file://', 'http://') : src;
                            element.src = src && src.indexOf('http') != -1 ? src : 'http:' + src;
                        });
                        return $sce.trustAsHtml($html.html());
                    }
                };

                WidgetHome.showDescription = function (description) {
                    return !((description == '

') || (description == '

'));
                };
                $rootScope.deviceHeight = window.innerHeight;
                $rootScope.deviceWidth = window.innerWidth;
                $rootScope.backgroundImage = "";
                WidgetHome.loadMore = function () {
                    console.log('>>>>>>>>>>>>>> inside load more widget home controller');
                    if (WidgetHome.busy) return;
                    WidgetHome.busy = true;
                    if (WidgetHome.data.content.storeURL && WidgetHome.data.content.consumerKey && WidgetHome.data.content.consumerSecret)
                        getSections(WidgetHome.data.content.storeURL, WidgetHome.data.content.consumerKey, WidgetHome.data.content.consumerSecret);
                    else
                        WidgetHome.sections = [];
                };

                WidgetHome.showItems = function (slug) {
                    if (WidgetHome.data.design.itemListLayout)
                        ViewStack.push({
                            template: WidgetHome.data.design.itemListLayout,
                            params: {
                                slug: slug,
                                controller: "WidgetItemsCtrl as WidgetItems",
                                shouldUpdateTemplate : true
                            }
                        });
                };

                WidgetHome.goToCart = function () {
                    ViewStack.push({
                        template: 'Checkout',
                        params: {
                            url: WidgetHome.data.content.storeURL + '/cart'
                        }
                    });
                };

                var currentStoreUrl = "";

                var getSections = function (storeURL, consumerKey, consumerSecret) {
                    console.log('<<<<<<<<<<<<<<<<<< inside get section of widget home controller');
                    Buildfire.spinner.show();
                    var success = function (result) {
                            Buildfire.spinner.hide();
                            console.log("********************************", result.data);
                            WidgetHome.sections = WidgetHome.sections.length ? WidgetHome.sections.concat(result.data.product_categories) : result.data.product_categories;
                            WidgetHome.pageNumber = WidgetHome.pageNumber + 1;
                            if (result && result.data && result.data.product_categories && (result.data.product_categories.length == PAGINATION.sectionsCount)) {
                                WidgetHome.busy = false;
                            }
                        }
                        , error = function (err) {
                            Buildfire.spinner.hide();
                            console.error('Error In Fetching category list', err);
                        };
                    WooCommerceSDK.getSections(storeURL, consumerKey, consumerSecret, WidgetHome.pageNumber).then(success, error);
                };

                /*
                 * Fetch user's data from datastore
                 */

                var init = function () {
                    var success = function (result) {
                            WidgetHome.data = result.data;
                            if (!WidgetHome.data.design)
                                WidgetHome.data.design = {};
                            if (!WidgetHome.data.content)
                                WidgetHome.data.content = {};
                            if (!WidgetHome.data.settings)
                                WidgetHome.data.settings = {};
                            if (WidgetHome.data.content.storeURL) {
                                currentStoreUrl = WidgetHome.data.content.storeURL;
                            }
                            if (!WidgetHome.data.design.sectionListLayout) {
                                WidgetHome.data.design.sectionListLayout = LAYOUTS.sectionListLayout[0].name;
                            }
                            if (!WidgetHome.data.design.itemListLayout) {
                                WidgetHome.data.design.itemListLayout = LAYOUTS.itemListLayout[0].name;
                            }
                            console.log("WidgetHome.data.design.backgroundImage", WidgetHome.data.design.itemDetailsBgImage)
                            if (!WidgetHome.data.design.itemDetailsBgImage) {
                                $rootScope.backgroundImage = "";
                            } else {
                                $rootScope.backgroundImage = WidgetHome.data.design.itemDetailsBgImage;
                            }
                            if (WidgetHome.data.content.storeURL && WidgetHome.data.content.consumerKey && WidgetHome.data.content.consumerSecret)
                                getSections(WidgetHome.data.content.storeURL, WidgetHome.data.content.consumerKey, WidgetHome.data.content.consumerSecret);
                            else
                                WidgetHome.sections = [];
                        }
                        , error = function (err) {
                            console.error('Error while getting data', err);
                        };
                    DataStore.get(TAG_NAMES.WOOCOMMERCE_INFO).then(success, error);
                };

                var onUpdateCallback = function (event) {
                    setTimeout(function () {
                        if (event && event.tag) {
                            switch (event.tag) {
                                case TAG_NAMES.WOOCOMMERCE_INFO:
                                    WidgetHome.data = event.data;
                                    if (!WidgetHome.data.design)
                                        WidgetHome.data.design = {};
                                    if (!WidgetHome.data.design.sectionListLayout) {
                                        WidgetHome.data.design.sectionListLayout = LAYOUTS.sectionListLayout[0].name;
                                    }
                                    if (!WidgetHome.data.design.itemListLayout) {
                                        WidgetHome.data.design.itemListLayout = LAYOUTS.itemListLayout[0].name;
                                    }
                                    if (!WidgetHome.data.content.storeURL) {
                                        WidgetHome.sections = [];
                                        currentStoreUrl = "";
                                        WidgetHome.busy = false;
                                    }
                                    if (!WidgetHome.data.design.itemDetailsBgImage) {
                                        $rootScope.backgroundImage = "";
                                    } else {
                                        $rootScope.backgroundImage = WidgetHome.data.design.itemDetailsBgImage;
                                    }
                                    if (WidgetHome.data.content.storeURL && currentStoreUrl != WidgetHome.data.content.storeURL) {
                                        WidgetHome.sections = [];
                                        WidgetHome.busy = false;
                                        WidgetHome.pageNumber = 1;
                                        WidgetHome.loadMore();
                                    }
                                    if (WidgetHome.view) {
                                        WidgetHome.view.loadItems(WidgetHome.data.content.carouselImages);
                                    }

                                    break;
                            }
                            $scope.$digest();
                            $rootScope.$digest();
                        }
                    }, 0);
                };

                /**
                 * DataStore.onUpdate() is bound to listen any changes in datastore
                 */
                DataStore.onUpdate().then(null, null, onUpdateCallback);

                $rootScope.$on("Carousel:LOADED", function () {
                    WidgetHome.view = null;
                    if (!WidgetHome.view) {
                        WidgetHome.view = new buildfire.components.carousel.view("#carousel", [], "WideScreen");
                    }
                    if (WidgetHome.data && WidgetHome.data.content.carouselImages) {
                        WidgetHome.view.loadItems(WidgetHome.data.content.carouselImages, null, "WideScreen");
                    } else {
                        WidgetHome.view.loadItems([]);
                    }
                });

                /*crop image on the basis of width heights*/
                WidgetHome.cropImage = function (url, settings) {
                    var options = {};
                    if (!url) {
                        return "";
                    }
                    else {
                        if (settings.height) {
                            options.height = settings.height;
                        }
                        if (settings.width) {
                            options.width = settings.width;
                        }
                        return buildfire.imageLib.cropImage(url, options);
                    }
                };
                $scope.$on("$destroy", function () {
                    DataStore.clearListener();
                });

                $rootScope.$on('VIEW_CHANGED', function (e, type, view) {
                    if (type === 'POPALL') {
                        WidgetHome.data.content.storeURL = null;
                        WidgetHome.sections = [];
                        WidgetHome.busy = false;
                        WidgetHome.pageNumber = 1;
                        $scope.$digest();
                    }
                    if (type === 'POP') {
                        DataStore.onUpdate().then(null, null, onUpdateCallback);
                    }
                });

                init();
            }]);
})(window.angular);
<|endoftext|>