/* ###########################################################

   Pricing

 * ########################################################### */

function calculatePrice() {

   var debug = 0;   
   
   // Get the initial base price
   var styleNode = xmlStyle.documentElement;
   var initialTotal = 0;
   
   // Get a list of all of the forms
   var formNodes = xmlStyle.getElementsByTagName("form");
   
   /* Iteration 1
    * 
    * In this iteration, we will go through and fill up all of the hidden price fields
    * with the currently selected price. This interation DOES NOT CARE about multipliers.
    * We look at the multipliers in the second iteration
    */
   for (var i=0; i < formNodes.length; i++) {
      var formName = fetchAttributeFromNode(formNodes.item(i),'id');
      // Lets go through each field on the form
      for (var x=0; x < formNodes.item(i).childNodes.length; x++) {
         var fieldName       = fetchAttributeFromNode(formNodes.item(i).childNodes.item(x),'id');
         var hiddenFieldName = fetchAttributeFromNode(formNodes.item(i).childNodes.item(x),'pricefield');
         var hiddenFieldObj  = document.forms[formName].elements[hiddenFieldName];

         if (fieldName && hiddenFieldName) {
            hiddenFieldObj.value = fetchAttributeFromSelectedFormElement(formName,fieldName,"price");

            // The pricecontrol field is use for setting the price to zero IF the control field is not checked
            var priceControlField  = fetchAttributeFromNode(formNodes.item(i).childNodes.item(x),'pricecontrol');
            if (priceControlField) {
               // See if the control field is OFF (ie not checked).
               // If it is off, then we must zero the hidden price field
               var priceControlObj  = document.forms[formName].elements[priceControlField];
               if (priceControlObj.checked == false) {
                  hiddenFieldObj.value = 0;
               }
               
            }
            
            initialTotal += parseFloat(hiddenFieldObj.value);
            
         }
            
      }

}

   //DEBUG*alert("Initial total before multipliers: $" + initialTotal);

   /* Iteration 2
    * 
    * In this iteration, we will go through and process any multipliers
    */

   for (var i=0; i < formNodes.length; i++) {
      var formName = fetchAttributeFromNode(formNodes.item(i),'id');
      // Lets go through each field on the form
      for (var x=0; x < formNodes.item(i).childNodes.length; x++) {
         var fieldName       = fetchAttributeFromNode(formNodes.item(i).childNodes.item(x),'id');
         //If the above call returns false, then there is no action to take with this node
         if(fieldName == false) { continue; }
         
         // The pricecontrol field is use for setting the price to zero IF the control field is not checked
         var priceControlField  = fetchAttributeFromNode(formNodes.item(i).childNodes.item(x),'pricecontrol');
         if (priceControlField) {
            // See if the control field is OFF (ie not checked).
            // If it is off, then continue as the price field is already zero and we will not worry about multipliers
            var priceControlObj  = document.forms[formName].elements[priceControlField];
            if (priceControlObj.checked == false) {
               continue;
            }
         }
         

         // Lets see if there are any multipliers for the selected item.
         // If there are, then we must do the calculations
         var fieldNode = fetchNodeFromSelectedFormElement (formName,fieldName);
         // If there are no childNodes, continue with the  form element
         if (!fieldNode.childNodes) continue;
         for (y=0; y < fieldNode.childNodes.length; y++) {
            // Get the multipliers node as we will be working with it
            var multipliersNode = fieldNode.childNodes.item(y);
            // Get the multipler form and field
            var mulForm  = fetchAttributeFromNode (multipliersNode,"form");
            var mulField = fetchAttributeFromNode (multipliersNode,"field");
            // Great, now we need to iterate through each possible multipler and see
            // if it is relevant for us to use
            for (n=0; n < multipliersNode.childNodes.length;n++) {
               // Get the multipler node so we can work with it
               var multiplierNode = multipliersNode.childNodes.item(n);
               // Put all of the values of this multipler into variables for our easy reference
               var mulValue = fetchAttributeFromNode (multiplierNode,"value");
               var chkForm  = fetchAttributeFromNode (multiplierNode,"chkform");
               var chkField = fetchAttributeFromNode (multiplierNode,"chkfield");
               var chkValue = fetchAttributeFromNode (multiplierNode,"chkvalue");
               
               // First thing we check is if the chkValue is a *.
               // If so, then we apply this multiplier
               // OR; If the exact check works out to be true, then apply the multiplier
               if ((chkValue == "*") || (chkValue == (fetchAttributeFromSelectedFormElement (chkForm,chkField,"value")))) {
                  // Work out multipler and break out of for loop
                  var hiddenFieldName = fetchAttributeFromFormField (mulForm,mulField,"pricefield");
                  var hiddenFieldObj  = document.forms[mulForm].elements[hiddenFieldName];
                  var previousPrice   = hiddenFieldObj.value;
                  if (multiplierNode.nodeName == "multiplier" || multiplierNode.nodeName == "multiplication") {
                     hiddenFieldObj.value = parseFloat(hiddenFieldObj.value) * parseFloat(mulValue);
                  } else if (multiplierNode.nodeName == "addition") {
                     hiddenFieldObj.value = parseFloat(hiddenFieldObj.value) + parseFloat(mulValue);
                  } else if (multiplierNode.nodeName == "subtraction") {
                     hiddenFieldObj.value = parseFloat(hiddenFieldObj.value) - parseFloat(mulValue);
                  } else if (multiplierNode.nodeName == "division") {
                     hiddenFieldObj.value = parseFloat(hiddenFieldObj.value) / parseFloat(mulValue);
                  }
                  //debugMessage(debug,"calculatePrice", mulForm + " : " + mulField + "  Previous price: " + previousPrice + " \tType: " + multiplierNode.nodeName + "\tValue: " + mulValue + "\tNew price: " + hiddenFieldObj.value);
                  break;
               }

            }     
         }
      }
   }
   
   // We have now gone through and updated all price fields to include changes by the multiplers.
   // Now, add up all of the totals to get the final price.
   var total = 0;
   for (var i=0; i < formNodes.length; i++) {
      var formName = fetchAttributeFromNode(formNodes.item(i),'id');
      // Lets go through each field on the form
      for (var x=0; x < formNodes.item(i).childNodes.length; x++) {
         var hiddenFieldName = fetchAttributeFromNode(formNodes.item(i).childNodes.item(x),"pricefield");
         var hiddenFieldObj  = document.forms[formName].elements[hiddenFieldName];
         // Make sure that we are only trying to add numbers together to get the total.
         if ((hiddenFieldObj) && !(isNaN(hiddenFieldObj.value))) {
            total += parseFloat(hiddenFieldObj.value);
         }
      }
   }
         
   // Need to round the total off to nearest dollar amount
   total = Math.round(total);
   
   return(total); 
      
}


function buyRing() {

	if (saveXML('buy') == 1) {	
		
		//alert('The ring is saved, it\'s id was: ' + global_ring_design + ' and is now ' + document.all.xmlDesign.getElementsByTagName("ring_design")[0].getAttribute("id") + '. Now we need to do the next step');

      global_ring_design = document.all.xmlDesign.getElementsByTagName("ring_design")[0].getAttribute("id");
	   orderFormStd.submit();
         
   } else {
		
		alert("You ring could not be saved, please correct the errors shown before continuing");
		
	}

}

function save_ring_design(action, ring_design_xml) {
  //Action MUST be either buy or save
  var xmlDoc = document.all.xmlDesign;
  var ring_designs = xmlDoc.getElementsByTagName("ring_design");
  
  if (validateAddress(document.getElementById(action + "_username").value) == false) {
    ring_message(action,0,"Invalid email address");
	 return 0;
  };
  
  //IF the email address is public@gilletts.com.au then add in request attribute customerid= to override for the save
  //This allows us to load the ring as one person and save as public2gilletts.com.au
    
  var req = new phpRequest();
  req.add('action',action);
  req.add('username',document.getElementById(action + "_username").value);
  req.add('password',document.getElementById(action + "_password").value);
  req.add('name',document.getElementById(action + "_name").value);
  req.add('comments',document.getElementById(action + "_comments").value);
  req.add('state',ring_designs[0].getAttribute("state"));
  req.add('style',ring_designs[0].getAttribute("style"));
  req.add('ring_design',ring_designs[0].getAttribute("id"));
  req.add('save_copy',document.getElementById(action + "_copy").checked == true ? 1 : 0);
  req.add('ring_design_xml',ring_design_xml.xml);

  var response = req.execute();
  var message_node = response.documentElement.getElementsByTagName("message").item(0);
  var text = message_node.childNodes(0).childNodes(0).nodeValue;
  var status = message_node.childNodes(1).childNodes(0).nodeValue;
  ring_message(action,status,text);
  
  var pos = text.indexOf('password');
  if (pos > 1) {
	   display(action + "_password"); 
	   document.getElementById(action + "_password").value = "";
  } else {
		nodisplay(action + "_password"); 
  }
  
  if ((status == 1)){
	
	   global_username = document.getElementById(action + '_username').value;
   	global_username = document.getElementById(action + '_username').value;

		if (document.getElementById(action + '_remember_me').checked == 1) {
		   if (global_username != "public@gilletts.com.au") registerCookie("store_username",global_username);
		} else {
			deleteCookie("store_username");
		}
		var ringDesignNodes = response.getElementsByTagName("ring_design");  // Grab all of the ring_design nodes from the XML
      document.all.xmlDesign.loadXML(ringDesignNodes[0].xml);  // Set the design XML to be node XML as extracted above
	   setDesignFormFields();
				
  }
  
  return status;
		
}

function validateEmailAddress(theemail,action) {
	
	if (validateAddress(theemail) == false) {
  
		ring_message(action,0,"Invalid email address");
		return 0;
		
	} else {
  	
		if (theemail  == "public@gilletts.com.au") {
			
			document.getElementById(action + "_overwrite").disabled = false;
			document.getElementById(action + "_overwrite").checked = true;
			
			display(action + "_password"); 
			document.getElementById(action + "_password").value = "";
			
					
		} else {
			
			//setDesignFormFields();
			
		}
		
	}
	
	
}


function checkPrice () {
   var debug = 0;
   if (recalcPriceNow) {
      if (elapsedTime() > 3) {
         var normalPrice = calculatePrice();
         setFieldValue("goForm","normalPrice",normalPrice);
         //debugMessage(debug,"checkPrice","New price: " + newPrice + " Elasped time:" + elapsedTime());
         var price;

         price = Math.round(normalPrice*cur_exchange_rate); // Convert the price
         priceDiv.innerHTML = cur_symbol_left + price + cur_symbol_right; // Display the converted price

         setFieldValue("goForm","convertedPriceCurrency",cur_isocode);
         setFieldValue("goForm","convertedPriceSymbol",cur_symbol_left);
         setFieldValue("goForm","convertedPrice",price);
         
         // Set the pricing information in the buy design forms
         document.getElementById("buy_buybutton").value = "Buy Now";
			document.getElementById("buy_buybutton").disabled = false;
         setFieldValue("orderFormStd","products_price",normalPrice);
         
         setNiceXML();         

         recalcPriceNow = false;
         resetTimer();
      }
   }
   
   setTimeout("checkPrice()",2000);

}



