/***********************************************
** File:      %W%
** Created:   22.2.2005
** Author:    filali
** Modified:  03/14/05
** Copyright: I-Next Ltd
**
** Description:
**   Purchase javascript
** Updates:
**   23.08.06: Add function xmlhttpPost which allow the cgi to return results
**   05.10.05: Add functions (allDigits, inValidCharSet, isValidCreditCardNumber, LuhnCheck) to handle credit card check
***********************************************/
/* ident %W% */

function xmlhttpPost(strURL,queryStr) {
	var xmlHttpReq = false;
	var self = this;
	// Mozilla/Safari
	if (window.XMLHttpRequest) {
		self.xmlHttpReq = new XMLHttpRequest();
	}
	// IE
	else if (window.ActiveXObject) {
		self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	document.body.style.cursor='wait';
	self.xmlHttpReq.open('POST', strURL, true);
	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	self.xmlHttpReq.onreadystatechange = function() {
    if (self.xmlHttpReq.readyState == 4) {
      document.body.style.cursor='default';

      // Is it a success?
      var response = self.xmlHttpReq.responseText;
      var siteshortname = '';
      if (response.lastIndexOf('|') != -1) {
        response = response.split('|');
        siteshortname = response[1];
        response = response[0];
      }
      if (response == '1'){
        updatepage('The quantity has been updated successfully');

       // ok now we need to update the mini basket
       var cookie_name = siteshortname+'_basket_cookie';
       var theCookie = getCookie(cookie_name);
       if (theCookie != null) {
         theCookie = theCookie.split(':::');
         var nItems = theCookie[0];
         var total  = theCookie[1];
         var theSpan = document.getElementById('mini_basket_items');
         if (theSpan != null) {theSpan.innerHTML = nItems;}
         theSpan = document.getElementById('mini_basket_total');
         if (theSpan != null) {theSpan.innerHTML = total;}
       }
      }
      else{
        // display error message
        updatepage(self.xmlHttpReq.responseText);
      }
    }
	}
	self.xmlHttpReq.send(queryStr);
}

function updatepage(responseStr){
	alert(responseStr);
}

function process_form(product_code,sku_code,dimension,colour,basket_qty)
{

  // Check that the user accepts cookies
  if (document.cookie == ''){
    alert('Please Enable Cookies.\n\nIn order to use the Online Purchase System you need to enable cookies in your browser.\n');
  }
  else{

    // Initialise random number so that result will not be cached
    var randomnumber = Math.floor(Math.random()*10000000000000000000000000000000000000000000000001);

    // Build URL
    var url = "/cgi/eb_commerce/update_basket.cgi";

    // Set Parameters
    var queryString = "product_code=" + product_code + "&sku_code=" + sku_code ;
    queryString += "&dimension=" + dimension +"&colour=" + colour;
    queryString += "&quantity=" + basket_qty+'&ms='+randomnumber;

    // Execute query
    xmlhttpPost(url,queryString);
  }
}


function process_override_form(product_code,sku_code,dimension,colour,basket_qty,o_title,o_description,o_price)
{

  // Check that the user accepts cookies
  if (document.cookie == ''){
    alert('Please Enable Cookies.\n\nIn order to use the Online Purchase System you need to enable cookies in your browser.\n');
  }
  else{

    // Initialise random number so that result will not be cached
    var randomnumber = Math.floor(Math.random()*10000000000000000000000000000000000000000000000001);

    // Build URL
    var url = "/cgi/eb_commerce/update_basket_override.cgi";

    // Set Parameters
    var queryString = "product_code=" + product_code + "&sku_code=" + sku_code ;
    queryString += "&dimension=" + dimension +"&colour=" + colour;
    queryString += "&quantity=" + basket_qty +"&o_price=" + o_price;
    queryString += "&o_title=" + o_title+"&o_description="+o_description+'&ms='+randomnumber;
//alert(queryString);
    // Execute query
    xmlhttpPost(url,queryString);
  }
}

function update_config(purchase_item_id, mode, option, quantity, new_quantity, old_quantity, style_option, block_data) {

  // Check that the user accepts cookies
  if (document.cookie == ''){
    alert('Please Enable Cookies.\n\nIn order to use the Online Purchase System you need to enable cookies in your browser.\n');
  }
  else{

    // Initialise random number so that result will not be cached
    var randomnumber = Math.floor(Math.random()*10000000000000000000000000000000000000000000000001);

    // Build URL
    var url = "/cgi/eb_commerce/do_product_config.cgi";

    // Set Parameters
    var queryString = "purchase_item_id="+purchase_item_id+"&mode="+mode+"&option="+option+"&quantity="+quantity+"&new_quantity="+new_quantity+"&old_quantity="+old_quantity+"&ms="+randomnumber;

    // Do we have the personalisation inputs?
    if (update_config.arguments.length > 6) { queryString += "&style_option="+style_option };
    if (update_config.arguments.length > 7) { queryString += "&block_data="+block_data };

    // Execute query
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
      self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
      self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    document.body.style.cursor='wait';
    self.xmlHttpReq.open('POST', url, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
      if (self.xmlHttpReq.readyState == 4) {
        document.body.style.cursor='default';
        // Is it a success?
        var response = self.xmlHttpReq.responseText;
        if (response != 1) {
          alert(response);
        }
        else {

          if (old_quantity * new_quantity * quantity == 1) {

            var here = window.location.href;
            here = here.split('?');
            here = here[0];
            window.location = here;
          }
          else if (window.opener && !window.opener.closed) {
            var here = window.opener.location.href;
            here = here.split('?'); // remove the querystring
            here = here[0];
            window.opener.location = here;
            window.setTimeout("window.close()", 1);
          }
        }
      }
    }
    self.xmlHttpReq.send(queryString);
  }
}


function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
	var result = true;

	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}

	return result;
}

function isValidCreditCardNumber(payment_form){

 // Set variables
 var result = true;
 var ccNum = payment_form.card_number.value;

 // Check that the number is not null
 if (payment_form.card_number.value.length > 0){

   // Check it's just numbers
   if (!allDigits(ccNum)){
     alert('Please enter only numbers (no dashes or spaces) for the card number.');
     payment_form.card_number.focus();
     return false;
   }
   else{// Check it's valid
     if (!LuhnCheck(ccNum)){
       answer = confirm ("The card number <" + ccNum + "> appears to be invalid. Please click on 'Cancel' to change it or 'OK' to confirm.");
       if (answer == true){
         return true;
       }
       else{
         payment_form.card_number.focus();
         return false;
       }
     }
     else{
       return true;
     }
   }
 }
 else{// Submit the form
   return true;
 }
}

function LuhnCheck(str)
{
  var result = true;

  var sum = 0;
  var mul = 1;
  var strLen = str.length;

  for (i = 0; i < strLen; i++)
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;

  return result;
}

function getCookie(name) {
  // returns value of cookie or null if cookie does not exist
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

function do_config(mode, location, item, old_quantity, quantity, option) {
  var width=800;
  var height = 400;

  // create the query string
  var queryStr = "?mode="+mode+"&purchase_item_id="+item+"&old_quantity="+old_quantity+"&quantity="+quantity+"&option="+option;
  location = location + queryStr;
  // popup the config window
  if (mode != 'personalisation') {
    popup(location, width, height);
  }
  else {
    height = screen.height;
    popup(location, width, height, 1);  // need the scrollbars on
  }
}

function get_XY( new_width, new_height) {
  // returns the top left hand corner coords of the window centered horizontally.
  var scrolledX, scrolledY;
  if( self.pageYOffset ) {
    scrolledX = self.pageXOffset;
    scrolledY = self.pageYOffset;
  } else if( document.documentElement && document.documentElement.scrollTop ) {
    scrolledX = document.documentElement.scrollLeft;
    scrolledY = document.documentElement.scrollTop;
  } else if( document.body ) {
    scrolledX = document.body.scrollLeft;
    scrolledY = document.body.scrollTop;
  }

  // Determine the coordinates of the center of the page

  var centerX, centerY;
  if( self.innerHeight ) {
    centerX = self.innerWidth;
    centerY = self.innerHeight;
  } else if( document.documentElement && document.documentElement.clientHeight ) {
    centerX = document.documentElement.clientWidth;
    centerY = document.documentElement.clientHeight;
  } else if( document.body ) {
    centerX = document.body.clientWidth;
    centerY = document.body.clientHeight;
  }
  var x = centerX/2;
  var y = centerY/2;
  var x = x - (new_width / 2) - 16;
  var y = 50;  // config here to suit client's design

  return x+","+y;
}

function close_config() {
  // close the popup window
  if ( window.pop) {window.pop.close(); }
  if (window.opener && !window.opener.closed) {
    window.opener.location.reload();
  }
}

function popup( win, w, h, scroll ){
  if ( window.pop ){ window.pop.close(); } // close an open one
  if ( popup.arguments.length < 2 ){ w = 320; };
  if ( popup.arguments.length < 3 ){ h = 480; };
  if ( popup.arguments.length < 4 ){
   scroll = "scrollbars=0";
  }
  else {
    scroll = "scrollbars=1";
  }
  pop = window.open( win,'return','toolbar=no,location=no,directories=no,status=yes,'+scroll+',resizable=no,copyhistory=no,locationbar=no,width=' + w + ',height=' + h + ',screenX=0,screenY=0,top=0,left=0');

}

function swapImg (id, code, suffix) {
  // get the image
  var myImage = document.getElementById(id);
  if (myImage != null) {
    // construct the new image path
    var path = "/gifs/personalisation/"+code+"."+suffix;
    myImage.src = path;
  }


}






























