/**
 * teclan JavaScript file for The Nail Company.
 * @version	1.0
 * @date	08/10/08
 * @author	Lewis A MacKenzie
 * Copyright teclan 2008
 */

String.prototype.trim = function() { 
  return this.replace(/^\s+|\s+$/, '');
};

var $$ = function(id) {
  return document.getElementById(id);
};

function fixSearches() {
  var searchType = $$('searchType');
  var searchBrand = $$('searchBrand');
  if (searchType && searchBrand) {
    var opts = searchType.getElementsByTagName("OPTION");
	for (var i = 0; i < opts.length; i++) {
	  opts[i].value = opts[i].value.toLowerCase();
	}
	opts = searchBrand.getElementsByTagName("OPTION");
	for (var i = 0; i < opts.length; i++) {
	  opts[i].value = opts[i].value.toLowerCase();
	}
  }
}

if (window.attachEvent) { 
  window.attachEvent("onload", fixSearches); 
} 
else {  
  window.addEventListener("load", fixSearches, false); 
}

//The HTTP request object
var request = null;
var mainForm = null;

/**
 * Called when the user adds to cart. It sets the 
 * loading image visible and initialises the HTTP request.
 */
function addToCart(theForm) {
  //var theForm = document.getElementById(theFormID);
  if (theForm) {
	mainForm = theForm;
    setLoaderVisible(true);
	var qs = getQueryString(theForm);
  	httpRequest("POST", "http://www.thenailcompany.co.uk/cgi-bin/ca000999.cgi", true, qs);
  }
}

/**
 * Updates the contents of the ibox with a message and a loading image.
 */
function setLoaderVisible(visible) {
  /*var iboxATC = document.getElementById("ibox_content");
  if (iboxATC) {
     iboxATC.innerHTML = "<div align='center'><br>Please wait while your shopping cart is updated...<br><br><img src='addingToCart.gif' /></div>";
  }*/
  if (visible) {
    //mainForm.parentNode.innerHTML = "<div><br>Please wait while your shopping cart is updated...<br><br><img src='addingToCart.gif' /></div>";
	mainForm.style.display = "none";
	document.getElementById("loader").style.display = "block";
  }
  else {
	document.getElementById("loader").style.display = "none";
  }
}

function showCartOptions() {
  var elem = document.getElementById('atc');
  if (elem) {
    elem.style.display = elem.style.display == 'block' ? 'none' : 'block';
  }
}

/**
 * Parses a form and builds a query string.
 */
function getQueryString(theForm) {

  var queryString = "";
  var elementCount = theForm.elements.length;
  for (var i = 0; i < elementCount; i++) {
      queryString += theForm.elements[i].name + "=" + encodeURIComponent(theForm.elements[i].value);
      if (i < elementCount - 1) queryString += "&";
  }
  return queryString;
  //return "SID=22&PAGE=PRODUCT&PAGEFILENAME=K-Sa-Ra__.html&Q_22=1";
}

/**
 * Initialises the HTTP request object and then posts the query.
 */
function httpRequest(reqType, url, asynch, queryString) {
  //Mozilla
  if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
  }
  //Microsoft
  else if (window.ActiveXObject) {
    request = new ActiveXObject("Msxml2.XMLHTTP");
    if (!request) request = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (request) {
    request.onreadystatechange = handleResponse;
    try {
      request.open(reqType, url, asynch);
      request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      request.send(queryString);
    }
    catch (e) {
      alert(e);
    }
  }
  else {
    window.alert("Your browser does not support AJAX!");
  }
}

/**
 * Handles the response from the HTTP request.
 */
function handleResponse() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      if (request.responseText.indexOf("<!--ATCERROR-->") == -1) {
		//hideIbox();
		setLoaderVisible(false);
		changeOpac(0, 'cart-status');
		document.getElementById('cart-status').style.display = 'block';
		doOpacity('cart-status', 0, 100, 800);
      }
      else {
        alert("Failed");
      }
    }
    else {
      window.alert("XMLHttpRequest failed!");
    }
  }
}

/**
 * Quick function to get elemnt by id
 */
var $ = function(id) {
  return document.getElementById(id);
};

/**
 * Changes opacity of an element gradually.
 */
function doOpacity(id, opacStart, opacEnd, millisec) {
  var speed = Math.round(millisec / 100);
  var timer = 0;
  
  if (opacStart > opacEnd) {
    for(var i = opacStart; i >= opacEnd; i--) {
      setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
	  timer++;
    }
  } 
  else if (opacStart < opacEnd) {
    for (var i = opacStart; i <= opacEnd; i++) {
      setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
	  timer++;
    }
  }
}

/**
 * Cross-browser opacity changer.
 */
function changeOpac(opacity, id) {
  var object = document.getElementById(id).style; 
  object.opacity = (opacity / 100);
  object.MozOpacity = (opacity / 100);
  object.KhtmlOpacity = (opacity / 100);
  object.filter = "alpha(opacity=" + opacity + ")";
}

/**
 * Constructs an email body and opens default client.
 */
function emailAFriend(productName) {
  var script = "I thought you might be interested in " + productName + ".\n\nYou can view it at the following URL\n\n" + window.location;
  var subject = encodeURI(productName + " from The Nail Company");
  window.location.href = 'mailto:?subject=' + subject + '&body=' + encodeURI(script);
}

/**
 * Checks review form before submission.
 */
function checkReviewForm() {
  /*var theForm = $('ibox_content').getElementByTagsName('FORM')[0];
  if (theForm) {
    if (!theForm.Name.value) {
	  alert("Please enter your name.");
	  theForm.Name.focus();
	  return false;
	}
	if (!theForm.EmailAddress.value) {
	  alert("Please enter your email address.");
	  theForm.EmailAddress.focus();
	  return false;
	}
	if (!(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(theForm.EmailAddress.value))) {
	  alert("The email address must match the format 'name@domain.com'.");
	  theForm.EmailAddress.focus();
	  return false;
	}
	if (!theForm.Review.value) {
	  alert("Please enter your review text.");
	  theForm.Review.focus();
	  return false;
	}
  }*/
  return true;
}



/** legacy booking form code **/
function validateForm(theForm){
   		
   		if (theForm.forename.value==""){
			alert("You have omitted your first name!");
			theForm.forename.focus();
			return false;
			}		
		if (theForm.surname.value==""){
			alert("You have omitted your last name!");
			theForm.surname.focus();
			return false;
			}
		if (theForm.AddressLine1.value==""){
			alert("You have omitted part of your address!");
			theForm.AddressLine1.focus();
			return false;
			}
		if (theForm.Town.value==""){
			alert("You have omitted your town!");
			theForm.Town.focus();
			return false;
			}
		if (theForm.County.value==""){
			alert("You have omitted your county!");
			theForm.County.focus();
			return false;
			}
		if (theForm.Postcode.value==""){
			alert("You have omitted your postcode!");
			theForm.Postcode.focus();
			return false;
			}
		if (theForm.daytimeTelephone.value=="" && theForm.mobileTelephone.value==""){
			alert("You have omitted your telephone contact number!");
			theForm.daytimeTelephone.focus();
			return false;
			}
		coursesSelected=false;
		for (x=0;x<11;x++){
			if (theForm.Requested_Course[x].checked==true){
				coursesSelected=true;
			}
		}
		if (coursesSelected==false){
			alert("You have not selected any courses");
			return false;
		}
		if (isValidDate(theForm.Course_Date_1DBeg_Manicure)==false){
			return false;
			}
		if (isValidDate(theForm.Course_Date_2DBeg_NailExtension)==false){
			return false;
			}
		if (isValidDate(theForm.Course_Date_4DBeg_NailExtension)==false){
			return false;
			}
		if (isValidDate(theForm.Course_Date_1DInt_NailExtensionWS)==false){
			return false;
			}
		if (isValidDate(theForm.Course_Date_1DAdv_Manicure)==false){
			return false;
			}
		if (isValidDate(theForm.Course_Date_1DAdv_NailTechniquesWS)==false){
			return false;
			}
		if (isValidDate(theForm.Course_Date_6DaySuperSaver)==false){
			return false;
			}
		if (isValidDate(theForm.Course_Date_1DIntro_Spangles)==false){
			return false;
			}
		if (isValidDate(theForm.Course_Date_1DAdv_NailArt)==false){
			return false;
			}
		if (isValidDate(theForm.Course_Date_2D_SpanglesGold)==false){
			return false;
			}
		if (isValidDate(theForm.Course_Date_2D_MiniBeauty)==false){
			return false;
			}
			
		
		
   return true;
   }
   
   function isValidDate(field){
   		var isValid=true;
   		if (field.disabled==true){
			isValid=true;
			}
		else{
			 
			 dateArray=field.value.split("/")
			 if (dateArray.length!=3){
			 	isValid=false;
				}
			else{
				if (isNaN(dateArray[0])){
			 		isValid=false;
					}
				else{
					if(dateArray[0]<1 || dateArray[0]>31){
						isValid=false;
						}				
					}	
				if (isNaN(dateArray[1])){
				 	isValid=false;
					}
				else{
					if(dateArray[1]<1 || dateArray[1]>12){
						isValid=false;
						}				
					}	
				 if (isNaN(dateArray[2])){
				 	isValid=false;
					}
				else{
					if(dateArray[2]<2003){
						isValid=false;
						}
					}
				}
			
						
			if  (isValid==false){
				alert("You have entered an invalid date!\n\nPlease re-enter the date using then format\n\n\tdd/mm/yyyy")
				field.select();
				field.focus();
				}
			}
			
		return isValid;
			
			
   }


	function setDateField(theField, dateField){
		
		if (theField.checked==true){
			dateField.disabled=false;
			dateField.select();
			dateField.focus();
			}
		else{
			dateField.disabled=true;
			}
	}  
	
	function setTCstate(cb){
		if (cb.checked==true) {
			document.request.formSubmit.disabled=false;
			}
		else{
			document.request.formSubmit.disabled=true;
			}
	}



function addToFavourites(title) {
  var url = window.location.toString();
  if (window.sidebar) {
    window.sidebar.addPanel(title, url, "");
  }
  else if(window.opera && window.print) {
    var elem = document.createElement('a');
    elem.setAttribute('href', url);
    elem.setAttribute('title', title);
    elem.setAttribute('rel', 'sidebar');
    elem.click();
  } 
  else if (document.all) {
    window.external.AddFavorite(url, title);
  }
}

function checkSubFormCol() {
  var name = $$('tmname');
  var email = $$('tmemail');
  if (name) {
    if (name.value.trim() == '') {
	  window.alert("Please enter your name.");
	  name.focus();
	  return false;
	}
  }
  if (email) {
    if (!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(email.value)) {
	  window.alert("Please enter a valid email address.");
	  email.focus();
	  email.select();
	  return false;
	}
  }
  return name && email;
}

function saveAnchor(productAnchor) {
  var theURL = window.location.href.toString();
  if (window.location.hash) {
    theURL = theURL.substring(0, theURL.indexOf("#"));
  }
  setCookie("ACTINIC_REFERRER", theURL + "#" + productAnchor);
}