/*global alert, $, concat */

var website = {};
var values = [], loadPage = 'load', currPage = false;

website.emailChecked	= false;
website.currentqtyval	= false;
website.ismetro		= false;
website.dpostcode	= false;
website.deltype		= false;
website.delivery	= false;
website.pickup		= false;
website.postage		= false;
website.laying		= false;
website.layingset	= false;
website.showlayrate	= false;
website.saveddata	= false;
website.nodelivery	= false;

function checkEmail(email) {
	
	var purl, self = this;
	this.result = false;

	function confirmEmail(val){
		self.result = val;
		website.emailChecked = self.result;
		$('#emailconfirmed').val('yes');
	}

	purl = "scripts/ajax.php?action=checkemail&email="+email+"&sid="+Math.random();
	$.ajax({ url: purl, success: function(html) { if(html === "false") { alert("Invalid Email Address Entered!"); $('#emailconfirmed').val(''); } else { confirmEmail(true); } } });// alert("result = "+emailCheck);

//	website.emailChecked = this.result;
	return this.result;

}

function subscribeNewsletter() {
	var name, email, purl;

	name = $('#name').val();
	email = $('#email').val();

	if (website.emailChecked !== false) { // alert("web thingy = "+website.emailChecked);
		purl = "scripts/ajax.php?action=newssub&name="+name+"&email="+email+"&sid="+Math.random();
	} else {
	//	alert("failing!");
		return false;
	}

	purl = encodeURI(purl);

	$('#newssubres').load( purl );

	/* $.ajax({ url: purl, success: function(html) { $("#newssubres").append(html); } }); */
}

function checkNewsSub() {
	var name, email, chk;
	name = $('#name').val();
	email = $('#email').val();

	chk = checkEmail(email);
	setTimeout(function(){ if(chk === false && website.emailChecked === false) { return false; } if(name && email){ subscribeNewsletter(); } else { alert("Please complete both fields first..."); return false; }}, 500);
}

function contactGreener() {
	var name, email, phone, message, purl;

	name = $('#qename').val();
	email = $('#qeemail').val();
//	phone = $('#contactphone').val();
	message = $('#qenquiry').val();

	if(message === '') { message = "No message was submitted."; }

	message = message.replace(/,/g, '');
	$('#qeresponse').html('One moment please, sending your inquiry');

/*	purl = "scripts/ajax.php?action=contactus&name="+name+"&email="+email+"&phone="+phone+"&message="+message+"&sid="+Math.random();
	purl = encodeURI(purl);

	$('#contactform').load( purl ); */

	$.post("scripts/ajax.php?action=contactus", { name: name, email: email, message: message}, function(data) { $('#qeresponse').html(data); });

}

function contactCheck() {

	var name, email, phone, purl, tested = false;

	name = $('#contactname').val();
	email = $('#contactemail').val();
	phone = $('#contactphone').val();

	tested = checkEmail(email); // alert(tested); alert(website.emailChecked);
	
	setTimeout(function(){	if (tested === false && website.emailChecked === false) { return false; } if (!isFinite(phone)) { alert("Please enter a valid phone number"); return false; } }, 600);

	setTimeout(function(){ if(name !== '' && email !== '' && phone !== '' && isFinite(phone) && (tested === true || website.emailChecked === true)){
					contactExpressway();
				}
				else {
					alert("Please complete all required fields before submitting");
					return false;
				}
	}, 1200);
}

function galleryChanger(gallery, elm) {
	
	var purl;
	purl = "scripts/ajax.php?action=gallerychange&gallery="+gallery+"&sid="+Math.random();

	$('#workBox').load( purl );

	function reset(){
		if ($('#photos')) {
			$(document).ready(function(){
				$('#photos').galleryView({
					panel_width: 620,
					panel_height: 329,
					frame_width: 69,
					frame_height: 69
				});
			});
		} else {
			setTimeout( function(){ reset(); }, 100);
		}
	}
	if (elm) { // alert("is elm!");
		setTimeout( function(){ reset(); }, 1000);
	}
	
	/* Using HTML DOM to change class of clicked <li> */
	if (elm) {
		$("li").removeClass("subBntCurrent").addClass("subBnt");
		elm.parentNode.className='subBnt subBntCurrent';
	}

	/* move page up to view gallery */
	setTimeout(function() { document.location.hash = 'work'; }, 1100);
}

function getProduct(pid, val, lid) {

	var purl;
	$('#servicesBoxRight').html('<p><img style="border:0;" alt="Loading - please wait" src="../images/loading.gif" /> One moment please - fetching data...</p>');
	if(val === 's') {
		pid = "ser-"+pid;
	} else {
		pid = "pro-"+pid;
	}
	purl = "scripts/ajax.php?action=getproduct&pid="+pid+"&sid="+Math.random();

	document.location.hash = 'viewup';
	$('#servicesBoxRight').load( purl );
	setTimeout(function(){ document.location.hash = 'viewup'; }, 100);
	$("li").removeClass("current");
	lid.parentNode.className = 'current';
	
}

function getGets(sString, find) {
	var name, gvalue, vPair, i, sPairs; 
	sString=sString.substring(1);
	sPairs=sString.split("&");
	if(sPairs.length===1){
		sPairs=sString; vPair=sPairs.split("="); name=vPair[0]; gvalue=vPair[1];
		if(name===find){ return gvalue; } else { return "0"; }
	} else {
		for(i=0;i<=sPairs.length;i++){
			/* iterate */
			vPair=sPairs.split("="); name=vPair[0]; gvalue=vPair[1];
			if(name===find){ return gvalue; } else { return "0";}
		}
	}
}

function saveCheckout( pid, total ) {
    var purl, ret = false;

    purl = "scripts/ajax.php?action=savecheckout&pid="+pid+"&total="+total+"&sid="+Math.random();
 
 //   alert("saving the world at "+ purl);

    $.ajax({ url: purl, success: function(html) { if(html === "false") { ret = false; } else { ret = true; } } });

    setTimeout( function() { return ret; }, 1000);

}

function checkForm() {
	if($('pplform')) {
		$('checkingout').innerHTML = '<br /><br /><h2>One moment please -  opening Paypal (R) checkout page...</h2>';
		setTimeout(function(){ $('pplform').submit(); }, 10000); 
/*		alert("Paypal OK!"); */
	} else {
		$('form-addclassified').action = 'https://www.paypal.com/cgi-bin/webscr';
		$('checkingout').innerHTML = '<br /><br /><h2>One moment please -  opening Paypal (R) checkout page...</h2>';
		setTimeout(function(){ $('form-addclassified').submit(); }, 10000);
/*		alert("Standard form only!!"); */
	}
}

function contactThem() {
    var name, email, phone, message, purl;
    
    email   = $('#cemail').val();
    if(website.emailChecked === false) { website.emailChecked = checkEmail(email); } // false;  }

    if(website.emailChecked !== false) {
	name    = $('#cname').val();
	phone   = $('#cphone').val();
	message = $('#message').val();

	if(name && message) {

	    message = message.replace(/,/g, '');

	    purl = "scripts/ajax.php?action=contactus&email="+email+"&name="+name+"&phone="+phone+"&message="+message+"&sid="+Math.random();	   

	    purl = encodeURI(purl);

	    $('#contactForm').load( purl );
	} else {
	    alert("Please complete all required fields before submitting. Thank You!");
	    return false;
	}
    }
    else {
	alert("Please enter a valid email address. Thank You!");
	return false;
    }
}

function setQtyVal(val) {
	if(val >= 1) {
		website.currentQtyVal = val;
	}
}

function setSessionValue(k, v) {
    var purl;
    purl = "scripts/ajax.php?action=setSessionValue&k="+k+"&v="+v+"&sid="+Math.random();

    $.ajax({ url: purl, success: function(html) { } });
}

function resetQtyVal(iid, val){
	var purl, req, divid, liid, clritm, dir;
	divid = "#item_"+iid;
	liid  = "#list_"+iid;

	if(website.currentQtyVal < val) {
	    dir = "up";
	} else if(website.currentQtyVal > val && val != 0) {
	    dir = "down";
	} else {
	    dir = "delete";
	}

	clritm = function(list, id) {	//$('#ctotal').html(nt.toFixed(2));  alert(id);
		var ot, st, nt, elm;
		ot = $('#carttotal').val();	// alert("ot = "+ot);
		st = $('#subt_'+id).val();	// alert("st = "+st);
		nt = (ot - st);	
						// alert("nt = "+nt);
		$('#carttotal').val(nt);
		$('#grandtotal').val(nt);
		
		list = list.replace("#", "");
		
		$('#ctotal').html(nt.toFixed(2));
		$('#cthead').html(nt.toFixed(2));

		document.getElementById(list).style.display = 'none';
	//	alert(list);
		
	}
	rstitm = function(htm, did) {

	//	alert(htm);

	    setTimeout( function() { document.location = '/shopping/?sc=1'; }, 500);
	    /*
		var expl, nt;
		expl = htm.split("|", 2);

	//	alert(expl);

		nt = expl[0];	//	alert(nt);
		$('#carttotal').val(nt);
		$('#grandtotal').val(nt);

		if($("#ctotal")) {
	//	    alert("nt ="+nt);		    
	//	    if(nt.indexOf(".") !== -1) { // alert("is indexOf!");
	//		nt = nt.toFixed(2);
	//	    }
	//	    alert(nt);
		    document.getElementById('ctotal').innerHTML = nt; //.toFixed(2);
		    document.getElementById('cthead').innerHTML = nt; //.toFixed(2);
	//	    $("span#ctotal").html(nt.toFixed(2)); // innerHTML = nt; //.toFixed(2); //
		} else { alert("Total price unavailable!"); }

		htm = expl[1]; //	alert(htm);
		$(did).html(htm); */
	}

//	alert(website.sessId);

	purl = "scripts/ajax.php?action=updateCartQty&iid="+iid+"&v="+val+"&sessid="+website.sessId+"&sid="+Math.random();

	if(val != 0) $(divid).html('One moment please - updating data...');

	$.ajax({ url: purl, success: function(html) { if(html) { if(html == "delete") { clritm(liid, iid); } else { rstitm(html, divid); /* $(divid).html(html); */ } } } });
}

function deleteItem(iid) {
    var purl;
    purl = "scripts/ajax.php?action=deleteItem&iid="+iid+"&sessid="+website.sessId+"&sid="+Math.random();

//	if(val != 0) $(divid).html('One moment please - updating data...');

	$.ajax({ url: purl, success: function(html) { if(html) { if(html == "done") { /* Well done!! */ $('#list_'+iid).html('Item deleted! One moment, reloading page.'); setTimeout(function() { document.location='/shopping'; }, 500); } else { /* Not so well done */ alert("An error has prevented the deletion from running smoothly"); } } } });
}

function chkQtyVal(iid, val) {
	if(val) {
		if(val !== website.currentQtyVal) {
			// sent via AJAX /
			resetQtyVal(iid, val);
		}
	}
}

function processPrice(liid){
    var pid, price, ot, nt = new Number(0);
    if (liid === "layingmessage") {
	pid = "laying";
    } else if (liid === "postagemessage") {
	pid = 'postage'; // "postage";
    } else {
	pid = "delivery";
    }
    price  = $('#'+pid).val();
    ot	    = $('#carttotal').val();
    nt = (Number(price) + Number(ot));

    if (liid === "postagemessage") {
	// ab fab
    } else {
	$('#carttotal').val(nt);
	$('#ctotal').html ( nt ); //.toFixed(2) );
	$('#grandtotal').val(nt);
    }

    $('#'+liid).html('<span>Please select &#39;Update&#39; to complete process.</span>').show();
}

/*
function setDelivery(val, e, id) {
 //   alert(e);
    e.preventDefault;
    var shutup, closer = { "pickup":"delivery","delivery":"pickup"};

    shutup = closer[val];
//    alert("shutup = "+shutup);
    $('#'+shutup).hide();
    if (val === "pickup") {
//	alert("ID = "+id);
	    document.getElementById(id).className = "cartselected";
	    document.getElementById('deliverypicker').className = 'cartselector';
	    $('#deliveryaddress').hide();
	    $('#layingbox').hide();
	    if ($('#outsidemetro')) {
	        $('#outsidemetro').hide();
	    }
	    if ($('#insidemetro')) {
	        $('#insidemetro').hide();
	    }
	    website.saveddelivery = $('#delivery').html();
	    $('#delivery').html('');
	    $('#delivery').hide();
	    website.saveddeliveryaddress = $('#deliveryaddress').html();
	    $('#deliveryaddress').html('');
	    website.savedoutsidemetro = $('#outsidemetro').html();
	    $('#outsidemetro').html('');
	    website.saveddeliveryoutside = $('#delivery_outside').html();
	    $('#delivery_outside').html('');

	    if (website.savedpickup != '') {
		$('#pickup').html( website.savedpickup );
	    }
	
    }
    if (val === "delivery") {
/*	$('#'+id).toggleClass("cartselected", 1); 
	    document.getElementById(id).className = "cartselected";
	    document.getElementById('pickuppicker').className = 'cartselector';
	    website.savedpickup = $('#pickup').html();
	    website.savedpickup = $('#pickup').html('');
	    if ($('#metrocheck').val() == "yes") {
	        if (website.saveddelivery != '') {
		        $('#delivery').html(website.saveddelivery);
	        }
	        $('#delivery').show();
	            if (website.saveddeliveryaddress != '') {
        //	        alert("reseting delivery address for metrocheck = yes");
		            $('#deliveryaddress').html(website.saveddeliveryaddress);
		            $(function() { $('#deliverydate').datepicker({dateFormat: 'dd/mm/yy', minDate: +1, beforeShowDay: function(date) { var day = date.getDay(); return [ (day != 0) ]; } }); })
	/*	$('#deliverydate').datepicker({dateFormat: 'dd/mm/yy', minDate: +1, beforeShowDay: function(date) { var day = date.getDay(); return [ (day != 0) ]; } }); */
	 /*   if (website.saveddeliveryoutside != '') {
		$('#delivery_outside').html(website.saveddeliveryoutside);
	    }
	    $('#delivery_outside').show();
	    alert("metro is checked!");
	    if ($('#insidemetro')) {
		$('#insidemetro').show();
	    } else {
		if ($('#deliveryaddress')) {
		    $('#deliveryaddress').hide();
		}
	    } 
	    } $('#deliverydate').datepicker({dateFormat: 'dd/mm/yy', minDate: +1, beforeShowDay: function(date) { var day = date.getDay(); return [ (day != 0) ]; } });else if ($('#metrocheck').val() == "no") {
	        if (website.saveddeliveryoutside != '') {
		        $('#delivery_outside').html(website.saveddeliveryoutside);
	        }
	        $('#delivery_outside').show();

	  /*  if (website.saveddelivery != '') {
		$('#delivery').html(website.saveddelivery);
	    }
	    $('#delivery').show();
	    if (website.saveddeliveryaddress != '') {
		$('#deliveryaddress').html(website.saveddeliveryaddress);
	    } 
	    } else {
	        $('#delivery').show();
	        if (website.saveddeliveryaddress != '' && $('#deliveryaddress').innerHTML == '') {
		        $('#deliveryaddress').html(website.saveddeliveryaddress);
		        $('#deliverydate').datepicker({dateFormat: 'dd/mm/yy', minDate: +1, beforeShowDay: function(date) { var day = date.getDay(); return [ (day != 0) ]; } });
	        }
	    }
    }
    
    $('#'+val).show();

    if (val === "delivery") {
	    $('#layingbox').show();
    }

    if (website.quoteonly == true && val == "delivery") {
	    $('#outsidemetro').show();
    }
}
*/

function setDelivery(val, e, id) {
    e.preventDefault;
    var shutup, closer = { "pickup":"delivery","delivery":"pickup"};

    shutup = closer[val];

    $('#'+shutup).hide();
    if (val === "pickup") {
	    document.getElementById(id).className = "cartselected";
	    document.getElementById('deliverypicker').className = 'cartselector';
	    $('#deliveryaddress').hide();
	    $('#layingbox').hide();

	    if ($('#outsidemetro')) {
	        $('#outsidemetro').hide();
	    }
	    if ($('#insidemetro')) {
	        $('#insidemetro').hide();
	    }
	    website.saveddeliveryoutside = $('#delivery_outside').html();
	    $('#delivery_outside').html('');

//	    website.saveddelivery = $('#delivery').html();
//	    $('#delivery').html('');
//	    $('#delivery').hide();
//	    website.saveddeliveryaddress = $('#deliveryaddress').html();
//	    $('#deliveryaddress').html('');
//	    website.savedoutsidemetro = $('#outsidemetro').html();
//	    $('#outsidemetro').html('');
//	    website.saveddeliveryoutside = $('#delivery_outside').html();
//	    $('#delivery_outside').html('');
//	    if (website.savedpickup != '') {
//		$('#pickup').html( website.savedpickup );
//	    }
	    $('#delchecker').val('0');
	    $('#pickup').show();

	    if (website.delivery !== false) {
		website.delivery = false;
	    }
	    if (website.quoteonly !== false) {
		website.quoteonly = false;
	    }


    }

    if (val === "delivery") {
	    document.getElementById(id).className = "cartselected";
	    document.getElementById('pickuppicker').className = 'cartselector';
	    $('#pickup').hide();
	    $('#delivery').show();
	    $('#layingbox').show();
	    $('#delchecker').val('1');

	    if (website.pickup !== false) {
		website.pickup = false;
	    }

	    if (website.quoteonly == true) {
		website.quoteonly == false;
//		$('#outsidemetro').show();
	    }
    }
    
}

function pickupCheck() {
    var d, p, e, n;
    
    d	 = $('#pickupdate').val();
    p	 = $('#phonenumber').val();
    e	 = $('#pemail').val();
    n	 = $('#fullname').val();

    if (d) {
       if (p) {
	  if (e) {
	     if(n) {
		return true;
	     } else {
		alert("Please comprete you name fank you");
		return false;
	     }
	  } else {
	    alert("Please comprete youz email fanks!");
	    return false;
	  }
       } else {
	  alert("Please pee first into the phone number... p ="+p);
	  return false;
       }
    } else {
	alert("No date mate!");
	return false;
    }         
}

function setPickup() {
    var d, p, e, n, purl, doneski;

    doneski = function() {
	website.pickup	    = true;
	website.delivery    = false;
	website.laying	    = false;
	website.postage	    = false;
	$('#pickupmess').html('<br />Pickup details have been cached. Please continue...');
    }

    if (pickupCheck()) {
	d	 = $('#pickupdate').val();
	p	 = $('#phonenumber').val();
	e	 = $('#pemail').val();
	n	 = $('#fullname').val();
	purl = '/scripts/ajax.php?sessid='+website.sessId+'&action=setPickup&d='+d+'&p='+p+'&e='+e+'&n='+n+'&sid='+Math.random();  
	$.ajax({ url: purl, success: function(html) { if (html != "error") { doneski(); /* Another happy landin! */ } else { alert("All gone bad!!"); alert(html); } }});
    }
/*(

    if (d) {
       if (p) {
	  if (e) {
	     if(n) {
		purl = '/scripts/ajax.php?sessid='+website.sessId+'&action=setPickup&d='+d+'&p='+p+'&e='+e+'&n='+n+'&sid='+Math.random();  
		$.ajax({ url: purl, success: function(html) { if (html != "error") { doneski(); } else { alert("All gone bad!!"); alert(html); } }});
	     } else {
		alert("Please comprete you name fank you");
	     }
	  } else {
	    alert("Please comprete youz email fanks!");
	  }
       } else {
	  alert("Please pee firtst into the phone number... p ="+p);
       }
    } else {
       alert("how can we do it if we dont know when silly??");
    }
    */
}

function testPostcode(e) {
//    alert("e = "+e);
    if (e == "stop") return false;
    var postcode, purl;
    postcode = $('#postcode').val();

    if (postcode == '0000') { alert("Please enter your postcode before continuing"); return false; }
    if(postcode == '' || postcode == undefined) return false;

 //   alert("postcode = "+postcode);
    var pcok = function() {
	website.savedoutdata = $('#outsidemetro').innerHTML;
	$('#outsidemetro').hide();
	$('#outsidemetro').html('');
	$('#getquoteonly').val("0");
	$('#pcok').show();
	$('#pcoktext').html("Thank you. Your delivery postcode has been confirmed. Please enter your complete delivery address below.");
	$('#pcoktext').show();
	$('#pc').val(postcode);
	if (website.saveddeliveryaddress != '' && website.saveddeliveryaddress != undefined) {
	    $('#deliveryaddress').html(website.saveddeliveryaddress);
	}
//	alert($('#deliveryaddress').length);
	if ($('#deliveryaddress').length > 0) {

//	    alert("Stand and deliver!");

	    $('#deliveryaddress').show();
	    $('#deliverydate').datepicker({dateFormat: 'dd/mm/yy', minDate: +1, beforeShowDay: function(date) { var day = date.getDay(); return [ (day != 0) ]; } });
	} else {

//	    alert("No deli found!");

	    if ($('#insidemetro').length > 0) {

//		alert("get inside mate!");

		$('#insidemetro').show();
	    } else {

//		alert("Nothing in here!!");
	    }
	}
	$('#check_out').val("check out");
	//	alert("success said cess much to his own pleasure!");
	$('#quotebutton').hide();
	$('#paypalcheckout').show();
	website.quoteonly = false;
	$('#metrocheck').val('yes');
	setSessionValue('metropostcode', 'yes');
	setSessionValue('postcode', postcode);
    }

    var nopc = function() {
	$('#pcok').hide();
	$('#pcoktext').html('');
	$('#layingbox').hide();
	$('#nopc').val(postcode);
	$('#outsidemetro').show();
	$('#check_out').val("get quote");
	$('#getquoteonly').val("1");
	website.saveddeliveryaddress = $('#deliveryaddress').html();
	website.metropostcode = false;
	website.pickup = false;
	website.quoteonly     = true;
	$('#deliveryaddress').html('');
	$('#deliveryaddress').hide();
	website.saveddelivery = $('#delivery').html();
	$('#delivery').html('');
	$('#delivery_outside').show();
	$('#paypalcheckout').hide();
	$('#quotebutton').show();
	$('#metrocheck').val('no');
	setSessionValue('metropostcode', 'no');
    }

    purl = '/scripts/ajax.php?action=testMetro&pc='+postcode+'&sid='+Math.random();
    $.ajax({ url: purl, success: function(html) { if (html) { if(html == "no") { nopc(); } else { pcok(); } } else { alert("An undetermined error has occurred. Please go home!"); } } });
}

function saveDeliveryStatus(postcode,n,s,t,d,q,dcost,ph,e) {
    var purl;
//    alert("saving the del, not good for hell!");

    purl = "/scripts/ajax.php?action=saveDelivery&pc="+postcode+"&n="+n+"&s="+s+"&t="+t+"&ph="+ph+"&d="+d+"&e="+e+"&q="+q+"&c="+dcost+"&sid="+Math.random();
    $.ajax({ url: purl, success: function(html) { if (html == "error") { alert("Error! An unknown error has prevented your Delivery details from being saved"); } else { $('#delmess').html('Delivery data has been successfully cached'); } } });
}

function savePostageStatus(postcode,n,s,t,q,pcost,e,ph) {
    var purl;
    purl = "/scripts/ajax.php?action=addPostage&pc="+postcode+"&n="+n+"&s="+s+"&t="+t+"&q="+q+"&e="+e+"&ph="+ph+"&status=true&c="+pcost+"&sid="+Math.random();

//    alert(purl);

    $.ajax({ url: purl, success: function(html) { if (html == "error") { alert("Postage could not be added. Please try again"); } else { if (website.postagestate == true) { $('#postageres').html('Thankyou. Postage details have been saved for this purchase'); website.postagestate == false; } else { /* Zippo again! */ } } } });
}

function deliveryCheck(dcost) {
    var d,n,s,t,q,pc,p,ec;
    if (website.nodelivery == true) return false;

//    alert("de live ery!");

//    if ($('#name') && $('#street') && $('#town')) { // alert(' get me out a here!! '); return false; }
    d = $('#deliverydate').val();
    if (d == '' || d == undefined) {
	d = $('#deliverydater').val();
    }
    if (d === '' || d === undefined) {
	d = $('.deliverydate').val();
    }
    n = $('#name').val();
    s = $('#street').val();
    t = $('#town').val();
    p = $('#dphone').val(); //  alert("phone = "+p);
    q = $('#getquoteonly').val();
    e = $('#email').val();

    if ($('#name') && $('#street') && $('#town')) {

//	alert("de cost of de war is 2 dollar + "+dcost);

      checkEmail(e);
      if (n) {
	if (s) {
	    if (t) {
		if (d) {
		    if (p && isFinite(p)) {	// alert("e = "+e);
			if (e) { // && checkEmail(e)) {
		//	    checkEmail(e);
			    ec = $('#emailconfirmed').val();
		//	    alert("ec = "+ec);
		//	    alert("emailChecked = "+website.emailChecked);
			    if (ec == "yes" || website.emailChecked == true) {
		//		alert("the EEEE male is good!");
				pc = $('#postcode').val();
				if ((pc >= 1) && isFinite(pc)) {
		//		    alert("pc is OK!");
				    website.delivery = true;
				    if ($('#getquoteonly').val() == '0') {
					$('#layingbox').show();
					website.delivery    = true;
				    } else {
			//		alert("val = "+ $('#getquoteonly').val());
					website.quoteonly   = true;
					website.pickup	    = false;
					website.delivery    = false;
//					website.laying	    = false;
					website.postage	    = false;
				    }
				    saveDeliveryStatus($('#postcode').val(),n,s,t,d,q,dcost,p,e);
				} else {
			//	    alert("Hey! We got no PC!");				    
				    return false;
				}
			    } else {
				alert("Please enter a valid email address!");
				return false;
			    }
			} else {
			    alert("No Email Address was found");
			    return false;
			}
		    } else {
			alert("Please enter a valid Phone number");
			return false;
		    }
		} else {
		    alert("Please select your preferred delivery date");
		    return false;
		}
	    } else {
		alert("Please enter a Town / Suburb for delivery");
		return false;
	    }
	} else {
	    alert("Please enter your Street for delivery");
	    return false;
	}
      } else {
	alert("Please enter your Name for delivery and contact purposes");
	return false;
      }
    }
/*    } else {
	alert("I am a lert!");
    } */
    
}

function postageCheck(pcost) {
    var n,s,t,q;
//    alert("de poster boy is here!");
//    if ($('#name') && $('#street') && $('#town')) { // alert(' get me out a here!! '); return false; }
    n = $('#name').val();
    s = $('#street').val();
    t = $('#town').val();
    p = $('#postcode').val();
    q = $('#getquoteonly').val();
    e = $('#email').val();
    ph = $('#postphone').val();	//  alert("phoner = "+ph);

    if (n) {
	if (s) {
	    if (t) {
		if (p) {
		    if (website.postagestate == true) {

	//		alert("we wait on the state mate!");

			website.postage = true;
	//	    if ($('#getquoteonly').val() == '0') {
	//		$('#layingbox').show();
	//	    }
			savePostageStatus(p,n,s,t,q,'10',e,ph);
			website.pickup	    = false;
			website.delivery    = false;
			return true;
		    } else {

	//		alert("not saving postage data, already saved!");

			if (website.postage == true) {

	//		    alert("Yes. its true!");

			    return true;
			} else {
			    return false;
			}
		    }
		} else {
		    alert("Please enter your Postcode for postage delivery");
		}
	    } else {
		alert("Please enter a Town / Suburb for Postage delivery");
	    }
	} else {
	    alert("Please enter a Lot Number and Street Name for Postage delivery");
	}
    } else {
	alert("Please enter your Name for Postage delivery and Contact purposes");
    }
/*    } else {
	alert("I am a lert!");
    } */
    
}

function quoteCheck() {
    var n,s,t,p,d, ph;
//    alert("q u o t e!");
    n = $('#name').val();
    s = $('#street').val();
    t = $('#town').val();
    p = $('#postcode').val();
    if (p == '' || p == undefined || p == '0000') {
	p = $('#nopc').val();
    }
    d = $('#deliverydatequote').val();
    ph = $('#dphone').val();

    if (n) {
	if (s) {
	    if (t) {
		if (p) {
		    if (d) {
			if (ph && ph != '' && isFinite(ph)) {
			    if (website.layingset == true) {
				return true;
			    } else {
				alert("Please select a Laying option (Yes / No) for this quote");
				return false;
			    }
			} else {
			    alert("Please enter a valid phone number containing only numeric values");
			    $('#dphone').val('').focus();
			    return false;
			}
		    } else {
			alert("Please select your preferred date for delivery");
			return false;
    		    }
		} else {
		    alert("Please enter your Postcode for postage delivery");
		    return false;
		}
	    } else {
		alert("Please enter a Town / Suburb for Postage delivery");
		return false;
	    }
	} else {
	    alert("Please enter a Lot Number and Street Name for Postage delivery");
	    return false;
	}
    } else {
	alert("Please enter your Name for Postage delivery and Contact purposes");
	return false
    }    
}

function setLaying(s,v, c) {
    if (s == 1) {
	if (v == "yes") {
	    $('#layingcost').show();
	    $('#layingyes').show();
	    $('#layingextras').show();
	    $('#layingno').hide();
	} else if (v == "no") {
	    $('#layingno').show();
	    $('#layingextras').hide();
	}
    }
//    alert(v);
    if (v == "yes") {
	website.laying	= true;
    }
    else
	website.laying	= false;

    $('#layingvalue').val(v);
    website.layingset	= true;
    var req, purl;
    purl = '/scripts/ajax.php?action=setLayingChoice&v='+v+'&c='+c+'&sid='+Math.random();
    $.ajax({ url: purl, success: function(html) { if (html == "error") { alert("Error! An unknown error has prevented your Laying choice from being saved"); } } });
 //   } else if (s === 2) {

}

function checkOut() {
    /* Test delivery first ! */
    var conf, delcheck, ec;
    if (website.delivery !== false) {

//	alert("The delivery man has been activated! Stand and deliver!!");
	deliveryCheck($('#dcost').val());
	ec = $('#emailconfirmed').val();
	if (website.laying !== false && ec == "yes") {
	    conf = true; // confirm("Thankyou. You are now ready to proccess your payment via Paypal. Would you like to continue?");
	    alert("Thankyou. You will now be redirected to Paypal");
	    if (conf === true) { // alert("You have chosen to continue to Paypal. Prepare yourself for battle!");
		return true;
	    }
	    else
		return false;
	} else {

	    alert("Please choose an option for Laying. Thankyou");
	    return false;
	}

    } else if (website.pickup !== false) {
	ec = $('#emailconfirmed').val();
//	alert("The pickup man is active, lockup u'r daughters!");
	if (pickupCheck() && ec == "yes") {
	    conf = true; // confirm("Thankyou. You are now ready to proccess your payment via Paypal. Would you like to continue?");
	    alert("Thankyou. You will now be redirected to Paypal");
	    if (conf === true) { // alert("You have chosen to continue to Paypal. Prepare yourself for battle!");	
		return true;
	    }
	    else
		return false;
	}
	else
	    return false;

    } else if (website.postage !== false) {

//	alert("post awayyyyyyyy!!");

	if (postageCheck()) {

//	    alert("we passed the postage test, efff the rest!");
	    conf =true; // confirm("Thankyou. You are now ready to proccess your payment via Paypal. Would you like to continue?");
	    alert("Thankyou. You will now be redirected to Paypal");
	    if (conf === true) { // alert("You have chosen to continue to Paypal. Prepare yourself for battle!");	
		return true;
	    }
	    else
		return false;
	} else {
	    return false;
	}

    } else if (website.quoteonly !== false) {
//	alert("lend me a quote matey!");
      if (quoteCheck()) {
	conf = true;// confirm("Thankyou. Your quote request will now be forwarded to Greenerlawn. Would you like to continue?");
	if (conf === true) {
	    return true;
	}
	else
	    return false;
      }
      else
	  return false;

    } else {

	if (website.postagewaiting == true) {
  //	    alert("we are waiting yes!");
	    conf = confirm("Do you wish to purchase this item without postage? Please select OK to continue or Cancel to continue shopping");
	    if(conf === true ) {
		return true;
	    }
	    else
		return false;
	} else {
	    delcheck = $('#delchecker').val();
	    if (delcheck == 1) {
//		alert("del baby equals 1");
		if (deliveryCheck($('#dcost').val())) {
//		    alert("deliver me a postman!");
		    if (website.delivery == false ) {
//			alert("Hmm, its true now...");
			website.delivery = true;			
		    }
		    return true;
		}
	    } else {
		alert("No checkout option is set. Please ensure all fields are correctly completed, exit the last field to initiate validation. Thankyou");
		return false;
	    }
	}
	return false;
    }
}

function showLayingDetails() {
    if (website.showlayrate == false) {
	$('#layingrates').show();
	website.showlayrate = true;
    } else if(website.showlayrate == true) {
	$('#layingrates').hide();
	website.showlayrate = false;
    }
}$('#delchecker').val('1');

function clearSession() {
    var purl;
/*    purl = '/scripts/ajax.php?action=clearSession&sid='+Math.random();
    $.ajax({ url: purl, success: function(html) { if (html == "error") { alert("Your session data could not be cleared correctly"); } else { document.location='/shopping'; } } }); */


	document.location='/shopping?clearsession=1';
}

function setHotkey(id) {
//    alert("setting hotkey on "+id);
    $('#'+id).bind( 'keydown', 'return', testPostcode );
}

function addPostage(state) {
    var purl;
//    alert("status = "+state);
    
    if (state == true) {
	website.postagestate = true;
	$('#postageaddress').show();
    } else {
	website.postage = false;
	purl = '/scripts/ajax.php?action=addPostage&status='+state+'&sid='+Math.random();
	$.ajax({ url: purl, success: function(html) { if (html == "error") { alert("Postage could not be added. Please try again"); } else { if (state == true) { $('#postageres').html('Thankyou. Postage cost has been added to this purchase'); } else { $('#postageres').html('Postage cost has been removed from this purchase. No postage will be added. Your purchase will be picked up in person.'); } } } });
    }
}

function clearPostage() {
    var purl;
//    alert("status = "+state);
    
    website.postage = false;

    purl = '/scripts/ajax.php?action=clearPostage&sid='+Math.random();
    $.ajax({ url: purl, success: function(html) { if (html == "error") { /* */ } else { /* */ } } });
}

function clearDelivery() {
    var purl;
    
 //   alert("clearing delivery from bolivery");
    
    website.delivery = false;

    purl = '/scripts/ajax.php?action=clearDelivery&sid='+Math.random();
    $.ajax({ url: purl, success: function(html) { if (html == "error") { /* */ } else { /* */ } } });
}

function checkPhoneNumber(e, id) {
    var charCode = (e.which) ? e.which : e.keyCode;
    if (charCode > 31 && (charCode < 46 ||(charCode==47) || charCode > 57)) { 
	alert('Only Numbers Allowed');
	$(id).val('');
	return false;
    }
}

