//send contact form
function sendContactForm(data)
{
	$('formContainer').style.display	= 'none';
	$('loader').style.display			= 'inline';
	new Ajax.Request('/contact/send' , {
										  method:'post', 
										  postBody:data,
										  onSuccess: function(transport){
										     var json = transport.responseText.evalJSON();
										     if(json.error) {
										     	$('formContainer').style.display	= 'inline';
												$('loader').style.display			= 'none';
										     	alert('Error detected!\n' + json.message);
											 } else {
											 	$('loader').style.display		= 'none';
											 	alert(json.message);
											 }
										   }
									  }
						);
}

function sendSubscriptionForm(data)
{
	$('formnewsletterShowElement').style.display	= 'none';
	$('formnewsletterloader').style.display			= 'inline';
	new Ajax.Request('/contact/send' , {
										  method:'post', 
										  postBody:data,
										  onSuccess: function(transport){
										     var json = transport.responseText.evalJSON();
										     if(json.error) {
										     	$('formnewsletterloader').style.display			= 'none';
										     	$('formnewsletterShowElement').style.display	= 'inline';
										     	alert(json.message);
											 } else {
											 	$('formnewsletterloader').style.display	= 'none';
											 	alert('Your subscription has been received');
											 }
										   }
									  }
						);
	return false;
}

//dummy var
var summary = 0;
var finish	= 0;

//reload shopping cart
function getShoppingCart()
{
	new Ajax.Request('/cart/smallshopping', {
										  method:'get',
										  onSuccess: function(transport){
										     var json = transport.responseText.evalJSON();
										     $('shoppingcart').innerHTML = json;
										     finish = 1;
										   }
									  }
						);
}

//reload full shopping cart
function shoppingCartDetail(currency)
{
	new Ajax.Request('/cart/fullshopping/currency/' + currency, {
										  method:'get',
										  onSuccess: function(transport){
										     var json = transport.responseText.evalJSON();
										     $('shoppingCartDetail').innerHTML = json.dynamic;
										     $('shoppingCartDetailStep2').innerHTML = json.static;
										     $('shoppingCartSummary').innerHTML = json.static;
										   }
									  }
						);
}

//change quantity of a product
function shoppingChangeQuantity(id, qte, currency)
{
	//change the value in the session array
	new Ajax.Request('/cart/modifyqte/product/' + id + '/qte/' + qte, {
										  method:'get',
										  onSuccess: function(transport){
										     var json = transport.responseText.evalJSON();
										     if(json.error) {
										     	alert('Error detected');
											 } else {
												//reload the shopping cart (big)
												shoppingCartDetail(currency);
												//reload the shopping cart (small)
												getShoppingCart();
											 }
										   }
									  }
						);
}

//remove item from the shopping cart
function shoppingRemoveProduct(id, currency)
{
	//change the value in the session array
	new Ajax.Request('/cart/remove/product/' + id , {
										  method:'get',
										  onSuccess: function(transport){
										     var json = transport.responseText.evalJSON();
										     if(json.error) {
										     	alert('Error detected');
											 } else {
											 	//reload the shopping cart (big)
												shoppingCartDetail(currency);
											 	//reload the shopping cart (small)
												getShoppingCart();
											 }
										   }
									  }
						);
}

//validate checkout form
function validateCheckOutForm(data)
{
	//change proceed image
	$('proceedIMG').style.display = 'none';
	$('processing').style.display = 'block';
	//change the value in the session array
	new Ajax.Request('/cart/validate' , {
										  method:'post', 
										  postBody:data,
										  onSuccess: function(transport){
										     //alert(transport.responseText);
										     var json = transport.responseText.evalJSON();
										     if(json.error) {
										     	$('proceedIMG').style.display = 'block';
												$('processing').style.display = 'none';
										     	alert('Error detected : \n' + json.message);
											 } else {
											 	//rebuild shopping cart
											 	shoppingCartDetail(json.devise)
											 	var loop = 0;
											 	while (loop < 1) {
											 		if (finish == 1) {
											 			loop 	= 1;	//to stop the loop
											 			copyBillingToShipping('billing', 'summarybilling', false);//copy billing informations into summary
											 			copyBillingToShipping('shipping', 'summaryshipping', false);//copy shipping informations into summary
											 			$('cc_number_summury').value 		= $('cc_number').value;
											 			$('cc_name_summury').value 			= $('cc_name').value;
											 			$('cc_type_summury').value 			= $('cc_type').value;
											 			$('cc_expire_month_summury').value 	= $('cc_expire_month').value;
											 			$('cc_expire_year_summury').value 	= $('cc_expire_year').value;
											 			$('orderID').innerHTML				= json.orderID;
											 			$('message').innerHTML				= json.message;
											 			summary = 1;	//redirect to summary
													 	checkSummary(); //show summary layer
													 	emptySC();		//empty the shopping cart
													 	window.location.href 				= '#topsummary';
												 	}
											 	}
											 }
										  }
									    }
						);
}

//help me choose
function getNextStep(id, step) 
{
    //get the next step
    $('productsAjax').innerHTML = '<p id="help-me-choose-title">Searching...</p>';

    if (parseFloat(step) < 4) {
        new Ajax.Updater('', '/help-me-choose/nextstep',
        {
    		method:'post',
    		postBody:'id='+id+'&step='+step+'&lang=en',
    		onComplete:	function(t){
    					   var output = t.responseText;
    					   if (output.match(/step output/i)) {
	    					   $('help-me-choose-cell'+step).innerHTML = output;
	                           $('help-me-choose-cell'+step).style.display = 'inline';
                           }
    					   //get the product link
                           //new Ajax.Updater('', '/help-me-choose/product',
                           //{
                           //  method:'post',
                           //  postBody:'id='+id+'&lang=en',
                           //  onComplete:	function(z){
                        //					   //alert(z.responseText);
                        //					   $('productsAjax').innerHTML = z.responseText;
                        //		            }
                        //	}
                        //	);
    		            }
    	}
    	);
    } 

    //get the product link
    new Ajax.Updater('', '/help-me-choose/product',
    {
        method:'post',
        postBody:'id='+id+'&lang=en',
        onComplete:	function(z){
                        //alert(z.responseText);
                        var html = z.responseText;
                        if (html.match(/table/i)) {
                      		$('productsAjax').innerHTML = '<div class="message">We recommend the following product(s):</div>' + html;
                      	} else {
                      		$('productsAjax').innerHTML = '';
                      	}
                    }
     }
     );
}

//reload shopping cart based on the selected country
function ReloadSC(country, state)
{
	if (country == 1) {
		//set the session var to Quebec
		new Ajax.Request('/cart/statesetter/state/' + state , 
		{
			method:'get', 
			onSuccess: 	function(transport){
							var json = transport.responseText.evalJSON();
							if(json.complete) {
								//reload
								shoppingCartDetail('CAD');
							}
						}
			});
		//show message
		$('currencyupdate').style.display = 'inline';
	} else {
		shoppingCartDetail('US');
		$('currencyupdate').style.display = 'none';
	}
}


function emptySC()
{
	new Ajax.Request('/cart/emptysc' , { method:'post'});
}

function validateSeoLogin(data)
{
	new Ajax.Request('/seo/validatelogin' , {
										  method:'post', 
										  postBody:data,
										  onSuccess: function(transport){
										     //alert(transport.responseText);
										     var json = transport.responseText.evalJSON();
										     if(json.error) {
										     	$('error').innerHTML = 'Invalid login';
											 } else {
											 	window.location.href  = '/seo';
											 }
										  }
										  });
}

function saveMetatag(data)
{
  $('error').innerHTML  = 'processing...';
	new Ajax.Request('/seo/saveedit' , {
										  method:'post', 
										  postBody:data,
										  onSuccess: function(transport){
										     //alert(transport.responseText);
										     var json = transport.responseText.evalJSON();
										     if(json.error) {
										     	$('error').innerHTML = json.message;
											 } else {
											 	$('error').innerHTML  = 'Data saved...';
											 	//$('formdiv').innerHTML = '';
											 }
										  }
										  });
}

//build URL by adding the product and quantity
function redirectAddProduct(productURL, quantity)
{
	var url = 'https://www.wheelimmobilizers.com/cart/add';
	url     = url + productURL + '/quantity/' + quantity;
	
	window.location.href = url;
	window.event.returnValue=false;
}

//check if user can have access to summary
function checkSummary()
{
	if (summary > 0) {
		$('lyr1').style.display='none';
		$('lyr2').style.display='none';
		$('lyr3').style.display='block';
		$('lyr1_img').src='/assets/progress_meter1_off.gif';
		$('lyr2_img').src='/assets/progress_meter2_off.gif';
		$('lyr3_img').src='/assets/progress_meter3_on.gif';
	} else {
		alert('You must complete the Checkout Information step before accessing the Summary.');
	}
}

//Copy billing information to shipping information
function copyBillingToShipping(from, to, callCreateProvince)
{
	['name_', 'company_', 'address_', 'city_', 'country_', 'state_', 'zip_', 'phone_', 'fax_', 'email_', 'emailconfirm_'].each(function(s) {
  		$(s + to).value = $(s + from).value
		if (s == 'country_' && callCreateProvince) {
				CreateProvince('country_' + to, 'state_' + to);
		}
	});
}

//Show prvince/state based on the country selection
function CreateProvince(country, state) 
{
  var Primary = $(country).selectedIndex;
  if ((Primary == null) || (Primary == 0)) return;
  if (Primary == 1) {
	  var ProvState = new Array;
	  ProvState[0] = new Option("Alberta");
	  ProvState[1] = new Option("British Columbia");
	  ProvState[2] = new Option("Manitoba");
	  ProvState[3] = new Option("New Brunswick");
	  ProvState[4] = new Option("Newfoundland");
	  ProvState[5] = new Option("Nova Scotia");
	  ProvState[6] = new Option("Northwest Territories");
	  ProvState[7] = new Option("Nunavut");
	  ProvState[8] = new Option("Ontario");
	  ProvState[9] = new Option("Prince Edward Island");
	  ProvState[10] = new Option("Quebec");
	  ProvState[11] = new Option("Saskatchewan");
	  ProvState[12] = new Option("Yukon");
  }

  if (Primary == 2) {
	  var ProvState = new Array;
	  ProvState[0] = new Option("Alabama");
	  ProvState[1] = new Option("Arizona");
	  ProvState[2] = new Option("Arkansas");
	  ProvState[3] = new Option("California");
	  ProvState[4] = new Option("Colorado");
	  ProvState[5] = new Option("Connecticut");
	  ProvState[6] = new Option("Delaware");
	  ProvState[7] = new Option("Florida");
	  ProvState[8] = new Option("Georgia");
	  ProvState[9] = new Option("IdahoState");
	  ProvState[10] = new Option("Illinois");
	  ProvState[11] = new Option("Indiana");
	  ProvState[12] = new Option("Iowa");
	  ProvState[13] = new Option("Kansas");
	  ProvState[14] = new Option("Kentucky");
	  ProvState[15] = new Option("Louisiana");
	  ProvState[16] = new Option("Maine");
	  ProvState[17] = new Option("Maryland");
	  ProvState[18] = new Option("Massachusetts");
	  ProvState[19] = new Option("Michigan");
	  ProvState[20] = new Option("Minnesota");
	  ProvState[21] = new Option("Mississippi");
	  ProvState[22] = new Option("Missouri");
	  ProvState[23] = new Option("Montana");
	  ProvState[24] = new Option("Nebraska");
	  ProvState[25] = new Option("Nevada");
	  ProvState[26] = new Option("NewHampshire");
	  ProvState[27] = new Option("NewJersey");
	  ProvState[28] = new Option("NewMexico");
	  ProvState[29] = new Option("NewYork");
	  ProvState[30] = new Option("NorthCarolina");
	  ProvState[31] = new Option("NorthDakota");
	  ProvState[32] = new Option("Ohio");
	  ProvState[33] = new Option("Oklahoma");
	  ProvState[34] = new Option("Oregon");
	  ProvState[35] = new Option("Pennsylvania");
	  ProvState[36] = new Option("RhodeIsland");
	  ProvState[37] = new Option("SouthCarolina");
	  ProvState[38] = new Option("SouthDakota");
	  ProvState[39] = new Option("Tennessee");
	  ProvState[40] = new Option("Texas");
	  ProvState[41] = new Option("Utah");
	  ProvState[44] = new Option("Vermont");
	  ProvState[42] = new Option("Virginia");
	  ProvState[43] = new Option("Washington");
	  ProvState[44] = new Option("WestVirginia");
	  ProvState[45] = new Option("Wisconsin");
	  ProvState[46] = new Option("Wyoming");
  }
  
  //add option base on the country selected
  for (i=$(state).options.length; i>0; i--) { 
  	$(state).options[i] = null;
  }

  for(i=0; i<ProvState.length; i++) {
  	$(state).options[i] = ProvState[i];
  }
	
  $(state).options[0].selected = true;

}


//layer
function synchTab(frameName) {

  var elList, i;

  // Exit if no frame name was given.

  if (frameName == null)
    return;

  // Check all links.

  elList = document.getElementsByTagName("A");
  for (i = 0; i < elList.length; i++)

    // Check if the link's target matches the frame being loaded.

    if (elList[i].target == frameName) {

      // If the link's URL matches the page being loaded, activate it.
      // Otherwise, make sure the tab is deactivated.

      if (elList[i].href == window.frames[frameName].location.href) {
        elList[i].className += " activeTab";
        elList[i].blur();
      }
      else
        removeName(elList[i], "activeTab");
    }
}

function removeName(el, name) {

  var i, curList, newList;

  if (el.className == null)
    return;

  // Remove the given class name from the element's className property.

  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != name)
      newList.push(curList[i]);
  el.className = newList.join(" ");
}


/*************************************************************************
  This code is from Dynamic Web Coding at http://www.dyn-web.com/
  Copyright 2001-3 by Sharon Paine 
  See Terms of Use at http://www.dyn-web.com/bus/terms.html
  regarding conditions under which you may use this code. 
  This notice must be retained in the code as is!
*************************************************************************/



var cur_lyr;    // holds id of currently visible layer
function swapLayers(id) { 
  if (cur_lyr) hideLayer(cur_lyr);
  showLayer(id);
  cur_lyr = id;
}

/* function showLayer(id) {
  var lyr = getElemRefs(id);
  if (lyr && lyr.css) lyr.css.display = "block";
}  */

function showLayer(id, tab) {
var lyr = getElemRefs(id);
if (lyr && lyr.css) {
lyr.css.display = "block";
}

var tabu = getElemRefs(tab);
if (tabu.className) {
tabu.className = "activeTab";
}
}

function hideLayer(id, tab) {
var lyr = getElemRefs(id);
if (lyr && lyr.css) lyr.css.display = "none";

var tabu = getElemRefs(tab);
if (tabu.className) {
tabu.className = "tab";
}
}

/* function hideLayer(id) {
  var lyr = getElemRefs(id);
  if (lyr && lyr.css) lyr.css.display = "none";
} */

function getElemRefs(id) {
    var el = (document.getElementById)? document.getElementById (id): (document.all)? document.all[id]: (document.layers)? document.layers[id]: null;
    if (el) el.css = (el.style)? el.style: el;
    return el;
}

//add only numeric value to a field
function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

