<commit_before> /**
 *  Copyright (C) 2010 Cloud.com, Inc.  All rights reserved.
 *
 * This software is licensed under the GNU General Public License v3 or later.
 *
 * It is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

function afterLoadNetworkJSP($leftmenuItem1) {
    var zoneObj = $leftmenuItem1.data("jsonObj");
    if(zoneObj == null)
	    return;

    showMiddleMenu();
    disableMultipleSelectionInMidMenu();

    //switch between different tabs - Public Network page
    var $publicNetworkPage = $("#public_network_page");
    var tabArray = [$publicNetworkPage.find("#tab_details"), $publicNetworkPage.find("#tab_ipallocation"), $publicNetworkPage.find("#tab_firewall"), $publicNetworkPage.find("#tab_loadbalancer")];
    var tabContentArray = [$publicNetworkPage.find("#tab_content_details"), $publicNetworkPage.find("#tab_content_ipallocation"), $publicNetworkPage.find("#tab_content_firewall"), $publicNetworkPage.find("#tab_content_loadbalancer")];
    var afterSwitchFnArray = [publicNetworkJsonToDetailsTab, publicNetworkJsonToIpAllocationTab, publicNetworkJsonToFirewallTab, publicNetworkJsonToLoadBalancerTab];
    switchBetweenDifferentTabs(tabArray, tabContentArray, afterSwitchFnArray);

    //switch between different tabs - Direct Network page
    var $directNetworkPage = $("#direct_network_page");
    var tabArray = [$directNetworkPage.find("#tab_details"), $directNetworkPage.find("#tab_ipallocation")];
    var tabContentArray = [$directNetworkPage.find("#tab_content_details"), $directNetworkPage.find("#tab_content_ipallocation")];
    var afterSwitchFnArray = [directNetworkJsonToDetailsTab, directNetworkJsonToIpAllocationTab];
    switchBetweenDifferentTabs(tabArray, tabContentArray, afterSwitchFnArray);

    //populate items into middle menu
    var $midmenuContainer = $("#midmenu_container").empty();

    //public network
    if(zoneObj.networktype == "Advanced") {
        $.ajax({
            data: createURL("command=listNetworks&isSystem=true&zoneId="+zoneObj.id),
            dataType: "json",
            async: false,
            success: function(json) {
                var items = json.listnetworksresponse.network;
                if(items != null && items.length > 0) {
                    var item = items[0];
                    var $midmenuItem1 = $("#midmenu_item").clone();
                    $midmenuItem1.data("toRightPanelFn", publicNetworkToRightPanel);
                    publicNetworkToMidmenu(item, $midmenuItem1);
                    bindClickToMidMenu($midmenuItem1, publicNetworkToRightPanel, publicNetworkGetMidmenuId);
                    $midmenuContainer.append($midmenuItem1.show());
                    $midmenuItem1.click();
                }
            }
        });
    }

    //direct network
    $.ajax({
		data: createURL("command=listNetworks&type=Direct&zoneId="+zoneObj.id),
		dataType: "json",
		success: function(json) {
			var items = json.listnetworksresponse.network;
			if (items != null && items.length > 0) {
				for (var i = 0; i < items.length; i++) {
					var $midmenuItem1 = $("#midmenu_item").clone();
                    $midmenuItem1.data("toRightPanelFn", directNetworkToRightPanel);
                    directNetworkToMidmenu(items[i], $midmenuItem1);
                    bindClickToMidMenu($midmenuItem1, directNetworkToRightPanel, directNetworkGetMidmenuId);
                    $midmenuContainer.append($midmenuItem1.show());
				}
			}
		}
	});
}

//***** Public Network (begin) ******************************************************************************************************
function publicNetworkGetMidmenuId(jsonObj) {
    return "midmenuItem_publicnetework_" + jsonObj.id;
}

function publicNetworkToMidmenu(jsonObj, $midmenuItem1) {
    $midmenuItem1.attr("id", publicNetworkGetMidmenuId(jsonObj));
    $midmenuItem1.data("jsonObj", jsonObj);

    /*
    var $iconContainer = $midmenuItem1.find("#icon_container").show();
    $iconContainer.find("#icon").attr("src", "images/midmenuicon_storage_snapshots.png");
    */

    $midmenuItem1.find("#first_row").text("Public Network");
    $midmenuItem1.find("#second_row").text("Network ID: " + fromdb(jsonObj.id));
}

function publicNetworkToRightPanel($midmenuItem1) {
    copyActionInfoFromMidMenuToRightPanel($midmenuItem1);
    $("#right_panel_content").data("$midmenuItem1", $midmenuItem1);

    $("#public_network_page").show();
    $("#direct_network_page").hide();

    $("#public_network_page").find("#tab_details").click();
}

function publicNetworkJsonToDetailsTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #public_network_page #tab_content_details");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

	$thisTab.find("#grid_header_title").text(fromdb(jsonObj.networkofferingdisplaytext));

	$thisTab.find("#id").text(fromdb(jsonObj.id));
	$thisTab.find("#state").text(fromdb(jsonObj.state));
	$thisTab.find("#traffictype").text(fromdb(jsonObj.traffictype));
	$thisTab.find("#broadcastdomaintype").text(fromdb(jsonObj.broadcastdomaintype));
	setBooleanReadField(jsonObj.isshared, $thisTab.find("#isshared"));
	setBooleanReadField(jsonObj.issystem, $thisTab.find("#issystem"));
	$thisTab.find("#networkofferingname").text(fromdb(jsonObj.networkofferingname));
	$thisTab.find("#networkofferingdisplaytext").text(fromdb(jsonObj.networkofferingdisplaytext));
	$thisTab.find("#networkofferingid").text(fromdb(jsonObj.networkofferingid));
	$thisTab.find("#related").text(fromdb(jsonObj.related));
	$thisTab.find("#zoneid").text(fromdb(jsonObj.zoneid));
	$thisTab.find("#dns1").text(fromdb(jsonObj.dns1));
	$thisTab.find("#dns2").text(fromdb(jsonObj.dns2));
	$thisTab.find("#domainid").text(fromdb(jsonObj.domainid));
	$thisTab.find("#account").text(fromdb(jsonObj.account));

    $thisTab.find("#tab_container").show();
    $thisTab.find("#tab_spinning_wheel").hide();
}

function publicNetworkJsonToIpAllocationTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #public_network_page #tab_content_ipallocation");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

    $.ajax({
		data: createURL("command=listVlanIpRanges&zoneid="+ jsonObj.zoneid + "&networkid="+jsonObj.id),
		dataType: "json",
		success: function(json) {
		    var items = json.listvlaniprangesresponse.vlaniprange;
		    var $container = $thisTab.find("#tab_container").empty();
		    var $template = $("#directnetwork_iprange_template");
		    if(items != null && items.length > 0) {
		        for(var i=0; i<items.length; i++) {
		            var $newTemplate = $template.clone();
		            publicNetworkIprangeJsonToTemplate(items[i], $newTemplate);
		            $container.append($newTemplate.show());
		        }
		    }
		    $thisTab.find("#tab_container").show();
            $thisTab.find("#tab_spinning_wheel").hide();
		}
    });
}

function publicNetworkIprangeJsonToTemplate(jsonObj, $template) {
    $template.attr("id", "publicNetworkIprange_" + jsonObj.id);

    var ipRange = getIpRange(fromdb(jsonObj.startip), fromdb(jsonObj.endip));
    $template.find("#grid_header_title").text(ipRange);

    $template.find("#vlan").text(jsonObj.vlan)
    $template.find("#startip").text(fromdb(jsonObj.startip));
    $template.find("#endip").text(fromdb(jsonObj.endip));
}

function publicNetworkJsonToFirewallTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #public_network_page #tab_content_firewall");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

    $thisTab.find("#tab_container").show();
    $thisTab.find("#tab_spinning_wheel").hide();
}

function publicNetworkJsonToLoadBalancerTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #public_network_page #tab_content_loadbalancer");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

    $thisTab.find("#tab_container").show();
    $thisTab.find("#tab_spinning_wheel").hide();
}
//***** Public Network (end) ******************************************************************************************************

//***** Direct Network (begin) ******************************************************************************************************
function directNetworkGetMidmenuId(jsonObj) {
    return "midmenuItem_directnetework_" + jsonObj.id;
}

function directNetworkToMidmenu(jsonObj, $midmenuItem1) {
    $midmenuItem1.attr("id", directNetworkGetMidmenuId(jsonObj));
    $midmenuItem1.data("jsonObj", jsonObj);

    /*
    var $iconContainer = $midmenuItem1.find("#icon_container").show();
    $iconContainer.find("#icon").attr("src", "images/midmenuicon_storage_snapshots.png");
    */

    $midmenuItem1.find("#first_row").text(fromdb(jsonObj.name).substring(0,25));
    $midmenuItem1.find("#second_row").text("VLAN ID: " + fromdb(jsonObj.vlan));
}

function directNetworkToRightPanel($midmenuItem1) {
    copyActionInfoFromMidMenuToRightPanel($midmenuItem1);
    $("#right_panel_content").data("$midmenuItem1", $midmenuItem1);

    $("#direct_network_page").show();
    $("#public_network_page").hide();

    $("#direct_network_page").find("#tab_details").click();
}

function directNetworkJsonToDetailsTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #direct_network_page #tab_content_details");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

	$thisTab.find("#grid_header_title").text(fromdb(jsonObj.name));

	$thisTab.find("#id").text(fromdb(jsonObj.id));
	$thisTab.find("#name").text(fromdb(jsonObj.name));
	$thisTab.find("#displaytext").text(fromdb(jsonObj.displaytext));

    $thisTab.find("#vlan").text(fromdb(jsonObj.vlan));
    $thisTab.find("#gateway").text(fromdb(jsonObj.gateway));
    $thisTab.find("#netmask").text(fromdb(jsonObj.netmask));
    var ipRange = getIpRange(fromdb(jsonObj.startip), fromdb(jsonObj.endip));
    $thisTab.find("#iprange").text(ipRange);

    $thisTab.find("#domain").text(fromdb(jsonObj.domain));      //might be null
    $thisTab.find("#account").text(fromdb(jsonObj.account));    //might be null

    $thisTab.find("#tab_container").show();
    $thisTab.find("#tab_spinning_wheel").hide();
}

function directNetworkJsonToIpAllocationTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #direct_network_page #tab_content_ipallocation");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

    $.ajax({
		data: createURL("command=listVlanIpRanges&zoneid="+ jsonObj.zoneid + "&networkid="+jsonObj.id),
		dataType: "json",
		success: function(json) {
		    var items = json.listvlaniprangesresponse.vlaniprange;
		    var $container = $thisTab.find("#tab_container").empty();
		    var $template = $("#directnetwork_iprange_template");
		    if(items != null && items.length > 0) {
		        for(var i=0; i<items.length; i++) {
		            var $newTemplate = $template.clone();
		            directNetworkIprangeJsonToTemplate(items[i], $newTemplate);
		            $container.append($newTemplate.show());
		        }
		    }
		    $thisTab.find("#tab_container").show();
            $thisTab.find("#tab_spinning_wheel").hide();
		}
    });
}

function directNetworkIprangeJsonToTemplate(jsonObj, $template) {
    $template.attr("id", "directNetworkIprange_" + jsonObj.id);

    var ipRange = getIpRange(fromdb(jsonObj.startip), fromdb(jsonObj.endip));
    $template.find("#grid_header_title").text(ipRange);

    $template.find("#vlan").text(jsonObj.vlan)
    $template.find("#startip").text(fromdb(jsonObj.startip));
    $template.find("#endip").text(fromdb(jsonObj.endip));
}
//***** Direct Network (end) ******************************************************************************************************

<commit_msg>bug 7448: zone tree - network - public network page - implement IP allocation tab.<commit_after> /**
 *  Copyright (C) 2010 Cloud.com, Inc.  All rights reserved.
 *
 * This software is licensed under the GNU General Public License v3 or later.
 *
 * It is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

function afterLoadNetworkJSP($leftmenuItem1) {
    var zoneObj = $leftmenuItem1.data("jsonObj");
    if(zoneObj == null)
	    return;

    showMiddleMenu();
    disableMultipleSelectionInMidMenu();

    //switch between different tabs - Public Network page
    var $publicNetworkPage = $("#public_network_page");
    var tabArray = [$publicNetworkPage.find("#tab_details"), $publicNetworkPage.find("#tab_ipallocation"), $publicNetworkPage.find("#tab_firewall"), $publicNetworkPage.find("#tab_loadbalancer")];
    var tabContentArray = [$publicNetworkPage.find("#tab_content_details"), $publicNetworkPage.find("#tab_content_ipallocation"), $publicNetworkPage.find("#tab_content_firewall"), $publicNetworkPage.find("#tab_content_loadbalancer")];
    var afterSwitchFnArray = [publicNetworkJsonToDetailsTab, publicNetworkJsonToIpAllocationTab, publicNetworkJsonToFirewallTab, publicNetworkJsonToLoadBalancerTab];
    switchBetweenDifferentTabs(tabArray, tabContentArray, afterSwitchFnArray);

    //switch between different tabs - Direct Network page
    var $directNetworkPage = $("#direct_network_page");
    var tabArray = [$directNetworkPage.find("#tab_details"), $directNetworkPage.find("#tab_ipallocation")];
    var tabContentArray = [$directNetworkPage.find("#tab_content_details"), $directNetworkPage.find("#tab_content_ipallocation")];
    var afterSwitchFnArray = [directNetworkJsonToDetailsTab, directNetworkJsonToIpAllocationTab];
    switchBetweenDifferentTabs(tabArray, tabContentArray, afterSwitchFnArray);

    //populate items into middle menu
    var $midmenuContainer = $("#midmenu_container").empty();

    //public network
    if(zoneObj.networktype == "Advanced") {
        $.ajax({
            data: createURL("command=listNetworks&isSystem=true&zoneId="+zoneObj.id),
            dataType: "json",
            async: false,
            success: function(json) {
                var items = json.listnetworksresponse.network;
                if(items != null && items.length > 0) {
                    var item = items[0];
                    var $midmenuItem1 = $("#midmenu_item").clone();
                    $midmenuItem1.data("toRightPanelFn", publicNetworkToRightPanel);
                    publicNetworkToMidmenu(item, $midmenuItem1);
                    bindClickToMidMenu($midmenuItem1, publicNetworkToRightPanel, publicNetworkGetMidmenuId);
                    $midmenuContainer.append($midmenuItem1.show());
                    $midmenuItem1.click();
                }
            }
        });
    }

    //direct network
    $.ajax({
		data: createURL("command=listNetworks&type=Direct&zoneId="+zoneObj.id),
		dataType: "json",
		success: function(json) {
			var items = json.listnetworksresponse.network;
			if (items != null && items.length > 0) {
				for (var i = 0; i < items.length; i++) {
					var $midmenuItem1 = $("#midmenu_item").clone();
                    $midmenuItem1.data("toRightPanelFn", directNetworkToRightPanel);
                    directNetworkToMidmenu(items[i], $midmenuItem1);
                    bindClickToMidMenu($midmenuItem1, directNetworkToRightPanel, directNetworkGetMidmenuId);
                    $midmenuContainer.append($midmenuItem1.show());
				}
			}
		}
	});
}

//***** Public Network (begin) ******************************************************************************************************
function publicNetworkGetMidmenuId(jsonObj) {
    return "midmenuItem_publicnetework_" + jsonObj.id;
}

function publicNetworkToMidmenu(jsonObj, $midmenuItem1) {
    $midmenuItem1.attr("id", publicNetworkGetMidmenuId(jsonObj));
    $midmenuItem1.data("jsonObj", jsonObj);

    /*
    var $iconContainer = $midmenuItem1.find("#icon_container").show();
    $iconContainer.find("#icon").attr("src", "images/midmenuicon_storage_snapshots.png");
    */

    $midmenuItem1.find("#first_row").text("Public Network");
    $midmenuItem1.find("#second_row").text("Network ID: " + fromdb(jsonObj.id));
}

function publicNetworkToRightPanel($midmenuItem1) {
    copyActionInfoFromMidMenuToRightPanel($midmenuItem1);
    $("#right_panel_content").data("$midmenuItem1", $midmenuItem1);

    $("#public_network_page").show();
    $("#direct_network_page").hide();

    $("#public_network_page").find("#tab_details").click();
}

function publicNetworkJsonToDetailsTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #public_network_page #tab_content_details");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

	$thisTab.find("#grid_header_title").text(fromdb(jsonObj.networkofferingdisplaytext));

	$thisTab.find("#id").text(fromdb(jsonObj.id));
	$thisTab.find("#state").text(fromdb(jsonObj.state));
	$thisTab.find("#traffictype").text(fromdb(jsonObj.traffictype));
	$thisTab.find("#broadcastdomaintype").text(fromdb(jsonObj.broadcastdomaintype));
	setBooleanReadField(jsonObj.isshared, $thisTab.find("#isshared"));
	setBooleanReadField(jsonObj.issystem, $thisTab.find("#issystem"));
	$thisTab.find("#networkofferingname").text(fromdb(jsonObj.networkofferingname));
	$thisTab.find("#networkofferingdisplaytext").text(fromdb(jsonObj.networkofferingdisplaytext));
	$thisTab.find("#networkofferingid").text(fromdb(jsonObj.networkofferingid));
	$thisTab.find("#related").text(fromdb(jsonObj.related));
	$thisTab.find("#zoneid").text(fromdb(jsonObj.zoneid));
	$thisTab.find("#dns1").text(fromdb(jsonObj.dns1));
	$thisTab.find("#dns2").text(fromdb(jsonObj.dns2));
	$thisTab.find("#domainid").text(fromdb(jsonObj.domainid));
	$thisTab.find("#account").text(fromdb(jsonObj.account));

    $thisTab.find("#tab_container").show();
    $thisTab.find("#tab_spinning_wheel").hide();
}

function publicNetworkJsonToIpAllocationTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #public_network_page #tab_content_ipallocation");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

    $.ajax({
		data: createURL("command=listVlanIpRanges&zoneid="+ jsonObj.zoneid), //don't need networkid because one zone has only one public network
		dataType: "json",
		success: function(json) {
		    var items = json.listvlaniprangesresponse.vlaniprange;
		    var $container = $thisTab.find("#tab_container").empty();
		    var $template = $("#directnetwork_iprange_template");
		    if(items != null && items.length > 0) {
		        for(var i=0; i<items.length; i++) {
		            var $newTemplate = $template.clone();
		            publicNetworkIprangeJsonToTemplate(items[i], $newTemplate);
		            $container.append($newTemplate.show());
		        }
		    }
		    $thisTab.find("#tab_container").show();
            $thisTab.find("#tab_spinning_wheel").hide();
		}
    });
}

function publicNetworkIprangeJsonToTemplate(jsonObj, $template) {
    $template.attr("id", "publicNetworkIprange_" + jsonObj.id);

    var ipRange = getIpRange(fromdb(jsonObj.startip), fromdb(jsonObj.endip));
    $template.find("#grid_header_title").text(ipRange);

    $template.find("#vlan").text(jsonObj.vlan)
    $template.find("#startip").text(fromdb(jsonObj.startip));
    $template.find("#endip").text(fromdb(jsonObj.endip));
}

function publicNetworkJsonToFirewallTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #public_network_page #tab_content_firewall");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

    $thisTab.find("#tab_container").show();
    $thisTab.find("#tab_spinning_wheel").hide();
}

function publicNetworkJsonToLoadBalancerTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #public_network_page #tab_content_loadbalancer");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

    $thisTab.find("#tab_container").show();
    $thisTab.find("#tab_spinning_wheel").hide();
}
//***** Public Network (end) ******************************************************************************************************

//***** Direct Network (begin) ******************************************************************************************************
function directNetworkGetMidmenuId(jsonObj) {
    return "midmenuItem_directnetework_" + jsonObj.id;
}

function directNetworkToMidmenu(jsonObj, $midmenuItem1) {
    $midmenuItem1.attr("id", directNetworkGetMidmenuId(jsonObj));
    $midmenuItem1.data("jsonObj", jsonObj);

    /*
    var $iconContainer = $midmenuItem1.find("#icon_container").show();
    $iconContainer.find("#icon").attr("src", "images/midmenuicon_storage_snapshots.png");
    */

    $midmenuItem1.find("#first_row").text(fromdb(jsonObj.name).substring(0,25));
    $midmenuItem1.find("#second_row").text("VLAN ID: " + fromdb(jsonObj.vlan));
}

function directNetworkToRightPanel($midmenuItem1) {
    copyActionInfoFromMidMenuToRightPanel($midmenuItem1);
    $("#right_panel_content").data("$midmenuItem1", $midmenuItem1);

    $("#direct_network_page").show();
    $("#public_network_page").hide();

    $("#direct_network_page").find("#tab_details").click();
}

function directNetworkJsonToDetailsTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #direct_network_page #tab_content_details");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

	$thisTab.find("#grid_header_title").text(fromdb(jsonObj.name));

	$thisTab.find("#id").text(fromdb(jsonObj.id));
	$thisTab.find("#name").text(fromdb(jsonObj.name));
	$thisTab.find("#displaytext").text(fromdb(jsonObj.displaytext));

    $thisTab.find("#vlan").text(fromdb(jsonObj.vlan));
    $thisTab.find("#gateway").text(fromdb(jsonObj.gateway));
    $thisTab.find("#netmask").text(fromdb(jsonObj.netmask));
    var ipRange = getIpRange(fromdb(jsonObj.startip), fromdb(jsonObj.endip));
    $thisTab.find("#iprange").text(ipRange);

    $thisTab.find("#domain").text(fromdb(jsonObj.domain));      //might be null
    $thisTab.find("#account").text(fromdb(jsonObj.account));    //might be null

    $thisTab.find("#tab_container").show();
    $thisTab.find("#tab_spinning_wheel").hide();
}

function directNetworkJsonToIpAllocationTab() {
    var $midmenuItem1 = $("#right_panel_content").data("$midmenuItem1");
    if($midmenuItem1 == null)
        return;

    var jsonObj = $midmenuItem1.data("jsonObj");
    if(jsonObj == null)
	    return;

	var $thisTab = $("#right_panel_content #direct_network_page #tab_content_ipallocation");
    $thisTab.find("#tab_container").hide();
    $thisTab.find("#tab_spinning_wheel").show();

    $.ajax({
		data: createURL("command=listVlanIpRanges&zoneid="+ jsonObj.zoneid + "&networkid="+jsonObj.id),
		dataType: "json",
		success: function(json) {
		    var items = json.listvlaniprangesresponse.vlaniprange;
		    var $container = $thisTab.find("#tab_container").empty();
		    var $template = $("#directnetwork_iprange_template");
		    if(items != null && items.length > 0) {
		        for(var i=0; i<items.length; i++) {
		            var $newTemplate = $template.clone();
		            directNetworkIprangeJsonToTemplate(items[i], $newTemplate);
		            $container.append($newTemplate.show());
		        }
		    }
		    $thisTab.find("#tab_container").show();
            $thisTab.find("#tab_spinning_wheel").hide();
		}
    });
}

function directNetworkIprangeJsonToTemplate(jsonObj, $template) {
    $template.attr("id", "directNetworkIprange_" + jsonObj.id);

    var ipRange = getIpRange(fromdb(jsonObj.startip), fromdb(jsonObj.endip));
    $template.find("#grid_header_title").text(ipRange);

    $template.find("#vlan").text(jsonObj.vlan)
    $template.find("#startip").text(fromdb(jsonObj.startip));
    $template.find("#endip").text(fromdb(jsonObj.endip));
}
//***** Direct Network (end) ******************************************************************************************************

<|endoftext|>


<commit_before>elation.require(['janusweb.janusbase'], function() {
  elation.component.add('engine.things.januslight', function() {
    this.postinit = function() {
      elation.engine.things.januslight.extendclass.postinit.call(this);
      this.defineProperties({
        light_directional: { type: 'bool', default: false, set: this.updateLight },
        light_range: { type: 'float', default: 10, set: this.updateLight },
        light_intensity: { type: 'float', default: 10, set: this.updateLight },
        light_cone_angle: { type: 'float', default: 0, set: this.updateLight },
        light_cone_exponent: { type: 'float', default: 1, set: this.updateLight },
        light_penumbra: { type: 'float', default: 1, set: this.updateLight },
        light_decay: { type: 'float', default: 1, set: this.updateLight },
        light_target: { type: 'object', set: this.updateLightTarget },
        light_shadow: { type: 'boolean', default: false, set: this.updateLight },
        light_shadow_near: { type: 'float', default: .1, set: this.updateLight },
        light_shadow_far: { type: 'float', set: this.updateLight },
        light_shadow_bias: { type: 'float', default: .0001, set: this.updateLight },
        light_shadow_radius: { type: 'float', default: 2.5, set: this.updateLight },
        light_helper: { type: 'boolean', default: false, set: this.updateLightHelper },
        collision_id: { type: 'string', default: 'sphere', set: this.updateCollider },
        collision_trigger: { type: 'boolean', default: true, set: this.updateCollider },
      });
    }
    this.createObject3D = function() {
      var obj = new THREE.Object3D();
      return obj;
    }
    this.updateColor = function() {
      this.updateLight();
    }
    this.createChildren = function() {
      elation.engine.things.januslight.extendclass.createChildren.call(this);

      this.createLight();
      this.updateLight();
      this.created = true;

      var scene = this.objects['3d'];
      while (scene.parent) {
        scene = scene.parent;
      }

      if (this.light_cone_angle == 0) {
        this.helper = new THREE.PointLightHelper(this.light);
      } else if (this.light_cone_angle == 1) {
        this.helper = new THREE.DirectionalLightHelper(this.light);
      } else {
        this.helper = new THREE.SpotLightHelper(this.light);
      }
      if (this.helper) {
        this.helper.traverse((n) => {
          n.layers.set(10);
        });
        scene.add(this.helper);
      }
      let placeholdergeo = this.getPlaceholderGeometry();
      if (placeholdergeo) {
        let placeholder = new THREE.Mesh(placeholdergeo, new THREE.MeshPhongMaterial({color: 0x666666, emissive: 0x333333, opacity: .8, transparent: true}));
        placeholder.layers.set(10);

        let collider = placeholder.clone();
        placeholder.userData.thing = this;
        collider.userData.thing = this;

        this.objects['3d'].add(placeholder);
        this.colliders.add(collider);
        this.placeholder = placeholder;
      }
    }
    this.getPlaceholderGeometry = function() {
      let placeholdergeo = null;
      if (this.light_cone_angle == 0) {
        placeholdergeo = new THREE.SphereBufferGeometry(.1);
      } else if (this.light_cone_angle == 1) {
        placeholdergeo = new THREE.SphereBufferGeometry(.1);
      } else {
        let angle = Math.acos(this.light_cone_angle),
            height = this.light_shadow_near,
            radius = Math.tan(angle) * height;
        placeholdergeo = new THREE.ConeBufferGeometry(radius, height);
        placeholdergeo.applyMatrix(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(-Math.PI/2, 0, 0)).setPosition(0, 0, height / 2));
      }
      return placeholdergeo;
    }
    this.update = function() {
      if (!this.light) {
        this.createLight();
        this.updateLight();
      }
      if (this.light && !this.light.parent) {
        this.objects['3d'].add(this.light);
      }
      if (this.helper) {
        this.helper.update();
      }
      if (this.light_directional || this.light_cone_angle == 1) {
        this.light.position.subVectors(this.light.position, this.light.target.position).add(player.pos);
        this.light.target.position.copy(player.pos);
      }
    }
    this.createLight = function() {
      if (!this.light) {
        if (this.light_directional || this.light_cone_angle == 1) {
          this.light = new THREE.DirectionalLight(this.properties.color, this.light_intensity);
          this.updateLightTarget();
        } else if (this.light_cone_angle == 0) {
          this.light = new THREE.PointLight(this.properties.color, 1, this.light_range);
          this.light.position.set(0,0,0);
        } else if (this.light_cone_angle > 0) {
          var angle = Math.acos(this.light_cone_angle);
          this.light = new THREE.SpotLight(this.properties.color, 1, this.light_range, angle, this.light_penumbra, this.light_decay);
          this.light.position.set(0,0,0);

          this.updateLightTarget();
        }
      }
    }
    this.updateLight = function() {
      if (this.light) {
        if (this.light.parent !== this.objects['3d']) {
          this.objects['3d'].add(this.light);
        }
        //this.light.intensity = this.light_intensity / 100;
        var avgscale = (this.scale.x + this.scale.y + this.scale.z) / 3;
        this.light.intensity = this.light_intensity / 100;
        this.light.penumbra = this.light_penumbra;
        this.light.decay = this.light_decay;
        this.light.color.copy(this.color);
        this.light.color.multiplyScalar(this.light_intensity * avgscale * avgscale);
        this.light.distance = this.light_range * avgscale;
        if (this.light_cone_angle > 0 && this.light_cone_angle < 1) {
          this.light.angle = Math.acos(this.light_cone_angle);
          if (this.placeholder) {
            this.placeholder.geometry = this.getPlaceholderGeometry();
          }
        }
        this.updateShadowmap();
      }
    }
    this.updateLightTarget = function() {
      if (!this.light) return;

      if (this.light_target) {
        if (elation.utils.isString(this.light_target)) {
          if (room.objects[this.light_target]) {
            let obj = room.objects[this.light_target];
            this.light.target = obj.objects['3d'];
          } else if (this.light_target == 'player') {
            this.light.target = player.objects['3d'];
          }
        } else if (this.light_target.objects && this.light_target.objects['3d']) {
          this.light.target = this.light_target.objects['3d'];
        } else if (this.light_target instanceof THREE.Object3D) {
          this.light.target = this.light_target;
        }
      }

      // If no target was specified, we're using the default, so make sure it's set up right
      var target = this.light.target;
      if (!target.parent) {
        this.objects['3d'].add(target);
        target.position.set(0,0,1);
      }
    }
    this.updateShadowmap = function() {
      var player = this.engine.client.player;
      var shadowSize = player.getSetting('render.shadows.size', elation.config.get('janusweb.materials.shadows.size', 512));

      this.light.castShadow = this.light_shadow;
      this.light.shadow.radius = this.light_shadow_radius;
      this.light.shadow.camera.near = elation.utils.any(this.light_shadow_near, 0.1);
      this.light.shadow.camera.far = elation.utils.any(this.light_shadow_far, this.light_range);
      this.light.shadow.camera.fov = 90;
      this.light.shadow.mapSize.set(shadowSize, shadowSize);
      this.light.shadow.bias = this.light_shadow_bias;

      // directional light shadow parameters
      let d = this.light_range;
      this.light.shadow.camera.left = -d;
      this.light.shadow.camera.right = d;
      this.light.shadow.camera.top = d;
      this.light.shadow.camera.bottom = -d;
    }
    this.getProxyObject = function(classdef) {
      if (!this._proxyobject) {
        this._proxyobject = elation.engine.things.janusobject.extendclass.getProxyObject.call(this, classdef);
        this._proxyobject._proxydefs = {
          light_range:         [ 'property', 'light_range'],
          light_intensity:     [ 'property', 'light_intensity'],
          light_cone_angle:    [ 'property', 'light_cone_angle'],
          light_cone_exponent: [ 'property', 'light_cone_exponent'],
          light_penumbra:      [ 'property', 'light_penumbra'],
          light_decay:         [ 'property', 'light_decay'],
          light_target:        [ 'property', 'light_target'],
          light_shadow:        [ 'property', 'light_shadow'],
          light_shadow_near:   [ 'property', 'light_shadow_near'],
          light_shadow_far:    [ 'property', 'light_shadow_far'],
          light_shadow_bias:   [ 'property', 'light_shadow_bias'],
          light_shadow_radius: [ 'property', 'light_shadow_radius'],
        };
      }
      return this._proxyobject;
    }
  }, elation.engine.things.janusbase);
});
<commit_msg>Added attribute comments<commit_after>elation.require(['janusweb.janusbase'], function() {
  elation.component.add('engine.things.januslight', function() {
    this.postinit = function() {
      elation.engine.things.januslight.extendclass.postinit.call(this);
      this.defineProperties({
        light_directional: { type: 'bool', default: false, set: this.updateLight },
        light_range: { type: 'float', default: 0, set: this.updateLight, min: 0, comment: 'Max distance at which light can affect objects' },
        light_intensity: { type: 'float', default: 10, set: this.updateLight, comment: 'Light brightness' },
        light_cone_angle: { type: 'float', default: 0, set: this.updateLight, min: 0, max: 1, comment: 'Light cone shape. 0 = directional, 1 = point light, anything inbetween is a spotlight' },
        light_cone_exponent: { type: 'float', default: 1, set: this.updateLight },
        light_penumbra: { type: 'float', default: 1, set: this.updateLight, min: 0, max: 1, comment: 'Spotlight fall-off. 0 is crisp, 1 is smooth' },
        light_decay: { type: 'float', default: 2, set: this.updateLight, comment: 'The amount the light dims along the distance of the light. Default is 1. For physically correct lighting, set this to 2.' },
        light_target: { type: 'object', set: this.updateLightTarget },
        light_shadow: { type: 'boolean', default: false, set: this.updateLight, comment: 'Light casts shadows on scene' },
        light_shadow_near: { type: 'float', default: .1, set: this.updateLight },
        light_shadow_far: { type: 'float', set: this.updateLight },
        light_shadow_bias: { type: 'float', default: .0001, set: this.updateLight },
        light_shadow_radius: { type: 'float', default: 2.5, set: this.updateLight },
        light_helper: { type: 'boolean', default: false, set: this.updateLightHelper },
        collision_id: { type: 'string', default: 'sphere', set: this.updateCollider },
        collision_trigger: { type: 'boolean', default: true, set: this.updateCollider },
      });
    }
    this.createObject3D = function() {
      var obj = new THREE.Object3D();
      return obj;
    }
    this.updateColor = function() {
      this.updateLight();
    }
    this.createChildren = function() {
      elation.engine.things.januslight.extendclass.createChildren.call(this);

      this.createLight();
      this.updateLight();
      this.created = true;

      var scene = this.objects['3d'];
      while (scene.parent) {
        scene = scene.parent;
      }

      if (this.light_cone_angle == 0) {
        this.helper = new THREE.PointLightHelper(this.light);
      } else if (this.light_cone_angle == 1) {
        this.helper = new THREE.DirectionalLightHelper(this.light);
      } else {
        this.helper = new THREE.SpotLightHelper(this.light);
      }
      if (this.helper) {
        this.helper.traverse((n) => {
          n.layers.set(10);
        });
        scene.add(this.helper);
      }
      let placeholdergeo = this.getPlaceholderGeometry();
      if (placeholdergeo) {
        let placeholder = new THREE.Mesh(placeholdergeo, new THREE.MeshPhongMaterial({color: 0x666666, emissive: 0x333333, opacity: .8, transparent: true}));
        placeholder.layers.set(10);

        let collider = placeholder.clone();
        placeholder.userData.thing = this;
        collider.userData.thing = this;

        this.objects['3d'].add(placeholder);
        this.colliders.add(collider);
        this.placeholder = placeholder;
      }
    }
    this.getPlaceholderGeometry = function() {
      let placeholdergeo = null;
      if (this.light_cone_angle == 0) {
        placeholdergeo = new THREE.SphereBufferGeometry(.1);
      } else if (this.light_cone_angle == 1) {
        placeholdergeo = new THREE.SphereBufferGeometry(.1);
      } else {
        let angle = Math.acos(this.light_cone_angle),
            height = this.light_shadow_near,
            radius = Math.tan(angle) * height;
        placeholdergeo = new THREE.ConeBufferGeometry(radius, height);
        placeholdergeo.applyMatrix(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(-Math.PI/2, 0, 0)).setPosition(0, 0, height / 2));
      }
      return placeholdergeo;
    }
    this.update = function() {
      if (!this.light) {
        this.createLight();
        this.updateLight();
      }
      if (this.light && !this.light.parent) {
        this.objects['3d'].add(this.light);
      }
      if (this.helper) {
        this.helper.update();
      }
      if (this.light_directional || this.light_cone_angle == 1) {
        this.light.position.subVectors(this.light.position, this.light.target.position).add(player.pos);
        this.light.target.position.copy(player.pos);
      }
    }
    this.createLight = function() {
      if (!this.light) {
        if (this.light_directional || this.light_cone_angle == 1) {
          this.light = new THREE.DirectionalLight(this.properties.color, this.light_intensity);
          this.updateLightTarget();
        } else if (this.light_cone_angle == 0) {
          this.light = new THREE.PointLight(this.properties.color, 1, this.light_range);
          this.light.position.set(0,0,0);
        } else if (this.light_cone_angle > 0) {
          var angle = Math.acos(this.light_cone_angle);
          this.light = new THREE.SpotLight(this.properties.color, 1, this.light_range, angle, this.light_penumbra, this.light_decay);
          this.light.position.set(0,0,0);

          this.updateLightTarget();
        }
      }
    }
    this.updateLight = function() {
      if (this.light) {
        if (this.light.parent !== this.objects['3d']) {
          this.objects['3d'].add(this.light);
        }
        //this.light.intensity = this.light_intensity / 100;
        var avgscale = (this.scale.x + this.scale.y + this.scale.z) / 3;
        this.light.intensity = this.light_intensity / 100;
        this.light.penumbra = this.light_penumbra;
        this.light.decay = this.light_decay;
        this.light.color.copy(this.color);
        this.light.color.multiplyScalar(this.light_intensity * avgscale * avgscale);
        this.light.distance = this.light_range * avgscale;
        if (this.light_cone_angle > 0 && this.light_cone_angle < 1) {
          this.light.angle = Math.acos(this.light_cone_angle);
          if (this.placeholder) {
            this.placeholder.geometry = this.getPlaceholderGeometry();
          }
        }
        this.updateShadowmap();
      }
    }
    this.updateLightTarget = function() {
      if (!this.light) return;

      if (this.light_target) {
        if (elation.utils.isString(this.light_target)) {
          if (room.objects[this.light_target]) {
            let obj = room.objects[this.light_target];
            this.light.target = obj.objects['3d'];
          } else if (this.light_target == 'player') {
            this.light.target = player.objects['3d'];
          }
        } else if (this.light_target.objects && this.light_target.objects['3d']) {
          this.light.target = this.light_target.objects['3d'];
        } else if (this.light_target instanceof THREE.Object3D) {
          this.light.target = this.light_target;
        }
      }

      // If no target was specified, we're using the default, so make sure it's set up right
      var target = this.light.target;
      if (!target.parent) {
        this.objects['3d'].add(target);
        target.position.set(0,0,1);
      }
    }
    this.updateShadowmap = function() {
      var player = this.engine.client.player;
      var shadowSize = player.getSetting('render.shadows.size', elation.config.get('janusweb.materials.shadows.size', 512));

      this.light.castShadow = this.light_shadow;
      this.light.shadow.radius = this.light_shadow_radius;
      this.light.shadow.camera.near = elation.utils.any(this.light_shadow_near, 0.1);
      this.light.shadow.camera.far = elation.utils.any(this.light_shadow_far, this.light_range);
      this.light.shadow.camera.fov = 90;
      this.light.shadow.mapSize.set(shadowSize, shadowSize);
      this.light.shadow.bias = this.light_shadow_bias;

      // directional light shadow parameters
      let d = this.light_range;
      this.light.shadow.camera.left = -d;
      this.light.shadow.camera.right = d;
      this.light.shadow.camera.top = d;
      this.light.shadow.camera.bottom = -d;
    }
    this.getProxyObject = function(classdef) {
      if (!this._proxyobject) {
        this._proxyobject = elation.engine.things.janusobject.extendclass.getProxyObject.call(this, classdef);
        this._proxyobject._proxydefs = {
          light_range:         [ 'property', 'light_range'],
          light_intensity:     [ 'property', 'light_intensity'],
          light_cone_angle:    [ 'property', 'light_cone_angle'],
          light_cone_exponent: [ 'property', 'light_cone_exponent'],
          light_penumbra:      [ 'property', 'light_penumbra'],
          light_decay:         [ 'property', 'light_decay'],
          light_target:        [ 'property', 'light_target'],
          light_shadow:        [ 'property', 'light_shadow'],
          light_shadow_near:   [ 'property', 'light_shadow_near'],
          light_shadow_far:    [ 'property', 'light_shadow_far'],
          light_shadow_bias:   [ 'property', 'light_shadow_bias'],
          light_shadow_radius: [ 'property', 'light_shadow_radius'],
        };
      }
      return this._proxyobject;
    }
  }, elation.engine.things.janusbase);
});
<|endoftext|>


<commit_before>/* Hides 'my-profile-box by default */

console.log("saldjflsdjfklsjdlf");

/* This is the angular for the main window */
function () {
  angular.module('MainWindow',[]).controller('MainCtrl',function($scope) {
    /* EDIT THE FOLLOWING FOR REAL DATA */

    console.log("b");

    /* The defaults for the home page.
     * The only thing that should show is the sidebar and the fb login.
     */
    $scope.user = false;
    $scope.friend = false;
    $scope.search = false;
    $scope.map = false;

    console.log($scope.user);
    console.log($scope.user);
    console.log($scope.user);
    console.log($scope.user);
    console.log($scope.user);

  });
}();
<commit_msg>please work<commit_after>/* Hides 'my-profile-box by default */

console.log("saldjflsdjfklsjdlf");

/* This is the angular for the main window */
angular.module('MainWindow',[]).controller('MainCtrl',function($scope) {
  /* EDIT THE FOLLOWING FOR REAL DATA */

  console.log("b");

  /* The defaults for the home page.
   * The only thing that should show is the sidebar and the fb login.
   */
  $scope.user = false;
  $scope.friend = false;
  $scope.search = false;
  $scope.map = false;

  console.log($scope.user);
  console.log($scope.user);
  console.log($scope.user);
  console.log($scope.user);
  console.log($scope.user);

});
<|endoftext|>


<commit_before>/**
 * Handles validation on a model
 *
 * Uses Anchor for validating
 * https://github.com/balderdashy/anchor
 */

var _ = require('lodash');
var anchor = require('anchor');
var async = require('async');
var utils = require('../utils/helpers');
var hasOwnProperty = utils.object.hasOwnProperty;
var WLValidationError = require('../error/WLValidationError');

/**
 * Build up validations using the Anchor module.
 *
 * @param {String} adapter
 */

var Validator = module.exports = function(adapter) {
  this.validations = {};
};

/**
 * Builds a Validation Object from a normalized attributes
 * object.
 *
 * Loops through an attributes object to build a validation object
 * containing attribute name as key and a series of validations that
 * are run on each model. Skips over type and defaultsTo as they are
 * schema properties.
 *
 * Example:
 *
 * attributes: {
 *   name: {
 *     type: 'string',
 *     length: { min: 2, max: 5 }
 *   }
 *   email: {
 *     type: 'string',
 *     required: true
 *   }
 * }
 *
 * Returns: {
 *   name: { length: { min:2, max: 5 }},
 *   email: { required: true }
 * }
 */

Validator.prototype.initialize = function(attrs, types, defaults) {
  var self = this;

  defaults = defaults || {};

  this.reservedProperties = ['defaultsTo', 'primaryKey', 'autoIncrement', 'unique', 'index', 'collection', 'dominant', 'through',
          'columnName', 'foreignKey', 'references', 'on', 'groupKey', 'model', 'via', 'size',
          'example', 'validationMessage', 'validations', 'populateSettings', 'onKey', 'protected'];

  if(defaults.ignoreProperties && Array.isArray(defaults.ignoreProperties)) {
    this.reservedProperties = this.reservedProperties.concat(defaults.ignoreProperties);
  }

  // add custom type definitions to anchor
  types = types || {};
  anchor.define(types);

  Object.keys(attrs).forEach(function(attr) {
    self.validations[attr] = {};

    Object.keys(attrs[attr]).forEach(function(prop) {

      // Ignore null values
      if(attrs[attr][prop] === null) return;

      // If property is reserved don't do anything with it
      if(self.reservedProperties.indexOf(prop) > -1) return;

      // use the Anchor `in` method for enums
      if(prop === 'enum') {
        self.validations[attr]['in'] = attrs[attr][prop];
        return;
      }

      self.validations[attr][prop] = attrs[attr][prop];
    });
  });
};

/**
 * Validate
 *
 * Accepts an object of values and runs them through the
 * schema's validations using Anchor.
 *
 * @param {Object} values to check
 * @param {Boolean} presentOnly only validate present values
 * @param {Function} callback
 * @return Array of errors
 */

Validator.prototype.validate = function(values, presentOnly, cb) {
  var self = this,
      errors = {},
      validations = Object.keys(this.validations);

  // Handle optional second arg
  if(typeof presentOnly === 'function') {
    cb = presentOnly;
  }
  // Use present values only or all validations
  else if(presentOnly) {
    validations = _.intersection(validations, Object.keys(values));
  }

  function validate(validation, cb) {
    var curValidation = self.validations[validation];

    // Build Requirements
    var requirements = _.cloneDeep(anchor(curValidation));

    // Grab value and set to null if undefined
    var value = values[validation];
    if(typeof value == 'undefined') value = null;

    // If value is not required and empty then don't
    // try and validate it
    if(!curValidation.required) {
      if(value === null || value === '') return cb();
    }

    // if required is set to 'false', don't enforce as required rule
    if (curValidation.hasOwnProperty('required')&&!curValidation.required) {
        return cb();
    }

    // If Boolean and required manually check
    if(curValidation.required && curValidation.type === 'boolean' && (typeof value !== 'undefined' && value !== null)) {
      if(value.toString() == 'true' || value.toString() == 'false') return cb();
    }

    // If type is integer and the value matches a mongoID let it validate
    if(hasOwnProperty(self.validations[validation], 'type') && self.validations[validation].type === 'integer') {
      if(utils.matchMongoId(value)) return cb();
    }

    // Rule values may be specified as sync or async functions.
    // Call them and replace the rule value with the function's result
    // before running validations.
    async.each( Object.keys(requirements.data), function (key, cb) {
      if (typeof requirements.data[key] !== 'function') return cb();

      // Run synchronous function
      if (requirements.data[key].length < 1) {
        requirements.data[key] = requirements.data[key].apply(values, []);
        return cb();
      }

      // Run async function
      requirements.data[key].call(values, function (result) {
        requirements.data[key] = result;
        cb();
      });
    }, function() {

      // If the value has a dynamic required function and it evaluates to false lets look and see
      // if the value supplied is null or undefined. If so then we don't need to check anything. This
      // prevents type errors like `undefined` should be a string.
      // if required is set to 'false', don't enforce as required rule
      if (requirements.data.hasOwnProperty('required') && !requirements.data.required) {
        if(value === null) return cb();
      }

      // Validate with Anchor
      var err = anchor(value).to(requirements.data, values);

      // If No Error return
      if(!err) return cb();

      // Build an Error Object
      errors[validation] = [];

      err.forEach(function(obj) {
        if(obj.property) delete obj.property;
        errors[validation].push({ rule: obj.rule, message: obj.message });
      });

      return cb();
    });

  }

  // Validate all validations in parallel
  async.each(validations, validate, function allValidationsChecked () {
    if(Object.keys(errors).length === 0) return cb();

    cb(errors);
  });

};
<commit_msg>#867: fixes `required: false` prevents all other validators from running<commit_after>/**
 * Handles validation on a model
 *
 * Uses Anchor for validating
 * https://github.com/balderdashy/anchor
 */

var _ = require('lodash');
var anchor = require('anchor');
var async = require('async');
var utils = require('../utils/helpers');
var hasOwnProperty = utils.object.hasOwnProperty;
var WLValidationError = require('../error/WLValidationError');

/**
 * Build up validations using the Anchor module.
 *
 * @param {String} adapter
 */

var Validator = module.exports = function(adapter) {
  this.validations = {};
};

/**
 * Builds a Validation Object from a normalized attributes
 * object.
 *
 * Loops through an attributes object to build a validation object
 * containing attribute name as key and a series of validations that
 * are run on each model. Skips over type and defaultsTo as they are
 * schema properties.
 *
 * Example:
 *
 * attributes: {
 *   name: {
 *     type: 'string',
 *     length: { min: 2, max: 5 }
 *   }
 *   email: {
 *     type: 'string',
 *     required: true
 *   }
 * }
 *
 * Returns: {
 *   name: { length: { min:2, max: 5 }},
 *   email: { required: true }
 * }
 */

Validator.prototype.initialize = function(attrs, types, defaults) {
  var self = this;

  defaults = defaults || {};

  this.reservedProperties = ['defaultsTo', 'primaryKey', 'autoIncrement', 'unique', 'index', 'collection', 'dominant', 'through',
          'columnName', 'foreignKey', 'references', 'on', 'groupKey', 'model', 'via', 'size',
          'example', 'validationMessage', 'validations', 'populateSettings', 'onKey', 'protected'];

  if(defaults.ignoreProperties && Array.isArray(defaults.ignoreProperties)) {
    this.reservedProperties = this.reservedProperties.concat(defaults.ignoreProperties);
  }

  // add custom type definitions to anchor
  types = types || {};
  anchor.define(types);

  Object.keys(attrs).forEach(function(attr) {
    self.validations[attr] = {};

    Object.keys(attrs[attr]).forEach(function(prop) {

      // Ignore null values
      if(attrs[attr][prop] === null) return;

      // If property is reserved don't do anything with it
      if(self.reservedProperties.indexOf(prop) > -1) return;

      // use the Anchor `in` method for enums
      if(prop === 'enum') {
        self.validations[attr]['in'] = attrs[attr][prop];
        return;
      }

      self.validations[attr][prop] = attrs[attr][prop];
    });
  });
};

/**
 * Validate
 *
 * Accepts an object of values and runs them through the
 * schema's validations using Anchor.
 *
 * @param {Object} values to check
 * @param {Boolean} presentOnly only validate present values
 * @param {Function} callback
 * @return Array of errors
 */

Validator.prototype.validate = function(values, presentOnly, cb) {
  var self = this,
      errors = {},
      validations = Object.keys(this.validations);

  // Handle optional second arg
  if(typeof presentOnly === 'function') {
    cb = presentOnly;
  }
  // Use present values only or all validations
  else if(presentOnly) {
    validations = _.intersection(validations, Object.keys(values));
  }

  function validate(validation, cb) {
    var curValidation = self.validations[validation];

    // Build Requirements
    var requirements = _.cloneDeep(anchor(curValidation));

    // Grab value and set to null if undefined
    var value = values[validation];
    if(typeof value == 'undefined') value = null;

    // If value is not required and empty then don't
    // try and validate it
    if(!curValidation.required) {
      if(value === null || value === '') return cb();
    }

    // If Boolean and required manually check
    if(curValidation.required && curValidation.type === 'boolean' && (typeof value !== 'undefined' && value !== null)) {
      if(value.toString() == 'true' || value.toString() == 'false') return cb();
    }

    // If type is integer and the value matches a mongoID let it validate
    if(hasOwnProperty(self.validations[validation], 'type') && self.validations[validation].type === 'integer') {
      if(utils.matchMongoId(value)) return cb();
    }

    // Rule values may be specified as sync or async functions.
    // Call them and replace the rule value with the function's result
    // before running validations.
    async.each( Object.keys(requirements.data), function (key, cb) {
      if (typeof requirements.data[key] !== 'function') return cb();

      // Run synchronous function
      if (requirements.data[key].length < 1) {
        requirements.data[key] = requirements.data[key].apply(values, []);
        return cb();
      }

      // Run async function
      requirements.data[key].call(values, function (result) {
        requirements.data[key] = result;
        cb();
      });
    }, function() {

      // If the value has a dynamic required function and it evaluates to false lets look and see
      // if the value supplied is null or undefined. If so then we don't need to check anything. This
      // prevents type errors like `undefined` should be a string.
      // if required is set to 'false', don't enforce as required rule
      if (requirements.data.hasOwnProperty('required') && !requirements.data.required) {
        if(value === null) return cb();
      }

      // Validate with Anchor
      var err = anchor(value).to(requirements.data, values);

      // If No Error return
      if(!err) return cb();

      // Build an Error Object
      errors[validation] = [];

      err.forEach(function(obj) {
        if(obj.property) delete obj.property;
        errors[validation].push({ rule: obj.rule, message: obj.message });
      });

      return cb();
    });

  }

  // Validate all validations in parallel
  async.each(validations, validate, function allValidationsChecked () {
    if(Object.keys(errors).length === 0) return cb();

    cb(errors);
  });

};
<|endoftext|>


<commit_before>var Crypto = require('crypto');
var semver = require('semver');

var Datasource = require('./datasource');

// Map configuration object

/// API: Create MapConfig from configuration object
//
/// @param obj js MapConfiguration object, see
///        http://github.com/CartoDB/Windshaft/wiki/MapConfig-specification
///
function MapConfig(config, datasource) {
    // TODO: inject defaults ?
    this._cfg = config;

    if ( ! semver.satisfies(this.version(), '>= 1.0.0 <= 1.5.0') ) {
        throw new Error("Unsupported layergroup configuration version " + this.version());
    }

    if ( ! this._cfg.hasOwnProperty('layers') ) {
        throw new Error("Missing layers array from layergroup config");
    }

    this._cfg.layers.forEach(function(layer, i) {
    if ( ! layer.hasOwnProperty('options') ) {
        throw new Error("Missing options from layer " + i + " of layergroup config");
    }
    // NOTE: interactivity used to be a string as of version 1.0.0
    if ( Array.isArray(layer.options.interactivity) ) {
        layer.options.interactivity = layer.options.interactivity.join(',');
    }
  });

    /**
    * @type {Datasource}
    */
    this._datasource = datasource;

    this._id = null;
}

function md5Hash(s) {
    return Crypto.createHash('md5').update(s).digest('hex');
}

/// API: Get serialized version of this MapConfig
MapConfig.prototype.serialize = function() {
    if (this._datasource.isEmpty()) {
        return JSON.stringify(this._cfg);
    }
    return JSON.stringify({
        cfg: this._cfg,
        ds: this._datasource.obj()
    });
};

/// API: Get identifier for this MapConfig
MapConfig.prototype.id = function() {
    if (this._id === null) {
        this._id = md5Hash(JSON.stringify(this._cfg));
    }
    //debug('MapConfig.id=%s', this._id);
    return this._id;
};

/// API: Get configuration object of this MapConfig
MapConfig.prototype.obj = function() {
    return this._cfg;
};

MapConfig.prototype.version = function() {
    return this._cfg.version || '1.0.0';
};

MapConfig.prototype.setDbParams = function(dbParams) {
    this._cfg.dbparams = dbParams;
    this.flush();
};

MapConfig.prototype.flush = function() {
    // flush id so it gets recalculated
    this._id = null;
};

/// API: Get type string of given layer
//
/// @param num layer index (0-based)
/// @returns a type string, as read from the layer
///
MapConfig.prototype.layerType = function(num) {
    var lyr = this.getLayer(num);
    if ( ! lyr ) {
        return undefined;
    }
    return this.getType(lyr.type);
};

MapConfig.prototype.getType = function(type) {
    return getType(type);
};

function getType(type) {
    // TODO: check validity of other types ?
    return (!type || type === 'cartodb') ? 'mapnik' : type;
}

/*****************************************************************************
 * Layers
 ****************************************************************************/

MapConfig.prototype.getLayerId = function(layerIndex) {
    return getLayerId(this._cfg, layerIndex);
};

function getLayerId(rawMapConfig, layerIndex) {
    var layer = rawMapConfig.layers[layerIndex];
    if (layer.id) {
        return layer.id;
    }

    var layerType = getType(layer.type);
    var layerId = 'layer' + getLayerIndexByType(rawMapConfig, layerType, layerIndex);
    if (layerType !== 'mapnik') {
        layerId = layerType + '-' + layerId;
    }
    return layerId;
}

MapConfig.prototype.getIndexByLayerId = function (layerId) {
    var layers = this.getLayers();

    for (var i = 0; i < layers.length; i++) {
        if (layers[i].id === layerId) {
            return i;
        }
    }

    return -1;
};

/// API: Get layer by index
//
/// @returns undefined on invalid index
///
MapConfig.prototype.getLayer = function(layerIndex) {
    return this._cfg.layers[layerIndex];
};

MapConfig.prototype.getLayers = function() {
    return this._cfg.layers.map(function(_layer, layerIndex) {
        return this.getLayer(layerIndex);
    }.bind(this));
};

MapConfig.prototype.getLayerIndexByType = function(type, mapConfigLayerIdx) {
    return getLayerIndexByType(this._cfg, type, mapConfigLayerIdx);
};

function getLayerIndexByType(rawMapConfig, type, mapConfigLayerIdx) {
    var typeLayerIndex = 0;
    var mapConfigToTypeLayers = {};

    rawMapConfig.layers.forEach(function (layer, layerIdx) {
        if (getType(layer.type) === type) {
            mapConfigToTypeLayers[layerIdx] = typeLayerIndex++;
        }
    });

    return mapConfigToTypeLayers[mapConfigLayerIdx];
}

MapConfig.prototype.getLayerOption = function(layerIndex, optionName, defaultValue) {
    var layerOption = defaultValue;
    var layer = this.getLayer(layerIndex);
    if (layer && layer.options.hasOwnProperty(optionName)) {
        layerOption = layer.options[optionName];
    }
    return layerOption;
};

/*****************************************************************************
 * Datasource
 ****************************************************************************/

MapConfig.prototype.getLayerDatasource = function (layerIndex) {
    var datasource = this._datasource.getLayerDatasource(layerIndex) || {};

    var layerSrid = this.getLayerOption('srid');
    if (layerSrid) {
        datasource.srid = layerSrid;
    }

    return datasource;
};

/**
 * À la Factory method
 *
 * @param {Object} rawConfig
 * @param {Datasource} [datasource=Datasource.EmptyDatasource()]
 * @returns {MapConfig}
 */
function create(rawConfig, datasource) {
    if (rawConfig.ds) {
        return new MapConfig(rawConfig.cfg, new Datasource(rawConfig.ds));
    }
    datasource = datasource || Datasource.EmptyDatasource();
    return new MapConfig(rawConfig, datasource);
}

module.exports = MapConfig;
// Factory like method to create MapConfig objects when you are unsure about being
// able to provide all the MapConfig collaborators or you have to create a MapConfig
// object from a serialized version
module.exports.create = create;

module.exports.getLayerId = getLayerId;
<commit_msg>Fix missing param<commit_after>var Crypto = require('crypto');
var semver = require('semver');

var Datasource = require('./datasource');

// Map configuration object

/// API: Create MapConfig from configuration object
//
/// @param obj js MapConfiguration object, see
///        http://github.com/CartoDB/Windshaft/wiki/MapConfig-specification
///
function MapConfig(config, datasource) {
    // TODO: inject defaults ?
    this._cfg = config;

    if ( ! semver.satisfies(this.version(), '>= 1.0.0 <= 1.5.0') ) {
        throw new Error("Unsupported layergroup configuration version " + this.version());
    }

    if ( ! this._cfg.hasOwnProperty('layers') ) {
        throw new Error("Missing layers array from layergroup config");
    }

    this._cfg.layers.forEach(function(layer, i) {
    if ( ! layer.hasOwnProperty('options') ) {
        throw new Error("Missing options from layer " + i + " of layergroup config");
    }
    // NOTE: interactivity used to be a string as of version 1.0.0
    if ( Array.isArray(layer.options.interactivity) ) {
        layer.options.interactivity = layer.options.interactivity.join(',');
    }
  });

    /**
    * @type {Datasource}
    */
    this._datasource = datasource;

    this._id = null;
}

function md5Hash(s) {
    return Crypto.createHash('md5').update(s).digest('hex');
}

/// API: Get serialized version of this MapConfig
MapConfig.prototype.serialize = function() {
    if (this._datasource.isEmpty()) {
        return JSON.stringify(this._cfg);
    }
    return JSON.stringify({
        cfg: this._cfg,
        ds: this._datasource.obj()
    });
};

/// API: Get identifier for this MapConfig
MapConfig.prototype.id = function() {
    if (this._id === null) {
        this._id = md5Hash(JSON.stringify(this._cfg));
    }
    //debug('MapConfig.id=%s', this._id);
    return this._id;
};

/// API: Get configuration object of this MapConfig
MapConfig.prototype.obj = function() {
    return this._cfg;
};

MapConfig.prototype.version = function() {
    return this._cfg.version || '1.0.0';
};

MapConfig.prototype.setDbParams = function(dbParams) {
    this._cfg.dbparams = dbParams;
    this.flush();
};

MapConfig.prototype.flush = function() {
    // flush id so it gets recalculated
    this._id = null;
};

/// API: Get type string of given layer
//
/// @param num layer index (0-based)
/// @returns a type string, as read from the layer
///
MapConfig.prototype.layerType = function(num) {
    var lyr = this.getLayer(num);
    if ( ! lyr ) {
        return undefined;
    }
    return this.getType(lyr.type);
};

MapConfig.prototype.getType = function(type) {
    return getType(type);
};

function getType(type) {
    // TODO: check validity of other types ?
    return (!type || type === 'cartodb') ? 'mapnik' : type;
}

/*****************************************************************************
 * Layers
 ****************************************************************************/

MapConfig.prototype.getLayerId = function(layerIndex) {
    return getLayerId(this._cfg, layerIndex);
};

function getLayerId(rawMapConfig, layerIndex) {
    var layer = rawMapConfig.layers[layerIndex];
    if (layer.id) {
        return layer.id;
    }

    var layerType = getType(layer.type);
    var layerId = 'layer' + getLayerIndexByType(rawMapConfig, layerType, layerIndex);
    if (layerType !== 'mapnik') {
        layerId = layerType + '-' + layerId;
    }
    return layerId;
}

MapConfig.prototype.getIndexByLayerId = function (layerId) {
    var layers = this.getLayers();

    for (var i = 0; i < layers.length; i++) {
        if (layers[i].id === layerId) {
            return i;
        }
    }

    return -1;
};

/// API: Get layer by index
//
/// @returns undefined on invalid index
///
MapConfig.prototype.getLayer = function(layerIndex) {
    return this._cfg.layers[layerIndex];
};

MapConfig.prototype.getLayers = function() {
    return this._cfg.layers.map(function(_layer, layerIndex) {
        return this.getLayer(layerIndex);
    }.bind(this));
};

MapConfig.prototype.getLayerIndexByType = function(type, mapConfigLayerIdx) {
    return getLayerIndexByType(this._cfg, type, mapConfigLayerIdx);
};

function getLayerIndexByType(rawMapConfig, type, mapConfigLayerIdx) {
    var typeLayerIndex = 0;
    var mapConfigToTypeLayers = {};

    rawMapConfig.layers.forEach(function (layer, layerIdx) {
        if (getType(layer.type) === type) {
            mapConfigToTypeLayers[layerIdx] = typeLayerIndex++;
        }
    });

    return mapConfigToTypeLayers[mapConfigLayerIdx];
}

MapConfig.prototype.getLayerOption = function(layerIndex, optionName, defaultValue) {
    var layerOption = defaultValue;
    var layer = this.getLayer(layerIndex);
    if (layer && layer.options.hasOwnProperty(optionName)) {
        layerOption = layer.options[optionName];
    }
    return layerOption;
};

/*****************************************************************************
 * Datasource
 ****************************************************************************/

MapConfig.prototype.getLayerDatasource = function (layerIndex) {
    var datasource = this._datasource.getLayerDatasource(layerIndex) || {};

    var layerSrid = this.getLayerOption(layerIndex, 'srid');
    if (layerSrid) {
        datasource.srid = layerSrid;
    }

    return datasource;
};

/**
 * À la Factory method
 *
 * @param {Object} rawConfig
 * @param {Datasource} [datasource=Datasource.EmptyDatasource()]
 * @returns {MapConfig}
 */
function create(rawConfig, datasource) {
    if (rawConfig.ds) {
        return new MapConfig(rawConfig.cfg, new Datasource(rawConfig.ds));
    }
    datasource = datasource || Datasource.EmptyDatasource();
    return new MapConfig(rawConfig, datasource);
}

module.exports = MapConfig;
// Factory like method to create MapConfig objects when you are unsure about being
// able to provide all the MapConfig collaborators or you have to create a MapConfig
// object from a serialized version
module.exports.create = create;

module.exports.getLayerId = getLayerId;
<|endoftext|>


<commit_before>/**
	The MIT License (MIT)

	Copyright (c) 2014 MyChannel-Apps.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	@author		Adrian Preuß <Bizarrus>
	@docs	http://www.mychannel-apps.de/documentation/kcode/link
*/

/*
	@docs	http://www.mychannel-apps.de/documentation/KLink_constructor
*/
function KLink(text, command_left, command_right) {
	var _text			= '';
	var _command_left	= undefined;
	var _command_right	= undefined;
	var _hover			= true;
	var _hover_image	= undefined;

	function KLink(text, command_left, command_right) {
		_text			= text || '';
		_command_left	= command_left;
		_command_right	= command_right;
	}

	function prepareLink(string) {
		return string.replace(/(<|>|\||°)/g, '\\$1');
	}

	/*
		@docs	http://www.mychannel-apps.de/documentation/KLink_setCommand
	*/
	this.setCommand = function(command_left, command_right) {
		_command_left	= command_left;
		_command_right	= command_right;
		return this;
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/KLink_enableHover
	*/
	this.enableHover = function(state) {
		_hover = state;
		return this;
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/KLink_setHoverImage
	*/
	this.setHoverImage = function(image) {
		if(_text instanceof KImage) {
			_hover_image = image;
		} else {
			Logger.warn('You can only use KImage.setHoverImage(image) when you bind a KImage!');
		}

		return this;
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/KLink_toString
	*/
	this.toString = function() {
		var buffer = new StringBuffer('°>');

		if(_text instanceof KImage) {
			if(_hover == false) {
				_text.noPush(true);
				_hover_image.noPush(true);
			}

			buffer.append(_text.toString(true));

			if(_hover_image != undefined) {
				buffer.append('|' + _hover_image.toString(true));
			}

			buffer.append('<>--<>');
		} else {
			if(_hover == false) {
				buffer.append('_h');
			}

			buffer.append(prepareLink(_text));
		}

		if(_command_left != undefined) {
			buffer.append('|' + _command_left.replace(/\|/g, '\\\\\\\\\\|'));
		}

		if(_command_right != undefined) {
			buffer.append('|' + _command_right.replace(/\|/g, '\\\\\\\\\\|'));
		}

		buffer.append('<°');
		return buffer.toString();
	};

	KLink(text, command_left, command_right);
};<commit_msg>KLink: add getText()<commit_after>/**
	The MIT License (MIT)

	Copyright (c) 2014 MyChannel-Apps.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	@author		Adrian Preuß <Bizarrus>
	@docs	http://www.mychannel-apps.de/documentation/kcode/link
*/

/*
	@docs	http://www.mychannel-apps.de/documentation/KLink_constructor
*/
function KLink(text, command_left, command_right) {
	var _text			= '';
	var _command_left	= undefined;
	var _command_right	= undefined;
	var _hover			= true;
	var _hover_image	= undefined;

	function KLink(text, command_left, command_right) {
		_text			= text || '';
		_command_left	= command_left;
		_command_right	= command_right;
	}

	function prepareLink(string) {
		return string.replace(/(<|>|\||°)/g, '\\$1');
	}

	/*
		@docs	http://www.mychannel-apps.de/documentation/KLink_getText
	*/
	this.getText = function() {
		return _text;
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/KLink_setCommand
	*/
	this.setCommand = function(command_left, command_right) {
		_command_left	= command_left;
		_command_right	= command_right;
		return this;
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/KLink_enableHover
	*/
	this.enableHover = function(state) {
		_hover = state;
		return this;
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/KLink_setHoverImage
	*/
	this.setHoverImage = function(image) {
		if(_text instanceof KImage) {
			_hover_image = image;
		} else {
			Logger.warn('You can only use KImage.setHoverImage(image) when you bind a KImage!');
		}

		return this;
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/KLink_toString
	*/
	this.toString = function() {
		var buffer = new StringBuffer('°>');

		if(_text instanceof KImage) {
			if(_hover == false) {
				_text.noPush(true);
				_hover_image.noPush(true);
			}

			buffer.append(_text.toString(true));

			if(_hover_image != undefined) {
				buffer.append('|' + _hover_image.toString(true));
			}

			buffer.append('<>--<>');
		} else {
			if(_hover == false) {
				buffer.append('_h');
			}

			buffer.append(prepareLink(_text));
		}

		if(_command_left != undefined) {
			buffer.append('|' + _command_left.replace(/\|/g, '\\\\\\\\\\|'));
		}

		if(_command_right != undefined) {
			buffer.append('|' + _command_right.replace(/\|/g, '\\\\\\\\\\|'));
		}

		buffer.append('<°');
		return buffer.toString();
	};

	KLink(text, command_left, command_right);
};<|endoftext|>


<commit_before>module.exports = function (grunt) {

  grunt.initConfig({

    pkg: grunt.file.readJSON('package.json'),

    // Pre-commands
    run: {
      prepare: {
        exec: 'rm -rf ../static/ && mkdir ../static' // We want to clean all statics when running Grunt
      },
      bower: {
        exec: 'bower install'
      }
    },

    /**
     *  ----------- JAVASCRIPT -------------
     *
     */

    // Uglify JS files
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> \n*/',
      },
      dist: {
        files: {
          '../static/js/main.min.js': '../static/js/main.min.js'
        },
        options: {
          mangle: false
        }
      }
    },

    // Transpile to ES5 JS
    browserify: {
      dist: {
        options: {
          transform: [
            ["babelify", {presets: ["es2015", "stage-0", "react"]}]
          ]
        },
        files: {
          "../static/js/main.min.js": ["./js/app.js"]
        }
      }
    },

    // Check JS Syntax!
    jshint: {
      files: ['gruntfile.js', '../static/js/**/*.js'],
      options: {
        globals: {
          jQuery: true,
          console: true,
          module: true
        }
      }

    },

    /**
     *  ----------- SASS -------------
     *
     */
    // Compile SASS into CSS
    compass: {
      dist: {
        options: {
          sassDir: './sass',
          cssDir: '../static/css',
          environment: 'production',
          outputStyle: 'compressed'
        }
      },
      dev: {
        options: {
          sassDir: './sass',
          cssDir: '../static/css',
          environment: 'development'
        }
      }
    },

    /**
     *  ----------- OTHER TASKS-------------
     *
     */

    // Copy only useful files into /static after bower install
    bowercopy: {
      // Javascript files
      js: {
        options: {
          destPrefix: '../static/js'
        },
        files: {
          'bootstrap.min.js': 'bootstrap/dist/js/bootstrap.min.js',
          'jquery.min.js': 'jquery/dist/jquery.min.js',
          'jquery.min.map': 'jquery/dist/jquery.min.map'
        }
      },
      // CSS Files
      css: {
        options: {
          destPrefix: '../static/css'
        },
        files: {
          'bootstrap.min.css': 'bootstrap/dist/css/bootstrap.min.css',
          'bootstrap.min.css.map': 'bootstrap/dist/css/bootstrap.min.css.map',
        }
      },
      // Fonts files
      fonts: {
        options: {
          destPrefix: '../static/fonts'
        },
        files: {
          '': ['bootstrap/dist/fonts/*', '../fonts/*']
        }
      },
      // Images
      images: {
        options: {
          destPrefix: '../static/images'
        },
        files: {
          '': '../images/*'
        }
      },
      // Videos
      videos: {
        options: {
          destPrefix: '../static/videos'
        },
        files: {
          '': '../videos/*'
        }
      }
    },

    // Watcher
    watch: {
      scripts: {
        files: [
          './sass/**/*.scss',
          './js/**/*.js'
        ],
        tasks: ['compass:dev', 'browserify']
      }
    }

  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-run');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-bowercopy');

  // Default task.
  grunt.registerTask('default', ['run:prepare', 'run:bower', 'compass:dev', 'browserify', 'uglify', 'bowercopy', 'watch']);
  grunt.registerTask('build-dev', ['run:prepare', 'run:bower', 'compass:dev', 'browserify', 'uglify', 'bowercopy']);
  grunt.registerTask('windows', ['run:bower', 'compass:dev', 'browserify', 'uglify', 'bowercopy', 'watch']);

};
<commit_msg>Delete Video task from Gruntfile<commit_after>module.exports = function (grunt) {

  grunt.initConfig({

    pkg: grunt.file.readJSON('package.json'),

    // Pre-commands
    run: {
      prepare: {
        exec: 'rm -rf ../static/ && mkdir ../static' // We want to clean all statics when running Grunt
      },
      bower: {
        exec: 'bower install'
      }
    },

    /**
     *  ----------- JAVASCRIPT -------------
     *
     */

    // Uglify JS files
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> \n*/',
      },
      dist: {
        files: {
          '../static/js/main.min.js': '../static/js/main.min.js'
        },
        options: {
          mangle: false
        }
      }
    },

    // Transpile to ES5 JS
    browserify: {
      dist: {
        options: {
          transform: [
            ["babelify", {presets: ["es2015", "stage-0", "react"]}]
          ]
        },
        files: {
          "../static/js/main.min.js": ["./js/app.js"]
        }
      }
    },

    // Check JS Syntax!
    jshint: {
      files: ['gruntfile.js', '../static/js/**/*.js'],
      options: {
        globals: {
          jQuery: true,
          console: true,
          module: true
        }
      }

    },

    /**
     *  ----------- SASS -------------
     *
     */
    // Compile SASS into CSS
    compass: {
      dist: {
        options: {
          sassDir: './sass',
          cssDir: '../static/css',
          environment: 'production',
          outputStyle: 'compressed'
        }
      },
      dev: {
        options: {
          sassDir: './sass',
          cssDir: '../static/css',
          environment: 'development'
        }
      }
    },

    /**
     *  ----------- OTHER TASKS-------------
     *
     */

    // Copy only useful files into /static after bower install
    bowercopy: {
      // Javascript files
      js: {
        options: {
          destPrefix: '../static/js'
        },
        files: {
          'bootstrap.min.js': 'bootstrap/dist/js/bootstrap.min.js',
          'jquery.min.js': 'jquery/dist/jquery.min.js',
          'jquery.min.map': 'jquery/dist/jquery.min.map'
        }
      },
      // CSS Files
      css: {
        options: {
          destPrefix: '../static/css'
        },
        files: {
          'bootstrap.min.css': 'bootstrap/dist/css/bootstrap.min.css',
          'bootstrap.min.css.map': 'bootstrap/dist/css/bootstrap.min.css.map',
        }
      },
      // Fonts files
      fonts: {
        options: {
          destPrefix: '../static/fonts'
        },
        files: {
          '': ['bootstrap/dist/fonts/*', '../fonts/*']
        }
      },
      // Images
      images: {
        options: {
          destPrefix: '../static/images'
        },
        files: {
          '': '../images/*'
        }
      }
    },

    // Watcher
    watch: {
      scripts: {
        files: [
          './sass/**/*.scss',
          './js/**/*.js'
        ],
        tasks: ['compass:dev', 'browserify']
      }
    }

  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-run');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-bowercopy');

  // Default task.
  grunt.registerTask('default', ['run:prepare', 'run:bower', 'compass:dev', 'browserify', 'uglify', 'bowercopy', 'watch']);
  grunt.registerTask('build-dev', ['run:prepare', 'run:bower', 'compass:dev', 'browserify', 'uglify', 'bowercopy']);
  grunt.registerTask('windows', ['run:bower', 'compass:dev', 'browserify', 'uglify', 'bowercopy', 'watch']);

};
<|endoftext|>