var ajaxObjectArray = new Array();

function getCookie(name) {
    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 setCookie(cookieName,cookieValue,nDays,path,domain) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue) + 
							";expires="+expire.toGMTString() +
							((path) ? "; path=" + path : "") +
				        ((domain) ? "; domain=" + domain : "");
}
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

//BEGIN: hovering functions
function hoverOn(hover_id, _id) {

	//initialization stuff
	hover_outerDiv = document.getElementById('outer_' + hover_id);
	hover_innerDiv = document.getElementById('inner_' + hover_id);
	hover_descDiv = hover_innerDiv.getElementsByTagName('DIV')[0];
	hover_img = hover_innerDiv.getElementsByTagName('IMG')[0];
	hover_descDiv.innerHTML = '';
	hover_img.src = '';

	var onloading = document.getElementById('onloading_' + hover_id);

	//display container
	hover_outerDiv.style.position = 'absolute';
	hover_outerDiv.style.display = 'inline';
	
	//get option description by ajax
	ajaxObject = new sack();

	switch(hover_id) {
		case 'hover_1':
			ajaxReqFile = 'ajax.getOptionName.php';
			imgDir = 'options/';
			break;
		case 'hover_2':
			ajaxReqFile = 'ajax.getFinishTypeName.php';
			imgDir = 'finish_types/';
			break;
		case 'hover_3':
			ajaxReqFile = 'ajax.getOptionName.php';
			imgDir = 'options/';
			ajaxObject.setVar('type', 'tyre_addons');
	}

	//assign img src
	hover_img.src = path + 'images/' + imgDir + _id + '-m.jpg';

	ajaxObject.requestFile = path + ajaxReqFile;
	ajaxObject.method = 'GET';
	ajaxObject.setVar('id', _id);

	ajaxObject.onLoading = function() {
		onloading.style.display = 'inline';
	}

	ajaxObject.onCompletion = function() {
		if (res = ajaxObject.response) {
			//alert(res);
			hover_descDiv.innerHTML = res;
			onloading.style.display = 'none';
			hover_innerDiv.style.display = 'inline';
		}
	};
	ajaxObject.runAJAX();
}

function hoverOff() {
	hover_descDiv.innerHTML = '';
	hover_img.src = '';
	hover_innerDiv.style.display = 'none';
	hover_outerDiv.style.display = 'none';
	//show sel: ie fix
	//showHideSel('tirekit');
}

function hoverMove(e) {

	if (hover_outerDiv.style) {
		if (document.all) {
			hover_outerDiv.style.zIndex='100';
			hover_outerDiv.style.left = e.x + 10 + 'px';
			hover_outerDiv.style.top = e.y + 10 + 'px';
		}
		else {
			//var _offset = (hover_outerDiv.id == 'outer_hover_2') ? 150 : 0;
			var _offset =0;
			hover_outerDiv.style.left = e.layerX - _offset + 'px';
			hover_outerDiv.style.top = e.layerY + 10 + 'px';
		}
	}
}

function hoverOnTyre(hover_id, title, _img) {

	//initialization stuff
	hover_outerDiv = document.getElementById('outer_' + hover_id);
	hover_innerDiv = document.getElementById('inner_' + hover_id);
	hover_descDiv = hover_innerDiv.getElementsByTagName('DIV')[0];
	hover_img = hover_innerDiv.getElementsByTagName('IMG')[0];
	hover_descDiv.innerHTML = '';
  var onloading = document.getElementById('onloading_' + hover_id);
  
  //display loading
  onloading.style.display = 'inline';
  
  //display container
  hover_outerDiv.style.position = 'absolute';
  hover_outerDiv.style.display = 'inline';
    
  hover_img.onload = function() {
    hover_descDiv.innerHTML = title;
    onloading.style.display = 'none';
    //$(hover_outerDiv).animate({width:hover_img.width, height:hover_img.height}, 1000);
    hover_innerDiv.style.display = 'inline';
  }
	setTimeout(function(){hover_img.src = path + _img}, 2000);

}
//END: hovering functions

//BEGIN: car brand/model filter functions
function select_model(site_url, modelpath) {
	if(modelpath != "") {
		location.href = site_url + modelpath;
	}
}

function mDropShow() {
	var el = document.getElementById('mbody');
	if (isHidden(el)) {
		unhide(el);
		setTimeout(function(){msel_visible = true}, 10);
	}
}

function mDropHide() {
	var el = document.getElementById('mbody');
	if (msel_visible) {
		hide(el);
		msel_visible = false;
	}
}

function mSelect(obj, data) {
	var el = document.getElementById('mhead');
	var f_url = document.getElementById('f_url');
	var f_model_id = document.getElementById('f_model_id');
	var f_brand_id = document.getElementById('f_brand_id');
	var div = document.createElement('div');
	var content = obj.innerHTML;

	f_url.value = data.url_string;
	f_model_id.value = data.model_id;
	f_brand_id.value = data.brand_id;
	div.className = 'mitem';
	div.innerHTML = content;
	el.innerHTML = '';
	el.appendChild(div);
}

function mFilterByBrand(id){
	if (id === '0')
		return;

	var div_onloading = document.getElementById('monloading');
	var f2gif = document.getElementById('f2gif');
	var btnfind = document.getElementById('btnfind');
	var container = document.getElementById('mbody');

	//reset model filter
	var mhead = document.getElementById('mhead');
	var f_url = document.getElementById('f_url');
	mhead.innerHTML = '&nbsp;Select Model';
	f_url.value = '';

	ajaxRequestFile = 'ajax.getModelsByBrand.php';
	ajaxObjectArray[ajaxObjectArray.length] = new sack();
	var ajaxIndex = ajaxObjectArray.length-1;

	ajaxObjectArray[ajaxIndex].requestFile = path + ajaxRequestFile;
	ajaxObjectArray[ajaxIndex].method = 'GET';
	ajaxObjectArray[ajaxIndex].setVar('id', id);
	
	ajaxObjectArray[ajaxIndex].onLoading = function() {
		hide(f2gif);
		hide(mhead);
		hide(btnfind);
		unhide(div_onloading);
	}
	
	ajaxObjectArray[ajaxIndex].onCompletion = function() {
		if (res = ajaxObjectArray[ajaxIndex].response) {
			//document.writeln(res);
			var arr = eval(res);
			var item = new Object();
			var hsep = new Object();
			var br = new Object();
			var img_container = new Object();
			var img = new Object();
			var span = new Object();
			var urlstr = new String();
			var f_model_id = new String();
			var f_data = getFCookieData();
			f_model_id = f_data[1];
			
			var data = function() {
				this.url_string = '';
				this.model_id = '';
				this.brand_id = '';
			}

			container.innerHTML = '';

			for (i in arr) {
				//alert(arr[i].id);
				item = document.createElement('div');
				img_container = document.createElement('div');
				img = document.createElement('img');
				span = document.createElement('span');
				hsep = document.createElement('hr');
				mdata = new data;
				mdata.url_string = arr[i].url_string;
				mdata.model_id = arr[i].id;
				mdata.brand_id = id;

				var ocfunc = function (mdata) {
						return function () {
								mSelect(this, mdata);
								this.className = 'mitem selected';
						}
				}(mdata);
				item.className = 'mitem';
				img_container.className = 'left';
				hsep.className = 'hsep';
				item.onmouseover = function(){mOver(this)};
				item.onmouseout = function(){mOut(this)};
				item.onclick = ocfunc;
				img.src = path + 'images/models/' + arr[i].id + '-s.jpg';
				span.innerHTML = arr[i].name;
				img_container.appendChild(img);
				item.appendChild(img_container);
				item.appendChild(span);
				container.appendChild(item);
				container.appendChild(hsep);
				if (arr[i].id == f_model_id)
					mSelect(item, mdata);
			}
			if (arr.length > 0)
				container.removeChild(hsep);

			hide(div_onloading);
			unhide(f2gif);
			unhide(mhead);
			unhide(btnfind);
		}
	};
	ajaxObjectArray[ajaxIndex].runAJAX();
}

function mOver(obj) {
	obj.className = 'mitem over';
}

function mOut(obj) {
	obj.className = 'mitem out';
}

function applyFilter() {
	var f_url = document.getElementById('f_url');
	var f_model_id = document.getElementById('f_model_id');
	var f_brand_id = document.getElementById('f_brand_id');
	var el = document.getElementById('mhead');
	
	if (f_url.value == '')
		displayWarning(el, 6);
	else {
		//set cookie
		setCookie('f_data', encodeURIComponent(f_brand_id.value + '|' + f_model_id.value), 30);

		//redirect
		window.location = path + f_url.value;
	}
}

function displayWarning(obj, i) {
	if (!i) {
		obj.style.borderColor = '#7f8081 #eff0f0 #eff0f0 #7f8081';
		return;
	}
	obj.style.borderColor = (i % 2) ? 'red' : '#7f8081 #eff0f0 #eff0f0 #7f8081';
	setTimeout(function(){displayWarning(obj, --i)}, 500);
}

function unhide(el) {
	var re = /(.*)\s*hidden/;
	el.className = el.className.replace(re, "$1");
}

function hide(el) {
	var re = /(.*)\s*/;
	if (! isHidden(el))
		el.className = el.className.replace(re, "$1 hidden");
}

function isHidden(el) {
	if (el.className.match(/hidden/))
		return true;
	return false;
}

function fRemember() {
	var make = document.getElementsByName('make')[0];
	var f_brand_id = new String();
	var f_data = getFCookieData();

	if (f_brand_id = f_data[0]) {
		for (i=0; i<make.length; i++) {
			if (make[i].value == f_brand_id) {
				make[i].selected = true;
				mFilterByBrand(make[i].value);
			}
		}
	}
}

function getFCookieData() {
	return decodeURIComponent(getCookie('f_data')).split('|');
}
//END: car model filter functions

//wheelset page information blocks visibility toggle functions
function toggleSection(el) {
  var span = $(el).contents();
  var div= $(el).nextAll('div:first');
  var re = /(.+)Open|Close/;
  
  if ($(div).is(':hidden')) {
    $(div).slideDown('slow', function() {
      $(span).attr('class', $(span).attr('class').replace(re, "$1Close"));
    });
  }
  else {
    $(div).slideUp('slow', function() {
      $(span).attr('class', $(span).attr('class').replace(re, "$1Open"));
    });
  }
  return false;
}

//BEGIN: cart page items related functions
function ta_warn_remove(el) {
  if (el.checked !== true) {
    if (!confirm('Warning! By removing this item from cart, tyres will be supplied loose. Proceed?'))
      el.checked = false;
  }
}

function cartMarkRelated(el, type) {

  var state = $(el).attr('checked') ? true : false;
  var relType = false;

  //check if all items of same type are checked
  if(state && cartCheckAllMarked(el)!==0)
    return;

  $('table.cart input[name^=remove][rel='+type+']').each(function(){
    $(this).attr('checked', state).attr('disabled', state);
    re = /^([^:]+):.+/;
    if(relType = re.exec(this.id)){
      if (relType[1] !== type)
        cartMarkRelated($(this), relType[1]);
    }
  });

  return;
}

function cartCheckAllMarked(el) {
  var relType = false;
  re = /^([^:]+):.+/;
  if(relType = re.exec(el.id))
    return $('table.cart input[id^='+relType[1]+':]').not(':checked').length;
  return 0;
}
//END: cart page items related functions

//BEGIN: cart page checkout related functions
function verifyInput(el, type) {
  var val = $(el).val();
  var msgErr = '';
  switch (type) {
    case 'forename':
      var re = /[\]{}:"£#@!~\\\|\/<>$%\^&*()_=?;.,+0-9[]|^\s+$/;
      if ((val == '') || re.test(val) || val.length > 20) {
        msgErr = 'Unrecognised characters entered or overlong data, please check.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'surname':
      var re = /[\]{}:"£#@!~\\\|\/<>$%\^&*()_=?;.,+0-9\[]|^\s+$/;
      if ((val == '') || re.test(val) || val.length > 20) {
        msgErr = 'Unrecognised characters entered or overlong data, please check.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'company_name':
      var re = /[\]{}:"£#@!~\\\|\/<>$%\^&*()_=?;,+\[]|^\s+$/;
      if ((val !== '') && re.test(val) || val.length > 30) {
        msgErr = 'Unrecognised characters entered or overlong data, please check. You may leave this field blank.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'ec_vat':
      var re = /[^0-9a-zA-Z\s]|^\s+$/;
      if ((val !== '') && re.test(val) || val.length > 15) {
        msgErr = 'Unrecognised characters entered or overlong data, please check. You may leave this field blank.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'email':
      var re = /^[a-z0-9\._-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i;
      if (! re.test(val) || val.length > 255) {
        msgErr = 'Invalid email address or overlong data, please check.';
        showErr(el, msgErr);
      }
      break;
    case 'address1':
      var re = /[\]{}:"'£#@!~\\\|\/<>$%\^*()_=?;+\[]|^\s+$/;
      if ((val == '') || re.test(val) || val.length > 100) {
        msgErr = 'Unrecognised characters entered or overlong data, please check.';
        showErr(el, msgErr);
      }
      break;
    case 'address2':
      var re = /[\]{}:"'£#@!~\\\|\/<>$%\^*()_=?;+\[]|^\s+$/;
      if ((val !== '') && re.test(val) || val.length > 100) {
        msgErr = 'Unrecognised characters entered or overlong data, please check. You may leave this field blank.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'city':
      var re = /[\]{}:"'£#@!~\\\|\/<>$%\^&*()_=?;+0-9\[]|^\s+$/;
      if ((val == '') || re.test(val) || val.length > 40) {
        msgErr = 'Unrecognised characters entered or overlong data, please check.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'state':
      if ((val == '') && $('select[name=country_selector]').val() == 'US') {
        msgErr = 'Please select a state.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'postcode':
      var re = /[\]{}:"'£#@!~\\\|\/<>$%\^&*()_=?;+\[]|^\s+$/;
      if ((val == '') || re.test(val) || val.length > 10) {
        msgErr = 'Unrecognised characters entered or overlong data, please check.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'country_selector':
      if (val == '') {
        msgErr = 'Please select your country.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'telephone':
      var re = /[^0-9+.\s-]|^\s+$/;
      if ((val == '') || re.test(val) || val.length > 20) {
        msgErr = 'Unrecognised characters entered or overlong data, please check.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'mobilephone':
      var re = /[^0-9+.\s-]|^\s+$/;
      if ((val == '') || re.test(val)) {
        msgErr = 'Unrecognised characters entered, please check.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'vrm':
      var re = /[^0-9a-zA-Z]/;
      if ((val !== '') && re.test(val) || val.length > 7) {
        msgErr = 'Unrecognised characters entered, please check. You may leave this field blank.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'vin':
      var re = /[^0-9a-zA-Z]/;
      if ((val !== '') && re.test(val) || val.length > 17) {
        msgErr = 'Unrecognised characters entered, please check. You may leave this field blank.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'car_info':
      var re = /[\]{}:"'£#@!~\\\|<>$%\^&*()_=?;+\[]|^\s+$/;
      if ((val == '') || re.test(val)) {
        msgErr = 'Unrecognised characters entered, please check.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'details':
      var re = /[\]{}:"'#@!~\\\|<$%\^()_=?;+\[]|^\s+$/;
      if ((val !== '') && re.test(val)) {
        msgErr = 'Unrecognised characters entered, please check. You may leave this field blank.';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
    case 'tc':
      if ($(el).attr('checked') === false) {
        msgErr = 'Please read our terms and conditions by clicking the text on the left, then place a tick in the box to affirm';
        showErr(el, msgErr);
      }
      else
        hideErr(el);
      break;
  }
}

function showErr(el, msgErr) {
  if (! $(el).hasClass('err')) {
    $(el).addClass('err');
    if (!$(el).next().is('div')) {
      var div = document.createElement('div');
      $(div).addClass('hidden');
      $(div).html(msgErr);
      $(el).after(div);
      $(div).slideDown('slow');
    }
  }
}

function hideErr(el) {
  if ($(el).hasClass('err')) {
    $(el).removeClass('err');
    $(el).next('div').slideUp('slow', function(){
      if ($(el).hasClass('err'))
        $(el).next('div').slideDown('slow');
      else
        $(el).next('div').remove();
    });
    
  }
}

function hasEmptyElements() {
  var ret = false;
  $('form[name=checkout_form] input[rel=checkinput]').each(function(){
    //$(document.body).append($(this).attr('tagName') + ':' + $(this).val() + "<br>")});
    if ( $(this).val() == '' ) {
      //alert('has empty');
      ret = true;
      return;
    }
  });
  return ret;
}

function hasErrors() {
  if ($('form[name=checkout_form]:has(.err)').length)
    return true;
  return false;
}

function checkoutVerify() {
  $('form[name=checkout_form] input,textarea,select[rel=checkinput]').each(function(){
    verifyInput($(this), $(this).attr('name'));
  });
  if (hasErrors()) {
    return false;
  }

	//prevent submitting more than once
	$('input[rel=submit]').keypress(function(){return false});
	
	//initialize checkout
  checkoutSaveOrder();
}

function checkoutSaveOrder() {

	var divOverlay = $('<div/>');
	var divContainerOuter = $('<div/>');
	var divContainerInner = $('<div/>');
	var txtLoading = $('<div/>');
	var imgLoading = $('<img/>');
	var imgLoadingHeight = 32;
	var imgLoadingWidth = 32;
	var divContainerOuterInitialHeight = 250;
	var divContainerOuterInitialWidth = 250;
	var txtLoadingHeight = 35;
	var msg = '';
	var msgReturned = '';
	var msgOutput = '';
	var msgStatus = '';
	var exitCode = '';
	
	//scroll up window
	$(window).scrollTop(0);
	
	//load background
	divOverlay.addClass('checkout_overlay');
	divOverlay.css({opacity:0.8});
	divOverlay.height($(document).height());
	divOverlay.appendTo($(document.body));
	
	//loading: add text content
	txtLoading.addClass('text');
	txtLoading.text('Please wait for your order to be saved...');
	txtLoading.appendTo(divContainerInner);

	//loading: add rotating gif
	imgLoading.attr('src', path+'templates/images/ajax-loader4.gif');
	imgLoading.css({top:((divContainerOuterInitialHeight-imgLoadingHeight)/2)-txtLoadingHeight, left:(divContainerOuterInitialWidth-imgLoadingWidth)/2});
	imgLoading.addClass('loading');
	imgLoading.appendTo(divContainerInner);

	//add inner
	divContainerInner.addClass('checkout_container_inner');
	divContainerInner.appendTo(divContainerOuter);

	//add outer
	divContainerOuter.addClass('checkout_container_outer');
	divContainerOuter.css({left:($(document).width()-divContainerOuterInitialWidth)/2, opacity:0.9});
	divContainerOuter.appendTo($(document.body));//append to body in order not to overlap opacity with overlay div
	
	//main
	divContainerOuter.show('slow', function(){
		divContainerInner.fadeIn('fast', function(){
			$.ajax({
				type: "POST",
				url: path+"ajax.SaveOrder.php",
				data: $('form[name=checkout_form]').serialize(),
				dataType: 'html',
				timeout: 5000,
				cache: false,
				success: function(msg){
					//alert( "Data Saved: " + msg );
					//$('body').after(msg);
					exitCode = parseInt(msg);
				},
				error: function() {
					exitCode = -2;
				},
				complete: function() {
					if (exitCode === 0)
						checkoutDisplayBox('payment');
					else if (exitCode > 0)
						checkoutDisplayBox('error_fields');
					else if (exitCode == -1)
						checkoutDisplayBox('error_db');
					else if (exitCode == -2)
						checkoutDisplayBox('error_request');
				}
			});
		});
	});
}

function checkoutDisplayBox(type) {
	
	var divContainerOuter = $('.checkout_container_outer');
	var divContainerInner = $('.checkout_container_inner');
	var validateFields = false;

	divContainerInner.fadeOut('slow', function(){
		
		divContainerInner.empty();
		divContainerInner.appendTo($(document.body)).css({'position':'absolute','top':'-2000px','text-align':'center', 'width':'auto','display':'block'});
		
		switch(type) {
			case 'payment':
				var divText = ('<div>Please select your desired payment method:</div>');
				var arr = $('form[name=checkout_form] input[name=payment_type_allowed]').val().split(',');
				var numpieces = arr.length;
				var mr = 0;
        var _load = function(numpieces){
          if (!numpieces)
            setTimeout(function(){checkoutResizeBoxTo(divContainerInner.width(), divContainerInner.height(), validateFields)},10);
        };
	
				$(divText).css({'margin':'5px 0 10px 0','display':'block'}).appendTo(divContainerInner);
        timeout = 60000;//1 minute
        
				for (i in arr) {
					mr = --numpieces==0 ? 0 : 5;
          
          var _click = function(paymentType) {
            return function() {checkoutDisplayBox(paymentType)};
          }(arr[i]);
          
          var imgAlt = arr[i] == 'sagepay' ? 'click here to pay by card' : 'click here to pay by bank transfer';

          $('<img/>',{'load':function(){_load(numpieces)},'click':_click,'mouseover':function(){$(this).css({'opacity':'0.5'})},'mouseout':function(){$(this).css({'opacity':'1'})},'src':path+'templates/images/payment_'+arr[i]+'.jpg','title':imgAlt,'alt':imgAlt}).css({'border':'2px solid #D2D2D2','margin-right':mr+'px','cursor':'pointer'}).appendTo(divContainerInner);

				}
				break;
			case 'error_fields':
				validateFields = true;
			case 'error_db':
			case 'error_request':
				$('#checkout_container_'+type).clone().contents().appendTo(divContainerInner);
				checkoutResizeBoxTo(divContainerInner.width(), divContainerInner.height(), validateFields);
				timeout = 60000;//1 minute
				break;
			case 'sagepay':
			case 'bank':
        var cloned = $('#checkout_container_'+type).clone();
        var images = cloned.find('img');
        var lenImages = images.length;
        var _load = function() {
          if (!lenImages) {
            checkoutResizeBoxTo(divContainerInner.width(), divContainerInner.height(), validateFields);
          }
        };

        divContainerInner.css({'text-align':'left', 'width':'780px'});
        cloned.contents().appendTo(divContainerInner);
				timeout = 900000;//15 minutes

        if (lenImages) {
          images.each(function(){
            $('<img/>',{'load':function(){_load(--lenImages)},'src':$(this).attr('src')});
          });
        }
        else {
          checkoutResizeBoxTo(divContainerInner.width(), divContainerInner.height(), validateFields);
        }

				//record payment type chosen
				if ($('form[name=checkout_form] input[name=payment_type_selected]').length)
					$('form[name=checkout_form] input[name=payment_type_selected]').remove();
				$('form[name=checkout_form]').append('<input type="hidden" name="payment_type_selected" value="'+type+'" />');
		}
	});
}

function checkoutResizeBoxTo(w, h, validateFields) {
	
	var divContainerOuter = $('.checkout_container_outer');
	var divContainerInner = $('.checkout_container_inner');
	
	$(divContainerInner).hide('fast', function(){
		$(divContainerOuter).animate({
			'padding':'10px',
			'width':w,
			'height':h,
			left:($(document).width()-w)/2
		},
		{
			duration:1000,
			complete:function(){
				//display box
				divContainerInner.css({'position':'','top':''}).appendTo(divContainerOuter);
				divContainerInner.fadeIn('slow');
				//set timeout
				checkoutUpdateT0();
				$(document.body).bind('mousemove click', function(){checkoutUpdateT0();});
				checkoutTimeout(validateFields);
			}
		});
	});
}

function checkoutUpdateT0() {
	var d = new Date();
	t0 = d.getTime();
}

function checkoutTimeout(validateFields) {
	if ($('.checkout_container_inner').is(':hidden'))
		return;
	if (!$('.checkout_overlay').length)
		return;

	var d = new Date();
	var t1 = d.getTime();
	if (t1-t0 > timeout) {
		checkoutAbort(validateFields);
		$(document.body).unbind('mousemove');
		return;
	}
	setTimeout(function(){checkoutTimeout(validateFields)}, 1000);
}

function checkoutCountryFilter(c) {
	var cList = ['AD','AT','BE','BG','CA','CY','DK','FR','DE','GI','GR','HU','IL','IT','LV','LT','NL','NO','PL','PT','RO','SK','SI','ES','SE','CH','TR','GB','IE','JE','GG','US','JP','FI','XA','XB','XC','XF','XD','XE','IM','XG','XH'];

	for (i in cList) {
		if (cList[i] == c) {
			if($('form[name=checkout_form] input[name=payment_type_allowed]').length === 0)
				$('form[name=checkout_form]').append('<input type="hidden" name="payment_type_allowed" value="sagepay,bank" />');
			else
				$('form[name=checkout_form] input[name=payment_type_allowed]').val('sagepay,bank');
			return;
		}
	}
	if($('form[name=checkout_form] input[name=payment_type_allowed]').length === 0)
		$('form[name=checkout_form]').append('<input type="hidden" name="payment_type_allowed" value="bank" />');
	else
		$('form[name=checkout_form] input[name=payment_type_allowed]').val('bank');
}

function checkoutResume() {
	$('.checkout_container_outer').fadeOut('slow', function(){
		$('form[name=checkout_form]').submit();
	});
	return false;
}

function checkoutAbort(validateFields) {
	$('.checkout_container_outer').fadeOut('slow', function(){
		$('.checkout_container_outer').remove();
		$('.checkout_overlay').fadeOut('slow', function(){
			$(document.body).unbind('mousemove click', function(){checkoutUpdateT0();});
			$('.checkout_overlay').remove();
			if (validateFields) {
				$('form[name=checkout_form] input,textarea,select[rel=checkinput]').each(function(){
						verifyInput($(this), $(this).attr('name'));
					});
			}
		});
	});
	return false;
}
//END: cart page checkout related functions

//BEGIN: vat related functions
function vatSwitch(val) {

	var POSTdata = new Object();
	var wheelsData = new Array();
	var tyresData = new Array();
	var optionsData = new Array();
	var itemsData = new Array();
	var re = new RegExp();
	var resArr = new Object();
  
	var _load = function(imgLoading){

		imgLoading.appendTo($('#flags'));
		imgLoading.fadeIn('slow', function(){

			//save new vat preference
			setCookie('vat', val, 1, path);

			//return if there are no prices to be changed on this page
			if (!$('span.price').length) {
				imgLoading.fadeOut('slow', function(){
					imgLoading.remove();
					return;
				});
			}
		
			//get wheels' ids
			if ($('span.price[id^=wheel:]').length) {
				re = /wheel:(.+)/;
        $('span.price[id^=wheel:]').each(function(){
					wheelsData.push($(this).attr('id').replace(re, "$1"));
				});
			}
		
			//get tyres' partnumbers
			if ($('span.price[id^=tyre:]').length) {
				re = /tyre:(.+)/;
				$('span.price[id^=tyre:]').each(function(){
					tyresData.push($(this).attr('id').replace(re, "$1"));
				});
			}
			
			//get options' partnumbers
			if ($('span.price[id^=option:]').length) {
				re = /option:(.+)/;
				$('span.price[id^=option:]').each(function(){
					optionsData.push($(this).attr('id').replace(re, "$1"));
				});
			}
			
			//get cart items' ids
			if ($('span.price[id^=item:]').length) {
				re = /item:(.+)/;
				$('span.price[id^=item:]').each(function(){
					itemsData.push($(this).attr('id').replace(re, "$1"));
				});
			}

			//populate the data array to be posted
			POSTdata = {'wheels':wheelsData, 'tyres':tyresData, 'options':optionsData, 'items':itemsData};
			
			$.ajax({
				type: "POST",
				url: path+"ajax.vatSwitchPrices.php",
				data: POSTdata,
				dataType: 'text',
				cache: false,
				success: function(msg){
          //console.log(msg);
					//alert(msg);
					//$('body').after(msg);
					resArr = eval('new Object({'+msg+'})');
				},
				error: function(msg) {
					//alert( "returned with error:[" + msg + "]" );
				},
				complete: function() {
					imgLoading.fadeOut('slow', function(){

            //product page only: update tyres' total price
            $('div.tyre_block[id!=0]').each(function(){
              if ($(this).attr('id').indexOf(':') !== -1)
                $(this).find('span.price:last').html( Math.round ( 2 * ( parseFloat(resArr[$(this).find('span.price').eq(0).attr('id')]) + parseFloat(resArr[$(this).find('span.price').eq(1).attr('id')]) ) ) );
              else
                $(this).find('span.price:last').html( Math.round ( 4 * ( parseFloat(resArr[$(this).find('span.price').eq(0).attr('id')]) ) ) );
            });

            $('span[id].price').each(function(){
              if (resArr[$(this).attr('id')] !== undefined) {
                if (/\/cart\/?$/.test(window.location))//cart prices formatted with 2dp
                  $(this).html(number_format(resArr[$(this).attr('id')], 2));
                else
                  $(this).html(Math.round(resArr[$(this).attr('id')]));
              }
            });
  
            imgLoading.remove();
          });
        }
      });
    });
	}

  $('<img/>',{'load':function(){_load($(this))},'src':path+'templates/images/ajax-loader6.gif','style':'margin-left:2px'});
}

function countrySwitch(country_iso) {
  
  var POSTdata = new Object();
  var wheelsData = new Array();
	var tyresData = new Array();
	var optionsData = new Array();
	var itemsData = new Array();
	var re = new RegExp();
	var resArr = new Object();
  var imgLoading = new Image();

	var _load = function(imgLoading){

		imgLoading.appendTo($('#flags'));

		imgLoading.fadeIn('slow', function(){
      
      //save new country preference
      setCookie('country', country_iso, 30, path);
      
      $.get(path+'ajax.getVatDefault.php', {'country_iso':country_iso}, function(res){

        //update vat status
        setCookie('vat', res, 1, path);
        $('input[name=vat][value='+res+']').attr('checked','checked');
  
        //return if there are no prices to be changed on this page
        if (!$('span.price').length) {
          imgLoading.fadeOut('slow', function(){
            imgLoading.remove();
            return;
          });
        }
      
        //get wheels' ids
        if ($('span.price[id^=wheel:]').length) {
          re = /wheel:(.+)/;
          $('span.price[id^=wheel:]').each(function(){
            wheelsData.push($(this).attr('id').replace(re, "$1"));
          });
        }
      
        //get tyres' partnumbers
        if ($('span.price[id^=tyre:]').length) {
          re = /tyre:(.+)/;
          $('span.price[id^=tyre:]').each(function(){
            tyresData.push($(this).attr('id').replace(re, "$1"));
          });
        }
        
        //get options' partnumbers
        if ($('span.price[id^=option:]').length) {
          re = /option:(.+)/;
          $('span.price[id^=option:]').each(function(){
            optionsData.push($(this).attr('id').replace(re, "$1"));
          });
        }
        
        //get cart items' ids
        if ($('span.price[id^=item:]').length) {
          re = /item:(.+)/;
          $('span.price[id^=item:]').each(function(){
            itemsData.push($(this).attr('id').replace(re, "$1"));
          });
        }
  
        //populate the data array to be posted
        POSTdata = {'wheels':wheelsData, 'tyres':tyresData, 'options':optionsData, 'items':itemsData};
      
        $.ajax({
          type: "POST",
          url: path+"ajax.vatSwitchPrices.php",
          data: POSTdata,
          dataType: 'text',
          cache: false,
          success: function(msg){
            //~ alert(msg);
            //$('body').after(msg);
            resArr = eval('new Object({'+msg+'})');
          },
          error: function(msg) {
            //alert( "returned with error:[" + msg + "]" );
          },
          complete: function() {
            
            //update shipping country (cart page appliable only)
            $('tr.shipping td.description').html('Shipping to '+getCountryName(country_iso));
            if ($('tr.shipping td.price span').html() == '&nbsp;')
              $('tr.shipping td.price span').before('&pound;');

            //update tyres' total price (product page appliable only)
            $('div.tyre_block[id!=0]').each(function(){
              if ($(this).attr('id').indexOf(':') !== -1)
                $(this).find('span.price:last').html( Math.round ( 2 * ( parseFloat(resArr[$(this).find('span.price').eq(0).attr('id')]) + parseFloat(resArr[$(this).find('span.price').eq(1).attr('id')]) ) ) );
              else
                $(this).find('span.price:last').html( Math.round ( 4 * ( parseFloat(resArr[$(this).find('span.price').eq(0).attr('id')]) ) ) );
            });


            $('span.price').each(function(){
              if (resArr[$(this).attr('id')] !== undefined) {
                if (/\/cart\/?$/.test(window.location))//cart prices formatted with 2dp
                  $(this).html(number_format(resArr[$(this).attr('id')], 2));
                else
                  $(this).html(Math.round(resArr[$(this).attr('id')]));
              }
            });
            //end animation
            imgLoading.fadeOut('slow', function(){
                imgLoading.remove();
            });
          }
        });
      });
    });
  }
  $('<img/>',{'load':function(){_load($(this))},'src':path+'templates/images/ajax-loader6.gif','style':'margin-left:2px'});
}
//END: vat related functions

//BEGIN: misc functions
function number_format(number, decimals) {

  var divisor = Math.pow(10, decimals);
  var quotient = parseInt(Math.round(number*divisor)/divisor);
  var remainder = Math.round(number*divisor)%divisor;
  var arr = new Array();
  var quotientTmp = new Number();
  
  while (decimals--) {
    divisor = Math.pow(10, decimals);
    quotientTmp = parseInt(remainder / divisor);
    arr.push(quotientTmp);
    remainder -= quotientTmp*10;
  }
  
  return quotient + '.' + arr.join('');
}
//END: misc functions
