/**
 *  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 " + fromdb(domains[i].name) + " "); 
				}
			} 
		}
	});    
    
    $("#add_zone_shortcut").unbind("click").bind("click", function(event) {  
        /*      
        if($("#leftmenu_physical_resource").find("#physical_resource_arrow").hasClass("expanded_close") == true)
			$("#leftmenu_physical_resource").click(); //if Physical Resource arrow shows closed (i.e. zonetree is hidden), expand and show zonetree.     
        */
        
        //$addZoneWizard.find("#info_container").hide();	
        openAddZoneWizard();
        return false;
    });    
          
    $addZoneWizard.unbind("click").bind("click", function(event) {  
        var $thisWizard = $(this);
        var $target = $(event.target);
    
        switch($target.attr("id")) {
            case "close_button":
                closeAddZoneWizard();
                break;
            
            case "basic_mode":  //create VLAN in pod-level      
                //hide Zone VLAN Range in Add Zone(step 2), show Guest IP Range in Add Pod(step3)                 
                $thisWizard.find("#step2").find("#add_zone_vlan_container").hide();
                $thisWizard.find("#step3").find("#guestip_container, #guestnetmask_container").show();
                return true;
                break;
                
            case "advanced_mode":  //create VLAN in zone-level 
                //show Zone VLAN Range in Add Zone(step 2), hide Guest IP Range in Add Pod(step3) 
                $thisWizard.find("#step2").find("#add_zone_vlan_container").show();  
                $thisWizard.find("#step3").find("#guestip_container, #guestnetmask_container").hide();   
                return true;
                break;
            
            case "go_to_step_2": //step 1 => step 2   
                $thisWizard.find("#step1").hide();
                $thisWizard.find("#step2").show();
                break;    
                
            case "go_to_step_3": //step 2 => step 3
                var isValid = addZoneWizardValidateZond($thisWizard);
                if (!isValid) 
	                return;	
                $thisWizard.find("#step2").hide();
                $thisWizard.find("#step3").show();
                break;   
           
            case "back_to_step_2": //step 3 => step 2
                $thisWizard.find("#step3").hide();
                $thisWizard.find("#step2").show();
                break;    
                
            case "back_to_step_1": //step 2 => step 1
                $thisWizard.find("#step2").hide();
                $thisWizard.find("#step1").show();
                break; 
                
            case "submit_button": //step 3 => make API call
                var isValid = addZoneWizardValidatePod($thisWizard);
                if($thisWizard.find("#step3").find("#guestip_container").css("display") != "none")
                    isValid &= addZoneWizardValidateGuestIPRange($thisWizard);
                if (!isValid) 
	                return;	
            
                $thisWizard.find("#step3").hide();
                $thisWizard.find("#after_submit_screen").show();
                addZoneWizardSubmit($thisWizard);
                break;       
        }   
        
        return false;
    }); 
}
function addZoneWizardValidateZond($thisWizard) {    
	var isValid = true;					
	isValid &= validateString("Name", $thisWizard.find("#add_zone_name"), $thisWizard.find("#add_zone_name_errormsg"));
	isValid &= validateIp("DNS 1", $thisWizard.find("#add_zone_dns1"), $thisWizard.find("#add_zone_dns1_errormsg"), false); //required
	isValid &= validateIp("DNS 2", $thisWizard.find("#add_zone_dns2"), $thisWizard.find("#add_zone_dns2_errormsg"), true);  //optional	
	isValid &= validateIp("Internal DNS 1", $thisWizard.find("#add_zone_internaldns1"), $thisWizard.find("#add_zone_internaldns1_errormsg"), false); //required
	isValid &= validateIp("Internal DNS 2", $thisWizard.find("#add_zone_internaldns2"), $thisWizard.find("#add_zone_internaldns2_errormsg"), true);  //optional	
	if($thisWizard.find("#step2").find("#add_zone_vlan_container").css("display") != "none") {
		isValid &= validateString("VLAN Range", $thisWizard.find("#add_zone_startvlan"), $thisWizard.find("#add_zone_startvlan_errormsg"), false); //required
		isValid &= validateString("VLAN Range", $thisWizard.find("#add_zone_endvlan"), $thisWizard.find("#add_zone_endvlan_errormsg"), true);        //optional
	}	
	isValid &= validateCIDR("Guest CIDR", $thisWizard.find("#add_zone_guestcidraddress"), $thisWizard.find("#add_zone_guestcidraddress_errormsg"), false); //required
	return isValid;
}
function addZoneWizardValidatePod($thisWizard) {   
    var isValid = true;					
    isValid &= validateString("Name", $thisWizard.find("#add_pod_name"), $thisWizard.find("#add_pod_name_errormsg"));
    isValid &= validateCIDR("CIDR", $thisWizard.find("#add_pod_cidr"), $thisWizard.find("#add_pod_cidr_errormsg"));	
    isValid &= validateIp("Reserved System IP", $thisWizard.find("#add_pod_startip"), $thisWizard.find("#add_pod_startip_errormsg"));  //required
    isValid &= validateIp("Reserved System IP", $thisWizard.find("#add_pod_endip"), $thisWizard.find("#add_pod_endip_errormsg"), true);  //optional    
    return isValid;			
}
function addZoneWizardValidateGuestIPRange($thisWizard) {   
    var isValid = true;	
    isValid &= validateIp("Guest IP Range", $thisWizard.find("#startguestip"), $thisWizard.find("#startguestip_errormsg"));  //required
    isValid &= validateIp("Guest IP Range", $thisWizard.find("#endguestip"), $thisWizard.find("#endguestip_errormsg"), true);  //optional
    isValid &= validateIp("Guest Gateway", $thisWizard.find("#guestnetmask"), $thisWizard.find("#guestnetmask_errormsg"));  //required when creating
    return isValid;			
}
function addZoneWizardSubmit($thisWizard) {
	$thisWizard.find("#spinning_wheel").show();
	
	var moreCriteria = [];	
	
	var name = trim($thisWizard.find("#add_zone_name").val());
	moreCriteria.push("&name="+todb(name));
	
	var dns1 = trim($thisWizard.find("#add_zone_dns1").val());
	moreCriteria.push("&dns1="+encodeURIComponent(dns1));
	
	var dns2 = trim($thisWizard.find("#add_zone_dns2").val());
	if (dns2 != null && dns2.length > 0) 
	    moreCriteria.push("&dns2="+encodeURIComponent(dns2));						
						
	var internaldns1 = trim($thisWizard.find("#add_zone_internaldns1").val());
	moreCriteria.push("&internaldns1="+encodeURIComponent(internaldns1));
	
	var internaldns2 = trim($thisWizard.find("#add_zone_internaldns2").val());
	if (internaldns2 != null && internaldns2.length > 0) 
	    moreCriteria.push("&internaldns2="+encodeURIComponent(internaldns2));						
	 											
    if($thisWizard.find("#step2").find("#add_zone_vlan_container").css("display") != "none") {
		var vlanStart = trim($thisWizard.find("#add_zone_startvlan").val());	
		var vlanEnd = trim($thisWizard.find("#add_zone_endvlan").val());						
		if (vlanEnd != null && vlanEnd.length > 0) 
		    moreCriteria.push("&vlan=" + encodeURIComponent(vlanStart + "-" + vlanEnd));									
		else 							
			moreCriteria.push("&vlan=" + encodeURIComponent(vlanStart));		
	}	
	else { 
	    moreCriteria.push("&vlan=30"); //temporary hacking before bug 7143 is fixed ("VLAN parameter in CreateZone shouldn't be required") 
	} 			
	
	var guestcidraddress = trim($thisWizard.find("#add_zone_guestcidraddress").val());
	moreCriteria.push("&guestcidraddress="+encodeURIComponent(guestcidraddress));	
					
	if($thisWizard.find("#domain_dropdown_container").css("display") != "none") {
	    var domainId = trim($thisWizard.find("#domain_dropdown").val());
	    moreCriteria.push("&domainid="+domainId);	
	}
	
	var zoneId, podId, vlanId, $zoneNode, $podNode, gateway;	
	var afterActionMsg = "";						
    $.ajax({
        data: createURL("command=createZone"+moreCriteria.join("")),
	    dataType: "json",
	    async: false,
	    success: function(json) {	
	        afterActionMsg += "Zone was created successfully
You have successfully added your first Zone and Pod.  After clicking 'OK', this UI will automatically refresh to give you access to the rest of cloud features.
")
				        .dialog('option', 'buttons', { 
					        "OK": function() { 	
						        window.location.reload();
					        } 
				        }).dialog("open");
		        }
	        },
            error: function(XMLHttpResponse) {	
				handleError(XMLHttpResponse, function() {
					afterActionMsg += ("Failed to create Pod. " + parseXMLHttpResponse(XMLHttpResponse) + "" + fromdb(domains[i].name) + " "); 
				}
			} 
		}
	});   
       
    $addZoneLink.unbind("click").bind("click", function(event) {         
        if($("#leftmenu_physical_resource").find("#physical_resource_arrow").hasClass("expanded_close") == true)
			$("#leftmenu_physical_resource").click(); //if Physical Resource arrow shows closed (i.e. zonetree is hidden), expand and show zonetree.     
        
        $addZoneDialog.find("#info_container").hide();				
    
        $addZoneDialog
		.dialog('option', 'buttons', { 				
			"Add": function() { 
			    var $thisDialog = $(this);
								
				// validate values
				var isValid = true;					
				isValid &= validateString("Name", $thisDialog.find("#add_zone_name"), $thisDialog.find("#add_zone_name_errormsg"));
				isValid &= validateIp("DNS 1", $thisDialog.find("#add_zone_dns1"), $thisDialog.find("#add_zone_dns1_errormsg"), false); //required
				isValid &= validateIp("DNS 2", $thisDialog.find("#add_zone_dns2"), $thisDialog.find("#add_zone_dns2_errormsg"), true);  //optional	
				isValid &= validateIp("Internal DNS 1", $thisDialog.find("#add_zone_internaldns1"), $thisDialog.find("#add_zone_internaldns1_errormsg"), false); //required
				isValid &= validateIp("Internal DNS 2", $thisDialog.find("#add_zone_internaldns2"), $thisDialog.find("#add_zone_internaldns2_errormsg"), true);  //optional	
				if (getNetworkType() != "vnet") {
					isValid &= validateString("Zone - Start VLAN Range", $thisDialog.find("#add_zone_startvlan"), $thisDialog.find("#add_zone_startvlan_errormsg"), false); //required
					isValid &= validateString("Zone - End VLAN Range", $thisDialog.find("#add_zone_endvlan"), $thisDialog.find("#add_zone_endvlan_errormsg"), true);        //optional
				}
				isValid &= validateCIDR("Guest CIDR", $thisDialog.find("#add_zone_guestcidraddress"), $thisDialog.find("#add_zone_guestcidraddress_errormsg"), false); //required
				if (!isValid) 
				    return;							
				
				$thisDialog.find("#spinning_wheel").show();
				
				var moreCriteria = [];	
				
				var name = trim($thisDialog.find("#add_zone_name").val());
				moreCriteria.push("&name="+todb(name));
				
				var dns1 = trim($thisDialog.find("#add_zone_dns1").val());
				moreCriteria.push("&dns1="+encodeURIComponent(dns1));
				
				var dns2 = trim($thisDialog.find("#add_zone_dns2").val());
				if (dns2 != null && dns2.length > 0) 
				    moreCriteria.push("&dns2="+encodeURIComponent(dns2));						
									
				var internaldns1 = trim($thisDialog.find("#add_zone_internaldns1").val());
				moreCriteria.push("&internaldns1="+encodeURIComponent(internaldns1));
				
				var internaldns2 = trim($thisDialog.find("#add_zone_internaldns2").val());
				if (internaldns2 != null && internaldns2.length > 0) 
				    moreCriteria.push("&internaldns2="+encodeURIComponent(internaldns2));						
				 											
				if (getNetworkType() != "vnet") {
					var vlanStart = trim($thisDialog.find("#add_zone_startvlan").val());	
					var vlanEnd = trim($thisDialog.find("#add_zone_endvlan").val());						
					if (vlanEnd != null && vlanEnd.length > 0) 
					    moreCriteria.push("&vlan=" + encodeURIComponent(vlanStart + "-" + vlanEnd));									
					else 							
						moreCriteria.push("&vlan=" + encodeURIComponent(vlanStart));		
				}					
				
				var guestcidraddress = trim($thisDialog.find("#add_zone_guestcidraddress").val());
				moreCriteria.push("&guestcidraddress="+encodeURIComponent(guestcidraddress));	
								
				if($thisDialog.find("#domain_dropdown_container").css("display") != "none") {
				    var domainId = trim($thisDialog.find("#domain_dropdown").val());
				    moreCriteria.push("&domainid="+domainId);	
				}
														
                $.ajax({
			        data: createURL("command=createZone"+moreCriteria.join("")),
				    dataType: "json",
				    success: function(json) {				       
				        $thisDialog.find("#spinning_wheel").hide();
				        $thisDialog.dialog("close");
				        			        
				        var template = $("#leftmenu_zone_node_template").clone(true); 			            			   
			            var $zoneTree = $("#leftmenu_zone_tree").find("#tree_container");		     			
			            $zoneTree.prepend(template);	
	                    template.fadeIn("slow");				        
				    
					    var item = json.createzoneresponse.zone;					    
					    zoneJSONToTreeNode(item, template);						    	        
				    },
			        error: function(XMLHttpResponse) {
						handleError(XMLHttpResponse, function() {
							handleErrorInDialog(XMLHttpResponse, $thisDialog);	
						});
			        }
			    });
			}, 
			"Cancel": function() { 
			    var $thisDialog = $(this);
				$thisDialog.dialog("close"); 
				/*
				cleanErrMsg($thisDialog.find("#add_zone_name"), $thisDialog.find("#add_zone_name_errormsg"));
				cleanErrMsg($thisDialog.find("#add_zone_dns1"), $thisDialog.find("#add_zone_dns1_errormsg"));
				cleanErrMsg($thisDialog.find("#add_zone_dns2"), $thisDialog.find("#add_zone_dns2_errormsg"));
				cleanErrMsg($thisDialog.find("#add_zone_internaldns1"), $thisDialog.find("#add_zone_internaldns1_errormsg"));
				cleanErrMsg($thisDialog.find("#add_zone_internaldns2"), $thisDialog.find("#add_zone_internaldns2_errormsg"));
				cleanErrMsg($thisDialog.find("#add_zone_startvlan"), $thisDialog.find("#add_zone_startvlan_errormsg"));
				cleanErrMsg($thisDialog.find("#add_zone_guestcidraddress"), $thisDialog.find("#add_zone_guestcidraddress_errormsg"));
				*/
			} 
		}).dialog("open");        
        return false;
    });     
}