/**
*
* Functions for dynamically changing the shipping, shipping labels and totals
*/

var merchTotal = 0.00;
var discount = 0.00;
var grandTotal = 0.00;
var shipMethods = new Array();
var labelFmt = "Shipping with {shipMethod}";
var shipHeaderFmt = "ESTIMATE WITH {shipMethod}";
var curShipId = null;

/**
* Represents a shipping method
*/
function shipMethod(shipId, shipLabel, shipDescription, shipAmount) {
	this.shipId = shipId;
	this.shipLabel = shipLabel;
	this.shipDescription = shipDescription;
	this.shipAmount = shipAmount;
}

function changeSpShar(shipId) { /// to remove the $ from displayed price
	     curShipId = shipId; 
	     if(curShipId !=null){
		    document.getElementById(curShipId).innerHTML = document.getElementById(curShipId).innerHTML.replace('$', '');	
		 }
}	  

function changeShipMethod(shipId, shipHeaderLabelElementId, shipLabelElementId, shipAmtElementId, totalElementId, freeShip) {
	 changeSpShar();
	curShipId = shipId;
	var curMethod = shipMethods[shipId];
	if(curMethod != null) {
		var shipMethodLabel = curMethod.shipLabel;
		var newGrandTotal = formatCurrency(merchTotal - discount + curMethod.shipAmount);
		var shipLabel = labelFmt.replace("{shipMethod}", shipMethodLabel);
		if (shipMethodLabel.replace(/^\s+|\s+$/g,"") == "USPS") {
			shipMethodLabel = "USPS STANDARD";
		}
		var shipHeader = shipHeaderFmt.replace("{shipMethod}", shipMethodLabel.toUpperCase());
		if(shipHeader.indexOf('&TRADE;') != -1){
			shipHeader = shipHeader.replace('&TRADE;', '&trade;')
		}
		if (freeShip) {
			shipLabel = "Free Shipping";
			shipHeader = "FREE SHIPPING";
		}
		var shipPrice = formatCurrency(curMethod.shipAmount);
		if(shipPrice == '0.00'){
			document.getElementById(shipAmtElementId).innerHTML = 'Free';
		}else{
			document.getElementById(shipAmtElementId).innerHTML = shipPrice ;
		}
		document.getElementById(totalElementId).innerHTML = newGrandTotal;
		document.getElementById(shipLabelElementId).innerHTML = shipLabel;
		document.getElementById(shipHeaderLabelElementId).innerHTML = shipHeader;
	}
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') /*+ '$'*/ + num + '.' + cents);
}
/**
*
* Functions for Changing the addresses on the shipping bag when a new
* address is selected from the drop down list.
*/


var tempAddr;
var tempComp;
var tempLabel;
var addrItem;
var oldIndex = -1;
var addressList = new Array();
function address()
{
	this.Id = "";
	this.label ="";
	this.titleCode = "";
	this.firstName = "";
	this.lastName = "";
	this.middleName = "";
	this.company ="";
	this.address1 = "";
	this.address2 = "";
	this.address3 = "";
	this.city = "";	
	this.state_cd ="";
	this.country_cd = "";
	this.postal = "";
	this.phone ="";
	this.nightPhone ="";
}


function shipping_change() 
{
	var f = document.shipping_address;
	var addressSelect = f.selectAddressList;
	var newIndex = addressSelect.selectedIndex;
    if (newIndex == oldIndex)
    {
	    return;
	}
    oldIndex = newIndex;
	var selectedValue = addressSelect.options[newIndex].value;
	if (newIndex == 0)
    {
        alert("Please Select From One Available Option");
        return false;
    }
	if (newIndex == 1)
    {
	    
	    f["ADDRESS::firstName"].value = "";
	    f["ADDRESS::lastName"].value = "";
	    f["ADDRESS::ATR_CompanyName"].value="";
	    f["ADDRESS::address1"].value = "";
	    f["ADDRESS::address3"].value = "";
	    f["ADDRESS::city"].value = "";
	    f["ADDRESS::postal"].value = "";
	    
	    f["DayPhone1"].value ="";
	    f["DayPhone2"].value="";
	    f["DayPhone3"].value="";
	    
        f["NightPhone1"].value ="";
        f["NightPhone2"].value="";
        f["NightPhone3"].value="";
        
	   	if( f["ADDRESS::ATR_CustomerTitleCode"].options.length >0)
	    	f["ADDRESS::ATR_CustomerTitleCode"].options[0].selected = true;
	    if( f["ADDRESS::state_cd"].options.length >0)
		    f["ADDRESS::state_cd"].options[0].selected = true;
		if( f["ADDRESS::country_cd"].options.length >0)
		   f["ADDRESS::country_cd"].options[0].selected = true;
        return;
	}

    for (var i=0; i < addressList.length; i++)
    {
          if (selectedValue == addressList[i].Id)
          {
              
	       	  f["ADDRESS::firstName"].value = addressList[i].firstName;
			  f["ADDRESS::lastName"].value = addressList[i].lastName;
			  f["ADDRESS::ATR_CompanyName"].value = addressList[i].company;
			  f["ADDRESS::address1"].value = addressList[i].address1;
			  f["ADDRESS::address3"].value = addressList[i].address3;
			  f["ADDRESS::city"].value = addressList[i].city;
			  f["ADDRESS::postal"].value = addressList[i].postal;
			  
			  if(addressList[i].phone != ""){
			      f["DayPhone1"].value =addressList[i].phone.substring(0, 3);
			      f["DayPhone2"].value=addressList[i].phone.substring(3, 6);
			      f["DayPhone3"].value=addressList[i].phone.substring(6, 10);
			  }
		        
		        if(addressList[i].nightPhone != ""){
    		        f["NightPhone1"].value =addressList[i].nightPhone.substring(0, 3);
    		        f["NightPhone2"].value=addressList[i].nightPhone.substring(3, 6);
    		        f["NightPhone3"].value=addressList[i].nightPhone.substring(6, 10);
		        }
		        
			  for (var j = 0; j < f["ADDRESS::ATR_CustomerTitleCode"].options.length; j++) 
              {
                  if (f["ADDRESS::ATR_CustomerTitleCode"].options[j].value == addressList[i].titleCode) 
                  {
                      f["ADDRESS::ATR_CustomerTitleCode"].options[j].selected = true;
                      break;
                  }
              }
              for (var j = 0; j < f["ADDRESS::state_cd"].options.length; j++) 
              {
                  if (f["ADDRESS::state_cd"].options[j].value == addressList[i].state_cd) 
                  {
                      f["ADDRESS::state_cd"].options[j].selected = true;
                      break;
                  }
              }
              
              for (var j = 0; j < f["ADDRESS::country_cd"].options.length; j++) 
              {
                  if (f["ADDRESS::country_cd"].options[j].value == addressList[i].country_cd) 
                  {
                      f["ADDRESS::country_cd"].options[j].selected = true;
                      break;
                  }
              } 
              
              break;              
          }//if
     }//for    
 }
 
/**
*
* Functions for Changing the addresses on the shipping bag when a new
* address is selected from the drop down list.
*/
var submitVal = "";
function enable_gift_message()
{
	document.getElementById("ORDER<>ATR_OrderComments").disabled=false;
}
function disable_gift_message()
{
	document.getElementById("ORDER<>ATR_OrderComments").value="";
	document.getElementById("ORDER<>ATR_OrderComments").disabled=true;
}

function limitText(id, limitNum) {
	var limitField = document.getElementById(id);
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	}
}

function set_submit_action(action_name)
{
    
    if(action_name == 'SHIP_TO_BILL')
    {
        submitVal="ship_to_billing_address" ;
        submitFormAction="/checkout/order_review.jsp";
    }
    if(action_name == 'SHIP_TO_OTHER')
    {
        submitVal="ship_to_another_address" ;
        submitFormAction="/checkout/shipping_address.jsp";
    }
    if(action_name == 'MULTI_SHIP')
    {
        submitVal = "ship_to_multiple_address" ;
        submitFormAction="/checkout/multiple_shipping.jsp";
    }
}
function set_submit_input_values ()
{
   var loginPrefix = "";
   
   if(document.getElementById("loginPassword"))
       if(document.getElementById("loginPassword").value != "")
           loginPrefix="_new_acct";
   
   document.getElementById("bmSubmit").value=submitVal +loginPrefix;
   document.getElementById("bmAction").value=submitVal +loginPrefix;
}

function submitForm()
{
    set_submit_input_values();
    var form = document.getElementById("billing_address");
    form.action = submitFormAction;
    form.submit();
}

function prepareForm()
{
    set_submit_input_values();
    var form = document.getElementById("billing_address");
    form.action = submitFormAction;
}

/**
*
* Functions for multiple shipping
*/

function multi_shipping_change(id)
{
    //checkif add new address is selected
    var addrCtrl = document.getElementById("selectAddressList"+id);
	var selIndex =addrCtrl.selectedIndex;
    var selValue = addrCtrl.options[selIndex].value;
	if(selValue==0)
	{
		document.multiple_shipping.action = "/checkout/shipping_address.jsp";
		document.multiple_shipping.submit();
	}
}

function setActionSubmitForm(formName, action, useSSL) {
	var form = document.forms[formName];
	var prefix = "https://";
	if(useSSL != null && useSSL == "false") {
		prefix = "http://";
	}
	var pHost = document.location.host;
	var inx = pHost.indexOf(":");
	if(inx > -1 && prefix == "https://") {
		//This is a just for local environments not prod.
		pHost = pHost.substring(0,inx) + ":8" + pHost.substring(inx+2);
	}
	
	if(form != null) {
		var fullAction = prefix + pHost + action;
		form.action = fullAction;
		return true;
	}
	return false;
}


