// the FireBug extension for Firefox offers a bonafide JavaScript error console
// to prevent errors in browsers without it, create a dummy console object
// with the required methods
try {
      console.log('Starting ' + window.location);
} catch (err) {
    var console = new Object;
    console.log = function() { return true };
    console.debug = function() { return true; }; 
    console.info = function() { return true; };
    console.warn = function() { return true; }; 
    console.error = function() { return true; };
    console.assert = function() { return true; };
    console.assertEquals = function() { return true; };
    console.assertNotEquals = function() { return true; };
    console.assertGreater = function() { return true; };
    console.assertNotGreater = function() { return true; };
    console.assertLess = function() { return true; };
    console.assertNotLess = function() { return true; };
    console.assertContains = function() { return true; };
    console.assertNotContains = function() { return true; };
    console.assertTrue = function() { return true; };
    console.assertFalse = function() { return true; };
    console.assertNull = function() { return true; };
    console.assertNotNull = function() { return true; };
    console.assertUndefined = function() { return true; };
    console.assertNotUndefined = function() { return true; };
    console.assertInstanceOf = function() { return true; };
    console.assertNotInstanceOf = function() { return true; };
    console.assertTypeOf = function() { return true; };
    console.assertNotTypeOf = function() { return true; };
    console.trace = function() { return true; }; 
    console.time = function() { return true; };
    console.timeEnd = function() { return true; }; 
    console.count = function() { return true; };
};

/*
   image swappers. swap the content of an image with
   an id imgview_something_unique with the content
   of an image with id imgview_something_large
*/
function SwapImgView (eventObject) {
    if(! this.id ) {
        return true;
    };
    if(! this.id.match(/^imgview_/)) {
        return true;
    };
    if(this.id.match(/_large$/)) {
        return true;
    };
    var thumbnailid = this.id;
    var elements = thumbnailid.match(/^imgview_(.+)_.+?$/);
    var groupid = elements[1];
    console.log('Swapping images for group ' + groupid);
    var largeid = 'imgview_' + groupid + '_large';
    if(! this.src) {
        return true;
    };
    var source1 = this.src;
    source1 = source1.replace(/\/75\//, '/334/');
    var largeimage = document.getElementById(largeid);
    if(! largeimage) {
        return true;
    };
    if(! largeimage.src) {
        return true;
    };
    var source2 = largeimage.src;
    source2 = source2.replace(/\/334\//, '/75/');
    this.src=source2;
    largeimage.src = source1;
    return true;
};

tagListeners.addListenerForTag('img', 'onclick', SwapImgView);

// for every input element AddProduct_#ProductNo add a hidden input field
// NumOf_#ProductNo to the form and submit it to the basket
// (ie it needs GLOBAL_URL_STORE)
function AddProductToBasket(eventObject) {
    if(! this.name ) {
        return true;
    };
    if(this.name != 'productform') {
        return true;
    };
    window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
    var ProductNos = new Object();
    for(var i = 0; i < this.elements.length ; i++) {
        if(this.elements[i].name && this.elements[i].name.match(/^AddProduct_/)) {
            var IsSelected = this.elements[i].value;
            if((this.elements[i].type == 'checkbox') || (this.elements[i].type == 'radio')){
                if(this.elements[i].checked) {
                    IsSelected = 1;
                };
            };
            if(IsSelected == '1') {
                var matches = this.elements[i].name.match(/^AddProduct_(.+)$/);
                var ProductNo = matches[1];
                appendField('NumOf_' + ProductNo, '1', 'hidden', this);
            };
        };
    };
    this.setAttribute('action',   GLOBAL_URL_STORE + '/Offer/MultiAddProduct');
    this.submit();
}
tagListeners.addListenerForTag('form', 'onsubmit', AddProductToBasket);

// the counter for the personal message
function showRemainingChars() {
  
  if(! this.name) {
    return true;
  };
  if(! this.name == 'in_ca_of_UD_AccompanyingText') {
    return true;
  }
  var textareaObj = this;

  var displayObj = document.getElementById('accompanyingtextcount');

  var currenttext = textareaObj.value;
  
  var currentlength = currenttext.length;
  var maxlength = 200;
  var left = maxlength - currentlength;

  if (left < 0 ) {
    currenttext = currenttext.slice(0,(maxlength-1));
    textareaObj.value = currenttext;
    left = 0;
  };
  
  if(displayObj) {
    displayObj.innerHTML = left;
  };
  return true;
};
tagListeners.addListenerForTag('textarea', 'onkeyup', showRemainingChars);
tagListeners.addListenerForTag('textarea', 'onkeydown', showRemainingChars);
tagListeners.addListenerForTag('textarea', 'onchange', showRemainingChars);

// check if the syntax of a UK postal code is correct
function checkPostCodeUK(postcode) {

        if(postcode.match(/^GIR 0AA$/i)) {
          return true;
        };

        var inner = '';
        var outer = '';

        if(! postcode.match(/^\s*([a-z0-9]{2,4})\s+([a-z0-9]{3})\s*$/i)) {
          return false;
        };
        var elements = postcode.match(/^\s*([a-z0-9]{2,4})\s+([a-z0-9]{3})\s*$/i);

        
        inner = elements[2];
        outer = elements[1];
        

        if(inner.match(/[cikmov]/i)){
          return false;
        };

        if(! inner.match(/^\d[a-z]{2}$/i)){
          return false;
        };

        if(outer.match(/^[a-z][0-9]$/i)){
          return true;
        };

        if(outer.match(/^[a-z][a-z]\d$/i)){
          return true;
        };

        if(outer.match(/^[a-z]\d[a-z0-9]$/i)){
          return true;
        };

        if(outer.match(/^[a-z]{2}\d[a-z0-9]$/i)){
          return true;
        };


        return false;
      };



/*********************************************************

  validate the delivery data form. rather complex as
  this form can be valid when one of a group of fields
  is filled in. works indirectly because this form
  gets submitted by an onclick event of an <a

*********************************************************/
function validateDeliveryData(eventObject) {
  if(! this.id) {
    return true;
  };
  if(this.id != 'button_continue') {
    return true;
  };


  window.event? event.returnValue = false : eventObject.preventDefault();

  var formObject = document.forms['shippingaddressform'];
  
  // close the error div.
  var errorDisplay = document.getElementById('errordisplay');
  if(errorDisplay) {
    errorDisplay.style.display = 'none';
  }
  // some code nicked from the Utilities lib. Sorry.
  // build a hash labels that contains inputname => label object
  // also, reset all labels to their original color if possible
  var allLabels = document.getElementsByTagName('label');
  var labels = new Object;
  for(var i =0 ;i < allLabels.length ;i++) {
    // IE dies a horrible death if you try to access its for attribute.
    // Hence a custom attribute it is. Grrr.
    var labelInputName = allLabels[i].getAttribute('inputname');
    if(labelInputName) {
      var labelObject = allLabels[i];
      var labelObjectOrigColor = labelObject.getAttribute('origcolor');
      if(labelObjectOrigColor) {
        labelObject.style.color = labelObjectOrigColor;
      };
      labels[labelInputName] = labelObject;
    }
  };
  if(! validateFormRegExp(formObject)) {
    return false;
  };

  var errorColor = '#ff0000';
  // deal with flatno/propertyname/propno
  var flatNo =   getInputValue('in_ca_of_UD_ShippingFlatNumber', formObject);
  var propNo = getInputValue('in_ca_of_UD_ShippingPropertyNumber', formObject);
  var labelNames = ['in_ca_of_UD_ShippingFlatNumber',  'in_ca_of_UD_ShippingPropertyNumber'];
  if((! flatNo.match(/[a-zA-Z0-9]+/)) &&  (! propNo.match(/[a-zA-Z0-9]+/))) {

    for(var i = 0; i < labelNames.length ; i++) {
      var labelName = labelNames[i];
      var labelObject = labels[labelName];
      
    
      // get the original color for the label
      if(labelObject) {
        var labelStyleString ='';
        var labelObjectOrigColor = labelObject.getAttribute('origcolor');
        if(! labelObjectOrigColor) {
          labelObjectOrigColor = getStyle(labelObject, 'color');
          labelObject.setAttribute('origcolor', labelObjectOrigColor);
        };
        // and make it red
        labelObject.style.color = errorColor;
      };
    }
    errorDisplay.innerHTML = 'Please supply a flat number, property number or property name.';
    errorDisplay.style.display = 'block';
    for(var i = 0; i < formObject.elements.length ; i++) {
      if(formObject.elements[i].name == 'in_ca_of_UD_ShippingFlatNumber') {
        formObject.elements[i].focus();
        return false;
      }
    }
  };
  
  // check the postcode
  var PostcodeP1 = getInputValue('ShippingZipCode1', formObject);
  var PostcodeP2 = getInputValue('ShippingZipCode2', formObject);
  var PostcodeFull = PostcodeP1 + ' ' + PostcodeP2;
  if(! checkPostCodeUK(PostcodeFull)) {
    var labelObject = labels['in_ca_of_UD_ShippingZipCode'];
    if(labelObject) {
      var labelStyleString ='';
      var labelObjectOrigColor = labelObject.getAttribute('origcolor');
      if(! labelObjectOrigColor) {
        labelObjectOrigColor = getStyle(labelObject, 'color');
        labelObject.setAttribute('origcolor', labelObjectOrigColor);
      };
      labelObject.style.color = errorColor;
    };
    for(var i = 0; i < formObject.elements.length ; i++) {
      if(formObject.elements[i].name == 'ShippingZipCode1') {
        formObject.elements[i].focus();
        errorDisplay.innerHTML = 'Please supply a valid postcode';
        errorDisplay.style.display = 'block';
        return false;
      }
    }    
  }
  setInputValue('in_ca_of_UD_ShippingZipCode', formObject, PostcodeFull);
  formObject.submit();
}
tagListeners.addListenerForTag('a', 'onclick', validateDeliveryData);

// the full postcode goes into in_ca_of_UD_ShippingZipCode. if thisfield is not
// empty onload, split it and put the two elements in ShippingZipCode1 and
// ShippingZipCode2
function transferShippingZipCodeToSeparateFields() {
  var formObject = document.forms['shippingaddressform'];
  if(! formObject) {
    return true;
  };
  var PostcodeFull = getInputValue('in_ca_of_UD_ShippingZipCode', formObject);
  var PostcodeElements = PostcodeFull.split(/\s+/);
  if(PostcodeElements.length == 2) {
    var PostcodeP1 = PostcodeElements[0];
    var PostcodeP2 = PostcodeElements[1];
    setInputValue('ShippingZipCode1', formObject, PostcodeP1);
    setInputValue('ShippingZipCode2', formObject, PostcodeP2);    
  }
  return true;
}
window.addOnLoadListener(transferShippingZipCodeToSeparateFields);


/*********************************************************

  validate the billing data form. rather complex as
  this form can be valid when one of a group of fields
  is filled in. works indirectly because this form
  gets submitted by an onclick event of an <a

*********************************************************/
function validateBillingData(eventObject) {
  if(! this.id) {
    return true;
  };
  if(this.id != 'button_continue2') {
    return true;
  };

  // don't stop the event here. the error message is at the top and the
  // page is rather long so we *want* to return to the top
  //window.event? event.returnValue = false : eventObject.preventDefault();

  var formObject = document.forms['registrationform'];
  
  // close the error div.
  var errorDisplay = document.getElementById('errordisplay');
  if(errorDisplay) {
    errorDisplay.style.display = 'none';
  }
  // some code nicked from the Utilities lib. Sorry.
  // build a hash labels that contains inputname => label object
  // also, reset all labels to their original color if possible
  var allLabels = document.getElementsByTagName('label');
  var labels = new Object;
  for(var i =0 ;i < allLabels.length ;i++) {
    // IE dies a horrible death if you try to access its for attribute.
    // Hence a custom attribute it is. Grrr.
    var labelInputName = allLabels[i].getAttribute('inputname');
    if(labelInputName) {
      var labelObject = allLabels[i];
      var labelObjectOrigColor = labelObject.getAttribute('origcolor');
      if(labelObjectOrigColor) {
        labelObject.style.color = labelObjectOrigColor;
      };
      labels[labelInputName] = labelObject;
    }
  };
  if(! validateFormRegExp(formObject)) {
    return false;
  };

  var errorColor = '#ff0000';
  // deal with flatno/propertyname/propno
  var flatNo =   getInputValue('in_ca_cu_UD_Cust_FlatNumber', formObject);
  var propNo = getInputValue('in_ca_cu_UD_Cust_PropertyNumber', formObject);
  var labelNames = ['in_ca_cu_UD_Cust_FlatNumber', 'in_ca_cu_UD_Cust_PropertyNumber'];
  if((! flatNo.match(/[a-zA-Z0-9]+/)) &&  (! propNo.match(/[a-zA-Z0-9]+/))) {

    for(var i = 0; i < labelNames.length ; i++) {
      var labelName = labelNames[i];
      var labelObject = labels[labelName];    
    
      // get the original color for the label
      if(labelObject) {
        var labelStyleString ='';
        var labelObjectOrigColor = labelObject.getAttribute('origcolor');
        if(! labelObjectOrigColor) {
          labelObjectOrigColor = getStyle(labelObject, 'color');
          labelObject.setAttribute('origcolor', labelObjectOrigColor);
        };
        // and make it red
        labelObject.style.color = errorColor;
      };
    }
    errorDisplay.innerHTML = 'Please supply a flat number, property number or property name.';
    errorDisplay.style.display = 'block';
    for(var i = 0; i < formObject.elements.length ; i++) {
      if(formObject.elements[i].name == 'in_ca_cu_UD_Cust_FlatNumber') {
        formObject.elements[i].focus();
        return false;
      }
    }
  };

  
  // check the postcode
  var PostcodeP1 = getInputValue('zipcode1', formObject);
  var PostcodeP2 = getInputValue('zipcode2', formObject);
  var PostcodeFull = PostcodeP1 + ' ' + PostcodeP2;
  if(! checkPostCodeUK(PostcodeFull)) {
    var labelObject = labels['zipcode'];
    if(labelObject) {
      var labelStyleString ='';
      var labelObjectOrigColor = labelObject.getAttribute('origcolor');
      if(! labelObjectOrigColor) {
        labelObjectOrigColor = getStyle(labelObject, 'color');
        labelObject.setAttribute('origcolor', labelObjectOrigColor);
      };
      labelObject.style.color = errorColor;
    };
    for(var i = 0; i < formObject.elements.length ; i++) {
      if(formObject.elements[i].name == 'zipcode1') {
        formObject.elements[i].focus();
        errorDisplay.innerHTML = 'Please supply a valid postcode';
        errorDisplay.style.display = 'block';
        return false;
      }
    };
  }



  // deal with phone numbers
  var home =   getInputValue('in_ca_cu_UD_Cust_HomePhone', formObject);
  var work = getInputValue('in_ca_cu_UD_Cust_WorkPhone', formObject);
  var mobile = getInputValue('in_ca_cu_UD_Cust_MobilePhone', formObject);
  var phoneLabelNames = ['in_ca_cu_UD_Cust_HomePhone', 'in_ca_cu_UD_Cust_WorkPhone', 'in_ca_cu_UD_Cust_MobilePhone'];
  if((! home.match(/[a-zA-Z0-9]+/)) && (! work.match(/[a-zA-Z0-9]+/)) && (! mobile.match(/[a-zA-Z0-9]+/))) {

    for(var i = 0; i < phoneLabelNames.length ; i++) {
      var labelName = phoneLabelNames[i];
      var labelObject = labels[labelName];    
    
      // get the original color for the label
      if(labelObject) {
        var labelStyleString ='';
        var labelObjectOrigColor = labelObject.getAttribute('origcolor');
        if(! labelObjectOrigColor) {
          labelObjectOrigColor = getStyle(labelObject, 'color');
          labelObject.setAttribute('origcolor', labelObjectOrigColor);
        };
        // and make it red
        labelObject.style.color = errorColor;
      };
    }
    errorDisplay.innerHTML = 'Please supply a phone number';
    errorDisplay.style.display = 'block';
    for(var i = 0; i < formObject.elements.length ; i++) {
      if(formObject.elements[i].name == 'in_ca_cu_UD_Cust_HomePhone') {
        formObject.elements[i].focus();
        return false;
      }
    }
  };
  
  // process the referral separately to avoid jumping to a place in the page where
  // the error message can't be seen
  var labelObjectReferral = labels['in_ca_cu_Referral'];
  if(labelObjectReferral.getAttribute('origcolor')) {
    labelObject.style.color = labelObjectReferral.getAttribute('origcolor');
  };
  var errorDisplayReferral= document.getElementById('errordisplayreferral');
  if(errorDisplayReferral) {
    errorDisplayReferral.style.display = 'none';
  }
  var Referral= getInputValue('in_ca_cu_Referral', formObject);
  if(! Referral) {
    var labelObjectOrigColor = labelObjectReferral.getAttribute('origcolor');
    if(! labelObjectOrigColor) {
      labelObjectOrigColor = getStyle(labelObjectReferral, 'color');
      labelObjectReferral.setAttribute('origcolor', labelObjectOrigColor);
    };
    labelObjectReferral.style.color = errorColor;
    if(errorDisplayReferral) {
      errorDisplayReferral.innerHTML = 'Please tell us how you heard about this site.';
      errorDisplayReferral.style.display = 'block';
    };
    for(var i = 0 ; i < formObject.elements.length ; i++) {
      if(formObject.elements[i].name && (formObject.elements[i].name == 'in_ca_cu_Referral')) {
        // the payment dropdown is too far down. focus doesn't work
        this.href='#selectreferral';
        formObject.elements[i].focus();
      }
    };
    return false;
    
  }
 
  for(var i = 0; i < formObject.elements.length ; i++) {
      if(formObject.elements[i].name && (formObject.elements[i].name == 'in_ca_cu_AcceptedTC')) {
	  if(! formObject.elements[i].checked) {
	      alert('Please accept the terms and conditions');
	      formObject.elements[i].focus();
	      return false;
	  };
      };
      if(formObject.elements[i].name && (formObject.elements[i].name == 'in_ca_cu_Accepted18')) {
	  if(! formObject.elements[i].checked) {
	      alert('Please confirm that you are over 18 years of age');
	      formObject.elements[i].focus();
	      return false;
	  };
      };

  }
  
  // process the payment method separately to avoid jumping to a place in the page where
  // the error message can't be seen
  var labelObjectPayment = labels['in_ca_cu_PaymentType'];
  if(labelObjectPayment.getAttribute('origcolor')) {
    labelObject.style.color = labelObjectPayment.getAttribute('origcolor');
  };
  var errorDisplayPayment = document.getElementById('errordisplaypayment');
  if(errorDisplayPayment) {
    errorDisplayPayment.style.display = 'none';
  }
  var PaymentMethod = getInputValue('in_ca_cu_PaymentType', formObject);
  if(! PaymentMethod) {
    var labelObjectOrigColor = labelObjectPayment.getAttribute('origcolor');
    if(! labelObjectOrigColor) {
      labelObjectOrigColor = getStyle(labelObjectPayment, 'color');
      labelObjectPayment.setAttribute('origcolor', labelObjectOrigColor);
    };
    labelObjectPayment.style.color = errorColor;
    if(errorDisplayPayment) {
      errorDisplayPayment.innerHTML = 'Please select a payment method';
      errorDisplayPayment.style.display = 'block';
    };
    for(var i = 0 ; i < formObject.elements.length ; i++) {
      if(formObject.elements[i].name && (formObject.elements[i].name == 'in_ca_cu_PaymentType')) {
        // the payment dropdown is too far down. focus doesn't work
        this.href='#selectpaymentmethod';
        formObject.elements[i].focus();
      }
    };
    return false;
    
  }
  
  setInputValue('zipcode', formObject, PostcodeFull);
  formObject.submit();
}
tagListeners.addListenerForTag('a', 'onclick', validateBillingData);

// the full postcode goes into zipcode. if thisfield is not
// empty onload, split it and put the two elements in zipcode1 and
// zipcode2
function transferBillingZipCodeToSeparateFields() {
  var formObject = document.forms['registrationform'];
  if(! formObject) {
    return true;
  };
  var PostcodeFull = getInputValue('zipcode', formObject);
  var PostcodeElements = PostcodeFull.split(/\s+/);
  if(PostcodeElements.length == 2) {
    var PostcodeP1 = PostcodeElements[0];
    var PostcodeP2 = PostcodeElements[1];
    setInputValue('zipcode1', formObject, PostcodeP1);
    setInputValue('zipcode2', formObject, PostcodeP2);    
  }
  return true;
}
window.addOnLoadListener(transferBillingZipCodeToSeparateFields);


// while we're developing ignore google
//function urchinTracker() {
//    return true;
//};

function copyCode() {
  if(!this.name) {
    return true;
  }
  if(this.name != "submitvoucher") {
    return true;
  }
  var frm = document.forms.basketform;
  if(!frm) {
    return true;
  }
  var valuecode = frm.MarketingActionValueCode.value;
  if(valuecode == "" || valuecode == " ") {
    return true;
  }
  for(var i = 0; i < frm.elements.length; i++) {
    if(frm.elements[i].name.indexOf("MarketingActionValueCode_") > -1) {
      frm.elements[i].value = valuecode;
    }
  }
}
tagListeners.addListenerForTag('input', 'onclick', copyCode);




// Google analytics for the order confirmation page
if(GLOBAL_TEMPLATEID == 'OrderConfirmation') {
    try {
        window.addOnLoadListener(__utmSetTrans);
    } catch (err) {
        console.log('unable to assign google analytics for order conf page');
    };
};  


var faqExpandInfo = function(eventObject) {
    if(! this.href) {
        return true;
    };
    if(! this.href.match(/^.+\/opendiv_/)) {
        return true;
    };
    var divID = this.href.replace(/^.+\/opendiv_/, '');
    window.event? event.returnValue = false : eventObject.preventDefault();
    var divToOpen = document.getElementById(divID);
    if(divToOpen) {
        var divContainer = document.getElementById('faq_container');
        if(divContainer) {
            for(var i = 0; i < divContainer.childNodes.length ; i++) {
                var elementObject = divContainer.childNodes[i];
                if(! elementObject.tagName) {
                    continue;
                };
                if(! elementObject.id) {
                    continue;
                };
                if(elementObject.id.match(/^faq/)) {
                    elementObject.style.display = 'none';
                }
            }
        }
        divToOpen.style.display = 'block';
    }
};
tagListeners.addListenerForTag('a', 'onclick', faqExpandInfo);  
