window.onload = initForm;

function initForm() { 
  home_page_box_links();
  external_links();
  
  if (document.getElementById('fundraising_group')) {
    document.getElementById('fundraising_group').onclick = checkPromoCode;
    checkPromoCode();
  }
  
  if(document.getElementById('ship_to_invoice[ship_to_invoice]')) {   
    document.getElementById('ship_to_invoice[ship_to_invoice]').onclick = enableDeliveryDetials;
    enableDeliveryDetials();
  }
  if(document.getElementById('how_find')) {
    var how_find_index = document.getElementById('how_find').selectedIndex;
    var how_find = document.getElementById('how_find')[how_find_index].value;
    if (document.getElementById('other_how_did_find').value.length > 0 && how_find == 41) {
      document.getElementById('other_how_did_find_cont').style.display = 'block';
    } else if(document.getElementById('other_how_did_find').value.length > 0 && how_find != 41) {
      document.getElementById('other_how_did_find_cont').style.display = 'none';
    } else {
      document.getElementById('other_how_did_find_cont').style.display = 'none';
    }
    document.getElementById('how_find').onchange = showAdditonalField;
  }
  if(document.getElementById('initials')) {
    if(document.getElementById('product_input_0')) {
      var ScriptBlockArray = new Array(131, 141, 151, 161, 171, 181);
      var chosenVariantIndex = document.getElementById('option_61').selectedIndex;
      var chosenVariant = document.getElementById('option_61')[chosenVariantIndex].value;
      if(document.getElementById('initials') && inArray(chosenVariant, ScriptBlockArray)) {
        document.getElementById('initials').style.display = 'block';
      } else {
        document.getElementById('product_input_0').value = '';
      }
    }
  }
  if(document.getElementById('prod_id')){
    if(document.getElementById('prod_id').value == 351){
       document.getElementById('product_input_2').style.display = 'none';
       document.getElementById('product_input_3_label').style.display = 'none';
       document.getElementById('option_31').onchange = showAdditonalInputField;     
    }
  }
  if(document.getElementById('easytags_flash')) {
    insertFlashObject('easytags_flash', 'http://www.youtube.com/v/8I7aT7pNs_4&hl=en_US&fs=1&iv_load_policy=3&rel=0&border=1', 317, 200) 
  }
  if(document.getElementById('invoice_find_address')) {
    document.getElementById('invoice_find_address').onclick = findInvoiceAddressHandler;
  }
  if(document.getElementById('delivery_find_address')) {
    document.getElementById('delivery_find_address').onclick = findDeliveryAddressHandler;
  }
  if(document.getElementById('reg_find_address')) {
    document.getElementById('reg_find_address').onclick = findMyAccountAddressHandler;
  }
  if(document.getElementById('fundraising_group_select_group') && document.getElementById('fundraising_group')) {
    document.getElementById('fundraising_group_select_group').onchange = getFundraisingGroups;
  }
  
  if (document.getElementById('delivery_method')) {
    var onC="copyDeliveryMethod('delivery_method')";
    document.getElementById('delivery_method').onchange = new Function(onC);
  }
  
  user_menu(); 
}

function checkPromoCode() {
    if (document.getElementById('promocode').value != 'Cannot use Promotional Code with Fundraising Group') {
      promoCode = document.getElementById('promocode').value;
    }
    
    fundraisingGroup = document.getElementById('fundraising_group').value;

    if (fundraisingGroup == 'Please select') {
        document.getElementById('promocode').value = promoCode;
        document.getElementById('promocode').disabled = false;
    } else {
        document.getElementById('promocode').value = 'Cannot use Promotional Code with Fundraising Group';
        document.getElementById('promocode').disabled = true;
    }
}

function copyDeliveryMethod(method) {
    document.delivery_choice.submit();
}


// Show additional field for futher info
function showAdditonalField() {
  var how_find_index = document.getElementById('how_find').selectedIndex;
  var how_find = document.getElementById('how_find')[how_find_index].value;
  if(how_find == 41) {
    document.getElementById('other_how_did_find_cont').style.display = 'block';
  } else {
    document.getElementById('other_how_did_find_cont').style.display = 'none';
  }
}

// Show additional field for futher info
function showAdditonalInputField() {
  var selected = document.getElementById('option_31').selectedIndex;
  var letterStyle = document.getElementById('option_31')[selected].value;
  if(letterStyle == 21) {
     document.getElementById('product_input_2').style.display = 'block';
     document.getElementById('product_input_3_label').style.display = 'block';
  } else {
     document.getElementById('product_input_2').style.display = 'none';
     document.getElementById('product_input_3_label').style.display = 'none';
  }
}

// toggle input field
function toggleInputField() {
  if(this.value == 1491) {
    document.getElementById('specialsewon').style.display = 'inline';
  } else {
    document.getElementById('product_input_2').value = '';
    document.getElementById('specialsewon').style.display = 'none';
  }
}

// Assign event handlers to user menu
function user_menu() {
  if(!document.getElementsByTagName) {
    return;
  } else {
    var div = document.getElementById('user_menu_content');
    var images = div.getElementsByTagName("img"); 
    for(var i=0; i<images.length; i++) { 
      var image = images[i];
      if(image.getAttribute("id").substr(0, 8) == 'usermenu') {
        imageName = image.getAttribute("id");
        document.getElementById(imageName).onmouseover = user_menu_hover;
        document.getElementById(imageName).onmouseout = user_menu_hover;
      } 
    } 
  }
}

// User menu image rollovers
function user_menu_hover(e) {
  if(window.event) {
    var e = window.event;
  }
  var source = e.srcElement ? e.srcElement : e.target;
  var objectID = source.getAttribute("id");
  var splitString = document.getElementById(objectID).src.split('/');
  var imagePath = '';
  for(i=0;i<=splitString.length - 2;i++) {
    imagePath = imagePath + splitString[i] + '/'; 
  }
  if(splitString[splitString.length - 1].substr(9, 4) == 'over') {
    document.getElementById(objectID).src = imagePath + objectID + '.jpg'; 
  } else {
    document.getElementById(objectID).src = imagePath + objectID + 'over.jpg';
  }
}

// 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;
}

// Open links in new window
function external_links() { 
  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";
      }
    }
  } 
}

// Home page box links
function home_page_box_links() {
  if(document.getElementById('home_link_fundraising')) {
    document.getElementById('home_link_fundraising').onclick = fundraising_link;
    document.getElementById('home_link_labels').onclick = labels_link;
    document.getElementById('home_link_comments').onclick = comments_link;
  }
  if(document.getElementById('home_link_starter')) {
    document.getElementById('home_link_starter').onclick = starter_link;
    document.getElementById('home_link_school').onclick = school_link;
  }
  if(document.getElementById('home_easy_tags')) {
    document.getElementById('home_easy_tags').onclick = easytag_link;
    document.getElementById('home_stick_easys').onclick = stickeasys_link;
  } 
}

function fundraising_link() {
  window.location = "laundry-labels.htm"; 
}

function labels_link() {
  window.location = "what-to-label.htm"; 
}

function comments_link() {
  window.location = "comments.htm"; 
}

function starter_link() {
  window.location = "product.htm?product=starter-pack"; 
}

function school_link() {
  window.location = "product.htm?product=off-to-school-set"; 
}

function easytag_link() {
  window.location = "product.htm?product=easytags"; 
}

function stickeasys_link() {
  window.location = "product.htm?product=fab-and-funky-stickeasy"; 
}

function enableDeliveryDetials() {
  if(!document.getElementById('ship_to_invoice[ship_to_invoice]').checked || document.getElementById('ship_to_invoice[ship_to_invoice]').value == 0) {
    document.getElementById('delivery_details').style.display = 'block';
  } else {
    document.getElementById('delivery_details').style.display = 'none';
  }
}

function getFundraisingGroups() {
  var selectFundraising = document.getElementById('fundraising_group');
  xmlhttp.open("GET", 'logicajax/getFundraisingGroups.php?letter=' + this.value);
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      //selectFundraising.innerHTML = xmlhttp.responseText;
      var selectFundraisingOptions = xmlhttp.responseText;
      var selectFundraisingOptionsArray = selectFundraisingOptions.split("|");
      selectFundraising.options.length = 0;
      for(a=0;a<selectFundraisingOptionsArray.length;a++) {
        selectFundraising.options[a] = new Option(selectFundraisingOptionsArray[a], selectFundraisingOptionsArray[a], false, false);
      }
    }
  }  
  xmlhttp.send(null);
}

function getFullProductPrice(phpFile, 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;
    }
  }  
  xmlhttp.send(null);
}

function updatePrice(prodID, menuID, variantType) {
  if(document.getElementById('variantsIDs')) {
    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])) {
        variantValue = document.getElementById('option_' + variantID[i]).value;   
        variantsValues = variantsValues + variantValue + "|";   
      }
    }   
  } 
  if(document.getElementById('globalVariantsIDs')) {       
    var globalVariantsIDs = document.getElementById('globalVariantsIDs').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])) {
        globalVariantValue = document.getElementById('option_' + globalVariantID[i]).value;   
        globalVariantsValues = globalVariantsValues + globalVariantValue + "|";   
      }
    }           
  }       
  // Hide the initial field if not block or script design for the FAB & FUNKY Lables
  var FabFunkyArray = new Array();
  FabFunkyArray[0] = 11;
  FabFunkyArray[1] = 21;
  FabFunkyArray[2] = 71;
  FabFunkyArray[3] = 261;
  /*FabFunkyArray[4] = 371;*/
  FabFunkyArray[5] = 362;
  FabFunkyArray[6] = 382;
  FabFunkyArray[7] = 392;
  FabFunkyArray[8] = 402;
  /*FabFunkyArray[6] = 372;*/
  if(inArray(prodID, FabFunkyArray)) {
    if(document.getElementById('option_61')) {
      var ScriptBlockArray = new Array(131, 141, 151, 161, 171, 181);
      var chosenVariantIndex = document.getElementById('option_61').selectedIndex;
      var chosenVariant = document.getElementById('option_61')[chosenVariantIndex].value;
      // alert(chosenVariant + ' - ' + inArray(chosenVariant, ScriptBlockArray));
      if(document.getElementById('initials') && inArray(chosenVariant, ScriptBlockArray)) {
        document.getElementById('initials').style.display = 'block';
      } else {
        document.getElementById('initials').style.display = 'none';
      }      
    }
  }
  
  
  getFullProductPrice("logicajax/updateProductPrice.php?p=" + prodID + "&variantsIDs='" + variantsIDs + "'&globVariantsIDs='" + globalVariantsIDs
                       + "'&variantsValues='" + variantsValues + "'&globVariantsValues='" + globalVariantsValues + "'", "product_price");
}

function inArray(needle, haystack) { 
  for(var i = 0; i < haystack.length; i++) {
    if(haystack[i] == needle) {
      return true;   
    }
  }
  return false;
}

function insertFlashObject(objID, flashLocation, width, height, flashString) {
  var flashObject;
  flashObject = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' width='" + width + "' height='" + height + "'>";
  flashObject = flashObject + "<param name='wmode' value='transparent'>";
  flashObject = flashObject + "<param name='movie' value='" + flashLocation + "' />";
  flashObject = flashObject + "<param name='quality' value='high' />";
  if(typeof(flashString) == "undefined") {
    flashObject = flashObject + "<embed src='" + flashLocation + "' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='" + width + "' height='" + height + "' wmode='transparent'";
  } else {
    flashObject = flashObject + "<param name='FlashVars' value='" + flashString + "'";
    flashObject = flashObject + "<embed src='" + flashLocation + "' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='" + width + "' height='" + height + "' wmode='transparent' ";
    flashObject = flashObject + "FlashVars='" + flashString + "'";
  }
  flashObject = flashObject + "></embed></object>";
  if(document.getElementById(objID)) {
    document.getElementById(objID).innerHTML = flashObject;
  }
}

function getAddress(phpFile, objID) {
  var obj = document.getElementById(objID);  
  xmlhttp.open("GET", phpFile);
  xmlhttp.onreadystatechange = function() {
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      breaker = xmlhttp.responseText.indexOf("ERROR", xmlhttp.responseText);
      errorStr = xmlhttp.responseText.substring(0, breaker);
      if(errorStr.length != 0) {
        document.getElementById('message').innerHTML = errorStr;
      } else {
        
        // returning the address field
        $addressDelimiter = "ADDRESS1";
        breakerAddress = xmlhttp.responseText.indexOf($addressDelimiter, xmlhttp.responseText);
        addressStr = xmlhttp.responseText.substring(0, breakerAddress);
        document.getElementById(objID + '_address1_cont').innerHTML = addressStr.replace(/^\s+|\s+$/, '');
        
        // returning the address 2 field
        $address2Delimiter = "ADDRESS2";
        breakerAddress2 = xmlhttp.responseText.indexOf($address2Delimiter, xmlhttp.responseText);
        address2Str = xmlhttp.responseText.substring((breakerAddress + $address2Delimiter.length), breakerAddress2);
        document.getElementById(objID + '_address2').value = address2Str;
        
        switch(objID) {
          case 'reg':
            // returning the town field
            $townDelimiter = "TOWN";
            breakerTown = xmlhttp.responseText.indexOf($townDelimiter, xmlhttp.responseText);
            townStr = xmlhttp.responseText.substring((breakerAddress2 + $address2Delimiter.length), breakerTown);
            document.getElementById(objID + '_city').value = townStr;
          break;
          default:
            // returning the town field
            $townDelimiter = "TOWN";
            breakerTown = xmlhttp.responseText.indexOf($townDelimiter, xmlhttp.responseText);
            townStr = xmlhttp.responseText.substring((breakerAddress2 + $address2Delimiter.length), breakerTown);
            document.getElementById(objID + '_postaltown').value = townStr;
          break;
        }
        
        // returning the county field
        $countyDelimiter = "COUNTY";
        breakerCounty = xmlhttp.responseText.indexOf($countyDelimiter, xmlhttp.responseText);
        countyStr = xmlhttp.responseText.substring((breakerTown + $townDelimiter.length), breakerCounty);
        document.getElementById(objID + '_county').value = countyStr;
        
        // returning the postcode field
        $postcodeDelimiter = "POSTCODE";
        breakerPostcode = xmlhttp.responseText.indexOf($postcodeDelimiter, xmlhttp.responseText);
        postcodeStr = xmlhttp.responseText.substring((breakerCounty + $countyDelimiter.length), breakerPostcode);
        document.getElementById(objID + '_postcode').value = postcodeStr;
        
      }
    }
  }  
  xmlhttp.send(null);  
}

function findInvoiceAddressHandler() {
  var postcode = document.getElementById('invoice_postcode');
  var houseNumber = document.getElementById('invoice_house_number');
  if(postcode.value != null) {
    getAddress("logicajax/addressFinder.php?postcode=" + postcode.value + '&house_number=' + houseNumber.value + '&obj=invoice_', 'invoice');
  }
}
function findDeliveryAddressHandler() {
  var postcode = document.getElementById('delivery_postcode');
  var houseNumber = document.getElementById('delivery_house_number');
  if(postcode.value != null) {
    getAddress("logicajax/addressFinder.php?postcode=" + postcode.value + '&house_number=' + houseNumber.value + '&obj=delivery_', 'delivery');
  }
}

function findMyAccountAddressHandler() {
  var postcode = document.getElementById('reg_postcode');
  if(postcode.value != null) {
    getAddress("logicajax/addressFinder.php?postcode=" + postcode.value + '&obj=reg_', 'reg');
  }
}

function exp_col_left_cat(section, name){
  var content = 'side_menu_'+section;
  var link = 'side_menu_expand_'+section;
  /*if(document.getElementById(content).style.display == 'none'){
    document.getElementById(content).style.display = 'block';
    document.getElementById(link).innerHTML = '<a href=\"javascript: void(0); exp_col_left_cat('+section+', \''+name+'\')\" title=\"Collapse '+ name +' section\">\r\nCollapse\r\n<br/>\r\n<img src=\"images/template/collapse_arrow.gif\" width=\"9\" height=\"10\" alt=\"Collapse section\" title=\"Collapse '+ name +' section\" />\r\n</a>\r\n';
  }else{
    document.getElementById(content).style.display = 'none';
    document.getElementById(link).innerHTML = '<a href=\"javascript: void(0); exp_col_left_cat('+section+', \''+name+'\')\" title=\"Expand '+ name +' section\">\r\nExpand\r\n<br/>\r\n<img src=\"images/template/expand_arrow.gif\" width=\"9\" height=\"10\" alt=\"Expand section\" title=\"Expand '+ name +' section\" />\r\n</a>\r\n';
  }*/
  if(document.getElementById(content).className == 'side_menu_products_collapsed'){
    document.getElementById(content).className = 'side_menu_products';
    document.getElementById(link).innerHTML = '<a href=\"javascript: void(0); exp_col_left_cat('+section+', \''+name+'\')\" title=\"Collapse '+ name +' section\">\r\nCollapse\r\n<br/>\r\n<img src=\"images/template/collapse_arrow.gif\" width=\"9\" height=\"10\" alt=\"Collapse section\" title=\"Collapse '+ name +' section\" />\r\n</a>\r\n';
  }else{
    document.getElementById(content).className = 'side_menu_products_collapsed';
    document.getElementById(link).innerHTML = '<a href=\"javascript: void(0); exp_col_left_cat('+section+', \''+name+'\')\" title=\"Expand '+ name +' section\">\r\nExpand\r\n<br/>\r\n<img src=\"images/template/expand_arrow.gif\" width=\"9\" height=\"10\" alt=\"Expand section\" title=\"Expand '+ name +' section\" />\r\n</a>\r\n';
  }
}