$(document).ready(function(){

// recently viewed scroll pane
$("#recently_viewed").jScrollPane({scrollbarWidth:15, showArrows:true, arrowSize:6, dragMinHeight:90, dragMaxHeight: 90});

// product/category hover
$(".product_row_item_image, .category_item a").hover(

	function(){
	var parent_div = $(this).parent("div");
	$(parent_div).addClass("current_hover");
	},
	
	function(){
	var parent_div = $(this).parent("div");
	$(parent_div).removeClass("current_hover");
	}
	
);

// product images

$(".product_image a").click(function(){

	var rel = $(this).attr("rel");
	$("#product_images_left img").attr("src", "/images/products/medium/"+rel);

});

// IE dropdown fix
if(BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 8){

$("ul#main_nav ul").css("clear","left");
$("ul#main_nav ul").css("margin-top","0");
$("ul#main_nav ul ul").css("margin-top","-30px");

}

// homepage slideshow
slideshow();

});

function slideshow(){

var time_delay = 5000;

$("#home_1").css("z-index", "99");
$("#home_2").css("z-index", "98");
$("#home_2").show();
$("#home_1").delay(time_delay).fadeOut('slow', function(){
	
	$("#home_2").css("z-index", "99");
	$("#home_3").css("z-index", "98");
	$("#home_3").show();
	$("#home_2").delay(time_delay).fadeOut('slow', function(){
	
		$("#home_3").css("z-index", "99");
		$("#home_4").css("z-index", "98");
		$("#home_4").show();
		$("#home_3").delay(time_delay).fadeOut('slow', function(){
			
			$("#home_4").css("z-index", "99");
			$("#home_5").css("z-index", "98");
			$("#home_5").show();
			$("#home_4").delay(time_delay).fadeOut('slow', function(){
				
				$("#home_5").css("z-index", "99");
				$("#home_6").css("z-index", "98");
				$("#home_6").show();
				$("#home_5").delay(time_delay).fadeOut('slow', function(){
				
					$("#home_6").css("z-index", "99");
					$("#home_1").css("z-index", "98");
					$("#home_1").show();
					$("#home_6").delay(time_delay).fadeOut('slow', function(){

					slideshow();

					});				
				
				});
				
			});	
			
		});	
		
	});
	
});

}

// global functions

function get_radio_value(form_element_obj){

for (var i=0; i < form_element_obj.length; i++)
   {
   if (form_element_obj[i].checked)
      {
      var rad_val = form_element_obj[i].value;
      }
   }
   
   return rad_val;
}

var xmlhttp

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

function findPos(obj) {
	var curleft = curtop = 0;

	if (obj.offsetParent) {
	do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;

		} while (obj = obj.offsetParent);
	}

	return [curleft,curtop];
}

// browser detect

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// check / uncheck all checkboxes


function check_checkboxes(form_name){

var formObject = document.forms[form_name];

	for(var i=0; i< formObject.elements.length; i++){
	var e = formObject.elements[i];
	
		if(e.type == 'checkbox'){
		e.checked = true;
		}

	}

}

function uncheck_checkboxes(form_name){

var formObject = document.forms[form_name];

	for(var i=0; i< formObject.elements.length; i++){
	var e = formObject.elements[i];
	
		if(e.type == 'checkbox'){
		e.checked = false;
		}

	}

}

// cookie functions

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function add_to_basket(){

// build string

var options_string = "";
var i = 0;

for(x in option_array_for_js){
options_string+='&product_options['+i+']='+document.getElementById(option_array_for_js[x]).value;
i++;
}

var div = 'shopping_basket';
var url = '/functions/ajax/add_to_basket.php?product_id='+document.getElementById('product_id').value+'&qty='+document.getElementById('qty').value+options_string;

xmlhttp=GetXmlHttpObject();
if (xmlhttp==null){
  alert ("Your browser does not support XMLHTTP!");
  return;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4)
  {
  document.getElementById(div).innerHTML=xmlhttp.responseText;
  // basket popup
		window.scrollTo(0, 0);
		if(BrowserDetect.browser != 'Explorer'){
		$("#basket_popup").fadeIn().delay(4000).fadeOut();
		}
		else{
		$("#basket_popup").show();
		}
  }
};

xmlhttp.open("GET",url,true);
xmlhttp.send(null);

}

function add_to_wishlist(){

// build string

var options_string = "";
var i = 0;

for(x in option_array_for_js){
options_string+='&product_options['+i+']='+document.getElementById(option_array_for_js[x]).value;
i++;
}

var url = '/functions/ajax/add_to_wishlist.php?product_id='+document.getElementById('product_id').value+'&qty='+document.getElementById('qty').value+options_string;

xmlhttp=GetXmlHttpObject();
if (xmlhttp==null){
  alert ("Your browser does not support XMLHTTP!");
  return;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4)
  {
  show_popup(xmlhttp.responseText);
  }
};

xmlhttp.open("GET",url,true);
xmlhttp.send(null);

}

function show_popup(content){

// build popup

var divWidth = 438;
var divHeight = 300;

var divID = 'popup';
var box;

if(document.getElementById(divID)){
box = document.getElementById(divID);
}

else{
box = document.createElement("div");
box.setAttribute("id",divID);
document.body.appendChild(box);
}

	var scrollingLeft = Math.round((document.documentElement.clientWidth/2)-(box.style.width/2)) - (divWidth / 2);
	var scrollingTop = Math.round((document.documentElement.clientHeight/2)-(box.style.height/2)+document.documentElement.scrollTop) - (divHeight / 2);

	box.innerHTML = '<div id="popup_top">'+content+'</div><div id="popup_bottom"></div>';
	box.style.position = 'absolute';
	box.style.top = scrollingTop+'px';
	box.style.left = scrollingLeft+'px';
	box.style.zIndex = '100';
	box.style.display = 'block';

}

function post_login(){

var url = '/functions/ajax/account_login.php';
var params = "email="+document.getElementById('login_email').value+"&password="+document.getElementById('login_password').value;
params+=(document.getElementById('login_ref')) ? '&ref='+document.getElementById('login_ref').value : '' ;

xmlhttp=GetXmlHttpObject();
if (xmlhttp==null){
  alert ("Your browser does not support XMLHTTP!");
  return;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4)
  {
  
  var response_txt = xmlhttp.responseText;
  
	  if(response_txt.substring(0,4) == 'true'){
	  // logged in
	  document.getElementById('popup').style.display = 'none';
	  document.getElementById('account_navigation').innerHTML = response_txt.substring(4);
	  }
	  
	  else if(response_txt.substring(0,8) == 'redirect'){
	  location.href = response_txt.substring(8);
	  }
	  
	  else{
	  show_popup(response_txt);
	  }
	  
  }
};

xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);

}

function popup_login(ref){

var params = 'ref='+ref;
var url = '/functions/ajax/account_login.php';

xmlhttp=GetXmlHttpObject();
if (xmlhttp==null){
  alert ("Your browser does not support XMLHTTP!");
  return;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4)
  {
  show_popup(xmlhttp.responseText);
  }
};

xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);

}

function popup_logout(){

var div = 'account_navigation';
var url = '/functions/ajax/account_logout.php';

xmlhttp=GetXmlHttpObject();
if (xmlhttp==null){
  alert ("Your browser does not support XMLHTTP!");
  return;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4){
  document.getElementById(div).innerHTML=xmlhttp.responseText;
  }
};

xmlhttp.open("GET",url,true);
xmlhttp.send(null);

}

function validate_registration(){

var textfields = new Array('first_name', 'last_name', 'telephone');

var email = document.getElementById('email');
var confirm_email = document.getElementById('confirm_email');
var password = document.getElementById('password');
var confirm_password = document.getElementById('confirm_password');
var terms = document.getElementById('terms');

var valid = true
var error_msg = '';

// check text fields

	for(x in textfields){
	
		if(document.getElementById(textfields[x]).value.length == 0){
		document.getElementById(textfields[x]).style.border = '1px solid #cc0000';
		valid = false;
		}
		else{
		document.getElementById(textfields[x]).style.border = '1px solid #cccccc';
		}
	
	}
	
// check email

var emailValidationRule = new RegExp(/^[^@]+@([-\w]+\.)+[A-Za-z]{2,4}$/);

if(!emailValidationRule.test(email.value)){
email.style.border = '1px solid #cc0000';
valid = false;
}
else{
email.style.border = '1px solid #cccccc';
}

if(email.value != confirm_email.value){
confirm_email.style.border = '1px solid #cc0000';
valid = false;
}
else{
confirm_email.style.border = '1px solid #cccccc';
}

// check password

if(password.value.length < 6 || password.value.length > 16){
password.style.border = '1px solid #cc0000';
valid = false;
}
else{
password.style.border = '1px solid #cccccc';
}

if(password.value != confirm_password.value){
confirm_password.style.border = '1px solid #cc0000';
valid = false;
}
else{
confirm_password.style.border = '1px solid #cccccc';
}

// check terms

if(!terms.checked){
var error_msg = '<p>Please confirm that you agree to the <a href="/terms.htm" target="_blank">terms &amp; conditions</a> and <a href="/privacy.htm" target="_blank">privacy policy</a>.</p>';
valid = false;
}

// submit form or popup error

	if(!valid){
	show_popup('<h2>Registration error</h2><p>Some required fields were not completed.</p>'+error_msg+'<a onclick="document.getElementById(\'popup\').style.display = \'none\';" class="button"><img src="/images/ok_button.png" alt="OK" /></a>');
	}
	else{
	document.forms['registration_form'].submit();
	}

}

function validate_edit_details(){

var textfields = new Array('first_name', 'last_name', 'telephone');

var email = document.getElementById('email');
var confirm_email = document.getElementById('confirm_email');
var password = document.getElementById('password');
var confirm_password = document.getElementById('confirm_password');

var valid = true
var error_msg = '';

// check text fields

	for(x in textfields){
	
		if(document.getElementById(textfields[x]).value.length == 0){
		document.getElementById(textfields[x]).style.border = '1px solid #cc0000';
		valid = false;
		}
		else{
		document.getElementById(textfields[x]).style.border = '1px solid #cccccc';
		}
	
	}
	
// check email

var emailValidationRule = new RegExp(/^[^@]+@([-\w]+\.)+[A-Za-z]{2,4}$/);

	if(!emailValidationRule.test(email.value)){
	email.style.border = '1px solid #cc0000';
	valid = false;
	}
	else{
	email.style.border = '1px solid #cccccc';
	}

if(confirm_email.value.length > 0){

	if(email.value != confirm_email.value){
	confirm_email.style.border = '1px solid #cc0000';
	valid = false;
	}
	else{
	confirm_email.style.border = '1px solid #cccccc';
	}

}

else{
confirm_email.style.border = '1px solid #cccccc';
}

// check password

if(password.value.length > 0){

	if(password.value.length < 6 || password.value.length > 16){
	password.style.border = '1px solid #cc0000';
	valid = false;
	}
	else{
	password.style.border = '1px solid #cccccc';
	}

	if(password.value != confirm_password.value){
	confirm_password.style.border = '1px solid #cc0000';
	valid = false;
	}
	else{
	confirm_password.style.border = '1px solid #cccccc';
	}

}

else{
password.style.border = '1px solid #cccccc';
confirm_password.style.border = '1px solid #cccccc';
}

// submit form or popup error

	if(!valid){
	show_popup('<h2>Edit details error</h2><p>Some required fields were not completed.</p>'+error_msg+'<a onclick="document.getElementById(\'popup\').style.display = \'none\';" class="button"><img src="/images/ok_button.png" alt="OK" /></a>');
	}
	else{
	document.forms['edit_details_form'].submit();
	}

}

sfHover = function() {
	var sfEls = document.getElementById("main_nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++){
		sfEls[i].onmouseover=function(){
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function(){
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// Used in all pages to submit a form and optionally set a hidden 
// form varaible called 'navigate' to direct navgiation
function submitForm(formName, navigateValue) {
	if (navigateValue != null && navigateValue != "") {
		document.forms[formName].navigate.value = navigateValue;
	}
    document.forms[formName].submit();
}
