// JavaScript Document
$(function() {
   $("#signinopen").click(function() {
       $("#loginform").fadeIn("slow");
	   document.lf.email.focus();
   });
   $("#signinclose").click(function() {
       $("#loginform").fadeOut("slow");
   });
 });
function addtobasket(id){
	$.post("/incbasket.asp", { add: id }, 
		function(data){
			if (data=='fail'){
				alert('Your item cannot be added to your order as it will exceed our current stock levels.');
			} else {
				top.location="/basket.asp"
			}
		});
}
function stockreminder(id){
	$.post("/addreminder.asp", { add: id }, 
		function(data){
			alert('Thank you. We will email you when this product comes back into stock.');
		});
}
function openinvoice(id){
invoicewindow= window.open ("viewinvoice.asp?invoice_number="+id, "invoicewindow",
    "location=0,status=0,scrollbars=0,width=400,height=750");
invoicewindow.moveTo(0,0);
}
function chkoutok() {
	if (readCookie("retailer")=="True") {
		if (document.pcodeform.po_number.value==""){
			alert('Purchase order number is required.');
		} else {
		document.pcodeform.pay.value="yes";
		document.pcodeform.submit();
		}
	} else {
		document.pcodeform.pay.value="yes";
		document.pcodeform.submit();
	}
}
function chkship(tf) {
	if(tf.ok.value!=''){
		return false;
	}
	return true;
}

function chkdel(ok) {
	selind=1;
	sel=document.getElementById('delmethod');
	document.getElementById('opt1').style.visibility = "hidden";
	document.getElementById('opt1').style.display = "none";
	document.getElementById('opt2').style.visibility = "hidden";
	document.getElementById('opt2').style.display = "none";
	document.getElementById('opt3').style.visibility = "hidden";
	document.getElementById('opt3').style.display = "none";
	document.getElementById('opt4').style.visibility = "hidden";
	document.getElementById('opt4').style.display = "none";
	document.getElementById('opt5').style.visibility = "hidden";
	document.getElementById('opt5').style.display = "none";
	if(sel!= null){
		selind=sel[sel.selectedIndex].value;
		tdiv=document.getElementById('opt'+selind);
		tdiv.style.visibility = "visible";
		tdiv.style.display = "block";
		if (selind+''!=document.getElementById('dm').value+'') {
			document.getElementById('dm').value="";
		}
	}
	if(document.getElementById('dm').value!=""){
		tdiv=document.getElementById('cost');
		tdiv.style.visibility = "visible";
		tdiv.style.display = "block";
		tp=document.getElementById('total');
		tp.style.visibility = "visible";
		tp.style.display = "block";
	}
	if(document.getElementById('dm').value==""){
		tdiv=document.getElementById('cost');
		tdiv.style.visibility = "hidden";
		tdiv.style.display = "none";
	}
}
function validpcode(tf) {
	delmethod=tf.delmethod.value;
	if(delmethod==1||delmethod==2||delmethod==3) {
		if(!checkPostCode(tf.postcode.value)) {
			alert('Please enter a valid postcode');
			return false;
		}
		tf.postcode.value=checkPostCode(tf.postcode.value);
		return true;
		}
	return true;

}
function checknumeric(tf){
	if (tf.quantity.value != parseInt(tf.quantity.value)) {
		alert('Please enter a number for the quantity');
		return false;
	}
	return true;
	}

function so_clearInnerHTML(obj) {
	// so long as obj has children, remove them
	while(obj.firstChild) obj.removeChild(obj.firstChild);
}


function addtoretailerbasket(id){
	qid=document.getElementById(id);
	quantity=qid.value;
	qid.value=0;
	$.post("/retailerbasket.asp", { add: id, quantity: quantity },
		function(data){
			var baskettotal=document.getElementById('baskettotal');
			var newtotal = document.createElement("span");
			newtotal.innerHTML = CurrencyFormatted(unescape(readCookie("btotal")));
			so_clearInnerHTML(baskettotal);
			baskettotal.appendChild(newtotal);

			var bquantity=document.getElementById('basketitems');
			var newquantity = document.createElement("span");
			newquantity.innerHTML = readCookie("bquantity");
			so_clearInnerHTML(bquantity);
			bquantity.appendChild(newquantity);

			var added=document.getElementById('c'+id);
			var addtext = document.createElement("span");
			addtext.innerHTML = data+" in basket";
			so_clearInnerHTML(added);
			added.appendChild(addtext);
	});
}

function deletefrombasket(id){
	$.post("/basket.asp", { del: id });
	top.location="/basket.asp"
}

function setmed(im){
	
	var elem;
	if(document.getElementById) {
		var elem = document.getElementById("bigimage");
	} else if (document.all){
		var elem = document.all["bigimage"];
	}

	var tr = elem.firstChild;

    while(tr){
		tr.className = 'hidden';
        tr = tr.nextSibling;
    }
	changeClass(im,'shown');

}

function init() {
	P7_equalCols2(1,'col1','P','col2','P');
	P7_equalCols2(0,'ne1','P','ne2','P');
	for (i=0; i<document.links.length; i++) {
		if((location.href.indexOf(document.links[i])!=-1&&document.links[i].parentNode.parentNode.id=="nav")||(location.href=="http://snapperstuff.studiorepublic.com/"||location.href=="http://www.studiorepublic.com/")&&
			(document.links[i]=="http://snapperstuff.studiorepublic.com/default.asp"||document.links[i]=="http://www.studiorepublic.com/default.asp")&&document.links[i].parentNode.parentNode.id=="nav") {
			document.links[i].className="current";
		}
	}
}
function outputbread() {
	var adding=true;
	var op="";
	var parent;
	var row; for (row = 0; row < nav.length; ++row) { 
		var strloc='';
		strloc=strloc+window.location;
		var mat=nav[row][4];
		if (strloc.match('/'+mat)){
			 op=op+('<a href="' + nav[row][4] + '">' + nav[row][3] + '</a> &gt; ');
			parent=nav[row][1];
		}
	} 
	
	while (adding){
		adding=false;
		var row; for (row = 0; row < nav.length; ++row) { 
			if (nav[row][0]==parent){
				op= ('<a href="' + nav[row][4] + '">' + nav[row][3] + '</a> &gt; ') + op;
				parent=nav[row][1];
				adding=true;
			}
		} 
	}
	op= ('<a href="/">Home</a> &gt; ') + op;
	document.writeln(op);
}
function setcomment(selObj,orders_id){
	st=selObj.options[selObj.selectedIndex].value;
	if (st!=""){
	if(st==1){newtext='Your order number '+orders_id+' status has been set to pending';}
	if(st==2){newtext='Your order number '+orders_id+' status has been set to processing';}
	if(st==3){newtext='Your order number '+orders_id+' has been despatched. You can track the status of your order by clicking on the link below:\n\n';}
	if(st==4){newtext='Your order number '+orders_id+' status has been set to failed.\n\nPlease contact customer services for more information on 01420 525591 - between 9am and 5.30pm.';}
	if(st==5){newtext='Your order number '+orders_id+' is awaiting approval.';}
	if(st==6){newtext='Your order number '+orders_id+' has been declined.  Please contact customer services for more information on 01420 525591 - between 9am and 5.30pm';}
	document.form1.comment.value=newtext;
	}
}
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  if(selObj.options[selObj.selectedIndex].value!='-1'){
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
  }
}

function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

function sipanel() {
	if (readCookie("loggedin")) {
	document.write('<p><span class="welcome" id="signinopen">Welcome back '+readCookie("firstname")+'</span><a href="/view-account.asp">View Account</a> <a href="/logout.asp">Log out</a></p>');
	} 
	if (readCookie("retailer")&&!readCookie("mmc")) {
	document.write('<p><a href="/retailerhome.asp">View current stock list and place an order</a>');
	}
	if (readCookie("mmc")) {
	document.write('<p><a href="/mmc.asp">MMC home page</a>');
	}
	if ((readCookie("retailer"))||(readCookie("mmc"))||(readCookie("bquantity")!=null&&readCookie("bquantity")!=0)) {
	document.write('<p><a href="/basket.asp">Your basket:</a> Items: <span id="basketitems">'+readCookie("bquantity")+'</span>&nbsp;&nbsp;&nbsp;Total: &pound;<span id="baskettotal">'+CurrencyFormatted(unescape(readCookie("btotal")))+'</span></p>');
	}
	if (!readCookie("loggedin")) {
	document.write('<p><a id="signinopen" href="#">Sign in here</a>');
	}
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function vallogin(tf){
	if(document.getElementById) {
		var tf = document.getElementById("lf");
	} else if (document.all){
		var tf = document.all["lf"];
	}
	if(tf.email.value==""||tf.password.value==""){
		alert("Please enter your email and password and resubmit");
		return false;
	} else {
		tf.submit();
	}
}

function valpw(tf){
	if(tf.password.value!=tf.password2.value){
		alert("Both passwords must match");
		return false;
	} else if (tf.password.value==''){
		alert("Please enter a new password");
		return false;
	} else {
		tf.submit();
	}
}

function valButton(btn) {
    var cnt = -1;
    for (var i=btn.length-1; i > -1; i--) {
        if (btn[i].checked) {cnt = i; i = -1;}
    }
    if (cnt > -1) return btn[cnt].value;
    else return null;
}
   
   
function valreg(tf){
	msg='';
	pcf='';
	if(!valButton(tf.customers_gender)){msg='fail';}
	if(tf.customers_firstname.value==''){msg='fail';}
	if(tf.customers_lastname.value==''){msg='fail';}
	if(tf.customers_email_address.value==''){msg='fail';}
	if(tf.customers_telephone.value==''){msg='fail';}
	if(tf.entry_street_address.value==''){msg='fail';}
	if(tf.entry_city.value==''){msg='fail';}
	if(tf.entry_state.value==''){msg='fail';}
	if(tf.entry_postcode.value==''){msg='fail';}
	if(tf.entry_country_id.options[tf.entry_country_id.selectedIndex].value==222) {
		if(!checkPostCode(tf.entry_postcode.value)) {
			pcf='\nPlease enter a valid postcode';
		}
		tf.entry_postcode.value=checkPostCode(tf.entry_postcode.value);
	}
	if(tf.customers_password.value==''){msg='fail';}
	if(msg!=''&&pcf==''){
		alert('Please fill in all the mandatory fields');
		return false;
	}
	if(msg!=''&&pcf!=''){
		alert('Please fill in all the mandatory fields.\nPlease enter a valid postcode');
		return false;
	}
	if(msg==''&&pcf!=''){
		alert('Please enter a valid postcode');
		return false;
	}
	return true;
}

function valdel(tf){
	msg='';
	pcf='';
	if(tf.entry_firstname.value==''){msg='fail';}
	if(tf.entry_lastname.value==''){msg='fail';}
	if(tf.entry_street_address.value==''){msg='fail';}
	if(tf.entry_city.value==''){msg='fail';}
	if(tf.entry_state.value==''){msg='fail';}
	if(tf.entry_postcode.value==''){msg='fail';}
	if(tf.entry_country_id.options[tf.entry_country_id.selectedIndex].value==222) {
		if(!checkPostCode(tf.entry_postcode.value)) {
			pcf='\nPlease enter a valid postcode';
		}
		tf.entry_postcode.value=checkPostCode(tf.entry_postcode.value);
	}
	if(msg!=''&&pcf==''){
		alert('Please fill in all the mandatory fields');
		tf.entry_postcode.value=checkPostCode(tf.entry_postcode.value);
		return false;
	}
	if(msg!=''&&pcf!=''){
		alert('Please fill in all the mandatory fields.\nPlease enter a valid postcode');
		return false;
	}
	if(msg==''&&pcf!=''){
		alert('Please enter a valid postcode');
		return false;
	}
	return true;
}

function vallogin2(tf){
	if(document.getElementById) {
		var tf = document.getElementById("lf2");
	} else if (document.all){
		var tf = document.all["lf2"];
	}
	if(tf.email.value==""||tf.password.value==""){
		alert("Please enter your email and password and resubmit");
		return false;
	} else {
		tf.submit();
	}
}

function changeClass(Elem, myClass) {
	var elem;
	if(document.getElementById) {
		var elem = document.getElementById(Elem);
	} else if (document.all){
		var elem = document.all[Elem];
	}
	elem.className = myClass;
}

function checkPostCode (toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  
  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
  
  // Overseas Territories
  pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  //alert(postCode);
  if (valid) {return postCode;} else return false;
}



/* 
  ------------------------------------------------
  PVII Equal CSS Columns scripts -Version 2
  Copyright (c) 2005 Project Seven Development
  www.projectseven.com
  Version: 2.1.0
  ------------------------------------------------
*/
function P7_colH2(){ //v2.1.0 by PVII-www.projectseven.com
 var i,oh,h=0,tg,el,np,dA=document.p7eqc,an=document.p7eqa;if(dA&&dA.length){
 for(i=1;i<dA.length;i+=2){dA[i+1].style.paddingBottom='';}for(i=1;i<dA.length;i+=2){
 oh=dA[i].offsetHeight;h=(oh>h)?oh:h;}for(i=1;i<dA.length;i+=2){oh=dA[i].offsetHeight;
 if(oh<h){np=h-oh;if(!an&&dA[0]==1){P7_eqA2(dA[i+1].id,0,np);}else{
 dA[i+1].style.paddingBottom=np+"px";}}}document.p7eqa=1;
 document.p7eqth=document.body.offsetHeight;
 document.p7eqtw=document.body.offsetWidth;}
}
function P7_eqT2(){ //v2.1.0 by PVII-www.projectseven.com
 if(document.p7eqth!=document.body.offsetHeight||document.p7eqtw!=document.body.offsetWidth){P7_colH2();}
}
function P7_equalCols2(){ //v2.1.0 by PVII-www.projectseven.com
 var c,e,el;if(document.getElementById){document.p7eqc=new Array();
 document.p7eqc[0]=arguments[0];for(i=1;i<arguments.length;i+=2){el=null;
 c=document.getElementById(arguments[i]);if(c){e=c.getElementsByTagName(arguments[i+1]);
 if(e){el=e[e.length-1];if(!el.id){el.id="p7eq"+i;}}}if(c&&el){
 document.p7eqc[document.p7eqc.length]=c;document.p7eqc[document.p7eqc.length]=el}}
 setInterval("P7_eqT2()",10);}
}
function P7_eqA2(el,p,pt){ //v2.1.0 by PVII-www.projectseven.com
 var sp=10,inc=20,g=document.getElementById(el);np=(p>=pt)?pt:p;
 g.style.paddingBottom=np+"px";if(np<pt){np+=inc;
 setTimeout("P7_eqA2('"+el+"',"+np+","+pt+")",sp);}
}
function P7_colH3(){ //v2.1.0 by PVII-www.projectseven.com
 var i,oh,h=0,tg,el,np,dA=document.p7eqc,an=document.p7eqa;if(dA&&dA.length){
 for(i=1;i<dA.length;i+=2){dA[i+1].style.paddingBottom='';}for(i=1;i<dA.length;i+=2){
 oh=dA[i].offsetHeight;h=(oh>h)?oh:h;}for(i=1;i<dA.length;i+=2){oh=dA[i].offsetHeight;
 if(oh<h){np=h-oh;if(!an&&dA[0]==1){P7_eqA3(dA[i+1].id,0,np);}else{
 dA[i+1].style.paddingBottom=np+"px";}}}document.p7eqa=1;
 document.p7eqth=document.body.offsetHeight;
 document.p7eqtw=document.body.offsetWidth;}
}
function P7_eqT3(){ //v2.1.0 by PVII-www.projectseven.com
 if(document.p7eqth!=document.body.offsetHeight||document.p7eqtw!=document.body.offsetWidth){P7_colH3();}
}
function P7_equalCols3(){ //v2.1.0 by PVII-www.projectseven.com
 var c,e,el;if(document.getElementById){document.p7eqc=new Array();
 document.p7eqc[0]=arguments[0];for(i=1;i<arguments.length;i+=2){el=null;
 c=document.getElementById(arguments[i]);if(c){e=c.getElementsByTagName(arguments[i+1]);
 if(e){el=e[e.length-1];if(!el.id){el.id="p7eq"+i;}}}if(c&&el){
 document.p7eqc[document.p7eqc.length]=c;document.p7eqc[document.p7eqc.length]=el}}
 setInterval("P7_eqT3()",10);}
}
function P7_eqA3(el,p,pt){ //v2.1.0 by PVII-www.projectseven.com
 var sp=10,inc=20,g=document.getElementById(el);np=(p>=pt)?pt:p;
 g.style.paddingBottom=np+"px";if(np<pt){np+=inc;
 setTimeout("P7_eqA3('"+el+"',"+np+","+pt+")",sp);}
}
