window.onload = initForm;

function initForm() {
  externalLinks();
  if(document.getElementById('qcontact_enquiry')) {
    document.getElementById('qcontact_enquiry').onfocus = clearfield;
    document.getElementById('qcontact_enquiry').onblur = reinstatefield;
  }
  if(document.getElementById('rf_email')) {
    document.getElementById('rf_email').onfocus = clearfield;
    document.getElementById('rf_email').onblur = reinstatefield;
  }
  if(document.getElementById('delivery_country')) {
    document.getElementById('delivery_country').onchange = getShipping;
  }
  if(document.getElementById('delivery_country') && document.getElementById('delivery_country').value != '') {
     getShipping();
  }
  if(document.getElementById('tonersmart_type')) {
    document.getElementById('tonersmart_type').onchange = tsForm;
    document.getElementById('tonersmart_printer').onchange = tsForm;
    document.getElementById('tonersmart_model').onchange = tsForm;
  }
  if(document.getElementById('bundle_type')) {
    document.getElementById('bundle_type').onchange = bpForm;
    document.getElementById('bundle_printer').onchange = bpForm;
  }
  manufacturerForms();
}

function manufacturerForms() {
  if(!document.getElementsByTagName) {
    return;
  } else {
    var anchors = document.getElementsByTagName("select");
    for(var i=0;i<anchors.length;i++) {
      var anchor = anchors[i];
      if((anchor.id.substring(0, 5) == 'manu_') && (anchor.id.substring(0, 6) != 'manu_c')) {
        anchor.onchange = mnForm;
      }
    }
  }
}

function externalLinks() {
  if(!document.getElementsByTagName) {
    return;
  } else {
    var anchors = document.getElementsByTagName("a");
    for(var i=0;i<anchors.length;i++) {
      var anchor = anchors[i];
      if(anchor.getAttribute("href") && anchor.getAttribute("rel") == "external" || anchor.getAttribute("rel") == "external nofollow") {
        anchor.target = "_blank";
      }
    }
  }
}

function clearfield() {
  switch(this.id) {
    case 'qcontact_enquiry':
      trimValue = trim(this.value);
      if(trimValue == 'Enquiry') {
        this.value = '';
      }
    break;
    case 'rf_email':
      trimValue = trim(this.value);
      if(trimValue == 'Please enter email...') {
        this.value = '';
      }
    break;
  }
}

function reinstatefield() {
  switch(this.id) {
    case 'qcontact_enquiry':
      trimValue = trim(this.value);
      if(trimValue == '') {
        this.value = 'Enquiry';
      }
    break;
    case 'rf_email':
      trimValue = trim(this.value);
      if(trimValue == '') {
        this.value = 'Please enter email...';
      }
    break;
  }
}

function trim(str, chars) {
  return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function tsForm() {
  var selectIDType = 'tonersmart_type';
  var selectIDManufacturer = 'tonersmart_printer';
  var selectIDModel = 'tonersmart_model';
  var selectIDColour = 'tonersmart_colour';
  var selectValueType = document.getElementById(selectIDType).value;
  var selectValueManufacturer = document.getElementById(selectIDManufacturer).value;
  var selectValueModel = document.getElementById(selectIDModel).value;
  var selectValueColour = document.getElementById(selectIDColour).value;
  getTonersmartProductsData("logicajax/tonersmartproducts.php?" +
                            "typeID=" + selectIDType + "&typeValue=" + selectValueType +
                            "&manufacturerID=" + selectIDManufacturer + "&manufacturerValue=" + selectValueManufacturer +
                            "&modelID=" + selectIDModel + "&modelValue=" + selectValueModel +
                            "&colourID=" + selectIDColour + "&colourValue=" + selectValueColour, selectIDType, selectIDManufacturer, selectIDModel, selectIDColour);
}

function bpForm() {
  var selectIDType = 'bundle_type';
  var selectIDManufacturer = 'bundle_printer';
  var selectIDModel = 'bundle_model';
  var selectValueType = document.getElementById(selectIDType).value;
  var selectValueManufacturer = document.getElementById(selectIDManufacturer).value;
  var selectValueModel = document.getElementById(selectIDModel).value;
  getBundleProductsData("logicajax/bundleproducts.php?" +
                        "typeID=" + selectIDType + "&typeValue=" + selectValueType +
                        "&manufacturerID=" + selectIDManufacturer + "&manufacturerValue=" + selectValueManufacturer +
                        "&modelID=" + selectIDModel + "&modelValue=" + selectValueModel, selectIDType, selectIDManufacturer, selectIDModel);
}

function mnForm() {
  var manufacturerID = this.id.substring(6);
  var selectIDType = 'manu_t' + manufacturerID;
  var selectIDModel = 'manu_m' + manufacturerID;
  var selectIDColour = 'manu_c' + manufacturerID;
  var selectValueType = document.getElementById(selectIDType).value;
  var selectValueModel = document.getElementById(selectIDModel).value;
  var selectValueColour = document.getElementById(selectIDColour).value;
  /*alert("logicajax/manufacturerproducts.php?" +
                              "typeID=" + selectIDType + "&typeValue=" + selectValueType +
                              "&modelID=" + selectIDModel + "&modelValue=" + selectValueModel +
                              "&colourID=" + selectIDColour + "&colourValue=" + selectValueColour +
                              "&manufacturerID=" + manufacturerID, selectIDType, selectIDModel, selectIDColour, manufacturerID);*/
  getManufacturerProductsData("logicajax/manufacturerproducts.php?" +
                              "typeID=" + selectIDType + "&typeValue=" + selectValueType +
                              "&modelID=" + selectIDModel + "&modelValue=" + selectValueModel +
                              "&colourID=" + selectIDColour + "&colourValue=" + selectValueColour +
                              "&manufacturerID=" + manufacturerID, selectIDType, selectIDModel, selectIDColour, manufacturerID);
}

function getTonersmartProductsData(phpFile, idType, idMan, idModel, idColour) {
  var selectIDType = idType;
  var selectIDManufacturer = idMan;
  var selectIDModel = idModel;
  var selectIDColour = idColour;
  var selectValueType = document.getElementById(selectIDType).value;
  var selectValueManufacturer = document.getElementById(selectIDManufacturer).value;
  var selectValueModel = document.getElementById(selectIDModel).value;
  var selectValueColour = document.getElementById(selectIDColour).value;
  xmlhttp.open("GET", phpFile);
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var multiArray = xmlhttp.responseText.split('|');
      for(i=0;i<(multiArray.length);i++) {
        switch(i) {
          case 0:
            var obj = document.getElementById(selectIDType);
            var stickyValue = selectValueType;
          break;
          case 1:
            var obj = document.getElementById(selectIDManufacturer);
            var stickyValue = selectValueManufacturer;
          break;
          case 2:
            var obj = document.getElementById(selectIDModel);
            var stickyValue = selectValueModel;
          break;
          case 3:
            var obj = document.getElementById(selectIDColour);
            var stickyValue = selectValueColour;
          break;
        }
        obj.options.length = 0;
        var valueExists = false;
        var multiSplitArray = multiArray[i].split(',');
        for(j=0;j<(multiSplitArray.length);j++) {
          optionsArray = multiSplitArray[j].split('/');
          obj.options[j] = new Option(optionsArray[1], optionsArray[0]);
          if(stickyValue == optionsArray[0]) {
            valueExists = true;
          }
        }
        if(valueExists == true) {
          obj.value = stickyValue;
        } else {
          obj.value = 'a';
        }
      }
    }
  }
  xmlhttp.send(null);
}

function getBundleProductsData(phpFile, idType, idMan, idModel) {
  var selectIDType = idType;
  var selectIDManufacturer = idMan;
  var selectIDModel = idModel;
  var selectValueType = document.getElementById(selectIDType).value;
  var selectValueManufacturer = document.getElementById(selectIDManufacturer).value;
  var selectValueModel = document.getElementById(selectIDModel).value;
  xmlhttp.open("GET", phpFile);
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var multiArray = xmlhttp.responseText.split('|');
      for(i=0;i<(multiArray.length);i++) {
        switch(i) {
          case 0:
            var obj = document.getElementById(selectIDType);
            var stickyValue = selectValueType;
          break;
          case 1:
            var obj = document.getElementById(selectIDManufacturer);
            var stickyValue = selectValueManufacturer;
          break;
          case 2:
            var obj = document.getElementById(selectIDModel);
            var stickyValue = selectValueModel;
          break;
        }
        obj.options.length = 0;
        var valueExists = false;
        var multiSplitArray = multiArray[i].split(',');
        for(j=0;j<(multiSplitArray.length);j++) {
          optionsArray = multiSplitArray[j].split('/');
          obj.options[j] = new Option(optionsArray[1], optionsArray[0]);
          if(stickyValue == optionsArray[0]) {
            valueExists = true;
          }
        }
        if(valueExists == true) {
          obj.value = stickyValue;
        } else {
          obj.value = 'a';
        }
      }
    }
  }
  xmlhttp.send(null);
}

function getManufacturerProductsData(phpFile, idType, idModel, idColour, idMan) {
  var selectIDType = idType;
  var selectIDModel = idModel;
  var selectIDColour = idColour
  var manufacturerID = idMan;
  var selectValueType = document.getElementById(selectIDType).value;
  var selectValueModel = document.getElementById(selectIDModel).value;
  var selectValueColour = document.getElementById(selectIDColour).value;
  xmlhttp.open("GET", phpFile);
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var multiArray = xmlhttp.responseText.split('|');
      for(i=0;i<(multiArray.length);i++) {
        switch(i) {
          case 0:
            var obj = document.getElementById(selectIDType);
            var stickyValue = selectValueType;
          break;
          case 1:
            var obj = document.getElementById(selectIDModel);
            var stickyValue = selectValueModel;
          break;
          case 2:
            var obj = document.getElementById(selectIDColour);
            var stickyValue = selectValueColour;
          break;
        }
        obj.options.length = 0;
        var valueExists = false;
        var multiSplitArray = multiArray[i].split(',');
        for(j=0;j<(multiSplitArray.length);j++) {
          optionsArray = multiSplitArray[j].split('/');
          obj.options[j] = new Option(optionsArray[1], optionsArray[0]);
          if(stickyValue == optionsArray[0]) {
            valueExists = true;
          }
        }
        if(valueExists == true) {
          obj.value = stickyValue;
        } else {
          obj.value = 'a';
        }
      }
    }
  }
  xmlhttp.send(null);
}

// Switch product image
function switch_product_image(image, title) {
  var pImage;
  pImage = document.getElementById('product_image_src');
  pImage.src = 'images/products/main/' + image;
  pImage.title = title;
}

// Reset product image
function reset_product_image(image, title) {
  var pImage;
  pImage = document.getElementById('product_image_src');
  pImage.src = 'images/products/main/' + image;
  pImage.title = title;
}

function getPrice(phpFile, objID) {
  if(document.getElementById(objID)) {
      var obj = document.getElementById(objID);
      var title = new Array();
      var value = new Array();
      xmlhttp.open("GET", phpFile);
      xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          obj.innerHTML = xmlhttp.responseText;
          if(obj == 'delivery_menu') {
            document.getElementById('delivery_method').style.display = 'block';
           document.getElementById('delivery_method').value = document.getElementById('shipping_menu').options[document.getElementById('shipping_menu').selectedIndex].value;
          }
        }
      }
      xmlhttp.send(null);
    }

}

function updateTotalPriceQty() {
  var prodID = document.getElementById('product_id').value;
  var priceIdentifier = 'product_price_' + prodID;
  var priceResponse = document.getElementById(priceIdentifier).innerHTML;
  var quantity = document.getElementById('quantity').value;
  var priceSplit = priceResponse.substring(1);
  var priceEach = priceSplit + 0;
  var totalPrice = priceEach * quantity;
  var totalPrice = totalPrice.toFixed(2);
  var totalPriceIdentifier = 'total_price_' + prodID;
  document.getElementById(totalPriceIdentifier).innerHTML = totalPrice;
}

function updateTotalPriceQtyRadio() {
  var prodID = document.getElementById('product_id').value;
  var priceIdentifier = 'product_price_' + prodID;
  var priceResponse = document.getElementById(priceIdentifier).innerHTML;
  var quantity = document.getElementById('quantity').value;
  var priceSplit = priceResponse.substring(1);
  var priceEach = priceSplit + 0;
  var totalPrice = priceEach * quantity;
  var totalPrice = totalPrice.toFixed(2);
  var totalPriceIdentifier = 'total_price_' + prodID;
  document.getElementById(totalPriceIdentifier).innerHTML = totalPrice;
}

function updateTotalPrice(price) {
  var prodID = document.getElementById('product_id').value;
  var priceResponse = price;
  var quantity = document.getElementById('quantity').value;
  var priceSplit = priceResponse.substring(7);
  var priceEach = priceSplit + 0;
  var totalPrice = priceEach * quantity;
  var totalPrice = totalPrice.toFixed(2);
  var totalPriceIdentifier = 'total_price_' + prodID;
  document.getElementById(totalPriceIdentifier).innerHTML = totalPrice;
}

function updatePrice(prodID, menuID, variantType) {
  var quantity = document.getElementById('quantity').value;
  if(document.getElementById('variantsIDs_'+prodID)) {
    var variantsIDs = document.getElementById('variantsIDs').value;
    // Get the IDs of the variants
    variantID = variantsIDs.split('|');
    var variantsValues = '';
    // Loop through the variants based on their IDs and get the selected values
    for(i=0;i<variantID.length;i++) {
      if(document.getElementById('option_' + variantID[i] + '_' + prodID)) {
        variantValue = document.getElementById('option_' + variantID[i] + '_' + prodID).value;
        variantsValues = variantsValues + variantValue + "|";
      }
    }
  }
  if(document.getElementById('globalVariantsIDs_'+prodID)) {
    var globalVariantsIDs = document.getElementById('globalVariantsIDs_'+prodID).value;
    // Get the IDs of the global variants
    globalVariantID = globalVariantsIDs.split('|');
    var globalVariantsValues = '';
    // Loop through the global variants based on their IDs and get the selected values
    for(i=0;i<globalVariantID.length;i++) {
      if(document.getElementById('option_' + globalVariantID[i] + '_' + prodID)) {
        globalVariantValue = document.getElementById('option_' + globalVariantID[i] + '_' + prodID).value;
        globalVariantsValues = globalVariantsValues + globalVariantValue + "|";
      }
    }
  }
  getPrice("logicajax/updateProductPrice.php?p=" + prodID + "&variantsIDs='" + variantsIDs + "'&globVariantsIDs='" + globalVariantsIDs
            + "'&variantsValues='" + variantsValues + "'&globVariantsValues='" + globalVariantsValues + "'&qty=" + quantity, "product_price_" + prodID, 'delivery_menu');
}

function updatePriceRadio(prodID, menuID, variantType) {
  var quantity = document.getElementById('quantity').value;
  if(document.getElementById('variantsIDs_'+prodID)) {
    var variantsIDs = document.getElementById('variantsIDs').value;
    // Get the IDs of the variants
    variantID = variantsIDs.split('|');
    var variantsValues = '';
    // Loop through the variants based on their IDs and get the selected values
    for(i=0;i<variantID.length;i++) {
      if(document.getElementById('option_' + variantID[i] + '_' + prodID)) {
        variantValue = document.getElementById('option_' + variantID[i] + '_' + prodID).value;
        variantsValues = variantsValues + variantValue + "|";
      }
    }
  }
  if(document.getElementById('globalVariantsIDs_'+prodID)) {
    var globalVariantsIDs = document.getElementById('globalVariantsIDs_'+prodID).value;
    // Get the IDs of the global variants
    globalVariantID = globalVariantsIDs.split('|');
    var globalVariantsValues = '';
    // Loop through the global variants based on their IDs and get the selected values
    for(i=0;i<globalVariantID.length;i++) {
      if(document.getElementById('option_' + globalVariantID[i] + '_' + prodID)) {
        globalVariantValue = '';
        globalVariantBase = document.getElementById('option_' + globalVariantID[i] + '_' + prodID);
        globalVariantOptions = globalVariantBase.getElementsByTagName('input');
        for(j=0;j<globalVariantOptions.length;j++) {
          if(globalVariantOptions[j].checked) {
            globalVariantValue = globalVariantOptions[j].value;
          }
        }
        globalVariantsValues = globalVariantsValues + globalVariantValue + "|";
      }
    }
  }

  getPrice("logicajax/updateProductPrice.php?p=" + prodID + "&variantsIDs='" + variantsIDs + "'&globVariantsIDs='" + globalVariantsIDs
            + "'&variantsValues='" + variantsValues + "'&globVariantsValues='" + globalVariantsValues + "'&qty=" + quantity, "product_price_" + prodID);
}

function updatePriceRadioStart() {
  var quantity = document.getElementById('quantity').value;
  var prodID = document.getElementById('product_id').value;
  if(document.getElementById('variantsIDs_'+prodID)) {
    var variantsIDs = document.getElementById('variantsIDs').value;
    // Get the IDs of the variants
    variantID = variantsIDs.split('|');
    var variantsValues = '';
    // Loop through the variants based on their IDs and get the selected values
    for(i=0;i<variantID.length;i++) {
      if(document.getElementById('option_' + variantID[i] + '_' + prodID)) {
        variantValue = document.getElementById('option_' + variantID[i] + '_' + prodID).value;
        variantsValues = variantsValues + variantValue + "|";
      }
    }
  }
  if(document.getElementById('globalVariantsIDs_'+prodID)) {
    var globalVariantsIDs = document.getElementById('globalVariantsIDs_'+prodID).value;
    // Get the IDs of the global variants
    globalVariantID = globalVariantsIDs.split('|');
    var globalVariantsValues = '';
    // Loop through the global variants based on their IDs and get the selected values
    for(i=0;i<globalVariantID.length;i++) {
      if(document.getElementById('option_' + globalVariantID[i] + '_' + prodID)) {
        globalVariantValue = '';
        globalVariantBase = document.getElementById('option_' + globalVariantID[i] + '_' + prodID);
        globalVariantOptions = globalVariantBase.getElementsByTagName('input');
        for(j=0;j<globalVariantOptions.length;j++) {
          if(globalVariantOptions[j].checked) {
            globalVariantValue = globalVariantOptions[j].value;
          }
        }
        globalVariantsValues = globalVariantsValues + globalVariantValue + "|";
      }
    }
  }

  getPrice("logicajax/updateProductPrice.php?p=" + prodID + "&variantsIDs='" + variantsIDs + "'&globVariantsIDs='" + globalVariantsIDs
            + "'&variantsValues='" + variantsValues + "'&globVariantsValues='" + globalVariantsValues + "'&qty=" + quantity, "product_price_" + prodID);
}

function getShipping() {
  var country = document.getElementById('delivery_country').value;
  if(document.getElementById('shipping_menu')) {
    var shippingID = document.getElementById('shipping_menu').options[document.getElementById('shipping_menu').selectedIndex].value;
  } else {
    var shippingID = null;
  }
  var subTotal = document.getElementById('sub_total').innerHTML;
  getPrice("logicajax/shippingCharge.php?country=" + country + '&shippingID=' + shippingID + '&subTotal=' + subTotal, "delivery_menu");
}

function getGlossary(letter) {
  xmlhttp.open("GET", "logicajax/glossary.php?letter=" + letter);
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementById('glossary').innerHTML =  xmlhttp.responseText;
    }
  }
  xmlhttp.send(null);
}

function display_flash(file) {
  if(file == 'top_banner') {
    document.write('<object type="application/x-shockwave-flash" data="flash/top_banner.swf" width="566" height="136"><param name="movie" value="flash/top_banner.swf" /></object>');
  }
}

function toggle(id) {
  var testimonial;
  testimonial = document.getElementById('testimonial_' + id + '_short').style.display;
  if(testimonial == 'none') {
    document.getElementById('testimonial_' + id + '_short').style.display = 'block';
    document.getElementById('testimonial_' + id + '_full').style.display = 'none';
  } else {
    document.getElementById('testimonial_' + id + '_short').style.display = 'none';
    document.getElementById('testimonial_' + id + '_full').style.display = 'block';
  }
}
