var root = "/";
var TimeOut         = 300;
var currentLayer    = null;
var currentitem     = null;
var currentLayerNum = 0;
var noClose         = 0;
var closeTimer      = null;
var menutimer = new Array();

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 prices = $("#prices").val();	
	$.post(root+"docart.php", {id: id, action: 'add', type: type, prices: prices}, 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);
		if (checktotal()){
			$("#paybutton").attr("src", root+"images/paypal_but.png");
		}
		else{
			$("#paybutton").attr("src", root+"images/complete.png");
		}
	});
}

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 comment = $("#comment").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);
	$("#concomment").html(comment);
	$("#amount").val(total);
	
	
	$("#deliverydetails").hide(200);
	$("#confirm").show(200);
	$("#google").attr("src", "googleConversion.html");
}	

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

function paynow(method){
	var name = $("#name").val();
	var email = $("#email").val();
	var phone = $("#phone").val();
	var address = $("#address").val();
	var orderid = $("#orderid").val();
	var comment = $("#comment").val();
	var total = $("#amount").val();	
	var paid = total;
	if (method=="10%"){
		var paid=parseFloat(total) /10;
		var paid = paid.toFixed(2);
		$("#amount").val(paid);	
	}
	$.post(root + "saveorder.php", {name: name, email: email, phone: phone, address: address, orderid: orderid, total: total, method: method, paid: paid, comment: comment}, function(data){
		if(data == 1){	
			if (method != "phone"){
				$("#confirm").hide(200);
				$("#transferring").show(200);
				$("#paypal").submit();																																 
			}
			else {
				$("#confirm").hide(200);
				$("#completed").show(200);
				
				$.fn.colorbox({opacity: .4, href:'#contact', inline: true, onClosed: function(){
					$.get(root+"completephoneorder.php", {}, function(){																									  
						self.location.reload(0);
					});
				}});
			}
		}
	});
}

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 = $("input[name=emailaddress]").val();
	$("#newsletterresult").html('<center><img src="'+root+'images/loading.gif" width="32" height="32" /></center>');
	$("#newsletterresult").show();
	$("#newsletter").hide();	
	$.post(root+"newsletter.php", {emailaddress: email}, function (data){
		$("#newsletterresult").html(data);			
	});
	setTimeout("newsreturn()", 4000);
	return false;

}

function newsreturn(){
	$("input[name=emailaddress]").val("");
	$("#newsletterresult").hide();
	$("#newsletter").show();	
}


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 applyvoucher(){
	var code = $("#voucherCode").val();
	$.post(root+"docart.php", {action: 'voucher', code: code}, function(data){
		if (!data){
			updatecheckout();
			newAlert("<p>Gift Voucher "+code+" applied</p>");
		}
		else {
			newAlert(data);			
		}
	});
		
}

function removevoucher(){
	$.post(root+"docart.php", {action: 'removevoucher'}, function(data){
			updatecheckout();
	});	
}

function newAlert(msg){
	$("#messagetouser").html(msg);
	$.fn.colorbox({inline: true, href:'#messagetouser', opacity: .4, transition: 'none'});
}

function checktotal(){
	var total = $("#total").html();	
	if (parseFloat(total) > 0){
		return true;	
	}
	else{
		return false;	
	}
}

function gopayvoucher(){
	var voucher=$("input[name=voucher]").val();
	var username=$("input[name=username]").val();
	var useremail=$("input[name=useremail]").val();
	var buyeremail=$("input[name=buyeremail]").val();
	var buyername=$("input[name=buyername]").val();
	var amount=parseFloat($("input[name=amount]").val()) /100;
	var amount = amount.toFixed(2);
	if (parseFloat(amount) < 10 || isNaN(amount) || amount == ""){
		alert("You must purchase a voucher for more than 10 euro");
		return;
	}
	
	if (username == "" || useremail == "" || buyeremail == "" || buyername == ""){
		alert("You must enter your own email and name as well as the recipients name and email");
		return;	
	}
	
	
	$("input[name=amount]").val(amount);
	$("#paybutton").hide();
	$("#processbox").show();
	$.post(root+"saveorder.php", {orderid: voucher, method: 'Paypal', paymentamount: amount, type: 'voucher', buyeremail: buyeremail, buyername: buyername, username: username, useremail: useremail}, function(){
		$("#Paypalform").submit();
	});
	

}

function dropdownselect(num){
	$(".dropdown").slideUp(100);
	$(".smalldropdown").slideUp(100);
	if($("#dropbox"+num).is(':visible') == false){
		$("#dropbox"+num).slideDown(100);
	}
	
}

function dropselect(num, text, price, clink){
	
	$("#drop"+num+"text").html(text);
	$("#drop"+num).val(clink);
	$("#dropbox"+num).slideUp(100);
	if (num == 2){
		$("#dropbox1").load(root+'getranges.php?id='+clink);	
	}
	if (num == 1){
		$("#dropbox122").load(root+'getsizes.php?id='+clink);	
	}
	if (price != ""){
		var total = 0;
		var prices = $("#prices").val();
		prices = prices.split('|');
		var line;
		var found = false;
		for (i=0; i < prices.length; i++){
			line = prices[i].split('[]')
			if (line[0] == num){
				line[1] = price;
				prices[i] = line.join("[]");
				found = true;
			}
			total = parseFloat(line[1]) + parseFloat(total);
		}
		if (!found){
			prices.push(num+'[]'+price);	
			total = parseFloat(price) + parseFloat(total);
		}
		
		
		prices = prices.join('|');
		$("#prices").val(prices);
		$("#total").html(total);
		
	}	
}

function dropselectroof(num, text, price, clink){
	$("#drop"+num+"text").html(text);
	$("#drop"+num).val(clink);
	$("#dropbox"+num).slideUp(100);
	$("#frontroof").removeClass();
	$("#backroof").removeClass();
	$("#frontroof").addClass('frontroof'+clink+actw);
	$("#backroof").addClass('backroof'+clink+actw);
	$("#drop556").val(text)
	if (clink == "Pitched"){
		$("#roofline").show();	
	}
	else {
		$("#roofline").hide();	
	}
	
}

function Uncollapse(id){
	if ($("#"+id).is(":visible")){
		$("#"+id).slideUp(100);
		$("#"+id+"image").attr("src", root+"images/downarrow.png");
		if (menutimer[id]){
			clearTimeout(menutimer[id]);
		}
	}
	else {
		$("#"+id).slideDown(100);
		$("#"+id+"image").attr("src", root+"images/uparrow.png");
		 
		menutimer[id] = setTimeout("Uncollapse('"+id+"')", 5000);
	}
}

function addextra(plink, price, unique, id){
	var total = 0;
	var prices = $("#prices").val();
	prices = prices.split('|');
	var line;
	var found = false;
	var uniqueitems = new Array();
	if (unique){
		if ($("#"+plink+"check").attr("src") == root+"images/checkboxticked.png"){
			$("#"+plink+"check").attr("src", root+"images/checkbox.png");
			for(var i = 0; i < prices.length; i++){
				line = prices[i].split("[]");
				if (line[0] == plink){
					prices.splice(i, 1);	
				}
			}
			
		}
		else {
			$(".uniquecheck").attr("src", root+"images/checkbox.png");
			$("#"+plink+"check").attr("src", root+"images/checkboxticked.png");	
			$(".uniqueitem").each(function(){
				uniqueitems.push($(this).val());
			});
			
			for(var i = 0; i < prices.length; i++){				
				line = prices[i].split("[]");
				for (var j = 0; j < uniqueitems.length; j++){
					if (line[0] == uniqueitems[j]){
						prices.splice(i, 1);
					}
				}
			}
			
			prices.push(plink+"[]"+price);
			
		}
	}
	else{
		if ($("#"+plink+"check").attr("src") == root+"images/checkboxticked.png"){
			$("#"+plink+"check").attr("src", root+"images/checkbox.png");		
			for(var i = 0; i < prices.length; i++){
				line = prices[i].split("[]");
				if (line[0] == plink){
					prices.splice(i, 1);	
				}
			}
		}
		else {
			$("#"+plink+"check").attr("src", root+"images/checkboxticked.png");	
			prices.push(plink+"[]"+price);
		}
	}
	for(i=0; i< prices.length; i++){
		line = prices[i].split("[]");
		total = parseFloat(total) + parseFloat(line[1]);	
	}
	prices = prices.join("|");
	$("#prices").val(prices);
	$(".total").html(total.toFixed(2));
	if (menutimer[id]){
		clearTimeout(menutimer[id]);
		menutimer[id] = setTimeout("Uncollapse('"+id+"')", 5000);	
	}
}

function chooseprodsize(num, title, base, onduline, steel, fitting){
	var line;
	var total = 0;
	
	$("#dropbox8").slideUp(100);	
	$("#drop8text").html(title);
	
	$(".ondulineroofprice").html(onduline);
	$(".steelroofprice").html(steel);
	$(".fittingprice").html(fitting);

	var prices = $("#prices").val();
	prices = prices.split('|');
	prices[0] = num+"[]"+base; 
	
	for(i=0; i< prices.length; i++){
		line = prices[i].split("[]");
		if (line[0] == "steel"){
			line[1] = steel;	
		}
		if (line[0] == "onduline"){
			line[1] = onduline;	
		}
		if (line[0] == "fitting"){
			line[1] = fitting;	
		}
		prices[i]=line.join("[]");
		total = parseFloat(total) + parseFloat(line[1]);
			
	}
	prices = prices.join("|");
	$("#prices").val(prices);
	$(".total").html(total.toFixed(2));
	$("#proddescription").load(root+"proddesc.php?num="+num);
	$("#imgholder").load(root+"prodimages.php?num="+num);
	$("#mainimagebox").load(root+"bigprodimages.php?num="+num);
	$("#titlebar").html(title);
	
}

function addroof(type, id){
	var total = 0;
	var price = parseFloat($("."+type+"roofprice").html());
	var prices = $("#prices").val();
	prices = prices.split('|');
	var line;
	var uniqueitems = new Array();
	if ($("#"+type+"check").attr("src") == root+"images/checkboxticked.png"){
		$("#"+type+"check").attr("src", root+"images/checkbox.png");
		for(var i = 0; i < prices.length; i++){
			line = prices[i].split("[]");
			if (line[0] == type){
				prices.splice(i, 1);	
			}
		}
		
	}
	else {
		$(".uniquecheck").attr("src", root+"images/checkbox.png");
		$("#"+type+"check").attr("src", root+"images/checkboxticked.png");	
		$(".uniqueitem").each(function(){
			uniqueitems.push($(this).val());
		});
		
		for(var i = 0; i < prices.length; i++){				
			line = prices[i].split("[]");
			for (var j = 0; j < uniqueitems.length; j++){
				if (line[0] == uniqueitems[j]){
					prices.splice(i, 1);
				}
			}
		}
		
		prices.push(type+"[]"+price);

	}
	for(i=0; i< prices.length; i++){
		line = prices[i].split("[]");
		total = parseFloat(total) + parseFloat(line[1]);	
	}
	prices = prices.join("|");
	$("#prices").val(prices);
	$(".total").html(total.toFixed(2));
	if (menutimer[id]){
		clearTimeout(menutimer[id]);
		menutimer[id] = setTimeout("Uncollapse('"+id+"')", 5000);	
	}
}

function addfitting(){
	var total = 0;
	var price = parseFloat($(".fittingprice").html());
	var prices = $("#prices").val();
	prices = prices.split('|');
	var line;
	if ($("#fittingcheck").attr("src") == root+"images/checkboxticked.png"){
		$("#fittingcheck").attr("src", root+"images/checkbox.png");		
		for(var i = 0; i < prices.length; i++){
			line = prices[i].split("[]");
			if (line[0] == "fitting"){
				prices.splice(i, 1);	
			}
		}
	}
	else {
		$("#fittingcheck").attr("src", root+"images/checkboxticked.png");	
		prices.push("fitting[]"+price);
	}
	
	for(i=0; i< prices.length; i++){
		line = prices[i].split("[]");
		total = parseFloat(total) + parseFloat(line[1]);	
	}
	prices = prices.join("|");
	$("#prices").val(prices);
	$(".total").html(total.toFixed(2));
}

function adddelivery(){
	var total = 0;
	var price = parseFloat($(".deliveryprice").html());
	var prices = $("#prices").val();
	prices = prices.split('|');
	var line;
	if ($("#deliverycheck").attr("src") == root+"images/checkboxticked.png"){
		$("#deliverycheck").attr("src", root+"images/checkbox.png");		
		for(var i = 0; i < prices.length; i++){
			line = prices[i].split("[]");
			if (line[0] == "delivery"){
				prices.splice(i, 1);	
			}
		}
	}
	else {
		$("#deliverycheck").attr("src", root+"images/checkboxticked.png");	
		prices.push("delivery[]"+price);
	}
	
	for(i=0; i< prices.length; i++){
		line = prices[i].split("[]");
		total = parseFloat(total) + parseFloat(line[1]);	
	}
	prices = prices.join("|");
	$("#prices").val(prices);
	$(".total").html(total.toFixed(2));
}

function changemainimage(img, w, h, key){
	$("#themainimage").html('<a href="'+root+'uploads/products/'+img+'" onclick="showbigimage(\''+key+'\'); return false;" id="mainimglink"><img src="'+root+'uploads/products/'+img+'" width="'+w+'" height="'+h+'" id="mainimg" /></a>');
	$("#enlargelink").html('<a href="'+root+'uploads/products/'+img+'" onclick="showbigimage(\''+key+'\'); return false;" class="fright" style="color: #000066; cursor:pointer;"><img src="'+root+'images/magnify.png" style="vertical-align:middle" alt="Enlarge Image">Enlarge Image</a>');

}

function goshedbuild(){
	var width = $("input[name=width]").val();
	var length = $("input[name=length]").val();
	
	self.location= root+"shedbuilder.php?width="+width+"&length="+length;
	
}

function msgtouser(msg, flag){
	if (flag == "refresh"){
		$.fn.colorbox({open: true, html: "<p>"+msg+"</p>", opacity: .4, transition: 'none', onClosed: function(){self.location.reload(0);}});	
	}
	else {
		$.fn.colorbox({open: true, html: "<p>"+msg+"</p>", opacity: .4, transition: 'none'});	
	}
}

function showbigimage(key){
	$("#mainimagebox div").each(function(){
		if ($(this).attr('id') != key){
			$(this).hide();										 
		}
	});	
	var nextkey = parseInt(key) + 1;
	var prevkey = parseInt(key) - 1;
	$("#img"+key).show();
	
	if (key == 0){
		$("#previmage").hide();	
	}
	else {
		
		$("#previmage").html("<a href='javascript:void(0);' onclick=\"showbigimage('"+prevkey+"');\" style='color: #333;'>Prev Image</a>");
		$("#previmage").show();	
	}
	if (nextkey == totalimages){
		$("#nextimage").hide();	
	}
	else {
		
		$("#nextimage").html("<a href='javascript:void(0);' onclick=\"showbigimage('"+nextkey+"');\" style='color: #333;'>Next Image</a>");	
		$("#nextimage").show();
	}
	$.fn.colorbox({inline: true, href:'#mainimage', opacity: .4})
}


