
var root = "/";
var TimeOut         = 300;
var currentLayer    = null;
var currentitem     = null;
var currentLayerNum = 0;
var noClose         = 0;
var closeTimer      = null;

function mopen(n) {
  var l  = document.getElementById("menu"+n);
  var mm = document.getElementById("mmenu"+n);
	
  if(l) {
    mcancelclosetime();
    l.style.visibility='visible';
    if(currentLayer && (currentLayerNum != n))
      currentLayer.style.visibility='hidden';
    currentLayer = l;
    currentitem = mm;
    currentLayerNum = n;			
  } else if(currentLayer) {
    currentLayer.style.visibility='hidden';
    currentLayerNum = 0;
    currentitem = null;
    currentLayer = null;
 	}
}

function mclosetime() {
  closeTimer = window.setTimeout(mclose, TimeOut);
}

function mcancelclosetime() {
  if(closeTimer) {
    window.clearTimeout(closeTimer);
    closeTimer = null;
  }
}

function mclose() {
  if(currentLayer && noClose!=1)   {
    currentLayer.style.visibility='hidden';
    currentLayerNum = 0;
    currentLayer = null;
    currentitem = null;
  } else {
    noClose = 0;
  }
  currentLayer = null;
  currentitem = null;
}

document.onclick = mclose; 

function changeimg(val){
	var img = val.split("-");
	$.post(root+"imager.php", {image: img[1]}, function(data){
		var items = data.split(",");
		$("#picture").attr("src", root+"products/" + items[0]);
		$("#picture").attr("width", items[1]);
		$("#picture").attr("height", items[2]);
		$("#imagelink").attr("href",root+"products/" + items[0]);
		$("#imagelink").colorbox();
	});
}

function suggestme(val){
    $.post(root+"suggest.php", {val:val}, function (data){
        $("#suggester").html(data);
        $("#suggester").show();
    });
   
}

function hides(){
    $('#suggester').hide()
}

function addtocart(id, type){
	var quantity = $("#quantity").val();
	$.post(root+"docart.php", {id: id, action: 'add', quantity: quantity, type: type}, function(data){
		self.location = root+"checkout.php";
	});
}

function updatecart(num){
	$("#upd"+num).html("<img src='"+root+"images/load.gif' style='margin: 20px 0 0 10px;'  />");
	var q = $("input[name=qty"+num+"]").val();
	if (q != "" && !isNaN(q)){
		$.post(root+"docart.php", {action: 'update', num: num, q: q}, function(){
			updatecheckout();
		});
	}
	else {
		updatecheckout();	
	}
}

function removeitem(num){
	$("#rem"+num).html("<img src='"+root+"images/load.gif' style='margin: 20px 0 0 10px;'  />");
	$.post(root+"docart.php", {action: 'delete', num: num}, function(){
		updatecheckout();
	});
}

function updatecheckout(){
	$.post("docart.php", {action: "showbig"}, function(data){
		$("#bigcart").html(data);
	});
}

function selectmethod(){
	if ($("#ccdetails").is(":hidden")){
		$("#ccdetails").show();	
		$("#paybutton").html("Confirm Details");
	}
	else {
		$("#ccdetails").hide();	
		$("#paybutton").html("Proceeed to Paypal");
	}
}

function confirmdetails(){
	var name = $("#name").val();
	var email = $("#email").val();
	var phone = $("#phone").val();
	var address = $("#address").val();
	var total = $("#total").html();
	
	if (!total > 0){
		alert ("Your basket is empty");
		return;	
	}
	
	if ((name == "") || (email == "") || (address == "") || (phone == "")){
		alert("Please fill out all fields");
		return;
	}
	address = address.replace("\n", "<br />");
	address = address.replace("\r", "<br />");
	$("#conname").html(name);
	$("#conemail").html(email);
	$("#conphone").html(phone);
	$("#conaddress").html(address);
	$("#amount").val(total);
	
	
	$("#deliverydetails").hide(200);
	$("#confirm").show(200);		
}	

function backtoedit(){
	$("#deliverydetails").show(200);
	$("#confirm").hide(200);	
}

function paynow(){
	var name = $("#name").val();
	var email = $("#email").val();
	var phone = $("#phone").val();
	var address = $("#address").val();
	var orderid = $("#orderid").val();
	var total = $("#amount").val();	
	
	$.post(root + "saveorder.php", {name: name, email: email, phone: phone, address: address, orderid: orderid, total: total}, function(data){
		if(data == 1){
			$("#confirm").hide(200);
			$("#transferring").show(200);
			$("#paypal").submit();																																 
		}
	});
}

function checkme(number){
	var i, sum, weight;
	sum=0;
	for (i = 0; i < number.length - 1; i++) {
		weight = number.substr(number.length - (i + 2), 1) * (2 - (i % 2));
		sum += ((weight < 10) ? weight : (weight - 9));
	}
	if (parseInt(number.substr(number.length-1)) == ((10 - sum % 10) % 10)) {
		return true;
	} 
	else {
		return false;
	}
}



function checkEmail(e){
	var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
	var returnval=emailfilter.test(e)

	return returnval
}

function tellafriend(id){
	var title = $("#mail"+id).attr("title");
	$("input[name=prodid]").val(id);
	$.fn.colorbox({opacity: .5, inline: true, href:'#sendtofriend', title: title, width: 510, height: 310});
}

function sendproduct(){
	var id = $("input[name=prodid]").val();
	var sendername = $("input[name=sendername]").val();
	var senderemail = $("input[name=senderemail]").val();
	var receivername = $("input[name=receivername]").val();
	var receiveremail = $("input[name=receiveremail]").val();
	var errors = new Array();
	if (sendername == ""){
		errors.push("Your Name");	
	}
	if (receivername == ""){
		errors.push("Your Friend's Name");	
	}
	if (!checkEmail(senderemail)){
		errors.push("Your Email");	
	}
	if (!checkEmail(receiveremail)){
		errors.push("Your Friend's Email");	
	}
	if (errors.length > 0){
		errors.unshift("There are problems with the following fields:\n");
		errors = errors.join("\n");
		alert(errors);
	}
	else {
		$("#sendbutton").html("Sending Now...");

		$.post(root+"mailfriend.php", {id: id, sendername: sendername, senderemail: senderemail, receiveremail: receiveremail, receivername: receivername}, function(data){
			$("#sendtofriend").html("<h1>Send to a friend</h5><p>Your message has been sent to " + receivername + " ("+receiveremail+")</p>");																																							
		});
	}
}

function addtonewsletter(){
	var email = $("#emailaddress").val();
	$.post(root+"newsletter.php", {emailaddress: email}, function (data){
		$("#newsletterresult").html(data);
		$("#newsletter").hide();
		$("#newsletterresult").show();
		
	});
	setTimeout("newsreturn()", 4000);
	return false;

}

function newsreturn(){
	$("#emailaddress").val("");
	$("#newsletterresult").hide();
	$("#newsletter").show();	
}

function logmein(p){
	var email = $("input[name="+p+"memberemail]").val();
	var password = $("input[name="+p+"memberpassword]").val();
	$.post(root+"dologin.php", {email:email, password: password}, function(data){
		if(data == 1){
			self.location.reload(0);	
		}
		else {
			alert("Incorrect Email or Password.  Please try again");	
		}
	});
	
}

function signupmember(){
	var name = $("input[name=name]").val();
	var email = $("input[name=email]").val();
	var contactnumber = $("input[name=contactnumber]").val();
	var address1 = $("input[name=address1]").val();
	var address2 = $("input[name=address2]").val();
	var citytown = $("input[name=citytown]").val();
	var county = $("input[name=county]").val();
	var password1 = $("input[name=password1]").val();
	var password2 = $("input[name=password2]").val();
	
	var errors = new Array('<h2>There are problems:</h2>');
	
	if (name == ""){
		errors.push('Name Field');	
	}
	if (email == ""){
		errors.push('Email Field');	
	}
	if (contactnumber == ""){
		errors.push('Contact Number Field');	
	}
	if (address1 == ""){
		errors.push('Address 1 Field');	
	}
	if (citytown == ""){
		errors.push('City/Town Field');	
	}
	if (county == ""){
		errors.push('County Field');	
	}
	if (password1 == ""){
		errors.push('Password Field');	
	}
	if (password1 != password2){
		errors.push('Passwords do not match');	
	}
	
	if (errors.length > 1){
		$("#messagetouser").html(errors.join("<br />"));
		$.fn.colorbox({href: '#messagetouser', inline: true, opacity: .25});
		return;
	}
	$.post(root+'signup.php', {name: name, email: email, contactnumber: contactnumber, address1: address1, address2: address2, citytown: citytown, county: county, password1: password1, password2: password2}, function(data){
		$("#messagetouser").html(data);									  
		$.fn.colorbox({href: '#messagetouser', inline: true, opacity: .25});
	});
									
	
}

function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=0,width=720px,height=650px,left = 100,top = 100');");
}

function changeSpec(id){
	t = new Date();
	$.post(root+"changespec.php?t="+t.getTime(), {id: id});
}


function changeaddress(){
	$("#defaultaddress").hide();
	$("#addressdetails").show();
}

function setMain(cat){
	$.post('setmain.php', {main: cat}, function(data){
		self.location.reload(0);											
	});
}

$(window).bind("load",function(){

	$("ul.topnav li").click(function() { //When trigger is clicked...

		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click

		$(this).parent().hover(function() {
		}, function(){
			$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
		});

		//Following events are applied to the trigger (Hover events for the trigger)
		}).hover(function() {
			$(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});
					   
});

function showsubsub(id){
	$("#subsub"+id).css('height', 'auto');
	$("#show"+id).hide();
}

function validateform(formid){
	
	var errors = new Array("The following fields have errors:\n");
	var form = $("#"+formid).serialize().split("&");
	var modid = formid.substr(4);
	var name;
	$.each(form, function(i, v){
		
		name = v.split("=");	
  
		if (name[0] != "id"){
			if (($("#"+modid+name[0]).attr("rel") == "required" && name[1] == "") || (name[0] == "mpfc" && $("#"+modid+name[0]).val() != 5)){
				if (name[0] == "mpfc"){
					name[0] = "Spam Checker";
				}
				errors.push(ucfirst(name[0]));	
				
			}
		}
	});
	if (errors.length > 1){
		alert(errors.join("\n"));
		return false;	
	}
	return true;
}


function ucfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toUpperCase() + str.substr(1);
}
