function getRequestObject() {
  var localxmlhttp = null;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      localxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        localxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        localxmlhttp = false;
      }
    }
  @else
  localxmlhttp = false;
  @end @*/
  if (!localxmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      localxmlhttp = new XMLHttpRequest();
    } catch (e) {
      localxmlhttp = false;
    }
  }
  return localxmlhttp;
}

// Remove all child nodes from node
function removeChildrenFromNode(node) {
  if (node != undefined && node != null) {
    while (node.hasChildNodes()) {
      node.removeChild(node.firstChild);
    }
  }
}

// Convert text to something which can be used as a URL path
function textToUrlPath(text) {
  text = text.toLowerCase();
  var searchArray =  [/ /g,/[äáàâãå]/g,/[ëéèê]/g,/[ïíìî]/g,/[öóòôø]/g,/[üúùû]/g,/æ/g,/ß/g,/ñ/g,/ç/g,/š/g,/ý/g,/[.',]/g,/&/g,/[^\w\d\-\(\)]/g];
  var replaceArray = ["_","a","e","i","o","u","ae","ss","n","c","s","y","","&amp;",""];
  for (var i = 0; i < searchArray.length; i++) {
    text = text.replace(searchArray[i], replaceArray[i]);
  }
  return text;
}

// Show the noscript even if script is enabled. A good error method.
function showNoscript(div) {
  document.getElementById(div).innerHTML = document.getElementsByTagName("noscript")[0].innerHTML.replace( /&gt;/g, ">").replace(/&lt;/g, "<");
}

// Only show the "optgroup" optiongroup in the dropDownID, ie. restrict to just that group
function restrictOptgroup(dropDownID,optgroup) {
  var dropDownElement = document.getElementById(dropDownID);
  var groups = dropDownElement.getElementsByTagName('optgroup');
  var i;
  for (i=0; i<groups.length; i++) {
    if (groups[i].label == optgroup) {
      groups[i].style.display = 'block';
    } else {
      groups[i].style.display = 'none';
    }
  }
}

function populateProvinces (provinceID, country) {
  document.getElementById('countryCell').innerHTML = country;
  document.getElementById('provinceCell').innerHTML = '';
  document.getElementById('townCell').innerHTML = '';

  var xmlHttp = getRequestObject();
  
  if (null == xmlHttp) {
    alert("Javascript error. Unable to use AJAX.");
  } else {
    xmlHttp.open("GET", "/cgi-bin/ajax/getprovinces.pl?country=" + country, true);
    xmlHttp.onreadystatechange = function() {
      if (4 == xmlHttp.readyState) {
      	var provinceElement = document.getElementById(provinceID);
        removeChildrenFromNode(provinceElement);
        var blankOption = document.createElement("option");
        blankOption.setAttribute("value", "");
        provinceElement.appendChild(blankOption);

      	var provinces = xmlHttp.responseText.split("\n");
        for (var i = 0; i < provinces.length-1; i++) {
          var option = document.createElement("option");
          option.setAttribute("value", provinces[i]);
          var provinceTextNode = document.createTextNode(provinces[i]);
          option.appendChild(provinceTextNode);
          provinceElement.appendChild(option);
        }
      }
    };
    xmlHttp.send(null);
  }
}

function populateTowns (townID, province, country) {
  document.getElementById('provinceCell').innerHTML = province;
  document.getElementById('townCell').innerHTML = '';

  var xmlHttp = getRequestObject();
  
  if (null == xmlHttp) {
    alert("Javascript error. Unable to use AJAX.");
  } else {
    xmlHttp.open("GET", "/cgi-bin/ajax/gettowns.pl?country=" + country + "&province=" + province, true);
    xmlHttp.onreadystatechange = function() {
      if (4 == xmlHttp.readyState) {
      	var townElement = document.getElementById(townID);
        removeChildrenFromNode(townElement);
        var blankOption = document.createElement("option");
        blankOption.setAttribute("value", "");
        townElement.appendChild(blankOption);
        
      	var towns = xmlHttp.responseText.split("\n");
        for (var i = 0; i < towns.length-1; i++) {
          var option = document.createElement("option");
          option.setAttribute("value", towns[i]);
          var townTextNode = document.createTextNode(towns[i]);
          option.appendChild(townTextNode);
          townElement.appendChild(option);
        }
      }
    };
    xmlHttp.send(null);
  }
}

function setTown() {
  var town = document.getElementById('town');
  var townSuggestion = document.getElementById('townSuggestion');
  if ('' == town.options[town.selectedIndex].value || 0 == town.options[town.selectedIndex].value || null == town.options[town.selectedIndex].value) {
    document.getElementById('townCell').innerHTML = townSuggestion.value;
  } else {
    document.getElementById('townCell').innerHTML = town.options[town.selectedIndex].value;
  }

  var gc = new GClientGeocoder();
  gc.reset();

  var townID = document.getElementById('town');
  var provinceID = document.getElementById('province');
  var countryID = document.getElementById('country');
  gc.getLatLng((townID.options[townID.selectedIndex].value || townSuggestion.value) + ',' + provinceID.options[provinceID.selectedIndex].value + ',' + countryID.options[countryID.selectedIndex].value, function (point) {
  	  window.globalMapArray[0].clearOverlays();
  	  window.globalMapArray[0].setCenter(point,12)

      var marker = new GMarker(window.globalMapArray[0].getCenter(), {draggable: true});
      GEvent.addListener(marker, "dragend", function(latlng) {
        document.getElementById("googleMapLocator_Latitude").value = latlng.lat();
        document.getElementById("googleMapLocator_Longitude").value = latlng.lng();
      });
      window.globalMapArray[0].addOverlay(marker);
  	});
}

// Get URL parameters
function param() {
  var q = location.search.substring(1).replace(/\+/g, ' ');

  /* parse the query */
  var x = q.split('&'), i, name, t;
  /* q changes from string version of query to object */
  for (q={}, i=0; i<x.length; i++) {
    t = x[i].split('=', 2);
    name = unescape(t[0]);
    if (!q[name]) {
      q[name] = [];
    }
    if (t.length > 1) {
      q[name][q[name].length] = unescape(t[1]);
    }
    /* next two lines are nonstandard */
    else {
      q[name][q[name].length] = true;
    }
  }
  return q;
}

function productsMore(index) {
  $('#description_' + index).css('display', 'table-row');
  $('#imageCell_' + index).attr('rowspan', 2);
  $('#productImageIcon_' + index).css('display', 'none');
  $('#productImage_' + index).css('display', 'inline');
  $('#more_' + index).css('display', 'none');
  $('#less_' + index).css('display', 'inline');
}

function productsLess(index) {
  $('#imageCell_' + index).attr('rowspan', 1);
  $('#description_' + index).css('display', 'none');
  $('#productImageIcon_' + index).css('display', 'inline');
  $('#productImage_' + index).css('display', 'none');
  $('#more_' + index).css('display', 'inline');
  $('#less_' + index).css('display', 'none');
}

function showProductImages() {
  $('tr[id^="description_"]').css('display', 'table-row');
  $('td[id^="imageCell_"]').attr('rowspan', 2);
  $('img[id^="productImageIcon_"]').css('display', 'none');
  $('img[id^="productImage_"]').css('display', 'inline');
  $('a[id^="more_"]').css('display', 'none');
  $('a[id^="less_"]').css('display', 'inline');
  $('.showProductImages').css('display', 'none');
  $('.hideProductImages').css('display', 'inline');
}

function hideProductImages() {
  $('td[id^="imageCell_"]').attr('rowspan', 1);
  $('tr[id^="description_"]').css('display', 'none');
  $('img[id^="productImageIcon_"]').css('display', 'inline');
  $('img[id^="productImage_"]').css('display', 'none');
  $('a[id^="more_"]').css('display', 'inline');
  $('a[id^="less_"]').css('display', 'none');
  $('.showProductImages').css('display', 'inline');
  $('.hideProductImages').css('display', 'none');
}
