//Turn the XML text into a JavaScript XML doc
function parseXML(xmlText) {
  try { //Internet Explorer
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.loadXML(xmlText);
  } catch(e) {
    try { //Firefox, Mozilla, Opera, etc.
      parser = new DOMParser();
      xmlDoc = parser.parseFromString(xmlText,"text/xml");
    } catch(e) {
      alert(e.message);
      return;
    }
  }
  return xmlDoc;
}

// Get the HTTP Object
function getHTTPObject(){
  if (window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    if (window.XMLHttpRequest) 
      return new XMLHttpRequest();
    else {
      alert("Your browser does not support AJAX.");
      return null;
    }
  }
}

/************************************************************/
/*** The following functions set DOM elements on the page ***/
/*** once the response comes back from the web server     ***/
/************************************************************/

//Got dress description back from the server
function setDressDescriptionOutput() {
  if(desc_httpObject.readyState == 4) {
    //alert(desc_httpObject.responseText);
    var xmlObject = parseXML(desc_httpObject.responseText);
    //alert(xmlObject.getElementsByTagName("dress")[0]);
    document.getElementById('dressTitlePanel').innerHTML = xmlObject.getElementsByTagName("code")[0].childNodes[0].nodeValue;
    document.getElementById('dressDescriptionPanel').innerHTML = xmlObject.getElementsByTagName("description")[0].childNodes[0].nodeValue;
    //Set colour link visible if applicable
    var dressFabric = xmlObject.getElementsByTagName("dressFabric")[0].childNodes[0].nodeValue;
    if(dressFabric != "NULL") {
      currentDressFabric = dressFabric;
      document.getElementById("colourLink").innerHTML = "&lt; show dress colours";
    } else {
      currentDressFabric = "";
      document.getElementById("colourLink").innerHTML = "";
    }
  }
}

//Got dress images back from the server
function setDressImages() {
  if(img_httpObject.readyState == 4) {
    //Decode the XML string into an object
    var xmlObject = parseXML(img_httpObject.responseText);
    //First, populate the image sources and caption text fields
    var dressImageCollection = xmlObject.getElementsByTagName("dressImages")[0];
    totalImageCount = dressImageCollection.attributes[0].value;
    var dressImageElements = xmlObject.getElementsByTagName("dressImage");
    //Loop round the returned images and set the image source
    for(var i = 1; i <= dressImageElements.length; i++) {
      var thisDressImageUrl = dressImageElements[i - 1].getElementsByTagName("imageUrl")[0];
      var thisDressThumbUrl = dressImageElements[i - 1].getElementsByTagName("thumbnailUrl")[0];
      var thisDressZoomedUrl = dressImageElements[i - 1].getElementsByTagName("zoomedUrl")[0];
      var thisDressImageCaption = dressImageElements[i - 1].getElementsByTagName("imageCaption")[0];
      document.getElementById("dressImage_" + i).src = thisDressImageUrl.childNodes[0].nodeValue;
      document.getElementById("dressZoomImage_" + i).src = thisDressZoomedUrl.childNodes[0].nodeValue;
      document.getElementById("dressThumbnail_" + i).src = thisDressThumbUrl.childNodes[0].nodeValue;
      document.getElementById("dressImageCaption_" + i).innerHTML = thisDressImageCaption.childNodes[0].nodeValue;
    }
    //Make the first image visible
    if(dressImageElements.length > 0) {
      //document.getElementById("dressImage_1").style.visibility = "visible";
      document.getElementById("dressThumbnail_1").style.display = "block";
      document.getElementById("dressImageCaption_1").style.display = "block";
    }
    
    //If there is more than one image, make the next button work
    if(dressImageElements.length > 1) {
      document.getElementById("nextImage_link").className = "pageLink";
    }

    //Next, populate the image count field and activate next/prev button(s)
    document.getElementById("imageCount").innerHTML = "1 of " + String(totalImageCount);

  }
}

//Set the pop up with the colour swatch JPEGs
function setColourSwatches() {
  if(sw_httpObject.readyState == 4) {
    //alert(sw_httpObject.responseText);
    var colourPanel = document.getElementById("dressColourPanel");
    colourPanel.style.visibility = "visible";
    var xmlObject = parseXML(sw_httpObject.responseText);
    var fabric = xmlObject.getElementsByTagName("fabric")[0];
    var fabricName = fabric.attributes[0].value;
    var fabricDescription = fabric.attributes[1].value;
    var htmlStr = "<div style=\"position:relative;width:25px;height:25px;left:360px;border-style:solid;border-width:1px;color:#979fa2;text-align:center\"><a style=\"margin-top:5px\" href=\"javascript:void(0)\" onclick=\"document.getElementById('dressColourPanel').style.visibility = 'hidden'\">X</a></div>";
    htmlStr += "<div style=\"width:99%\" align=\"center\">";
    htmlStr += "This dress is made of <strong>" + fabricName + "</strong> - " + fabricDescription + "<br/>";
    htmlStr += "Available in the following colours:<br/>";
    var swatches = xmlObject.getElementsByTagName("swatch");
    htmlStr += "<table>";
    //Loop around rows
    for(var r = 0; r < swatches.length; r += 5) {
      //Loop around columns
      htmlStr += "<tr>";
      for(var c = 0; c < 5; c++) {
        htmlStr += "<td style=\"width:77px\">";
        if((r + c) < swatches.length) {
          var thisUrl = swatches[(r + c)].attributes[0].value;
          var thisTitle = swatches[(r + c)].childNodes[0].nodeValue;
          htmlStr += "<img src=\"" + thisUrl + "\">";
          htmlStr += "<br/>" + thisTitle;
        } else {
          htmlStr += "&nbsp";
        }
        htmlStr += "</td>";
      }
      htmlStr += "</tr>";
    }
    htmlStr += "</table>";
    htmlStr += "</div>";
    colourPanel.innerHTML = htmlStr;
  }
}

//Display the search results that have come back from the server
function setSearchResults() {
  if(se_httpObject.readyState == 4) {
    //alert(se_httpObject.responseText);
    var resultsPanel = document.getElementById("searchResultsPanel");
    resultsPanel.innerHTML = "<div style=\"position:relative;width:25px;height:25px;padding:0px;left:140px;border-style:solid;border-width:1px;color:#979fa2;text-align:center\"><a onclick=\"document.getElementById('searchResultsPanel').style.visibility = 'hidden';document.getElementById('searchQuery').value = ''\">X</a></div>";
    resultsPanel.style.visibility = "visible";
    var xmlObject = parseXML(se_httpObject.responseText);
    var searchResults = xmlObject.getElementsByTagName("searchResults");
    if(searchResults.length > 0) {
      if(searchResults[0].attributes[0].value == "found") {
        //Some search results have been found for the user's query
        //Display them in the search results window
        var resultList = xmlObject.getElementsByTagName("result");
        for(var r = 0; r < resultList.length; r++) {
          resultsPanel.innerHTML += "<div class=\"searchResultListing\"><a href=\"showSpecificDress.php?dressCode=" + resultList[r].childNodes[0].nodeValue + "\">" + resultList[r].childNodes[0].nodeValue + " (" + resultList[r].attributes[0].value + ")</a></div>";
        }
      } else {
        //No results have been found - inform the user in the results window
        resultsPanel.innerHTML += "No matching dresses found";
      }
    } else {
      alert("Sorry - search is not working right now, please try again later");
    }
  }
}

/**************************************/
/*** Geographic drilldown functions ***/
/**************************************/

function setCounties() {
  if(co_httpObject.readyState == 4) {
    //alert(co_httpObject.responseText);
    var xmlObject = parseXML(co_httpObject.responseText);
    var counties = xmlObject.getElementsByTagName("counties");
    if(counties[0].attributes[0].value == "OK") {
      //Valid query - show results in counties combo box
      document.getElementById("countyComboContainer").style.display = "block";
      var countyCombo = document.getElementById("countyCombo");
      //Remove all options
      countyCombo.options.length = 0;
      //Loop through counties results and add them into the combo box
      var countyArray = xmlObject.getElementsByTagName("county");
      //Add a "please select" option
      countyCombo.options[0] = new Option("Please Select...","");
      for(var c = 1; c <= countyArray.length; c++) {
        var thisCounty = countyArray[c - 1].childNodes[0].nodeValue;
        countyCombo.options[c] = new Option(thisCounty,thisCounty);
      }
      document.getElementById("countyComboContainer").style.visibility = "visible";
    } else {
      //No counties - hide subordinate panels
      document.getElementById("countyComboContainer").style.visibility = "hidden";
      document.getElementById("townComboContainer").style.visibility = "hidden";
    }
  }
}

function setTowns() {
  if(to_httpObject.readyState == 4) {
    //alert(to_httpObject.responseText);
    var xmlObject = parseXML(to_httpObject.responseText);
    var towns = xmlObject.getElementsByTagName("towns");
    if(towns[0].attributes[0].value == "OK") {
      //Valid query - show results in counties combo box
      document.getElementById("townComboContainer").style.display = "block";
      var townCombo = document.getElementById("townCombo");
      //Remove all options
      townCombo.options.length = 0;
      //Add a "please select" option
      townCombo.options[0] = new Option("Please Select...","");
      //Loop through counties results and add them into the combo box
      var townArray = xmlObject.getElementsByTagName("town");
      for(var c = 1; c <= townArray.length; c++) {
        var thisTown = townArray[c - 1].childNodes[0].nodeValue;
        townCombo.options[c] = new Option(thisTown,thisTown);
      }
      document.getElementById("townComboContainer").style.visibility = "visible";
    } else {
      //No town - hide subordinate panels
      document.getElementById("townComboContainer").style.visibility = "hidden";
    }
  }
}

function setStockists() {
  if(st_httpObject.readyState == 4) {
    //alert(st_httpObject.responseText);
    var xmlObject = parseXML(st_httpObject.responseText);
    var stockists = xmlObject.getElementsByTagName("stockists");
    if(stockists[0].attributes[0].value == "OK") {
      //Valid query - show results in counties combo box
      document.getElementById("stockistComboContainer").style.display = "block";
      var stockistCombo = document.getElementById("stockistCombo");
      //Remove all options
      stockistCombo.options.length = 0;
      //Remove all geolocations
      var geoLocContainer = document.getElementById("stockistGeolocations");
      geoLocContainer.innerHTML = "";
      //Add a "please select" option
      stockistCombo.options[0] = new Option("Please Select...","");
      //Loop through counties results and add them into the combo box
      var stockistArray = xmlObject.getElementsByTagName("stockist");
      for(var c = 1; c <= stockistArray.length; c++) {
        var thisStockistId = stockistArray[c - 1].attributes[0].value;
        var thisStockistName = stockistArray[c - 1].childNodes[0].nodeValue;
        stockistCombo.options[c] = new Option(thisStockistName,thisStockistId);
      }
      document.getElementById("stockistComboContainer").style.visibility = "visible";
    } else {
      //No stockist - hide subordinate panels
      document.getElementById("stockistComboContainer").style.visibility = "hidden";
    }
  }
}

/**********************************************************/
/*** These functions are called from events on the page ***/
/*** and send off requests to the web server            ***/
/**********************************************************/

//Get information about the dresses and set it asynchronously
function getDressDescription(dressCode) {
  desc_httpObject = getHTTPObject();
  if (desc_httpObject != null) {
      desc_httpObject.onreadystatechange = setDressDescriptionOutput;
      desc_httpObject.open("GET", "ajaxFacade.php?function=getDress&dressCode=" + dressCode, true);
      desc_httpObject.send(null); 
  }
}

//Get dress images and set them
function getDressImages(dressCode) {
  img_httpObject = getHTTPObject();
  if(img_httpObject != null) {
    img_httpObject.onreadystatechange = setDressImages;
    img_httpObject.open("GET","ajaxFacade.php?function=getDressImages&dressCode=" + dressCode, true);
    img_httpObject.send(null);
  }
}

//Get fabric details colour swatches for a given dress fabric
function getColourSwatches() {
  if(currentDressFabric.length > 0) {
    sw_httpObject = getHTTPObject();
    if(sw_httpObject != null) {
      sw_httpObject.onreadystatechange = setColourSwatches;
      sw_httpObject.open("GET","ajaxFacade.php?function=getSwatches&fabricCode=" + currentDressFabric, true);
      sw_httpObject.send(null);
    }
  }
}

//Get search results based on contents of search input box
function getSearchResults(searchString) {
  //alert("Key pressed: " + searchString.length);
  if(searchString.length > 1) {
    se_httpObject = getHTTPObject();
    if(se_httpObject != null) {
      se_httpObject.onreadystatechange = setSearchResults;
      se_httpObject.open("GET","ajaxFacade.php?function=search&searchQuery=" + searchString);
      se_httpObject.send(null);
    }
  } else {
    document.getElementById("searchResultsPanel").style.visibility = "hidden";
  }
}

/**************************************/
/*** Geographic drilldown functions ***/
/**************************************/

//Get counties based on a country string
function getCounties(country) {
  //Hide subordinate panels
  document.getElementById("townComboContainer").style.display = "none";
  document.getElementById("stockistComboContainer").style.display = "none";
  document.getElementById("stockistGeolocations").innerHTML = "";
  if(country.length > 0) {
    //User has selected country - get counties
    co_httpObject = getHTTPObject();
    if(co_httpObject != null) {
      co_httpObject.onreadystatechange = setCounties;
      co_httpObject.open("GET","ajaxFacade.php?function=getCounties&country=" + encodeURIComponent(country));
      co_httpObject.send(null);
    }
  } else {
    //No country selected - hide county
    if(document.getElementById("countyComboContainer")) {
      document.getElementById("countyComboContainer").style.display = "none";
    }
  }
}

//Get towns based on a county string
function getTowns(county) {
  //Hide stockist container
  document.getElementById("stockistComboContainer").style.display = "none";
  document.getElementById("stockistGeolocations").innerHTML = "";
  if(county.length > 0) {
    //User has selected country - get counties
    to_httpObject = getHTTPObject();
    if(to_httpObject != null) {
      to_httpObject.onreadystatechange = setTowns;
      to_httpObject.open("GET","ajaxFacade.php?function=getTowns&county=" + encodeURIComponent(county));
      to_httpObject.send(null);
    }
  } else {
    //No county selected - hide towns and stockists
    if(document.getElementById("townCombo")) {
      document.getElementById("townCombo").style.display = "none";
      document.getElementById("stockistCombo").style.display = "none";
    }
  }
}

//Get stockists based on a town string
function getStockists(town) {
  document.getElementById("stockistGeolocations").innerHTML = "";
  if(town.length > 0) {
    //User has selected country - get counties
    st_httpObject = getHTTPObject();
    if(st_httpObject != null) {
      st_httpObject.onreadystatechange = setStockists;
      st_httpObject.open("GET","ajaxFacade.php?function=getStockists&town=" + encodeURIComponent(town));
      st_httpObject.send(null);
    }
  } else {
    //No town selected - hide stockists
    if(document.getElementById("stockistCombo")) {
      document.getElementById("stockistCombo").style.display = "none";
    }
  }
}