// JavaScript Document
var $=jQuery.noConflict();
var isCFormOpen=false;
var fromTop=100;
var ajaxFormSubmitted=false;
var formRegisterAffiliates=false;

function show_overlay(text){	
	if($("div#formCContainer").length>0){
		$("div#formCContainer").html("");
		$("div#formCContainer").html("<div class='errMessage'><a name='targetAnchor' id='targetAnchor'></a><div class='errClose'>Close X</div><div id='errContent'></div><div class='noFloat'></div></div>"+text);
	}else if($("div#viewPlansContainer").length>0){
		$("div#viewPlansContainer").html("<div class='errMessage1'><div class='errClose'>X</div><div id='errContent'>" + text + "</div><div class='noFloat'></div></div>");
		$("div#viewPlansContainer").slideDown("fast");
	}
	if(!isCFormOpen){
			$("div#formCContainer").slideDown("fast");
			isCFormOpen=true;
		}
	attach_overlay_events();	
}


function attach_overlay_events(){
	//$("html, body").animate({ scrollTop: fromTop }, "slow");
	var elem=$("a#targetAnchor");
	//$("html, body").ScrollTo(elem.left, elem.top);
	$("div#action_button_create_account").click(function(){
		$("#hosted-payment-form").submit();
	});
	$("#hosted-payment-form").submit(function(e){
		e.preventDefault();		
		switch($("input#product_id", this).val()){
			case "73299":
			validateFormFree("73299");
			break;
			case "73300":
			validateFormFree("73300");
			break;
			case "73301":
			validateFormFree("73301");
			break;
			case "73302":
			validateFormFree("73302");
			break;
		}		
		//return false;		
	});
	$("div.errMessage div.errClose, div.errMessage1 div.errClose").click(function(){		
		$(this).parent("div").fadeOut("fast");
	});
}

function validateFormFree(formType){
	var vl = new DP.validateForm(formType);
    
	//passes validation settings
	if(formType=="73299" || formType=="87069"){
	vl.valSetting = {fileds : [
						{id : "subscription_customer_attributes_first_name", val : 0, msg : "First Name", type : ""},
						{id : "subscription_customer_attributes_last_name", val : 0, msg : "Last Name", type : ""},
						{id : "subscription_customer_attributes_email", val : 0, msg : "Email Address", type : "email"},
						{id : "subscription_customer_attributes_username", val : 0, msg : "Username", type : "alphanumonly"},
						{id : "subscription_customer_attributes_password", val : 0, msg : "Password", type : "alphanumonly"},
						{id : "subscription_customer_attributes_repassword", val : 0, msg : "Re-type Password", type : "alphanumonly"}
				        ]
	};
	}else if(formType=="73300" || formType=="73301" || formType=="73302"){
		vl.valSetting = {fileds : [
						{id : "subscription_customer_attributes_first_name", val : 0, msg : "First Name", type : ""},
						{id : "subscription_customer_attributes_last_name", val : 0, msg : "Last Name", type : ""},
						{id : "subscription_customer_attributes_email", val : 0, msg : "Email Address", type : "email"},
						{id : "subscription_customer_attributes_username", val : 0, msg : "Username", type : "alphanumonly"},
						{id : "subscription_customer_attributes_password", val : 0, msg : "Password", type : "alphanumonly"},
						{id : "subscription_customer_attributes_repassword", val : 0, msg : "Re-type Password", type : "alphanumonly"},
						{id : "subscription_payment_profile_attributes_full_number", val : 0, msg : "Card Number", type : "number"},
						{id : "subscription_payment_profile_attributes_expiration_month", val : 0, msg : "Expiration date (Month)", type : "number"},
						{id : "subscription_payment_profile_attributes_expiration_year", val : 0, msg : "Expiration date (Year)", type : "number"},
						{id : "subscription_payment_profile_attributes_first_name", val : 0, msg : "First Name on Card", type : ""},
						{id : "subscription_payment_profile_attributes_last_name", val : 0, msg : "Last Name on Card", type : ""}
				        ]
	};
	}else if(formType=="80000"){
		if($("input#subscription_payment_profile_attributes_full_number").length>0){
			vl.valSetting = {fileds : [						
						{id : "subscription_payment_profile_attributes_full_number", val : 0, msg : "Card Number", type : "number"},
						{id : "subscription_payment_profile_attributes_expiration_month", val : 0, msg : "Expiration date (Month)", type : "number"},
						{id : "subscription_payment_profile_attributes_expiration_year", val : 0, msg : "Expiration date (Year)", type : "number"},
						{id : "subscription_payment_profile_attributes_first_name", val : 0, msg : "First Name on Card", type : ""},
						{id : "subscription_payment_profile_attributes_last_name", val : 0, msg : "Last Name on Card", type : ""}
				        ]
	};
		}else{
			vl.valSetting = {fileds : [						
						{id : "product_id", val : 0, msg : "", type : "number"}
				        ]
	};
		}
	}
	return vl.runCheck();
}

function sendOrderToChargify(formType){
	displayAlert("<p>Adding your order...</p><p>It might take several moments while installing your application.</p>");
				
	switch(formType){		
		case "73299":		
		var postData="subscription[customer_attributes][first_name]=" + $("input[name='subscription[customer_attributes][first_name]']").val();
		postData +="&subscription[customer_attributes][last_name]=" + $("input[name='subscription[customer_attributes][last_name]']").val();
		postData +="&subscription[customer_attributes][email]=" + $("input[name='subscription[customer_attributes][email]']").val();
		postData +="&subscription[customer_attributes][phone]=" + $("input[name='subscription[customer_attributes][phone]']").val();
		postData +="&subscription[customer_attributes][username]=" + $("input[name='subscription[customer_attributes][username]']").val();
		postData +="&subscription[customer_attributes][password]=" + $("input[name='subscription[customer_attributes][password]']").val();
		postData +="&subscription[customer_attributes][package]=" + $("input[name='subscription[customer_attributes][package]']").val();
		postData +="&bloginfo[url]=" + $("input#bloginfo_url").val() + "&bloginfo[template_directory]=" + $("input#bloginfo_template_directory").val();	
		postData +="&context=addNewOrderToChargify";
		break;
		
		case "87069":		
		var postData="subscription[customer_attributes][first_name]=" + $("input[name='subscription[customer_attributes][first_name]']").val();
		postData +="&subscription[customer_attributes][last_name]=" + $("input[name='subscription[customer_attributes][last_name]']").val();
		postData +="&subscription[customer_attributes][email]=" + $("input[name='subscription[customer_attributes][email]']").val();
		postData +="&subscription[customer_attributes][phone]=" + $("input[name='subscription[customer_attributes][phone]']").val();
		postData +="&subscription[customer_attributes][username]=" + $("input[name='subscription[customer_attributes][username]']").val();
		postData +="&subscription[customer_attributes][password]=" + $("input[name='subscription[customer_attributes][password]']").val();
		postData +="&subscription[customer_attributes][package]=" + $("input[name='subscription[customer_attributes][package]']").val();
		postData +="&bloginfo[url]=" + $("input#bloginfo_url").val() + "&bloginfo[template_directory]=" + $("input#bloginfo_template_directory").val();	
		postData +="&context=addNewOrderToChargify&30day=1";
		break;
		
		case "73300":
		case "73301":
		case "73302":
		var postData="subscription[customer_attributes][first_name]=" + $("input[name='subscription[customer_attributes][first_name]']").val();
		postData +="&subscription[customer_attributes][last_name]=" + $("input[name='subscription[customer_attributes][last_name]']").val();
		postData +="&subscription[customer_attributes][email]=" + $("input[name='subscription[customer_attributes][email]']").val();
		postData +="&subscription[customer_attributes][phone]=" + $("input[name='subscription[customer_attributes][phone]']").val();
		postData +="&subscription[customer_attributes][username]=" + $("input[name='subscription[customer_attributes][username]']").val();
		postData +="&subscription[customer_attributes][password]=" + $("input[name='subscription[customer_attributes][password]']").val();
		postData +="&subscription[customer_attributes][package]=" + $("input[name='subscription[customer_attributes][package]']").val();
		postData +="&subscription[payment_profile_attributes][full_number]=" + $("input[name='subscription[payment_profile_attributes][full_number]']").val();
		postData +="&subscription[payment_profile_attributes][cvv]=" + $("input[name='subscription[payment_profile_attributes][cvv]']").val();
		postData +="&subscription[payment_profile_attributes][expiration_month]=" + $("select[name='subscription[payment_profile_attributes][expiration_month]']").val();	
		postData +="&subscription[payment_profile_attributes][expiration_year]=" + $("select[name='subscription[payment_profile_attributes][expiration_year]']").val();
		postData +="&subscription[payment_profile_attributes][first_name]=" + $("input[name='subscription[payment_profile_attributes][first_name]']").val();
		postData +="&subscription[payment_profile_attributes][last_name]=" + $("input[name='subscription[payment_profile_attributes][last_name]']").val();
		postData +="&subscription[payment_profile_attributes][billing_zip]=" + $("input[name='subscription[payment_profile_attributes][billing_zip]']").val();
		postData +="&bloginfo[url]=" + $("input#bloginfo_url").val() + "&bloginfo[template_directory]=" + $("input#bloginfo_template_directory").val();
		postData +="&context=addNewOrderToChargify";
		break;
		
		case "80000":
		var postData="subscription[customer_attributes][sid]=" + $("input[name='subscription[customer_attributes][sid]']").val();
		if($("select[name='subscription[customer_attributes][package]']").length>0){
			postData +="&subscription[customer_attributes][package]=" + $("select[name='subscription[customer_attributes][package]']").val();
		}
		if($("input[name='subscription[customer_attributes][componentStorage]']").length>0){
			postData +="&subscription[customer_attributes][componentStorage]=" + $("input[name='subscription[customer_attributes][componentStorage]']").val();
		}
		if($("input[name='subscription[customer_attributes][agents]']").length>0){
			postData +="&subscription[customer_attributes][agents]=" + $("input[name='subscription[customer_attributes][agents]']").val();
		}
		postData +="&subscription[customer_attributes][app]=" + $("input[name='subscription[customer_attributes][app]']").val();
		if($("input#subscription_payment_profile_attributes_full_number").length>0){
			postData +="&subscription[payment_profile_attributes][full_number]=" + $("input[name='subscription[payment_profile_attributes][full_number]']").val();
			postData +="&subscription[payment_profile_attributes][cvv]=" + $("input[name='subscription[payment_profile_attributes][cvv]']").val();
			postData +="&subscription[payment_profile_attributes][expiration_month]=" + $("select[name='subscription[payment_profile_attributes][expiration_month]']").val();	
			postData +="&subscription[payment_profile_attributes][expiration_year]=" + $("select[name='subscription[payment_profile_attributes][expiration_year]']").val();
			postData +="&subscription[payment_profile_attributes][first_name]=" + $("input[name='subscription[payment_profile_attributes][first_name]']").val();
			postData +="&subscription[payment_profile_attributes][last_name]=" + $("input[name='subscription[payment_profile_attributes][last_name]']").val();
			postData +="&subscription[payment_profile_attributes][billing_zip]=" + $("input[name='subscription[payment_profile_attributes][billing_zip]']").val();	
		}
		postData +="&bloginfo[url]=" + $("input#bloginfo_url").val() + "&bloginfo[template_directory]=" + $("input#bloginfo_template_directory").val();
		postData +="&context=updateOrderToChargify";
		break;
		
	}
				$.ajax({
						   type: "POST",
						   url: $("input#bloginfo_template_directory").val()+"/CHARGIFY_API/ajaxDispatcher.php",
						   data: postData,
						   dataType: "html",
						   success: function(responseText){
								if(responseText!=1){
									displayAlert(responseText);
									if($("input#trackingFileHere").val()!=""){
										$("input#trackingFile").val($("input#trackingFileHere").val());
										$("#frmTrackingOrdersInstaller").submit();
									}
									return false;
								}else if(responseText==1){
									alert("go ahead");
									return false;
								}
						   }
					});	
}


var DP = (typeof DP == "object") ? DP : {};

DP.validateForm = function(formType){
	
	
	
	stringAlert="Missing fields:\n\n";

    //generic check value method
	var formValidated = function()
	{	
		if(formType!="80000" && formType!="affiliates-registration-form"){	
			if($("input#subscription_customer_attributes_username").val()!=""){
				if($("input[name='subscription[agree_to_terms]']").is(':checked')){
					
				}else{
					displayAlert("Accept the Terms and Conditions!");
					return false;
				}
				displayAlert("<p>Validating your username...</p>");
				var postData="username=" + $("input#subscription_customer_attributes_username").val() + "&context=checkUsername";
				$.ajax({
						   type: "POST",
						   url: $("input#bloginfo_template_directory").val()+"/CHARGIFY_API/ajaxDispatcher.php",
						   data: postData,
						   dataType: "html",
						   success: function(responseText){
								if(responseText!=1){
									displayAlert(responseText);
									return false;
								}else if(responseText==1){
									sendOrderToChargify(formType);
									return false;
								}
						   }
					});		
			}
		}else if(formType=="80000"){
			sendOrderToChargify(formType);
		}else if(formType=="affiliates-registration-form"){
			if($("input#affiliates-registration-form-termsandcond").is(':checked') || $("input#affiliates-registration-form-termsandcond").val()==1){
					formRegisterAffiliates=true;
					$("#"+formType).submit();
				}else{
					displayAlert("Accept the Terms and Conditions!");
					return false;
				}
		}
			
	}
	
	
    var fromReset = function(elmId, wrongValue, messageText){
        //reset
        $(".from_wrp input").css({"border":"1px solid #ACA69F"});
        $(".from_wrp select").css({"border":"1px solid #ACA69F"});
        $("#error_messages").empty("");
    }

    //generic check value method
    var valueCheck = function(elmId, wrongValue, messageText){
        if($("#" + elmId).val() == wrongValue){
            createAlert(elmId, messageText);
			return false;
		}
			return true;
    }
    
    //alert method
    var createAlert = function(elmId, messageText){
        stringAlert +="<p>" + messageText + "</p>";
    }

    //zip validation
    var isZip = function(s){
        var reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
        if (!reZip.test(s)) {
            return false;
        }
        return true;
    }
    
    //checks if value is integer
    var isInt = function(n){
        var reInt = new RegExp(/^-?\d+$/);
        if (!reInt.test(n)) {
            return false;
        }
        return true;
    } 
	//checks if value is price
    var isPrice = function(n){
        var rePrice = new RegExp(/^\d+(\.\d{1,2})?$/);
        if (!rePrice.test(n)) {
            return false;
        }
        return true;
    }
	//checks if value is alphanumeric only
    var isAlphanumonly = function(n){
        var reAlphanumonly = new RegExp(/^[a-z0-9]+$/i);
        if (!reAlphanumonly.test(n)) {
            return false;
        }
        return true;
    } 
	
	//mail validation
    var isMail = function(s, elmId){
        var reMail = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        if (!reMail.test(s)) {
            return false;
        }		
        return true;
    }
    
    
    //public method checks fieds
    //requires 'valSetting' setting object
	
    this.runCheck = function(){
        //reseet form		
        //run checks
		var countTrueFilled=0;
		stringAlert="<h3>Missing fields:</h3>";
        for (i=0;i<this.valSetting.fileds.length;i++){
            
            if(this.valSetting.fileds[i].type == "zip"){
                //zip check
                if(isZip($("#" + this.valSetting.fileds[i].id).val()) == false){    
                    createAlert(this.valSetting.fileds[i].id, this.valSetting.fileds[i].msg);
                }
				else{
					countTrueFilled++;
				}
            }
            else if (this.valSetting.fileds[i].type == "number"){
                //checks for number
                if(isInt($("#" + this.valSetting.fileds[i].id).val()) == false){    
                    createAlert(this.valSetting.fileds[i].id, this.valSetting.fileds[i].msg);
                }
				else{
					countTrueFilled++;
				}
            }
			else if (this.valSetting.fileds[i].type == "price"){
                //checks for number
                if(isPrice($("#" + this.valSetting.fileds[i].id).val()) == false){    
                    createAlert(this.valSetting.fileds[i].id, this.valSetting.fileds[i].msg);
                }
				else{
					countTrueFilled++;
				}
            }
			else if (this.valSetting.fileds[i].type == "alphanumonly"){
                //checks for alphanumeric only, no spaces
                if(isAlphanumonly($("#" + this.valSetting.fileds[i].id).val()) == false){    
                    createAlert(this.valSetting.fileds[i].id, this.valSetting.fileds[i].msg);
                }
				else{
					countTrueFilled++;
				}
            }
			else if (this.valSetting.fileds[i].type == "email"){
                //checks for number
                if(isMail($("#" + this.valSetting.fileds[i].id).val(), this.valSetting.fileds[i].id) == false){    
                    createAlert(this.valSetting.fileds[i].id, this.valSetting.fileds[i].msg);
                }
				else{
					countTrueFilled++;
				}
            }
            else{
                //checks for value
                if(valueCheck(this.valSetting.fileds[i].id, this.valSetting.fileds[i].val, this.valSetting.fileds[i].msg))
				{
					countTrueFilled++;
				}
            }
        }
		if(countTrueFilled>=this.valSetting.fileds.length)
		{
				return formValidated();
		}
		else
		{
			displayAlert(stringAlert);
			return false;
		}
		
    }
	
	
} 

function displayAlert(a){
	//$("html, body").animate({ scrollTop: fromTop }, "fast");
	var elem=$("a#targetAnchor");
	//$("html, body").ScrollTo(elem.left, elem.top);
	$("div.errMessage div#errContent").html(a);
	$("div.errMessage").fadeIn("fast");
	$("div.errMessage div.errClose, div.errMessage1 div.errClose").click(function(){		
		$(this).parent("div").fadeOut("fast");
	});
}

function isNumber(a,b){
	var isNumber=/^\d+$/;
	if(!isNumber.test(a.val())){
		a.val(0);
		alert("Digits only!");
	}else{
		if(parseFloat(a.val())>b){
			a.val(b);
		}
	}
}

function validateFormRegisterAffiliates(){
	var vl = new DP.validateForm("affiliates-registration-form");    
	
	vl.valSetting = {fileds : [
						{id : "affiliates-registration-form-first-name", val : 0, msg : "First Name", type : ""},
						{id : "affiliates-registration-form-last-name", val : 0, msg : "Last Name", type : ""},
						{id : "affiliates-registration-form-user-login", val : 0, msg : "Username", type : ""},
						{id : "affiliates-registration-form-email", val : 0, msg : "Email", type : "email"},
						{id : "affiliates-registration-form-ppemail", val : 0, msg : "PayPal Email", type : "email"},
						{id : "affiliates-registration-form-what-experience", val : 0, msg : "What is your experience as a promoter?", type : ""},
						{id : "affiliates-registration-form-how-manysell", val : 0, msg : "How many units can you sell?", type : ""},
						{id : "affiliates-registration-form-how-hearabout", val : 0, msg : "How did you hear about this affiliate program?", type : ""}
				        ]
	}
	return vl.runCheck();
}

$(document).ready(function(){
	
	if($("input#affiliateregistererror").length>0){
		displayAlert($("input#affiliateregistererror").val());
	}
	
	$("#affiliates-registration-form").submit(function(e){
		if(formRegisterAffiliates===false){
		e.preventDefault();
		return validateFormRegisterAffiliates();	
		}
	});
	
	$("#affiliates-registration-form div#action_button_create_account").click(function(){
		$("#affiliates-registration-form").submit();
	});
	
	$("div#action_button_create_account").click(function(){
		$("#hosted-payment-form").submit();
	});
	$("#hosted-payment-form").submit(function(e){
		e.preventDefault();		
		switch($("input#product_id", this).val()){
			case "73299":
			validateFormFree("73299");
			break;
			case "87069":
			validateFormFree("87069");
			break;
			case "73300":
			validateFormFree("73300");
			break;
			case "73301":
			validateFormFree("73301");
			break;
			case "73302":
			validateFormFree("73302");
			break;
		}		
		//return false;		
	});
	$("div.errMessage div.errClose, div.errMessage1 div.errClose").click(function(){		
		$(this).parent("div").fadeOut("fast");
	});
	
	
	
	
	
	$("a#clickToUpdateBillingInformations").click(function(e){
		e.preventDefault();
		var postData="id=" + $("input[name='subscription[customer_attributes][sid]']").val() + "&bloginfo[template_directory]=" + $("input#bloginfo_template_directory").val() + "&bloginfo[url]=" + $("input#bloginfo_url").val() + "&context=showCreditCardUpdateWindow";				
				$.ajax({
						   type: "POST",
						   url: $("input#bloginfo_template_directory").val()+"/CHARGIFY_API/ajaxDispatcher.php",
						   data: postData,
						   dataType: "html",
						   success: function(responseText){
								$("div#updateBillingInformationContainer").html(responseText);
						   }
					});	
	});
	
	
	
	$("div.errMessage1 div.errClose").click(function(){		
		$(this).parent("div").fadeOut("fast");
	});
	var allTotal=0;
	var tempArrPackage=new Array("FREE", "BASIC", "PLUS", "PRO");
	$("input[name='subscription[customer_attributes][componentStorage]']").val(0);
	$("input[name='subscription[customer_attributes][agents]']").val(0);
	$("span#storageToUpgrade").html($("input[name='subscription[customer_attributes][componentStorage]']").val());
	$("span#agentToUpgrade").html($("input[name='subscription[customer_attributes][agents]']").val());
	
	$("option:first", "select[name='subscription[customer_attributes][package]']").attr("selected", "selected");
	
	$("span#planToUpgrade").html($("select[name='subscription[customer_attributes][package]'] option:selected").text());
	
	var selectedPackageValue=new Number($("select[name='subscription[customer_attributes][package]'] option:selected").val());
	
	selectedPackageValue=parseInt(selectedPackageValue);
	if($("div#viewPlansContainer").length>0){
		var postData="id=" + (selectedPackageValue+1) + "&context=showPlan";				
				$.ajax({
						   type: "POST",
						   url: $("input#bloginfo_template_directory").val()+"/CHARGIFY_API/ajaxDispatcher.php",
						   data: postData,
						   dataType: "html",
						   success: function(responseText){
								show_overlay(responseText);
						   }
					});	
	
	}
	$("input[name='subscription[customer_attributes][componentStorageAmount]']").val(0);
	$("input[name='subscription[customer_attributes][componentAgentAmount]']").val(0);
	
	allTotal=$("input[name='productPrice[" + selectedPackageValue + "]']").val()/100;
	
	$("h3#totalToUpgrade").html("<div>Total: $" + number_format(allTotal, 2, ".", ",") + "<span class='small'> (per mo.)</span></div>");
	
	var recentHash = window.location.hash; 
	if(recentHash!=""){	
	if(recentHash.indexOf("=")!=-1){	
		var curEdit=recentHash.split("=");
		var currPlan=curEdit[1];
		var postData="plan=" + currPlan + "&bloginfo[template_directory]=" + $("input#bloginfo_template_directory").val() + "&bloginfo[url]=" + $("input#bloginfo_url").val() + "&context=addNewPlan";
		$.ajax({
						   type: "POST",
						   url: $("input#bloginfo_template_directory").val()+"/CHARGIFY_API/ajaxDispatcher.php",
						   data: postData,
						   dataType: "html",
						   success: function(responseText){
								show_overlay(responseText);
						   }
					});	
	}
		
	}
	
	
	
	$("div#action_button_pricing").parent("a").click(function(e){
		$.removeData(this);
		e.preventDefault();
		var currPlan=$("div#action_button_pricing", this).attr("rel");
		var postData="plan=" + currPlan + "&bloginfo[template_directory]=" + $("input#bloginfo_template_directory").val() + "&bloginfo[url]=" + $("input#bloginfo_url").val() + "&context=addNewPlan";
				e.preventDefault();
				$.ajax({
						   type: "POST",
						   url: $("input#bloginfo_template_directory").val()+"/CHARGIFY_API/ajaxDispatcher.php",
						   data: postData,
						   dataType: "html",
						   success: function(responseText){							   
								show_overlay(responseText);
						   }
					});				 
		
	});
	
		
	$("select[name='subscription[customer_attributes][package]']").change(function(){
		var selectedPackageValue =$("option:selected", this).val();
		var selectedPackageValueInt =new Number($("option:selected", this).val());
		var selectedPackageValue =new Number($("option:selected", this).val());
		selectedPackageValue=parseInt(selectedPackageValue);
		selectedPackageValue+=1;
		var postData="id=" + selectedPackageValue + "&context=showPlan";				
				$.ajax({
						   type: "POST",
						   url: $("input#bloginfo_template_directory").val()+"/CHARGIFY_API/ajaxDispatcher.php",
						   data: postData,
						   dataType: "html",
						   success: function(responseText){
								show_overlay(responseText);
						   }
					});	
		
		
		
		$("span#planToUpgrade").html($("option:selected", this).text());
		var allTotal=parseFloat($("input[name='productPrice[" + selectedPackageValueInt + "]']").val()/100);
		var allTotalComponent=parseFloat($("input[name='subscription[customer_attributes][componentStorageAmount]']").val());
		allTotalComponent +=parseFloat($("input[name='subscription[customer_attributes][componentAgentAmount]']").val());
		if(allTotalComponent>0){
			$("h3#totalToUpgrade").html("<div>Total: $" + number_format(allTotal, 2, ".", ",") + "<span class='small'> (per mo.)</span></div><div class='small'>Additionals: $" + number_format(allTotalComponent, 2, ".", ",") + "<span class='small'> (once)</span></div>");
		}else{
			$("h3#totalToUpgrade").html("<div>Total: $" + number_format(allTotal, 2, ".", ",") + "<span class='small'> (per mo.)</span></div>");
		}
	});
	
	$("input[name='subscription[customer_attributes][componentStorage]']").keyup(function(){
		isNumber($(this), 100000);
		$sum=0;
		$sum=$("input#componentStoragePrice").val()*$(this).val();
		$("input[name='subscription[customer_attributes][componentStorageAmount]']").val($sum);	
		if($(this).val()>0){
			$("span#componentStorageAmount").html("(+ $" + number_format($sum, 2, ".", ",") + " once)");
			$("h3#blockStorageToUpgrade").show();			
			$("span#storageToUpgrade").html($(this).val() + " mb ($" + number_format($sum, 2, ".", ",") + " once)");
		}else{
			$("span#componentStorageAmount").html("");
			$("h3#blockStorageToUpgrade").hide();
			$("span#storageToUpgrade").html("");
		}
		var selectedPackageValue =$("select[name='subscription[customer_attributes][package]'] option:selected").val();
		var allTotal=0;
		var allTotalComponent=0;
		if($("select[name='subscription[customer_attributes][package]']").length>0){
		allTotal +=parseFloat($("input[name='productPrice[" + selectedPackageValue + "]']").val()/100);
		}
		if($("input[name='subscription[customer_attributes][componentStorageAmount]']").length>0){
		allTotalComponent +=parseFloat($("input[name='subscription[customer_attributes][componentStorageAmount]']").val());
		}
		if($("input[name='subscription[customer_attributes][componentAgentAmount]']").length>0){
		allTotalComponent +=parseFloat($("input[name='subscription[customer_attributes][componentAgentAmount]']").val());
		}
		if(allTotalComponent>0){
			$("h3#totalToUpgrade").html("<div>Total: $" + number_format(allTotal, 2, ".", ",") + "<span class='small'> (per mo.)</span></div><div class='small'>Additionals: $" + number_format(allTotalComponent, 2, ".", ",") + "<span class='small'> (once)</span></div>");
		}else{
			$("h3#totalToUpgrade").html("<div>Total: $" + number_format(allTotal, 2, ".", ",") + "<span class='small'> (per mo.)</span></div>");
		}
		
	});
	
	$("input[name='subscription[customer_attributes][agents]']").keyup(function(){
		isNumber($(this), 600);
		$sum=0;
		$sum=$("input#componentAgentPrice").val()*$(this).val();
		$("input[name='subscription[customer_attributes][componentAgentAmount]']").val($sum);		
		if($(this).val()>0){
			$("span#componentAgentAmount").html("(+ $" + number_format($sum, 2, ".", ",") + " once)");
			$("h3#blockAgentToUpgrade").show();
			$("span#agentToUpgrade").html($(this).val() + " ($" + number_format($sum, 2, ".", ",") + " once)");
		}else{
			$("span#componentAgentAmount").html("");
			$("h3#blockAgentToUpgrade").hide();
			$("span#agentToUpgrade").html("");
		}	
		var selectedPackageValue =$("select[name='subscription[customer_attributes][package]'] option:selected").val();
		var allTotal=0;
		var allTotalComponent=0;
		if($("select[name='subscription[customer_attributes][package]']").length>0){
			allTotal +=parseFloat($("input[name='productPrice[" + selectedPackageValue + "]']").val()/100);
		}
		if($("input[name='subscription[customer_attributes][componentStorageAmount]']").length>0){
			allTotalComponent +=parseFloat($("input[name='subscription[customer_attributes][componentStorageAmount]']").val());
		}
		if($("input[name='subscription[customer_attributes][componentAgentAmount]']").length>0){
			allTotalComponent +=parseFloat($("input[name='subscription[customer_attributes][componentAgentAmount]']").val());
		}
		if(allTotalComponent>0){
			$("h3#totalToUpgrade").html("<div>Total: $" + number_format(allTotal, 2, ".", ",") + "<span class='small'> (per mo.)</span></div><div class='small'>Additionals: $" + number_format(allTotalComponent, 2, ".", ",") + "<span class='small'> (once)</span></div>");
		}else{
			$("h3#totalToUpgrade").html("<div>Total: $" + number_format(allTotal, 2, ".", ",") + "<span class='small'> (per mo.)</span></div>");
		}
	});
	
	$("div#action_button_upgrade_account").click(function(){
		$("#hosted-upgrade-form").submit();
	});
	$("#hosted-upgrade-form").submit(function(e){
		e.preventDefault();		
		switch($("input#product_id", this).val()){
			case "80000":
			validateFormFree("80000");
			break;			
		}		
		//return false;		
	});
	
	if($("ul#affTabs li a").length>0){
		var hash=(window.location.hash!="")?window.location.hash.substring(1):"myTrackingLinks";
		$("ul#affTabs li a[href='#" +hash+ "']").addClass("hoveratag");
		$("div#" + hash).show();
	}
	
	$("ul#affTabs li a:not(.realLink)").click(function(e){		
		//e.preventDefault();
		$("ul#affTabs li a").removeClass("hoveratag");
		$("div.tabs").hide();
		$(this).addClass("hoveratag");
		$("div#" + $(this).attr("href")).show();
	});
	
	if($("div.affiliateLink input.mf-submit").length>0){
		$("div.affiliateLink input.mf-submit").zclip({
				path: "../wp-content/themes/responseque_reloaded/js/ZeroClipboard.swf",
				copy: function(){
				return $(this).prev().val();
			}
		});
	}
		
});


function number_format (number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');
    // *    returns 13: '100 050.00'
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
