// Holds an instance of XMLHttpRequest

var xmlHttp = createXmlHttpRequestObject();



// Display error messages (true) or degrade to non-AJAX behavior (false) 

var showErrors = true;



// Contains the link or form clicked or submitted by the visitor

var actionObject = '';



// This is true when the Place Order button is clicked, false otherwise

var placingOrder = false;

// Creates an XMLHttpRequest instance

function createXmlHttpRequestObject()

{

  // Will store the XMLHttpRequest object

  var xmlHttp;



  // Create the XMLHttpRequest object

  try

  {

    // Try to create native XMLHttpRequest object 

    xmlHttp = new XMLHttpRequest();

  }

  catch(e)

  {

    // Assume IE6 or older

    var XmlHttpVersions = new Array(

      "MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", 

      "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");



    // Try every id until one works

    for (i = 0; i < XmlHttpVersions.length && !xmlHttp; i++)

    {

      try

      {

        // Try to create XMLHttpRequest object

        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);

      }

      catch (e) {} // Ignore potential error

    }

  }



  // If the XMLHttpRequest object was created successfully, return it 

  if (xmlHttp)

  {

    return xmlHttp;

  }

  // If an error happened, pass it to handleError

  else 

  {

    handleError("Error creating the XMLHttpRequest object.");

  }

}



// Displays an the error message or degrades to non-AJAX behavior

function handleError($message)

{

  // Ignore errors if showErrors is false

  if (showErrors)

  {

    // Display error message

    alert("Error encountered: \n" + $message);

    return false;

  }

  // Fall back to non-AJAX behavior 

  else if (!actionObject.tagName)

  {

    return true;

  }

  // Fall back to non-AJAX behavior by following the link

  else if (actionObject.tagName == 'A')

  {

    window.location = actionObject.href;

  }

  // Fall back to non-AJAX behavior by submitting the form

  else if (actionObject.tagName == 'FORM')

  {

    actionObject.submit();

  }

}



// Adds a product to the shopping cart

function addProductToCart(form)

{

	

stock=parseInt(document.getElementById('Stock').value);

quantity=parseInt(document.getElementById('Quantity').value);

cartquantity=document.getElementById('cartQuantity').value;



if(cartquantity!=""){

	checkQuantity=parseInt(quantity+parseInt(cartquantity));

}else{

	checkQuantity=quantity;

}

if(checkQuantity <= stock){

  // Display "Updating" message

  document.getElementById('updating').style.visibility = 'visible';



  // Degrade to classical form submit if XMLHttpRequest is not available 

  if (!xmlHttp) return true;



  // Create the URL we open asynchronously 

  request = form.action + '&AjaxRequest';

  params  = null;

  // obtain selected attributes

  formSelects = form.getElementsByTagName('SELECT');



if (formSelects)

  {

    for (i = 0; i < formSelects.length; i++)

    {

      params += '&' + formSelects[i].name + '=';

      selected_index = formSelects[i].selectedIndex;

      params += encodeURIComponent(formSelects[i][selected_index].text);

    }

  }



  // Try to connect to the server

  try

  {

    // Continue only if the XMLHttpRequest object isn't busy

    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)

    {

      // Make a server request to validate the extracted data

      xmlHttp.open("POST", request);

      xmlHttp.setRequestHeader("Content-Type", 

                               "application/x-www-form-urlencoded");

      xmlHttp.onreadystatechange = addToCartStateChange;

      xmlHttp.send(params);

    }

  }

  catch (e)

  {

    // Handle error

    handleError(e.toString());

  }

  return false;

}else{

  document.getElementById('stockError').style.display = 'block';

  return false;



}

  // Stop classical form submit if AJAX action succeeded

}



// Function that retrieves the HTTP response

function addToCartStateChange()

{

  // When readyState is 4, we also read the server response

  if (xmlHttp.readyState == 4)

  {

    // Continue only if HTTP status is "OK"

    if (xmlHttp.status == 200)

    {

      try

      {

		 updateCartSummary();

      }

      catch (e)

      {

        handleError(e.toString());

      }

    }

    else

    {

      handleError(xmlHttp.statusText);

    }

  }

}



// Process server's response

function updateCartSummary()

{

  // Read the response

  response = xmlHttp.responseText;

    // Server error?

  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error") >= 0)

  {

    handleError(response);

  }

  else

  {

    // Extract the contents of the cart_summary div element

    var cartSummaryRegEx = /^<div class="box" id="basket" align="right">([\s\S]*)<\/div>$/m;

    matches = cartSummaryRegEx.exec(response);

    response = matches[1];

	// Update the cart summary box and hide the Loading message

    document.getElementById("basket").innerHTML = response;

    // Hide the "Updating..." message

	document.getElementById('updating').style.visibility = 'hidden';

  }

}







// Update the cart details shopping cart

function updateCartSum(quantity)

{

    document.getElementById('quantity').innerHTML = quantity;

}





// Called on shopping cart update actions

function executeCartAction(obj)

{

  // Degrade to classical form submit for Place Order action

  if (placingOrder) return true;



  // Display "Updating..." message

  document.getElementById('updating').style.visibility = 'visible';

  // Degrade to classical form submit if XMLHttpRequest is not available 

  if (!xmlHttp) return true;



  // Save object reference 

  actionObject = obj;

  

  // Initialize response and parameters

  response = '';

  params = '';

  q = '';



  // If a link was clicked we get its href attribute

  if (obj.tagName == 'A')

  {

    url = obj.href + '&AjaxRequest';

  }

  // If the form was submitted we get its elements

  else

  {

    url = obj.action + '&AjaxRequest';

    formElements = obj.getElementsByTagName('INPUT');



    if (formElements)

    {

      for (i = 0; i < formElements.length; i++)

      {

        if (formElements[i].name != 'place_order')

        {

          params += '&' + formElements[i].name + '=';

          params += encodeURIComponent(formElements[i].value);

		  }

      }

    }

  }



  // Try to connect to the server

  try

  {

    // Make server request only if the XMLHttpRequest object isn't busy

    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)

    { 

      xmlHttp.open("POST", url, true);

      xmlHttp.setRequestHeader("Content-Type", 

                               "application/x-www-form-urlencoded");

      xmlHttp.onreadystatechange = cartActionStateChange;

      xmlHttp.send(params);

	  }

  }

  catch (e)

  {

    // Handle error

    handleError(e.toString());

  }



  // Stop classical form submit if AJAX action succeeded

  return false;

}



// Function that retrieves the HTTP response

function cartActionStateChange()

{

  // When readyState is 4, we also read the server response

  if (xmlHttp.readyState == 4)

  {

    // Continue only if HTTP status is "OK"

    if (xmlHttp.status == 200)

    {

      try

      {

        // Read the response

        response = xmlHttp.responseText;

        // Server error?

        if (response.indexOf("ERRNO") >= 0 || response.indexOf("error") >= 0)

        {

          handleError(response);

        }

        else

        {

          // Update the cart

          document.getElementById("contents").innerHTML = response;

		  // Hide the "Updating..." message

          document.getElementById('updating').style.visibility = 'hidden';



// Editing the cart details basket

formQuantity=document.getElementsByName('quantity[]');

totalAmount=document.getElementById('TotalAmount');

Quan=0;

		if(formQuantity.length <= 0){

		document.getElementById('nCart').innerHTML='<p class="empty-cart">Your shopping cart is empty!</p>';

		}else{

			if (formQuantity)

				{

				  for (i = 0; i < formQuantity.length; i++)

				  {

					if (formQuantity[i].value != '')

					{

					   Quan += formQuantity[i].value * 1;

					}

				  }

			

				document.getElementById('quantity').innerHTML = 'Items: '+Quan;

					if(totalAmount != null){

					document.getElementById('Total').innerHTML = 'Total: &pound;'+totalAmount.value;

					}else{

						document.getElementById('Total').innerHTML = 'Total: &pound;0';

					}

			}

		}

	}

}

   catch (e)

   {

    // Handle error

   handleError(e.toString());

    }

    }

    else

    {

      // Handle error

      handleError(xmlHttp.statusText);

    }

  }

}



function checkAbove(){

	if(document.getElementById('checkABove').checked==true){

document.getElementById('dename').value=document.getElementById('name').value;

document.getElementById('desurname').value=document.getElementById('surname').value;

document.getElementById('deaddress1').value=document.getElementById('address1').value;

document.getElementById('deaddress2').value=document.getElementById('address2').value;

document.getElementById('decity').value=document.getElementById('city').value;

document.getElementById('depostalCode').value=document.getElementById('postalCode').value;

document.getElementById('decountry').value=document.getElementById('country').value;

}

	if(document.getElementById('checkABove').checked==false){

document.getElementById('dename').value="";

document.getElementById('desurname').value="";

document.getElementById('deaddress1').value="";

document.getElementById('deaddress2').value="";

document.getElementById('decity').value="";

document.getElementById('depostalCode').value="";

//document.getElementById('decountry').value="";

}

}



function Changecolor(){

	document.getElementById('start').style.backgroundColor="#6C786E";

}

function Backcolor(){

	document.getElementById('start').style.backgroundColor="#533221";

}

function Changecolor_app(){

	document.getElementById('start').style.backgroundColor="#6C786E";

}

function Backcolor_app(){

	document.getElementById('start').style.backgroundColor="#000000";

}

function makeactive(tab,id,divID) 
{ 
	document.getElementById("productdetails").className = "";
	document.getElementById("leathercare").className = ""; 
	document.getElementById("delivery").className = ""; 
	document.getElementById("returns").className = ""; 
	document.getElementById(tab).className = "active"; 
	
	var product_id = id;
	var oXmlHttp = new XMLHttpRequest();
	
	var hostname = top.location.host;
	var url = "/presentation/get.php?"+tab+"&product_id="+product_id;

	oXmlHttp.open("get",url,true);

	oXmlHttp.onreadystatechange=function(){
		
		if(oXmlHttp.readyState==1){
			//productDetails("Loading",divID);
		}
		
		if(oXmlHttp.readyState==4){
			if(oXmlHttp.status==200){
				productDetails(oXmlHttp.responseText,divID);
			}else{
				productDetails("An error occurred: " + oXmlHttp.statusText,divID);
			}
		}
		
	};

oXmlHttp.send(null);
} 

function productDetails(sText, divID){
	var div=document.getElementById(divID);
	div.innerHTML=sText;
	var divheight = document.getElementById(divID).offsetHeight;
	if(divheight>70){
		var eheight = divheight - 100;
		var pcontainer = 540;
		var npcontiner  = pcontainer + eheight;
		document.getElementById('resizeheight').style.height = divheight +'px';
		document.getElementById('resizeheight').style.paddingTop = divheight +'px';
		document.getElementById('productDetailsContainer').style.height = npcontiner +'px';
	}
}

function pressenter(event){
	key = event.keyCode;
	if (key==13){
		subscrib('emailErr');
	}
}


function subscrib(divID) 
{ 
	var email = document.getElementById("email").value;
	var oXmlHttp = new XMLHttpRequest();
	var hostname = top.location.host;
	var url = "/presentation/get.php?email="+email;
	oXmlHttp.open("get",url,true);

	oXmlHttp.onreadystatechange=function(){
		
		if(oXmlHttp.readyState==1){
			newsletter("Loading",divID);
		}
		
		if(oXmlHttp.readyState==4){
			if(oXmlHttp.status==200){
				newsletter(oXmlHttp.responseText,divID);
			}else{
				newsletter("An error occurred: " + oXmlHttp.statusText,divID);
			}
		}
		
	};

oXmlHttp.send(null);
} 

function newsletter(sText, divID){
	var div=document.getElementById(divID);
	div.innerHTML=sText;
}

function changeZoom(clr,proimg){
	var newimg = clr.toLowerCase() + '_' + proimg;
	var hostname = top.location.host;
	var imgpath = "/product_images/"+newimg;
	document.getElementById('colorid').innerHTML = '<a href="'+imgpath+'" id="zoom1" class="MagicZoom MagicThumb" rev="'+imgpath+'" rel="zoom-width:648px; zoom-height:400px"><img src="'+imgpath+'" border="0"  width="270" height="200" /></a>';
}
