/* ###########################################################

   Form Utilities
   
 * ########################################################### */


function getFieldValue (form,field) {
  try {
  
  var fieldObj = document.forms[form].elements[field];
    
  switch(fieldObj.type)  {
      case "text" :
      case "textarea" :
      case "password" :
      case "hidden" :
         return fieldObj.value;

      case "select-one" :
         var i = fieldObj.selectedIndex;
         if (i == -1)   return "";
         else   return (fieldObj.options[i].value == "") ? fieldObj.options[i].text : fieldObj.options[i].value;

      case "select-multiple" :
         var allChecked = new Array();
         for(i = 0; i < fieldObj.options.length; i++)
            if(fieldObj.options[i].selected)
               allChecked[allChecked.length] = (fieldObj.options[i].value == "") ? fieldObj.options[i].text : fieldObj.options[i].value;
         return allChecked;

      case "button" :
      case "reset" :
      case "submit" :
         return "";

      case "radio" :
      case "checkbox" :
         if (fieldObj.checked) { return 1; } else { return 0; }
      default :
         if(fieldObj[0].type == "radio")
         {
            for (i = 0; i < fieldObj.length; i++)
               if (fieldObj[i].checked)
                  return fieldObj[i].value;

            return "";
         }
         else if(fieldObj[0].type == "checkbox")
         {
            var allChecked = new Array();
            for(i = 0; i < fieldObj.length; i++)
               if(fieldObj[i].checked)
                  allChecked[allChecked.length] = fieldObj[i].value;

            return allChecked;
         }
         else
            var str = "";
            for (x in fieldObj) { str += x + "\n"; }
            alert("getFieldValue: " + e.message + ' for: ' + form + '.' + field);
         break;
   }
}catch(e) {
       alert('getFieldValue: ' + e.message + ' for ' + form + '.' + field);
   }
   
   return "";
}

function getFieldDisplay (field) {
  try {
  
  var fieldObj = document.getElementById(field);
    
  switch(fieldObj.type)  {
      case "text" :
      case "textarea" :
      case "password" :
      case "hidden" :
         return fieldObj.value;

      case "select-one" :
         var i = fieldObj.selectedIndex;
         if (i == -1)  {
            return "";
         } else {
            //alert('text: ' + fieldObj.options[i].text + ' :: value: ' + fieldObj.options[i].value);         
            return (fieldObj.options[i].text != "") ? fieldObj.options[i].text : fieldObj.options[i].value;
         }

      case "select-multiple" :
         var allChecked = new Array();
         for(i = 0; i < fieldObj.options.length; i++)
            if(fieldObj.options[i].selected)
               allChecked[allChecked.length] = (fieldObj.options[i].value == "") ? fieldObj.options[i].text : fieldObj.options[i].value;
         return allChecked;

      case "button" :
      case "reset" :
      case "submit" :
         return "";

      case "radio" :
      case "checkbox" :
         if (fieldObj.checked) { return 1; } else { return 0; }
      default :
         if(fieldObj[0].type == "radio")
         {
            for (i = 0; i < fieldObj.length; i++)
               if (fieldObj[i].checked)
                  return fieldObj[i].value;

            return "";
         }
         else if(fieldObj[0].type == "checkbox")
         {
            var allChecked = new Array();
            for(i = 0; i < fieldObj.length; i++)
               if(fieldObj[i].checked)
                  allChecked[allChecked.length] = fieldObj[i].value;

            return allChecked;
         }
         else
            var str = "";
            for (x in fieldObj) { str += x + "\n"; }
            alert("getFieldDisplay: " + e.message + ' for: ' + field);
         break;
   }
}catch(e) {
       alert('getFieldDisplay: no type  ' + e.message + ' for ' + field);
   }
   
   return "";
}

function setFieldValue (form,field,value) {

   var debug = 0;   
   
   /* This handles if a field has been changed modifies the size of a VML object,
      then collision detection will occur because handleCol = true
   
      HOWEVER, we skip it if we are setting the positionTopGemstone or positionLeftGemstone fields
      because it is too much of a performance hit with them.
   
   */
   
   if ((field.substr(0,20) == "positionLeftGemstone") || 
       (field.substr(0,19) == "positionTopGemstone") ||
       (field.substr(0,17) == "gemstoneScaleLeft") ||
       (field.substr(0,16) == "gemstoneScaleTop")
       ){
      handleCol = true;
   } else {
   
      var vmlF = fetchAttributeFromFormField (form,field,"vmlvisibility");
      if (vmlF) handleCol = true;
      vmlF = fetchAttributeFromFormField (form,field,"vmlheight");
      if (vmlF) handleCol = true;
      vmlF = fetchAttributeFromFormField (form,field,"vmlwidth");
      if (vmlF) handleCol = true;
      vmlF = fetchAttributeFromFormField (form,field,"handlecol");
      if (vmlF) handleCol = true;
   } 
   
 try {
 
   // If the field is positionLeftGemstone then calculate the gemstone scale and set it
   if ((form == "gemstoneForm") && (field.substr(0,20) == "positionLeftGemstone")) {
      var gNum = field.substr(20,field.length); // Get the gemstoneNumber
      setGemstoneLeftScale(gNum,value);
   } else if ((form == "gemstoneForm") && (field.substr(0,19) == "positionTopGemstone")) {
      var gNum = field.substr(19,field.length); // Get the gemstoneNumber
      setGemstoneTopScale(gNum,value);
   }
   

   var fieldObj = document.forms[form].elements[field];

   // Set what type of field type this is so that we know how to set it
      
   switch(fieldObj.type){
      case 'radio': case 'checkbox': if(parseInt(value)){fieldObj.checked=true;return true;}else{fieldObj.checked=false;return false;}
      case 'text': case 'hidden': case 'textarea': case 'password': fieldObj.value=value;return true;
      case 'select-one': case 'select-multiple': 
         var o=fieldObj.options;
         for(var i=0;i<o.length;i++){
            if(o[i].value==value){o[i].selected=true;}
            else{o[i].selected=false;}
            }
         return true;
      default :
         alert('What type of control is this? ' + form + '.' + field + '=' + value); 
         fieldObj.value = value;
   }
   
 } catch(e) {
      alert('setFieldValue: ' + e.message + ' for form: ' + form + ' and field ' + field + '=' + value);
   }
}

function incDropdown(form,field) {
   var fieldObj = document.forms[form].elements[field];
   if (fieldObj.selectedIndex < (fieldObj.length-1)) {
      var newIndex = parseInt(fieldObj.selectedIndex) + 1;
      trackFieldForUndo(form,field);
      setFieldValue(form,field,fieldObj[newIndex].value);
   }   
}

function decDropdown(form,field) {
   var fieldObj = document.forms[form].elements[field];
   if (fieldObj.selectedIndex > 0) {
      var newIndex = parseInt(fieldObj.selectedIndex) - 1;
      trackFieldForUndo(form,field);
      setFieldValue(form,field,fieldObj[newIndex].value);
   }   
}


function changeDropdown (form,field,increment) {

   var fieldObj = document.forms[form].elements[field];

   zoom  = getFieldValue("goForm","zoom");
   xmove = parseInt((oldClientX - event.clientX)/zoom);
   ymove = parseInt((oldClientY - event.clientY)/zoom);

   if ((ymove > increment) && (fieldObj.selectedIndex > 0)) {
      decDropdown(form,field);
      redraw();
      oldClientX=event.clientX
      oldClientY=event.clientY
   } else if ((ymove < -increment) && (fieldObj.selectedIndex < (fieldObj.length-1))) {
      incDropdown(form,field);
      redraw();
      oldClientX=event.clientX
      oldClientY=event.clientY
   }

}

// Both arrays MUST be the same size!
function loadDropdown(formName,fieldName,arrValue,arrText) {
  var previousText  = '';
  var previousValue = '';

  for (i=0;i<arrValue.length;i++) {

    // If the previous option is the same as this option, skip it.
    // We have this case with fingersizes
    if (previousValue == arrValue[i] || previousText == arrText[i]) {
      previousValue = arrValue[i];
      previousText  = arrText[i];
    } else {
      previousValue = arrValue[i];
      previousText  = arrText[i];
      
      var newElem = document.createElement("OPTION");
      newElem.text = arrText[i];
      newElem.value = arrValue[i];
      document.forms[formName].elements[fieldName].options.add(newElem)
    }
  
  } 

}

// Load the values from the XML file for formName and fieldName into the GUI
// dropdown on guiFormName and field guiFieldName
function loadDropdownFromXML (formName,fieldName,guiFormName,guiFieldName) {
   var arrValue = Array();
   var arrText  = Array();

   var formNodes = xmlStyle.getElementsByTagName("form"); // Grab all forms
   var nodes = fetchChildren(formNodes, "id", formName); // Grab all of the fields in this form
   nodes = fetchChildren(nodes, "id", fieldName); // Grab all of the item options in this field

   for (var i=0; i < nodes.length; i++) { // Go through all of the items
      if (!nodes.item(i).attributes) continue;
      var value = nodes.item(i).attributes.getNamedItem("value").value; // The value of the dropdown
      var text  = nodes.item(i).attributes.getNamedItem("display").value; // What people see
      arrValue.push(value);
      arrText.push(text);
   }
   loadDropdown(guiFormName,guiFieldName,arrValue,arrText);
}


/* 
 * This function will iterate through the XML file. It will look at each form
 * element defined in the XML file and set its value to be whatever is currently
 * set on the actual form.
*/

function updateXMLFromForm () {

   var debug = 0;
   var styleNode = xmlStyle.documentElement;

   // Get a list of all of the forms
   var formNodes = xmlStyle.getElementsByTagName("form");
   
   for (var i=0; i < formNodes.length; i++) {
      var formName = fetchAttributeFromNode(formNodes.item(i),'id');
      //debugMessage(debug,"updateXMLFromForm","Form: " + formName);
      // Lets go through each field on the form
      for (var x=0; x < formNodes.item(i).childNodes.length; x++) {
         var node = formNodes.item(i).childNodes.item(x);
         var fieldName  = fetchAttributeFromNode(node,'id');
         if (!fieldName) continue; // if fetchAttributeFromNode returns false, skip this entity
         var fieldValue = getFieldValue(formName,fieldName);
         //debugMessage(debug,"updateXMLFromForm","Field: " + fieldName + "\t\tValue: " + fieldValue);
         
         var fieldObj = document.forms[formName].elements[fieldName];

         switch(fieldObj.type){
            case 'text': case 'hidden': case 'textarea': case 'password': 
               setAttributeFromNode(node,"value",fieldValue);
            case 'select-one': case 'select-multiple': case 'radio': case 'checkbox':
               setAttributeFromNode(node,"default",fieldValue);
            default :
               setAttributeFromNode(node,"value",fieldValue);
         }

      }
   }
   debugMessage(debug,"updateXMLFromForm",xmlStyle.xml);
}


// Globals used for tracking what gets set - used for undo function
var global_undo_form  = new Array();
var global_undo_field = new Array();
var global_undo_value = new Array();

function trackFieldForUndo(form,field) {
   
   if (form.substr(0,3) != "UI_") {
      // Track the previous value of this option, to support the undo function
      global_undo_form.push(form);
      global_undo_field.push(field);
      global_undo_value.push(getFieldValue(form,field));   
   }
   
}


// Undoes the previous action
function undo() {
   var debug=0;
   
   var form  = global_undo_form.pop();
   var field = global_undo_field.pop();
   var value = global_undo_value.pop();

   if (!form) return; // If it is undefined (ie nothing in the undo array), then dontt do anything

   debugMessage(debug,"undo",form + "." + field + " = " + value);

   setFieldValue(form,field,value);
   rescaleGemstones(field); // This will re-scale the gemstones if ringwidth or fingersize changes
   redraw();
   opentab(getFieldValue("UI_goForm","currentTab")); // We do this to set the GUI with the latest values
}


//Update generic form
//If we can set onChange on each element, then call a generic function which
//find out the current form name, prefix and suffix
//then updates the corresponding hidden form name / element
//Use andrews getFieldValue and setFieldValue

function updateHidden(obj, parent) {
   var debug = 0;
   // Go through all the properties of the passed-in object 
   var newform  = parent.name.substring(3);
   /* If the newform name contains an underscore, then this means that the name is:
    * form_subform - we sometimes need subforms in the case of inlays for example.
    * Hence, the name we need is the first form name. We use this code to get it
   */
   if (newform.indexOf('_') != -1) { // If we get into this if then we have an _ in the newform name
      newform = newform.substring(0,newform.indexOf('_'));
   }      
   var newfield = parent.prefix.value + obj.name.substring(3); 
   var value    = getFieldValue(parent.name,obj.name);

   // This is to handle Gemstones. We need to determine which gemstone to update the size of
   if (newfield == "gemstoneSize") {
      var which = getFieldValue("UI_gemstoneForm","suffix");
      newfield = newfield + which;
   }   

   trackFieldForUndo(newform,newfield);

   setFieldValue(newform,newfield,value);
   debugMessage(debug,"updateHidden",newform + '.' + newfield + '=' + value);

   /* The zoom factor is set by the ring width and finger size, hence if it changes, we need to recalc it.   */
   if ((newfield == "ringWidth") || (newfield == "ringSize")) {
      resetLayersAndDivs();      
   }

   rescaleGemstones(newfield);

   redraw();
   opentab(getFieldValue("UI_goForm","currentTab")); // We do this to set the GUI with the latest values
   
}


function setDesignFormFields() {

   // We do this because we do not want the public user to be displayed in the your email address field.
   // We actually want *their* email address to be displayed there
   if (global_username == 'public@gilletts.com.au') {
      if (getCookie("store_username")) {
         global_username = getCookie("store_username");
      } else {
         global_username = '';
      }
   }

	var ringDesignNode  = document.all.xmlDesign.getElementsByTagName("ring_design")[0];	

	var state = ringDesignNode.getAttribute("state");
	
	if ((state == "public") || (state == "locked")) {
	
		document.getElementById("save_overwrite").disabled = true;
		document.getElementById("save_overwrite").checked = false;
		document.getElementById("save_copy").checked = true;
		
		document.getElementById("buy_overwrite").disabled = true;
		document.getElementById("buy_overwrite").checked = false;
		document.getElementById("buy_copy").checked = true;

	} else {
	
		document.getElementById("save_overwrite").disabled = false;
		document.getElementById("save_overwrite").checked = true;
		
		document.getElementById("buy_overwrite").disabled = false;
		document.getElementById("buy_overwrite").checked = true;
		
	}
   
   // Set all of the form values in the Save Design form
   document.getElementById("save_name").value        = fetchAttributeFromNode(ringDesignNode,'name') || '';
   document.getElementById("save_comments").value    = fetchAttributeFromNode(ringDesignNode,'comments') || '';
   document.getElementById("save_username").value    = global_username;
   document.getElementById("save_password").value    = global_password;

   // Set all of the form values in the Buy Design form
   document.getElementById("buy_name").value        = fetchAttributeFromNode(ringDesignNode,'name') || '';
   document.getElementById("buy_comments").value    = fetchAttributeFromNode(ringDesignNode,'comments') || '';
   document.getElementById("buy_username").value    = global_username;
   document.getElementById("buy_password").value    = global_password;

}

