/* ###########################################################

   XML Utilities
   
 * ########################################################### */


/* ****************************************************************************
*  fetchAttributeFromSelectedFormElement (formName,fieldName,attr)           
*
*  Returns the value of the attr attribute that is on the form formName
*  for the currently selected fieldName. Or, false if it can't find it.
*
*  formName   : The name of the form that contains the field
*  fieldName  : The name of the field
*  attr       : The name of the attribute you wish to get. e.g. size
*
********************************************************************************/

function fetchAttributeFromSelectedFormElement(formName,fieldName,attr) {

   node = fetchNodeFromSelectedFormElement (formName,fieldName);
   return(fetchAttributeFromNode(node,attr));

}

/* ****************************************************************************
*  fetchNodeFromSelectedFormElement (formName,fieldName)           
*
*  Returns the node that is on the form formName
*  where the fieldName value is fieldValue. Or, false if it can't find it.
*
*  formName   : The name of the form that contains the field
*  fieldName  : The name of the field
*
********************************************************************************/

function fetchNodeFromSelectedFormElement(formName,fieldName) {
   // Get a list of all of the forms
   
   var formNodes = xmlStyle.getElementsByTagName("form");
   var nodes = fetchChildren(formNodes, "id", formName);
   nodes = fetchChildren(nodes, "id", fieldName);

   return(fetchNode(nodes, "value", getFieldValue (formName,fieldName)));
   
}


/* ****************************************************************************
*  fetchAttributeFromFormField (formName,fieldName,attr)           
*
*  Returns the attribute from the field fieldName on the form formName.
*
*  formName   : The name of the form that contains the field
*  fieldName  : The name of the field
*  attr       : The name of the attribute you wish to get. e.g. pricefield
*
********************************************************************************/

function fetchAttributeFromFormField(formName,fieldName,attr) {
   // Get a list of all of the forms
   var formNodes = xmlStyle.getElementsByTagName("form");
   var nodes = fetchChildren(formNodes, "id", formName);
   node = fetchNode(nodes, "id", fieldName);
   return(fetchAttributeFromNode(node, attr));
}


/* ****************************************************************************
*  fetchChildren(nodes, attr, attrValue)           
*
*  Returns all of the childNodes when the attribute attr matches attrValue
*
*  node       : The node that we will be searching through
*  attr       : The name of the the attribute that we want the match to occur on
*  attrValue  : The value that the attribute must equal
*
********************************************************************************/

function fetchChildren(nodes, attr, attrValue) {

   for (var i=0; i < nodes.length; i++) {
      if (!nodes.item(i).attributes) continue;
      if (nodes.item(i).attributes.getNamedItem(attr).value == attrValue) {
         return (nodes.item(i).childNodes);
      }
   }
   
   return false;
}

/* ****************************************************************************
*  fetchNode(nodes, attr, attrValue)           
*
*  Returns the node where attr equals attrValue
*
*  nodes      : The nodes that we will be searching through
*  attr       : The name of the the attribute that we want the match to occur on
*  attrValue  : The value that the attribute must equal
*
********************************************************************************/

function fetchNode(nodes, attr, attrValue) {

   for (var i=0; i < nodes.length; i++) {
      if (!nodes.item(i).attributes) continue;
      if (nodes.item(i).attributes.getNamedItem(attr).value == attrValue) {
         return (nodes.item(i));
      }
   }
   
   return false;
}

/* ****************************************************************************
*  fetchAttributeFromNodesChild(node, attr, matchAttr, matchAttrValue)           
*
*  Given a node, it searches through its children until the attribute
*  matchAttr equals matchAttrValue. Then, it returns the value that is
*  in the attribute attr. Returns the value of the attribute (if found), otherwise returns false.
*
*  node       : The node that we will be searching through
*  attr       : The name of the the attribute that you want to know the value of
*  matchAttr  : The attribute that will be used for the condition
*  matchAttrValue : The value that matchAttr must equal
*
********************************************************************************/

function fetchAttributeFromNodesChild(node, attr, matchAttr, matchAttrValue) {

   for (var i=0; i < node.length; i++) {
      if (fetchAttributeFromNode(node.item(i),matchAttr) == matchAttrValue)
         return(fetchAttributeFromNode(node.item(i),attr))     
   }
   
   return false;
}

/* ****************************************************************************
*  fetchAttributeFromNode (node,attr)           
*
*  Given a node, it returns the passed in attributes attr value. If it doesn't
*  have any attributes, then returns false.
*
*  node       : The node that we will be checking the attribute for
*  attr       : The name of the the attribute that you want to know the value of
*
********************************************************************************/

function fetchAttributeFromNode (node,attr) {
   if (node.attributes && node.attributes.getNamedItem(attr)) { // Test to make sure that this attribute exists
      return node.attributes.getNamedItem(attr).value
   } else {
      return false;
   }  
}

/* ****************************************************************************
*  setAttributeFromNode (node,attr,value)           
*
*  Given a node, it sets the attr to the passed in value. If it doesn't
*  have any attributes, then returns false.
*
*  node       : The node that we will be setting the attribute for
*  attr       : The name of the the attribute that you want to set
*  value      : The value you wish to set the attr to
*
********************************************************************************/

function setAttributeFromNode (node,attr,value) {
   if (node.attributes && node.attributes.getNamedItem(attr)) { // Test to make sure that this attribute exists
      node.attributes.getNamedItem(attr).value = value;
      return true;
   } else {
      return false;
   }  
}

/* ****************************************************************************
*  saveXML ()
*
*  Creates the XML needed to save the current design into the saveXML object
*
********************************************************************************/
function saveXML(action) {

   var debug=0;

   updateXMLFromForm();
   var xmldoc = document.all.xmlDesign;
   debugMessage(debug,'start',xmldoc.xml);
   var ringDesignNode = xmldoc.getElementsByTagName("ring_design")[0];  // Grab the first (and only) ring_design node
   //Delete all the children of the ring design - i.e we have no settings   
   while (ringDesignNode.childNodes[0]) {
     ringDesignNode.removeChild(ringDesignNode.childNodes[0]);
   }
   
    debugMessage(debug,'removed',xmldoc.xml);
   // All of the element types to save
   var elementsArr = new Array("dropdown","checkbox","hidden");

   var xmlSave = new ActiveXObject("Microsoft.XMLDOM");

   baseNode = xmldoc.createElement("ring_design");   
   xmlSave.appendChild(baseNode);
   rootSaveNode = xmlSave.documentElement;
   
   var styleNode = xmlStyle.documentElement; // We are going to get all of the values from here

   for (counter in elementsArr) {

      var currentElement = elementsArr[counter];
      var elementNodes = xmlStyle.getElementsByTagName(currentElement);   
      for (var i=0; i < elementNodes.length; i++) {
         // Get all of the info that we may want
         var id  = fetchAttributeFromNode(elementNodes.item(i),'id');
         var def = fetchAttributeFromNode(elementNodes.item(i),'default');
         var val = fetchAttributeFromNode(elementNodes.item(i),'value');
                  
         var newNode = xmldoc.createElement(currentElement);
         var newNode2 = xmldoc.createElement(currentElement);
         
         if (id)  newNode.setAttribute('id',id);
         if (def) newNode.setAttribute('default',def);
         if (val) newNode.setAttribute('value',val);
         
         if (id)  newNode2.setAttribute('id',id);
         if (def) newNode2.setAttribute('default',def);
         if (val) newNode2.setAttribute('value',val);
            
         ringDesignNode.appendChild(newNode);
         rootSaveNode.appendChild(newNode2);
         
      }

   }
      
   if (action == "save_xml_only") {
      //document.all.xmlDesign.loadXML(xmldoc.xml);
      return;
   }
   
   //debugMessage(1,action,document.all.xmlDesign.xml);

	
   var status = save_ring_design(action,xmlSave); // Performs the save ring
   
   if (status == 1) { // If the save ring is OK, then let them buy it
   
		// Set all of the shopping cart form variables 
		setFieldValue("orderFormStd","id[txt_4]"," Design name: " + document.getElementById('buy_name').value + " --- Design ID: CR" + document.all.xmlDesign.getElementsByTagName("ring_design")[0].getAttribute("id") 
		              + " --- Email: " + global_username + " --- Ring size: " + getFieldDisplay("UI_ringSize"));
		
		// AFTER the save has sucessfully occured, we want to now load up all of the clients
		// designs into the My Designs section

		document.getElementById('buy_username').value = global_username;
		document.getElementById('buy_password').value = global_password;
		
		document.getElementById('load_username').value = global_username;
		document.getElementById('load_password').value = global_password;
		loadDesigns();		
		
	}
   
   return status;
	
}

/* ****************************************************************************
*  setDesignXML ()
*
*  Grabs all of the options out of the design XML file and sets all of the form
*  field variables as appropriate.
*
********************************************************************************/

function setDesignXML() {

   var xmldoc = document.all.xmlDesign;
   
   // All of the element types to load
   var elementsArr = new Array("dropdown","checkbox","hidden");

   for (counter in elementsArr) {

      var currentElement = elementsArr[counter];
      var elementNodes = xmldoc.getElementsByTagName(currentElement);   
      for (var i=0; i < elementNodes.length; i++) {
         // Get all of the info that we may want
         var id = fetchAttributeFromNode(elementNodes.item(i),'id');
         var def = fetchAttributeFromNode(elementNodes.item(i),'default');
         var val = fetchAttributeFromNode(elementNodes.item(i),'value');
         
         if (id && def) {
            // Grab the object
            var fieldObj = document.getElementById(id);
            // Set the form fields value
            setFieldValue(fieldObj.form.name,id,def);
         } else if (id && val) {
            // Grab the object
            var fieldObj = document.getElementById(id);
            // Set the form fields value
            setFieldValue(fieldObj.form.name,id,val);            
         }
         
      }

   }

}


var nice_settings_xml;

function setNiceXML() {
   
   var debug = 0;
   
   saveXML('save_xml_only');

	nice_settings_xml = new ActiveXObject("Microsoft.XMLDOM");
   baseNode = nice_settings_xml.createElement("nice_settings_xml");
   nice_settings_xml.appendChild(baseNode);
   rootSaveNode = nice_settings_xml.documentElement;
	
	baseSettingsRootNode = nice_settings_xml.createElement('base_settings');
	baseSettingsRootNode = rootSaveNode.appendChild(baseSettingsRootNode);
		
	var gemstoneSizes = new Array();
	var gemstoneTypes = new Array();
	var gemstoneSettings = new Array();
	var gemstonePositionTop = new Array();
	var gemstonePositionLeft = new Array();
	var gemstoneScaleTop = new Array();
	var gemstoneScaleLeft = new Array();
	var showGemstone = new Array();
	
	var inlayMetal = new Array();
	var inlayWidth = new Array();
	var inlayOffset = new Array();
	var showInlay = new Array();
	
	var convertedPrice;
	var convertedPriceCurrency;
	var convertedPriceSymbol;
	debugMessage(debug,'setNiceXML',document.all.xmlDesign.xml);
	var dropdowns = document.all.xmlDesign.getElementsByTagName("ring_design")[0].getElementsByTagName("*");
	var idValue = new String();
	
	for (var j = 0; j < dropdowns.length; j++) {
	
		var dropdownAttributes = dropdowns[j].attributes; // Node/Element interface
		
		var idAttribute = dropdownAttributes.getNamedItem("id");
		if (idAttribute) idValue = new String(idAttribute.value);
		
		var nodeText = getFieldDisplay(idValue);
    //  alert(nodeText);
            
		//var defaultAttribute = dropdownAttributes.getNamedItem("default");
		//if (defaultAttribute) nodeText = new String(defaultAttribute.value);

		//var valueAttribute = dropdownAttributes.getNamedItem("value");
		//if (valueAttribute) nodeText = new String(valueAttribute.value);
		
		if (idValue == "ringWidth" || idValue == "finish" || idValue == "titaniumColor" || idValue == "edges") {
			baseSettingsRootNode.appendChild(nice_settings_xml.createElement(idValue)).appendChild(nice_settings_xml.createTextNode(nodeText));
		}
		
		// Ringsize is treated differently because there are different sizes for different countries
		if (idValue == "ringSize") {
		   baseSettingsRootNode.appendChild(nice_settings_xml.createElement(idValue)).appendChild(nice_settings_xml.createTextNode(getFieldDisplay('UI_ringSize')));
		}	
		
		
		if ((idValue == "normalPrice") && (parseInt(nodeText) > 1)) baseSettingsRootNode.appendChild(nice_settings_xml.createElement(idValue)).appendChild(nice_settings_xml.createTextNode('AU $ ' + nodeText));
		if (idValue == "convertedPrice") convertedPrice = nodeText;
		if (idValue == "convertedPriceCurrency") convertedPriceCurrency = nodeText;
		if (idValue == "convertedPriceSymbol") convertedPriceSymbol = nodeText;
		
		if (/gemstone/i.test(idValue)) {
				var length = idValue.length -1;
				var id = idValue.substring(length);
				var what = idValue.substring(0,length);
				
				if (what == "gemstoneSize") {
			
								gemstoneSizes[id] = nodeText;
            				
				} else if (what == "gemstoneType") {
				
					gemstoneTypes[id] = nodeText;
				
				} else if (what == "gemstoneSetting") {
				
					gemstoneSettings[id] = nodeText;
				
				} else if (what == "gemstoneScaleTop") {
				
					gemstoneScaleTop[id] = nodeText;
					
				} else if (what == "gemstoneScaleLeft") {
				
					gemstoneScaleLeft[id] = nodeText;
					
				} else if (what == "positionTopGemstone") {
				
					gemstonePositionTop[id] = nodeText;
				
				} else if (what == "positionLeftGemstone") {
				
					gemstonePositionLeft[id] = nodeText;
					
				} else if (what == "showGemstone") {
				
					showGemstone[id] = nodeText;
					
				} else {
				
					//alert('Error: ' + what);
					
				}
						
		}
			
		if (/inlay/i.test(idValue)) {
						
			if (/Show/.test(idValue)) {
				
				pos = idValue.indexOf('Show');
				
			} else {
				
				pos = idValue.indexOf('inlay');
				
			}
				 
			var id = ucFirst(idValue.substring(0,pos));
			var what = idValue.substring(pos,idValue.length);
			
			//alert('orig ' + idValue + ' id: ' + id + ' what: ' + what + ' pos ' + pos);

			if (what == "inlayOffset") {
				
				inlayOffset[id] = nodeText;
					
			} else if (what == "inlayMetal") {

				inlayMetal[id] = nodeText;
				
			} else if (what == "inlayWidth") {
				
				inlayWidth[id] = nodeText;
			
			} else if (what == "ShowInlay") {
				
				showInlay[id] = nodeText;
			
			} else {
			
				alert('id: ' + id + ' what: ' + what + ' pos ' + pos);
				
			}
			
			
		}

  }
  
   baseSettingsRootNode.appendChild(nice_settings_xml.createElement('convertedPrice')).appendChild(nice_settings_xml.createTextNode(convertedPriceCurrency + ' ' + convertedPrice));
  
	gemstonesRootNode = nice_settings_xml.createElement('gemstones');
	gemstonesRootNode = rootSaveNode.appendChild(gemstonesRootNode);
	
	var nodesAdded = 0;
	
  for (var k = 0; k < gemstoneSizes.length; k++) {
	  
		if (showGemstone[k] == 1) {
         
         nodesAdded=1;
		
			gemstoneNode = nice_settings_xml.createElement('gemstone');
		 
			gemstoneNode.appendChild(nice_settings_xml.createElement('id')).appendChild(nice_settings_xml.createTextNode(k));
			gemstoneNode.appendChild(nice_settings_xml.createElement('type')).appendChild(nice_settings_xml.createTextNode(gemstoneTypes[k]));
			gemstoneNode.appendChild(nice_settings_xml.createElement('setting')).appendChild(nice_settings_xml.createTextNode(gemstoneSettings[k]));
			gemstoneNode.appendChild(nice_settings_xml.createElement('size')).appendChild(nice_settings_xml.createTextNode(gemstoneSizes[k]));
			gemstoneNode.appendChild(nice_settings_xml.createElement('scaleTop')).appendChild(nice_settings_xml.createTextNode(gemstoneScaleTop[k]));
			gemstoneNode.appendChild(nice_settings_xml.createElement('scaleLeft')).appendChild(nice_settings_xml.createTextNode(gemstoneScaleLeft[k]));
			gemstoneNode.appendChild(nice_settings_xml.createElement('positionTop')).appendChild(nice_settings_xml.createTextNode(gemstonePositionTop[k]));
			gemstoneNode.appendChild(nice_settings_xml.createElement('positionLeft')).appendChild(nice_settings_xml.createTextNode(gemstonePositionLeft[k]));
		 
			gemstonesRootNode.appendChild(gemstoneNode);
			
		} 
		  
  }
  
  if (nodesAdded == 0) {
     	gemstoneNode = nice_settings_xml.createElement('gemstone');
      gemstonesRootNode.appendChild(gemstoneNode);
      nodisplay("bound_gemstones");
  } else {
     display("bound_gemstones");
  }
		
	inlaysRootNode = nice_settings_xml.createElement('inlays');
	inlaysRootNode = rootSaveNode.appendChild(inlaysRootNode);
	
	nodesAdded = 0;
	
	for (k in showInlay) {
		
		if (showInlay[k] == 1) {
         
         nodesAdded = 1;
		
			newNode = nice_settings_xml.createElement('inlay');
		 
			newNode.appendChild(nice_settings_xml.createElement('id')).appendChild(nice_settings_xml.createTextNode(k));
			newNode.appendChild(nice_settings_xml.createElement('metal')).appendChild(nice_settings_xml.createTextNode(inlayMetal[k]));
			newNode.appendChild(nice_settings_xml.createElement('width')).appendChild(nice_settings_xml.createTextNode(inlayWidth[k]));
			newNode.appendChild(nice_settings_xml.createElement('offset')).appendChild(nice_settings_xml.createTextNode(inlayOffset[k]));
			
		 
			inlaysRootNode.appendChild(newNode);
			
		}  
	 
	 //alert(k + ' Size: ' + gemstoneSizes[k] + ' Type: ' + gemstoneTypes[k] + ' Setting: ' + gemstoneSettings[k]);
  
  }
	
	if (nodesAdded == 0) {
     	newNode = nice_settings_xml.createElement('inlay');
      inlaysRootNode.appendChild(newNode);
      nodisplay("bound_inlays");
   } else {
      display("bound_inlays");
   }
	
	document.all.nice_settings.loadXML(nice_settings_xml.xml);
	
	try {
      document.getObjectById("bound_gemstones").dataSrc = "#nice_settings";
   	document.getObjectById("bound_inlays").dataSrc = "#nice_settings";
	} catch(e) {
      
	}
		
}
