/**
 * Copyright 2006 Olivier Clavel
 *
 * This file is part of Renata Shop Website software.
 *
 * Renata Shop Website is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License,
 * or any later version.
 *
 * Renata Shop Website is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MediaNetLive portal software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @author Olivier Clavel <contact AT retiz DOT com>
 * @version $Id$
 */

/**
 * Dom parser implementation for navs where it is missing
 */
if (typeof DOMParser == "undefined") {
  DOMParser = function () {}
  
  DOMParser.prototype.parseFromString = function (str, contentType) {
    if (typeof ActiveXObject != "undefined") {
      var d = new ActiveXObject("Microsoft.XMLDOM");
      d.loadXML(str);
      return d;
    } else if (typeof XMLHttpRequest != "undefined") {
      var req = new XMLHttpRequest;
      req.open("GET", "data:" + (contentType || "application/xml") +
	       ";charset=utf-8," + encodeURIComponent(str), false);
      if (req.overrideMimeType) {
	req.overrideMimeType(contentType);
      }
      req.send(null);
      return req.responseXML;
    }
  }
 }

/**
 * document.importNode implementation for IE
 */
if(typeof document.importNode != "function"){
  document.importNode = function(importedNode, deep) {
    var newNode;
    
    if(importedNode.nodeType == 1) { // Node.ELEMENT_NODE
      newNode = document.createElement(importedNode.nodeName);
      for(var i = 0; i < importedNode.attributes.length; i++){
	var attr = importedNode.attributes[i];
	if (attr.nodeValue != null && attr.nodeValue != '') {
	  newNode.setAttribute(attr.name, attr.nodeValue);
	}
      }
      if (typeof importedNode.style != "undefined")
	newNode.style.cssText = importedNode.style.cssText;
    } else if(importedNode.nodeType == 3) { // Node.TEXT_NODE
      newNode = document.createTextNode(importedNode.nodeValue);
    }
    
    if(deep && importedNode.hasChildNodes()){
      for(var i = 0; i < importedNode.childNodes.length; i++) {
	newNode.appendChild(
			    document.importNode(importedNode.childNodes[i], true)
			    );
      }
    }
    return newNode;
  }
}

/**
 * Sets the cursor state for document and some specific elements
 *
 * @param string state The cursor state (see stylesheet definition)
 */
function setCursorState (state) {
  var form = document.getElementById("orderForm");
  if (state == 'auto') {
    buttonState = 'pointer';
  } else {
    buttonState = state;
  }
  document.body.style.cursor = state;
  if (form) {
    form.getElementsByTagName('button').item(0).style.cursor = buttonState;
  }
}

/**
 * Called when user clicks on add to cart
 */
function addToCart () {
  setCursorState('wait');
  var form = document.getElementById('orderForm');
  var clotheId = form.produit.value;
  var lang = document.body.className;
  var addUrl = '/' + lang + '/cartajax/clothe/add/' + clotheId + '/';
  addUrl += form.modele.value + '/' + form.couleur.value + '/' + form.taille.value + '/' + form.quantite.value;
  //  alert ("Url d'ajout: " + addUrl);
  form.reset();
  checkColors();
  var ajax = new GLM.AJAX();    
  ajax.callPage(addUrl, refreshCart);
}

/**
 * Clears a node from all its content
 * 
 * @param Node node The node to clear
 */
function clearNode (node) {
  while (node.firstChild) {
    node.removeChild(node.firstChild);
  }
}

/**
 * Called to delete a cart item (user clicks the link)
 *
 * @param int the item int the cart to delete
 */
function deleteCartItem (clotheId, itemNum) {
  var context;
  var form = document.getElementById('orderForm');
  if (form) {
    context = 'clothe';
  } else {
    context = 'cart';
  }
  var lang = document.body.className;
  var delUrl = '/' + lang + '/cartajax/' + context + '/delete/' + clotheId + '/' + itemNum;
  if (form) {
    form.reset();
    checkColors();
  }
  var ajax = new GLM.AJAX();
  ajax.callPage(delUrl, refreshCart);
}

/**
 * Parses a string into an xml document and returns the
 * result object.
 *
 * @param string xmlString The XML string content to parse
 */
function getXmlDocument (xmlString) {
  var myDocument; 

  var parser = new DOMParser();
  myDocument = parser.parseFromString(xmlString, "text/xml");
  return myDocument; 
}


/**
 * Updates summary cart
 *
 * @var Node content The content of the summary cart
 * @note: browser detection AND innerHTML sucks but I was short on 
 * solution to overcome a bug in safari where an imported <a> node from
 * an other xml document would not be clickable... I suspect this is a
 * Doctype/namespace issue that might be solved with document served as
 * application/xhtml+xml instead of text/html
 */
function updateSummary (newSummaryContent) {
  var summaryCart = document.getElementById('cart');
  clearNode(summaryCart);
  // Hack for Safari
  if (navigator.userAgent.indexOf("Safari") > 0) {
    var innerContent = new XMLSerializer().serializeToString(newSummaryContent);
    // Hack for Safari 1.3
    if (innerContent == undefined) {
      summaryCart.innerHTML = newSummaryConntent.innerXML();
    } else {
      summaryCart.innerHTML = new XMLSerializer().serializeToString(newSummaryContent);
    }
  } else {
    var newSummary = document.importNode(newSummaryContent, true);
    summaryCart.appendChild(newSummary);
  }
}

/**
 * Updates detailed cart
 *
 * @var Node content The content of the detailed cart
 * @note: browser detection AND innerHTML sucks but I was short on 
 * solution to overcome a bug in safari where an imported <a> node from
 * an other xml document would not be clickable... I suspect this is a
 * Doctype/namespace issue that might be solved with document served as
 * application/xhtml+xml instead of text/html
 */
function updateDetails (newCartContent) {
  var clotheCart = document.getElementById('clotheCart');
  if (clotheCart) {
    clearNode(clotheCart);
    if (newCartContent.childNodes.length > 0) {
      // We have something in the cart description
      var newCart;
      if (newCartContent.getElementsByTagName('table').length > 0) {
	// We really have a cart content
	//newCart = document.importNode(newCartContent.getElementsByTagName('table').item(0), true);
	newCart = newCartContent.getElementsByTagName('table').item(0);
      } else {
	// The cart is empty but we have a text saying it
	// This happens on the checkout page.
	//newCart = document.importNode(newCartContent.firstChild, true);
	newCart = newCartContent.firstChild;
	setPaymentState(false);
      }
      // Hack for safari
      if (navigator.userAgent.indexOf("Safari") > 0) {
	var innerContent = new XMLSerializer().serializeToString(newCart);
	// Hack for safari 1.3
	if (innerContent == undefined) {
	  clotheCart.innerHTML = newCart.innerXML;
	} else {
	  clotheCart.innerHTML =  new XMLSerializer().serializeToString(newCart);
	}
      } else {
	importedNode = document.importNode(newCart, true);
	clotheCart.appendChild(importedNode);
      }
      clotheCart.style.borderWidth = '1px';
      clotheCart.style.borderStyle = 'dashed';
      clotheCart.style.borderColor = 'rgb(246,232,193)';
    } else {
      // The cart is "really empty" nothing in the <cartContent> element
      // We disable style on the div. This happens on the clothes page
      clotheCart.style.borderWidth = '0px';
    }
  }
}

/**
 * Sets the paypal form visibility if it exists
 * 
 * @var boolean state true to enable false otherwise
 */
function setPaymentState(state) {
  var paypalForm = document.getElementById('paypalPay');
  if (paypalForm) {
    if (state) {
      paypalForm.style.display = 'block';
    } else {
      paypalForm.style.display = 'none';
    }
  }
}

/**
 * Refresh the cart once we have called the ajax page
 *
 * @param string content The content sent back to us
 */
function refreshCart (content) {
  //  alert (content);
  content = getXmlDocument(content);
  if (content.getElementsByTagName('error').length > 0) {
    alert ("Il y a eu une erreur:" + content.getElementsByTagName('error').item(0).firstChild.nodeValue);
  } else {
    updateSummary(content.getElementsByTagName('total').item(0).firstChild);
    updateDetails(content.getElementsByTagName('cartContent').item(0));
  }
  setCursorState('auto');
}


/**
 * Gets a current value for a select field
 * If no value is selected, selects the first one
 * in the list and returns it
 *
 * @param HTMLSelectElement selectObject The select to look at
 */
function getValueOrDefault (selectObject) {
  var i;
  var currentVal;
  for (i=0; i<selectObject.options.length; i++) {
    if (selectObject.options[i].selected) {
      currentVal = selectObject.options[i].value;
    }
  }
  if (currentVal == null) {
    selectObject.options[0].selected = true;
    currentVal = selectObject.options[0].value;
  }
  return currentVal;
}


/**
 * A function to display colors corresponding to a particular clothe model
 */
function checkColors () {
  var i;
  var modelId;
  var currentColors;
  var newOption;
  var modelSelect = document.getElementById('modele');
  var sizeSelect = document.getElementById('taille');
  var colorSelect = document.getElementById('couleur');
  var quantitySelect = document.getElementById('quantite');

  // Get the current selected model
  if (modelSelect.options) {
    modelId = getValueOrDefault(modelSelect);
    /*
    for (i=0; i<modelSelect.options.length; i++) {
      if (modelSelect.options[i].selected) {
	modelId = modelSelect.options[i].value;
	break;
      }
    }
    if (modelId == null) {
      modelSelect.options[0].selected = true;
      modelId = modelSelect.option[0].value;
    }
    */
  } else {
    modelId = modelSelect.value;
  }
  getValueOrDefault(sizeSelect);
  getValueOrDefault(quantitySelect);
  //  alert ("got model: " + modelId);

  //  alert ("Checking global colors object before looping: " + var_dump(modelsColors));
  // Get the colors associated to the current model
  for (i=0; i<modelsColors.length; i++) {
    if (modelsColors[i].modelId == modelId) {
      currentColors = modelsColors[i].colors;
      break;
      
    }
  }
  //  alert ("got colors: " + var_dump(currentColors)); 

  // Clear all options in the color select
  clearNode(colorSelect);
  //  alert ("cleared node: " + var_dump(colorSelect));

  // Add relevent colors to the select field
  for (i=0; i<currentColors.length; i++) {
    newOption = document.createElement('option');
    newOption.value = currentColors[i].id;
    newOption.appendChild(document.createTextNode(currentColors[i].name));
    if (i == 0) {
      newOption.selected = true;
    }
    colorSelect.appendChild(newOption);
  }
  //  alert ("colors added: " + var_dump(colorSelect));
}

/**
 * A model colors object
 *
 * @param int id The model identifier
 */
function modelColors (id) {
  this.modelId = id;
  this.colors = new Array();
  
  this.addColor = function (colorId, colorName) {
    this.colors[this.colors.length] = new color (colorId, colorName);
  }
}

/**
 * A color object
 *
 * @param int colorId The color identifier
 * @param string colorName The color name
 */
function color (colorId, colorName) {
  this.id = colorId;
  this.name = colorName;
}

