var xmlHttp = createXmlHttpRequestObject();
var mainImage = "";
var disabledControls = new Array();
var timer;
var requestTrigger = false;

function createXmlHttpRequestObject()
{
  var xmlHttp;
  
  try
  {
    xmlHttp = new XMLHttpRequest();
  }
  catch (e)
  {
    var XmlHttpVersions = new Array("Msxml2.XMLHTTP.6.0",
                                    "Msxml2.XMLHTTP.5.0",
				    "Msxml2.XMLHTTP.4.0",
				    "Msxml2.XMLHTTP.3.0", 
				    "Msxml2.XMLHTTP",
				    "Microsoft.XMLHTTP");
    for (var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++)
    {
      try
      {
         xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      }
      catch (e)
      {
      }
    }
  }
  
  if (!xmlHttp) {
    alert("Error creating the XMLHttpRequest object.");
  } else {
    return xmlHttp;
  }
}

function handleRequestStateChange()
{
  if (xmlHttp.readyState == 4)
  {
    if (xmlHttp.status == 200)
    {
      try
      {
        handleServerResponse();
      }
      catch (e)
      {
        alert ("Error reading the response: " + e.toString());
      }
    } else {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}

function handleServerResponse()
{
  for (i = 0; i < disabledControls.length; i++) {
    disabledControls[i].disabled = false;
  }
  
  button = document.getElementById("incartButton");
  if (button) {
    button.disabled = false;
    button.style.cursor = "default";
  }

  requestTrigger = false;
  disabledControls = new Array();
  
  var xmlResponse = xmlHttp.responseXML;
  
  if (!xmlResponse || !xmlResponse.documentElement) {
    throw("Invalid XML structure:\n" + xmlHttp.responseText);
  }
  
  var rootNodeName = xmlResponse.documentElement.nodeName;
  
  if (rootNodeName == "parsererror") {
    throw("Invalid XML structure:\n" + xmlHttp.responseText);
  }
  
  xmlRoot = xmlResponse.documentElement;

  if (rootNodeName != "response" || !xmlRoot.firstChild) {
    throw("Empty XML response:\n" + xmlHttp.responseText);
  }

  errorElement = xmlRoot.getElementsByTagName('error').item(0);
  
  if (!errorElement) {
    throw("response/error element expected:\n" + xmlHttp.responseText);
  }
  
  errorCodeElement = errorElement.getElementsByTagName('code').item(0);

  if (!errorCodeElement) {
    throw("response/error/code element expected:\n" + xmlHttp.responseText);
  }
  
  errorCode = errorCodeElement.firstChild.data;
  
  if (errorCode != '0') {
    errorDescription = errorElement.getElementsByTagName('description').item(0).firstChild.data;
    throw("Error response:\n" + errorDescription);
  }
  
  requestElement = xmlRoot.getElementsByTagName('request').item(0);

  if (!requestElement) {
    throw("response/request element expected:\n" + xmlHttp.responseText);
  }
  
  requestCommandElement = requestElement.getElementsByTagName('command').item(0);

  if (!requestCommandElement) {
    throw("response/request/command element expected:\n" + xmlHttp.responseText);
  }

  command = requestCommandElement.firstChild.data;
  
  requestActionElement = requestElement.getElementsByTagName('action').item(0);

  if (!requestActionElement) {
    throw("response/request/action element expected:\n" + xmlHttp.responseText);
  }

  action = requestActionElement.firstChild.data;
  
  answerElement = xmlRoot.getElementsByTagName('answer').item(0);

  if (!answerElement) {
    throw("response/answer element expected:\n" + xmlHttp.responseText);
  }
  
  switch (command) {
    case 'image':
      switch (action) {
        case 'get_url':
	  setImagesURL(answerElement);
	  break; // get_url
      }
      break; // image
    case 'price':
      switch (action) {
        case 'get':
	  setPrice(answerElement);
	  break; // get
      }
      break; // price
    case 'service_charge':
      switch (action) {
        case 'get':
	  setServiceCharge(answerElement);
	  break; // get
      }
      break; // service_charge
  }
}

function makeRequest(params, async)
{
  if (xmlHttp)
  {
    try
    {
      xmlHttp.open("GET", "requester.php?" + params, async);
      
      if (async) {
        xmlHttp.onreadystatechange = handleRequestStateChange;
      }
      
      xmlHttp.send(null);
      
      if (!async) {
        handleServerResponse();
      }
    }
    catch (e)
    {
      alert ("Can't connect to server:\n" + e.toString());
    }
  }
}

function setImagesURL(answerElement)
{
  aElement = document.getElementById("productImageA");
  bElement = document.getElementById("productImageB");
  priceElement = document.getElementById("productsPrice");
  summaElement = document.getElementById("Summa");
  if (aElement || bElement) {
    if (mainImage == "") {
      mainImage = aElement.innerHTML;
    }
    if (aElement) {
    	if (answerElement.firstChild.firstChild != null) {
      		aElement.innerHTML = "<img src="+answerElement.firstChild.firstChild.data+">";
    	} else {
      		aElement.innerHTML = mainImage;
    	}
    }
    
    if (bElement) {
    	if ((answerElement.childNodes.length > 1) && (answerElement.childNodes[1].firstChild != null)) {
      		bElement.innerHTML = "<img src="+answerElement.childNodes[1].firstChild.data+">";
    	} else {
      		bElement.innerHTML = "";
    	}
    }
    
    if ((answerElement.childNodes.length > 2) && (answerElement.childNodes[2].firstChild != null)) {
      priceElement.innerHTML = "<strong>" + answerElement.childNodes[2].firstChild.data + "</strong>";
    }
    if (summaElement) {
      if (answerElement.childNodes[3].firstChild != null) {
        summaElement.innerHTML = "<strong>" + total + answerElement.childNodes[3].firstChild.data + "</strong>";
      }
    }
  }
}

function setPrice(answerElement)
{
  priceElement = document.getElementById("productsPrice");
  summaElement = document.getElementById("Summa");
  if (priceElement) {
    if (answerElement.firstChild.firstChild != null) {
      priceElement.innerHTML = "<strong>" + answerElement.firstChild.firstChild.data + "</strong>";
    }
  }
  if (summaElement) {
    if (answerElement.childNodes[1].firstChild != null) {
      summaElement.innerHTML = "<strong>" + total + answerElement.childNodes[1].firstChild.data + "</strong>";
    }
  }
}

function setServiceCharge(answerElement)
{
  calculationElement = document.getElementById("calculation");

  if (calculationElement) {
    if (answerElement.childNodes[0].firstChild != null) {
       innerText = answerElement.childNodes[0].firstChild.data; 	
       innerText = innerText.replace(/text_1/, handling_price1);
       innerText = innerText.replace(/text_2/, handling_price2);
       innerText = innerText.replace(/text_3/, handling_price3);
       calculationElement.innerHTML = innerText;
    }
  }
}

function onOptionSelectChanged(pElement)
{
  tableElement = document.getElementById("optionsTable");
  selectArray = tableElement.getElementsByTagName("select");
  reqStr = "";
  for (i = 0; i < selectArray.length; i++) {
    disabledControls[disabledControls.length] = selectArray[i];
    selectArray[i].disabled = true;
    reqStr += (selectArray[i].name.match(/\d+/)+"-"+selectArray[i].value+",");
  }
  
  button = document.getElementById("incartButton");
  if (button) {
    button.disabled = true;
    button.style.cursor = "wait";
  }

  if (reqStr.length > 1) {
    reqStr = reqStr.substr(reqStr, reqStr.length - 1);
  }

  quantity = document.forms["cart_quantity"].products_qty.value;
  makeRequest('cmd_command=image&cmd_action=get_url&products_id=' + products_id + '&attributes='+ reqStr + '&quantity=' + quantity, true);
}

function onOptionRadioChanged(pElement)
{
  tableElement = document.getElementById("optionsTable");
  radioArray = tableElement.getElementsByTagName("input");
  reqStr = "";

  for (i = 0; i < radioArray.length; i++) {
    disabledControls[disabledControls.length] = radioArray[i];
    radioArray[i].disabled = true;
    if (radioArray[i].checked) {
      reqStr += (radioArray[i].name.match(/\d+/)+"-"+radioArray[i].value+",");
    }
  }

  button = document.getElementById("incartButton");
  if (button) {
    button.disabled = true;
    button.style.cursor = "wite";
  }

  if (reqStr.length > 1) {
    reqStr = reqStr.substr(reqStr, reqStr.length - 1);
  }

  makeRequest('cmd_command=image&cmd_action=get_url&products_id=' + products_id + '&attributes='+ reqStr, true);
}

function checkAttributesSelection()
{
  not_selected = false;

  tableElement = document.getElementById("optionsTable");
  selectArray = tableElement.getElementsByTagName("select");
  if (selectArray) {
    for (i = 0; i < selectArray.length; i++) {
      if (selectArray[i].value == -1) {
        not_selected = true;
	break;
      }
    }
  } else {
    tableElement = document.getElementById("optionsTable");
    radioArray = tableElement.getElementsByTagName("input");

    if (radioArray) {
      for (i = 0; i < radioArray.length; i++) {
        if (radioArray[i].value == -1) {
          not_selected = true;
	  break;
        }
      }
    }
  }

  if (not_selected) {
    alert(selection_alert);
    return false;
  } else {
    return checkOrderNumber();
  }
}

function checkOrderNumber() {
  quantity = document.forms["cart_quantity"].ordered_quantity.value;
  order_number = document.forms["cart_quantity"].ordered_order_no.value;

  if ((quantity != "") && (order_number == "" || order_number == 0)) {
    alert(invalid_order_alert);
    return false;
  } else {
    return !requestTrigger; 
  }
}

function isEnterKey(event)
{
  event = (event) ? event : (window.event) ? window.event : '';
  var theKey;
  if (event) {
    theKey = (event.which) ? event.which : event.keyCode;
  }
  return (theKey == 13);
}

function onQuantityChanged()
{
//  QuantityChanged();
}

function onQuantityKeyDown()
{
  clearTimeout(timer);
}

function onQuantityKeyUp(fld, event)
{
  if (!isEnterKey(event)) {
    timer = setTimeout(QuantityChanged, 200);
  }
}

function QuantityChanged()
{
  if (!requestTrigger) {
    requestTrigger = true;
    reqStr = "";
    if (document.getElementById("optionsTable")) {	
    tableElement = document.getElementById("optionsTable");
    selectArray = tableElement.getElementsByTagName("select");
    reqStr = "";
    for (i = 0; i < selectArray.length; i++) {
      disabledControls[disabledControls.length] = selectArray[i];
      selectArray[i].disabled = true;
      reqStr += (selectArray[i].name.match(/\d+/)+"-"+selectArray[i].value+",");
    }
} 
    button = document.getElementById("incartButton");
    if (button) {
      button.disabled = true;
      button.style.cursor = "wait";
    }
 
    if (reqStr.length > 1) {
      reqStr = reqStr.substr(reqStr, reqStr.length - 1);
    }

    quantity = document.forms["cart_quantity"].products_qty.value;
    makeRequest('cmd_command=price&cmd_action=get&products_id=' + products_id + '&attributes='+ reqStr + '&quantity=' + quantity, true);
  }
}

function onWasOrderedRButtonChanged(element)
{
//  alert(element.value);
}

function onLayoutQuantityChanged(element)
{
//  alert(element.value);
}

function onServiceChargeUpdate()
{
  if (!requestTrigger) {
    requestTrigger = true;
    
    LayoutQuantity = document.forms["cart_quantity"].layoutQuantity.value;
    WasOrdered = document.forms["cart_quantity"].was_ordered[1].checked;
    
    makeRequest('cmd_command=service_charge&cmd_action=get&products_id=' + products_id + '&was_ordered='+ WasOrdered + '&layout_quantity=' + LayoutQuantity, true);    
    
  }
}

