// This file uses jquery heavily - http://docs.jquery.com

//multibrowser width/height/scroll values
//from http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html

var serv_path=tellDir();

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


//SETTING UP OUR POPUP  
//0 means disabled; 1 means enabled;  
var popupStatus = 0; 
var tempVals = new Array();

//loading popup with jQuery magic!  
function showPopup(){  
	//loads popup only if it is disabled  
	if(popupStatus==0){  
		//$("#backgroundPopup").css({ "opacity": "0.7" });  
		$("#backgroundPopup").show();
		$("#popup").show();
		popupStatus = 1;
	}  
}  

//disabling popup with jQuery magic!  
function disablePopup() {
	//disables popup only if it is enabled
	if(popupStatus==1) {
		$("#backgroundPopup").hide();
		$("#popup").hide();
		popupStatus = 0;
	}
}

//centering popup
function centerPopup() {
	//request data for centering  
	var windowWidth = f_clientWidth();  
	var windowHeight = f_clientHeight();  
	var windowTop = f_scrollTop();
	var windowLeft = f_scrollLeft();
	var popupHeight = $("#popup").height();  
	var popupWidth = $("#popup").width();  

	//centering
	$("#popup").css({  
		"position": "absolute",  
		"top": windowHeight/2-popupHeight/2+windowTop,  
		"left": windowWidth/2-popupWidth/2+windowLeft 
	});  
	//only need force for IE6  	  
	//$("#backgroundPopup").css({  
	//	"height": windowHeight
	//});  
}  

function loadPopup(input) {
	$.post("ajax/popup.php", { name: input },  
		function(data){ 
			$('#popup').html(data);

			//Click the x event!  
			$("#popup_close").click(function(){  
				disablePopup();  
			});

			inputAddSubmit();

			//centering with css  
			centerPopup();

			//show popup  
			showPopup();  			
		}
	
	);
}

function error(input) {
	$("#error").text(input);
}

function sign_up() {
	error("");

	var email=$("#email").val();
	var re_type_email=$("#re_type_email").val();
	var password=$("#password").val();
	var first_name=$("#first_name").val();
	var last_name=$("#last_name").val();
	var professional_account=$('#professional_account').is(':checked');
	var special_offers=$('#special_offers').is(':checked');
	var terms=$('#terms').is(':checked');

	if(email=="" ||
           email=="E-mail" ||
           re_type_email=="" ||
           re_type_email=="Re-type your E-mail" ||
           password=="" ||
           password=="Create Password" ||
           first_name=="" ||
           first_name=="First Name" ||
           last_name=="" ||
           last_name=="Last Name") {
            error("All fields have to be filled."); return;
        }
	if(checkEmail(email)==0) { error("E-mail address is not valid."); return; }
	if(email!=re_type_email) { error("E-mail addresses are not the same."); return; }
	if(!terms) { error("Please accept our terms."); return; }

	$.post("ajax/signup.php", { email: email, password: password, first: first_name, last: last_name, pro: professional_account, special: special_offers },  
		function(data){
			var user_id=parseInt(data);
			if(isNaN(data)) user_id=0;
			if(user_id>0) {
				sign_up_mail(user_id, email, password, first_name, last_name, professional_account);
			}
			else {
				error(data);
			}
		}
	);
}

function sign_up_mail(user_id, email, password, first, last, pro) {
    var to=email;
    
    var middle_html=
        "<p>================================</p>"+
        "<p>Username: "+email+"<br /> "+
        "Password: "+password+"</p> "+
        "<p>================================</p>";
    
    var middle_txt=
        "================================\n"+
        "Username: "+email+"\n"+
        "Password: "+password+"\n"+
        "================================\n";
    
    if(pro) {
        $.post("ajax/email.php", { user_id: user_id, all_to: to, mail_id: 5, middle_html: middle_html, middle_txt: middle_txt, serv_path: serv_path, first: first, last: last },   
               function(data){ 
                   if(document.location.href.match("sign_out.")!=null)	document.location.href="./";
                   else document.location.href=document.location.href;
               }
               );
    }
    else {
        $.post("ajax/email.php", { user_id: user_id, all_to: to, mail_id: 4, middle_html: middle_html, middle_txt: middle_txt, serv_path: serv_path, first: first, last: last },   
               function(data){ 
                   if(document.location.href.match("sign_out")!=null)	document.location.href="./";
                   else document.location.href=document.location.href;
               }
               );
    }
}

function trade_account () {
	tempVals['email']=$("#email").val();
	tempVals['re_type_email']=$("#re_type_email").val();
	tempVals['password']=$("#password").val();
	tempVals['first_name']=$("#first_name").val();
	tempVals['last_name']=$("#last_name").val();
	tempVals['professional_account']=$('#professional_account').is(':checked');
	tempVals['special_offers']=$('#special_offers').is(':checked');
	tempVals['terms']=$('#terms').is(':checked');
	tempVals['temp']=$('#popup').html();
	
	$.post("ajax/popup.php", { name: "trade_account" },  
		function(data){ 
			$('#popup').html(data);
			
			$("#popup_close").click(function(){  
                                go_back();
			});
		}
	);
}

function go_back() {
	if(tempVals['terms']) $('#terms').checked=true; 
	$('#popup').html(tempVals['temp']);
	$("#email").val(tempVals['email']);
	$("#re_type_email").val(tempVals['re_type_email']);
	$("#password").val(tempVals['password']);
	$("#first_name").val(tempVals['first_name']);
	$("#last_name").val(tempVals['last_name']);
	//if(tempVals['professional_account']) $('#professional_account').is(':checked');
	//if(tempVals['special_offers']) $('#special_offers').is(':checked');
			
	$("#popup_close").click(function(){  
		disablePopup();  
	});
}

function sign_in() {
	error("");

	var email=$("#email1").val();
	var password=$("#password1").val();
	var remember=$("#remember_me").is(':checked');

	if(email=="" ||
           email=="E-mail" ||
           password=="" ||
           password=="Password" ) {
            error("Please fill E-mail and Password."); return; }
        
	$.post("ajax/signin.php", { email: email, password: password, remember: remember },  
               function(data){
                   if(data!="") error(data);
                   else {
                       if(document.location.href.match("sign_out")!=null)	document.location.href="./";
                       else document.location.href=document.location.href;
                   }
               }
               );
}

function show_forgotten() {
	$.post("ajax/popup.php", { name: "forgotten" },  
		function(data){ 
			$('#popup').html(data);

			//Click the x event!  
			$("#popup_close").click(function(){  
				disablePopup();  
			}); 
		}
	);
}

function forgotten() {
	error("");

	var email=$("#email").val();

	if(email=="" || email=="E-mail") { error("Please fill E-mail field."); return; }

	$.post("ajax/forgotten.php", { email: email, serv_path: serv_path },  
		function(data){
			if(data!="" && data!="Mail sent") error(data);
			else disablePopup();
		}
	);
}

function give_name(user_id) {
	error("");

	var new_folder=$("#new_folder").val();

	if(new_folder=="" || new_folder=="Enter the folder name here") { error("Please fill name field."); return; }

	$.post("ajax/new_folder.php", { new_folder: new_folder, user_id: user_id },  
		function(data){
			if(isNaN(data)) error(data);
			else upload_photos(data, "folder_"+data);
		}
	);
}

function upload_photos(folder, destination) {
    $.post("ajax/popup.php", { name: "upload_photos", folder: folder, destination: destination },  
           function(data){ 
               $('#popup').html(data);
               //Click the x event! 
               $("#popup_close").click(function(){
                       popupStatus=1;
                       disablePopup(); 
                   }); 
               
                   if(popupStatus==0) {
                       //centering with css
                       centerPopup();
                       
                       //show popup  
                       showPopup();
                   }
			popupStatus=2;
		}
	);
}

function show_remove_changes() {
	loadPopup("remove_changes");
}

function remove_pb() {
	loadPopup("remove_basket");
}

function edit_pb(folder) {
	$.post("ajax/popup.php", { name: "edit_basket", folder: folder },  
		function(data){ 
			$('#popup').html(data);

			//Click the x event!  
			$("#popup_close").click(function(){
				disablePopup(); 
			}); 

			//centering with css  
			centerPopup();

			//show popup  
			showPopup(); 
		}
	
	);
}

function edit_basket(f_id) {
	document.location.href="./order_photobooks_"+f_id;
}

function remove_basket() {
	$.post("ajax/pb_remove.php", { },  
		function(data){ 
			if(data=="") document.location.href="./my_folders";
			$("#errors").text(data);
		}
	);
}

function ten_percent() {
	loadPopup("ten_percent");
}

function warning_popup(warning_text, warning_title) {
	$.post("ajax/popup.php", { name: "warning_popup", warning_text: warning_text, warning_title: warning_title },  
		function(data){ 
			$('#popup').html(data);

			//Click the x event!  
			$("#popup_close").click(function(){
				disablePopup(); 
			}); 

			//centering with css  
			centerPopup();

			//show popup  
			showPopup(); 
		}
	
	);
}

function rename_folder(f_id) {
    $.post("ajax/popup.php", { name: "rename_folder", folder: f_id },  
           function(data){ 
               $('#popup').html(data);
               
               //Click the x event!  
               $("#popup_close").click(function(){
                       disablePopup(); 
                   }); 
               
			if(popupStatus==0) {
                            //centering with css  
                            centerPopup();
                            
                            //show popup  
                            showPopup();
			}
           }
           );
}

function new_f_name(f_id) {
	//error("");
	var new_name=$("#new_name").val();

	if(new_name=="" || new_name=="New name") {
            error("Please fill name field."); return;
        }

	$.post("ajax/new_name.php", { new_name: new_name, f_id: f_id },  
		function(data){
			if(data=="") document.location.href=document.location.href;
			else $("#error").text(data);
			//disablePopup();
		}
	);
}

function delete_folder(f_id) {
    $.post("ajax/popup.php", { name: "delete_folder", folder: f_id },  
           function(data){ 
               $('#popup').html(data);
               
               //Click the x event!  
               $("#popup_close").click(function(){
                       disablePopup(); 
                   }); 
               if(popupStatus == 0) {
                   //centre with css  
                   centerPopup();
                   showPopup();
               }
           }
           );
}

function actually_delete_folder(f_id) {
    $.post("ajax/folder_delete.php", { f_id: f_id },  
           function(data){
               if(data == "") {
                   document.location.href=document.location.href;
               }
               else {
                   $("#error").text(data);
               }
           }
           );
}

function confirm_photos_delete() {
    // Create array of ids to be deleted, this gets passed to popup.php
    // as a parameter.
    var photo_ids = [];

    // If there's only one photo to delete, photos[] won't be an array.
    var photos_array_length = document.popup_form["photos[]"].length;
    if (photos_array_length) {
        for(i = 0; i < document.popup_form["photos[]"].length; i++){
            var element = document.popup_form["photos[]"][i];
            if(element.checked){
                photo_ids.push(element.value);
            }
        }
    } else {
           var element = document.popup_form["photos[]"];
            if(element.checked){
                photo_ids.push(element.value);
            }
    }

    if (photo_ids.length == 0) { // Nothing was chosen
        alert("No photos were selected for deletion.");
    } else {
    $.post("ajax/popup.php", {
            name: "confirm_photos_delete",
                'photos[]': photo_ids
                },  
           function(data){ 
               $('#popup').html(data);
               
               //Click the x event!  
               $("#popup_close").click(function(){
                       disablePopup(); 
                   }); 
               if(popupStatus == 0) {
                   //centre with css  
                   centerPopup();
                   showPopup();
               }
           }
           );
    }
}

function photos_delete() {
    // Create array of ids to be deleted, this gets passed to photos_delete.php
    // as a parameter.
    var photo_ids = new Array();

    // If only one photo has been selected, photos[] won't be an array.
    var photos_array_length = document.cpd_form["photos[]"].length;
    if (photos_array_length) {
        for(i = 0; i < photos_array_length; i++){
            var element = document.cpd_form["photos[]"][i];
            photo_ids.push(element.value);
        }
    } else {
        var element = document.cpd_form["photos[]"];
        photo_ids.push(element.value);
    }
        
    $.post("ajax/photos_delete.php", { 'photos[]': photo_ids },  
           function(data){
               if(data == "") {
                   document.location.href=document.location.href;
               }
               else {
                   $("#error").text(data);
               }
           }
           );
}

function share_folder(f_id) {
    $.post("ajax/popup.php", { name: "share_folder", folder: f_id },  
           function(data){ 
               $('#popup').html(data);
               
               //Click the x event!  
               $("#popup_close").click(function(){
                       disablePopup(); 
                   }); 
               
               inputAddSubmit();
               
               if(popupStatus==0) {
                   //centering with css  
                   centerPopup();
                   
                   //show popup  
                   showPopup();
               }
           }
           
           );
}

function share_photobook_send(pb_id) {
    var share_url=serv_path+"photobook_share_"+pb_id;
    var all_to="";
    for(var i=1; i<5; i++) {
        var to=$("#email"+i).val();
        if(to!="" && to!="E-mail") {
            if(all_to!="") all_to+="#";
            all_to+=to;
        }
    }
    
    var middle_html=
"<br>"+
"<p>Please click <a href='"+share_url+"'>here</a> to view their album. You'll be able to view their photos online and even order your own albums from them.</p>"+
"<br>"+
"<p>If the above link doesn&#39;t work try copying and pasting the following into your browser:<br>"+
share_url+"</p>";
	var middle_txt=
"\nPlease copy and paste the following into your browser:\n"+
share_url+"\n"+
"\n"+
"You&#39;ll be able to view their photos online and even order your own albums from them.\n";

	if(all_to != "") {
            var p_cont = "";
            
            $.post("ajax/email.php", { user_id: main_user_id, all_to: all_to, mail_id: 3, middle_html: middle_html, middle_txt: middle_txt, serv_path: serv_path },  
                   function(data){
                       p_cont = data;
                       p_cont += '<div class="send_right"><p><input style="vertical-align: -18px; margin-left: 88px;" type="image" class="image" src="images/btn_ok.png" onclick="disablePopup();"/></p></div>';
                       $("#content_popup").html(p_cont);
                   }
                   );
            
	}
	else disablePopup();
}

function share_photobook(pb_id) {
	$.post("ajax/popup.php", { name: "share_photobook", pb_id: pb_id },  
		function(data){ 
			$('#popup').html(data);

			//Click the x event!  
			$("#popup_close").click(function(){
				disablePopup(); 
			}); 

			inputAddSubmit();

			if(popupStatus==0) {
				//centering with css  
				centerPopup();

				//show popup  
				showPopup();
			}
		}
	
	);
}

function share_folder_send(f_id) {
	var share_url=serv_path+"folder_share_"+f_id;
	var all_to="";
	for(var i=1; i<5; i++) {
		var to=$("#email"+i).val();
		if(to!="" && to!="E-mail") {
			if(all_to!="") all_to+="#";
			all_to+=to;
		}
	}
	
	var middle_html=
"<br>"+
"<p>Please click <a href='"+share_url+"'>here</a> to view their album.</p>"+
"<br>"+
"<p>If the above link doesn&#39;t work try copying and pasting the following into your browser:<br>"+
share_url+"</p>";
	var middle_txt=
"\nPlease copy and paste the following into your browser:\n"+
share_url+"\n"+
"\n"+
"You'll be able to view their photos online.\n";

	if(all_to!="") {
		var p_cont="";

		$.post("ajax/email.php", { user_id: main_user_id, all_to: all_to, mail_id: 2, middle_html: middle_html, middle_txt: middle_txt, serv_path: serv_path },   
			function(data){
				p_cont=data;
				p_cont+='<div class="send_right"><p><input style="vertical-align: -18px; margin-left: 88px;" type="image" class="image" src="images/btn_ok.png" onclick="disablePopup();"/></p></div>';
				$("#content_popup").html(p_cont);
			}
		);

	}
	else disablePopup();
}

function tell_a_friend_send() {
	var share_url=tellDir();
	var all_to="";
	for(var i=1; i<5; i++) {
		var to=$("#email"+i).val();
		if(to!="" && to!="E-mail") {
			if(all_to!="") all_to+="#";
			all_to+=to;
		}
	}

	var middle_html="";
	var middle_txt="";

	if(all_to!="") {
		var p_cont="";

		$.post("ajax/email.php", { user_id: main_user_id, all_to: all_to, mail_id: 1, middle_html: middle_html, middle_txt: middle_txt, serv_path: serv_path },  
			function(data){
				p_cont=data;
				p_cont+='<div class="send_right"><p><input style="vertical-align: -18px; margin-left: 88px;" type="image" class="image" src="images/btn_ok.png" onclick="disablePopup();"/></p></div>';
				$("#content_popup").html(p_cont);
			}
		);

	}
	else disablePopup();
}

function approve_pb(pb_id) {
	$.post("ajax/popup.php", { name: "pdf_approval", pb_id: pb_id },  
		function(data){ 
			$('#popup').html(data);

			//Click the x event!  
			$("#popup_close").click(function(){
				disablePopup(); 
			}); 

			if(popupStatus==0) {
				//centering with css  
				centerPopup();

				//show popup  
				showPopup();
			}
		}
	
	);
}

function approve_amendments_pb(pb_id) {
	$.post("ajax/popup.php", { name: "approve_amendments_pb", pb_id: pb_id },  
		function(data){ 
			$('#popup').html(data);

			//Click the x event!  
			$("#popup_close").click(function(){
				disablePopup(); 
			}); 

			if(popupStatus==0) {
				//centering with css  
				centerPopup();

				//show popup  
				showPopup();
			}
		}
	
	);
}

function pdf_confirm(pb_id) {
	$.post("ajax/pb_approve.php", { pb_id: pb_id },  
		function(data){
			if(data=="") document.location.href=document.location.href;
			else alert(data);
			//disablePopup();
		}
	);
}

function pdf_confirm2(pb_id) {
	$.post("ajax/pb_approve.php", { pb_id: pb_id },  
		function(data){
			if(data=="") document.location.href="./order_history";
			else alert(data);
			//disablePopup();
		}
	);
}

// FIXME: What's the point of this function?
// All it does is post the data to fill_bill.
function fill_bill_show(fill_u_id, fill_email, fill_first, fill_last, fill_addr1, fill_addr2, fill_city, fill_code, fill_phone, del_addr1, del_addr2, del_city, del_code, del_phone) {

    // These details come from My Details.  So this is the point to create an
    // array of blank invoice details, which will be amended later with the
    // cardholder's address details on the first order.
    var blank_invoice_fields = new Array;

    if (fill_addr1 == "") {
        blank_invoice_fields.push("fill_addr1");
    }
    if (fill_city == "") {
        blank_invoice_fields.push("fill_city");
    }
    if (fill_code == "") {
        blank_invoice_fields.push("fill_code");
    }
 
    
    $.post("ajax/popup.php", { name: "fill_bill", fill_u_id: fill_u_id, fill_email: fill_email, fill_first: fill_first, fill_last: fill_last, fill_addr1: fill_addr1, fill_addr2: fill_addr2, fill_city: fill_city, fill_code: fill_code, fill_phone: fill_phone, del_addr1: del_addr1, del_addr2: del_addr2, del_city: del_city, del_code: del_code, del_phone: del_phone, 'blank_invoice_fields[]': blank_invoice_fields },  
               function(data){ 
                   $('#popup').html(data);
                   
                   //Click the x event!  
                   $("#popup_close").click(function(){
                           disablePopup(); 
                       }); 
                   
                   inputAddSubmit();
                   
                   //centering with css  
                   centerPopup();
                   
                   //show popup  
			showPopup(); 
               }
	);
}

// This is where the cardholder information from the dialog is validated, and
// at the end it moves on to delivery information, whether that is automatically
// or manually filled in.
function fill_bill(u_id, del_addr1, del_addr2, del_city, del_code, del_phone) {
    //error("");
        
    var email=$("#email").val();
    var first_name=$("#first_name").val();
    var last_name=$("#last_name").val();
    var address1=$("#address1").val();
    var address2=$("#address2").val();
    var city=$("#city").val();
    var code=$("#code").val();
    var phone=$("#phone").val();
    var del_addr=$('#del_addr').is(':checked');
    var checkout_price=$("#checkout_price").val();
    
    if(email=="" || email=="E-mail") { error("E-mail has to be filled in."); return; }
    if(checkEmail(email)==0) { error("E-mail address is not valid."); return; }
    if(first_name=="" || first_name=="First Name") { error("First Name has to be filled in."); return; }
    if(last_name=="" || last_name=="Last Name") { error("Last Name has to be filled in."); return; }
    if(address1=="" || address1=="Address 1") { error("Address 1 has to be filled in."); return; }
    if(city=="" || city=="City / Town") { error("City / Town has to be filled in."); return; }
    if(code=="" || code=="Post Code") { error("Post Code has to be filled in."); return; }

    // Backfill the my details page in the event that it wasn't filled in
    // originally.
    // Create array of fields to be backfilled, this gets passed to
    // backfill_my_details.php as a parameter.
    var backfill_fields = [];

    // If only one field is needed, backfill_fields[] won't be an array.
    if (document.popup_form["backfills[]"]) {
        var array_length = document.popup_form["backfills[]"].length;
        if (array_length) {
            for(i = 0; i < document.popup_form["backfills[]"].length; i++){
                var element = document.popup_form["backfills[]"][i];
                backfill_fields.push(element.value);
            }
        } else {
            var element = document.popup_form["backfills[]"];
            backfill_fields.push(element.value);
        }
    }
    
    $.post('ajax/backfill_my_details.php', {
            'backfill_fields[]': backfill_fields,
                u_id: u_id,
                address1: address1,
                city: city,
                code: code }
        );
    
    if(first_name.length>20) {
        error("First Name was shortened (maximum length 20 characters).");
        $("#first_name").val(first_name.substr(0, 20));
        return; 
    }
    
    if(last_name.length>20) {
        error("Last Name was shortened (maximum length 20 characters).");
        $("#last_name").val(last_name.substr(0, 20));
        return; 
    }
    
    if(address1.length>100) {
        error("Address 1 was shortened (maximum length 100 characters).");
        $("#address1").val(address1.substr(0, 100));
        return; 
    }
    
    if(address2.length>100) {
        error("Address 2 was shortened (maximum length 100 characters).");
        $("#address2").val(address2.substr(0, 100));
        return; 
    }
    
    if(city.length>40) {
        error("City was shortened (maximum length 40 characters).");
        $("#city").val(city.substr(0, 40));
        return; 
    }
    
    if(code.length>10) {
        error("Postal Code was shortened (maximum length 10 characters).");
        $("#code").val(code.substr(0, 10));
        return; 
    }
    
    if(phone.length>20) {
        error("Phone number was shortened (maximum length 20 characters).");
        $("#phone").val(phone.substr(0, 20));
        return; 
    }
    
    $("#fill_bill").val("0");
    if(del_addr) {
        auto_fill_del(first_name, last_name, address1, address2, city, code, phone, checkout_price);
    } else {
        fill_del_show(first_name, last_name, address1, address2, city, code, phone, del_addr1, del_addr2, del_city, del_code, del_phone);
    }
}

function fill_bill_changes_show(fill_u_id, pb_id, total_price, fill_email, fill_first, fill_last, fill_addr1, fill_addr2, fill_city, fill_code, fill_phone) {
	$.post("ajax/popup.php", { name: "fill_bill_changes", pb_id: pb_id, total_price: total_price, fill_u_id: fill_u_id, fill_email: fill_email, fill_first: fill_first, fill_last: fill_last, fill_addr1: fill_addr1, fill_addr2: fill_addr2, fill_city: fill_city, fill_code: fill_code, fill_phone: fill_phone },  
		function(data){ 
			$('#popup').html(data);

			//Click the x event!  
			$("#popup_close").click(function(){
				disablePopup(); 
			}); 

			inputAddSubmit();

			//centering with css  
			centerPopup();

			//show popup  
			showPopup(); 
		}
	);
}

function fill_bill_changes(u_id, pb_id, total_price) {
	error("");
	
	var email=$("#email").val();
	var first_name=$("#first_name").val();
	var last_name=$("#last_name").val();
	var address1=$("#address1").val();
	var address2=$("#address2").val();
	var city=$("#city").val();
	var code=$("#code").val();
	var phone=$("#phone").val();
	var del_addr=$('#del_addr').is(':checked');
	var checkout_price=$("#checkout_price").val();

	if(email=="" || email=="E-mail") { error("E-mail has to be filled.<br>Go to 'My Details' to fill it."); return; }
	if(checkEmail(email)==0) { error("E-mail address is not valid."); return; }
	if(first_name=="" || first_name=="First Name") { error("First Name has to be filled."); return; }
	if(last_name=="" || last_name=="Last Name") { error("Last Name has to be filled."); return; }
	if(address1=="" || address1=="Address 1") { error("Address 1 has to be filled."); return; }
	if(city=="" || city=="City / Town") { error("City / Town has to be filled."); return; }
	if(code=="" || code=="Post Code") { error("Post Code has to be filled."); return; }

	if(first_name.length>20) {
		error("First Name was shortened (maximum length 20 characters).");
		$("#first_name").val(first_name.substr(0, 20));
		return; 
	}

	if(last_name.length>20) {
		error("Last Name was shortened (maximum length 20 characters).");
		$("#last_name").val(last_name.substr(0, 20));
		return; 
	}

	if(address1.length>100) {
		error("Address 1 was shortened (maximum length 100 characters).");
		$("#address1").val(address1.substr(0, 100));
		return; 
	}

	if(address2.length>100) {
		error("Address 2 was shortened (maximum length 100 characters).");
		$("#address2").val(address2.substr(0, 100));
		return; 
	}

	if(city.length>40) {
		error("City was shortened (maximum length 40 characters).");
		$("#city").val(city.substr(0, 40));
		return; 
	}

	if(code.length>10) {
		error("Postal Code was shortened (maximum length 10 characters).");
		$("#code").val(code.substr(0, 10));
		return; 
	}

	if(phone.length>20) {
		error("Phone number was shortened (maximum length 20 characters).");
		$("#phone").val(phone.substr(0, 20));
		return; 
	}

	$.post("ajax/pb_changes_checkout.php", {pb_id: pb_id, u_id: u_id, total_price: total_price, email: email, first: first_name, last: last_name, addr1: address1, addr2: address2, city: city, code: code, phone: phone},
	function(data){
            if(data!="") {
                if(data=="nodata") alert("Server internal error, please contact us.");
                else if(data.indexOf("no_sage_")>-1) {
                    var free_changes=pb_id+"_"+data.substring(8);
                    document.location.href="./thank-you.php?free_changes="+free_changes;
                }
                else {
                    $("#Crypt").val(data);
                    //warning_popup(data, "Error");
                    document.SagePayForm.submit();
                }
            }
            else document.location.href="./payment-error";
	});
}

function fill_del_show(first, last, address1, address2, city, code, phone, del_addr1, del_addr2, del_city, del_code, del_phone) {
	var bill_details=first+"#"+last+"#"+address1+"#"+address2+"#"+city+"#"+code+"#"+phone;
	$.post("ajax/popup.php", { name: "fill_del", bill_details: bill_details, fill_first: first, fill_last: last, fill_addr1: del_addr1, fill_addr2: del_addr2, fill_city: del_city, fill_code: del_code, fill_phone: del_phone },  
		function(data){ 
			$('#popup').html(data);

			//Click the x event!  
			$("#popup_close").click(function(){
				disablePopup(); 
			}); 

			inputAddSubmit();

			//centering with css  
			centerPopup();

			//show popup  
			showPopup(); 
		}
	
	);
}

// This is called upon return from pb_checkout.php by fill_del or auto_fill_del
function fill_del_return(data) {
    if(data != '') {
        if(data == 'nodata') {
            alert('Server internal error, please contact us.');
        } else if(data.indexOf("no_sage_") > -1) {
            var free_pb=data.substring(8);
            document.location.href="./thank-you.php?free_pb="+free_pb;
        } else {
            $("#Crypt").val(data);
            document.SagePayForm.submit();
        }
    } else{
        document.location.href='./payment-error';
    }
}

function auto_fill_del(first_name, last_name, address1, address2, city, code, phone, checkout_price) {
    var to_mail = $("#to_mail").html();
    
    // Nasty hack as to_mail was originally used to display, so contained HTML
    // &pound;s.  But these get stored in the database then look wrong when
    // used in the HTML email.  So convert back to HTML characters.
    var re = new RegExp(String.fromCharCode(163), 'g');
    //var to_mail_munged = to_mail.replace('&pound;');
    var to_mail_munged = to_mail.replace(re,'&pound;');
    var bill_details = first_name+"#"+last_name+"#"+address1+"#"+address2+"#"+city+"#"+code+"#"+phone;
    $.post("ajax/pb_checkout.php",
           { bill_details: bill_details,
                   first: first_name,
                   last: last_name,
                   addr1: address1,
                   addr2: address2,
                   city: city,
                   code: code,
                   phone: phone,
                   checkout_price: checkout_price,
                   order_details: to_mail_munged
                   },
           function(data) {
               fill_del_return(data);
           } );
}

function fill_del() {
    var first_name=$("#del_first_name").val();
    var last_name=$("#del_last_name").val();
    var address1=$("#del_address1").val();
    var address2=$("#del_address2").val();
    var city=$("#del_city").val();
    var code=$("#del_code").val();
    var phone=$("#del_phone").val();
    var checkout_price=$("#checkout_price").val();
    var to_mail=$("#to_mail").html();
    
    // Nasty hack as to_mail was originally used to display, so contained HTML
    // &pound;s.  But these get stored in the database then look wrong when
    // used in the HTML email.  So convert back to HTML characters.
    var re = new RegExp(String.fromCharCode(163), 'g');
    //var to_mail_munged = to_mail.replace('&pound;');
    var to_mail_munged = to_mail.replace(re,'&pound;');
    
    var bill_details=$("#bill_details").val();
    
    if(first_name=="" || first_name=="First Name") {
        error("First Name has to be filled."); return; }
    if(last_name=="" || last_name=="Last Name") {
        error("Last Name has to be filled."); return; }
    if(address1=="" || address1=="Address 1") {
        error("Address 1 has to be filled."); return; }
    if(city=="" || city=="City / Town") {
        error("City / Town has to be filled."); return; }
    if(code=="" || code=="Post Code") {
        error("Post Code has to be filled."); return; }
    
    if(first_name.length>20) {
        error("First Name was shortened (maximum length 20 characters).");
        $("#del_first_name").val(first_name.substr(0, 20));
        return; 
    }
    
    if(last_name.length>20) {
        error("Last Name was shortened (maximum length 20 characters).");
        $("#del_last_name").val(last_name.substr(0, 20));
        return; 
    }
    
    if(address1.length>100) {
        error("Address 1 was shortened (maximum length 100 characters).");
        $("#del_address1").val(address1.substr(0, 100));
        return; 
    }
    
    if(address2.length>100) {
        error("Address 2 was shortened (maximum length 100 characters).");
        $("#del_address2").val(address2.substr(0, 100));
        return; 
    }
    
    if(city.length>40) {
        error("City was shortened (maximum length 40 characters).");
        $("#del_city").val(city.substr(0, 40));
        return; 
    }
    
    if(code.length>10) {
        error("Postal Code was shortened (maximum length 10 characters).");
        $("#del_code").val(code.substr(0, 10));
        return; 
    }
    
    if(phone.length>20) {
        error("Phone number was shortened (maximum length 20 characters).");
        $("#del_phone").val(phone.substr(0, 20));
        return; 
    }
    
    $.post("ajax/pb_checkout.php", {
            bill_details: bill_details, first: first_name, last: last_name, addr1: address1, addr2: address2, city: city, code: code, phone: phone, checkout_price: checkout_price, order_details: to_mail_munged },
        function(data){
            fill_del_return(data);
        } );
    
}

function addfav() {
    // user agent sniffing is bad in general, but this is one of the times 
    // when it's really necessary
    var ua=navigator.userAgent.toLowerCase();
    var isKonq=(ua.indexOf('konqueror')!=-1);
    var isSafari=(ua.indexOf('webkit')!=-1);
    var isMac=(ua.indexOf('mac')!=-1);
    var buttonStr=isMac?'Command/Cmd':'CTRL';

    if(window.external && (!document.createTextNode ||
      (typeof(window.external.AddFavorite)=='unknown'))) {
        // IE4/Win generates an error when you
        // execute "typeof(window.external.AddFavorite)"
        // In IE7 the page must be from a web server, not directly from a local 
        // file system, otherwise, you will get a permission denied error.
        window.external.AddFavorite(document.location.href, document.title); // IE/Win
    } else if(isKonq) {
      	warning_popup('Please press CTRL + B to bookmark our site.', 'Bookmark This Page');
    } else if(window.opera) {
      	warning_popup('In order to bookmark this site you need to do so manually through your browser.', 'Bookmark This Page');
    } else if(window.home || isSafari) { // Firefox, Netscape, Safari, iCab
      	warning_popup('Please press '+buttonStr+' + D to bookmark our site.', 'Bookmark This Page');
    } else if(!window.print || isMac) { // IE5/Mac and Safari 1.0
      	warning_popup('Please press Command/Cmd + D to bookmark our site.', 'Bookmark This Page');
    } else {
      	warning_popup('In order to bookmark this site you need to do so manually through your browser.', 'Bookmark This Page');
    }
}

function continue_changes_popup(pb_id, changes_no) {
    $.post("ajax/popup.php", { name: "continue_changes", pb_id: pb_id, changes_no: changes_no },  
           function(data){ 
               $('#popup').html(data);
               
               //Click the x event!  
               $("#popup_close").click(function(){
                       disablePopup(); 
                   }); 
               
               if(popupStatus==0) {
                   //centering with css  
                   centerPopup();
                   
                   //show popup  
                   showPopup();
			}
           }
           );
}

function continue_changes_do(pb_id, changes_no) {
	if(changes_no>1) document.location.href="my_basket_changes_to_pdf_"+pb_id;
	else document.location.href="./order_history";
}

$(document).ready(function(){  
	//LOADING POPUP  
	//Click the button event!  
	$("#sign_in").click(function(){ loadPopup("sign_in"); });  
	$("#sign_up").click(function(){ loadPopup("sign_up"); });  
	$("#ten_percent").click(function(){ loadPopup("ten_percent"); });  
	$("#tell_a_friend").click(function(){ loadPopup("tell_a_friend"); });  
	$("#add_bookmark").click(function(){ addfav(); });  
	$("#please_sign").click(function(){ loadPopup("please_sign"); });  
	$("#please_sign2").click(function(){ loadPopup("please_sign"); });  
	$("#please_sign3").click(function(){ loadPopup("please_sign"); });  
	$("#please_sign_f1").click(function(){ loadPopup("please_sign"); });  
	$("#please_sign_f2").click(function(){ loadPopup("please_sign"); });  
	$("#please_sign_f3").click(function(){ loadPopup("please_sign"); });  
	$("#please_sign_f4").click(function(){ loadPopup("please_sign"); });  
	$("#please_sign_faq").click(function(){ loadPopup("please_sign"); });  
	$("#give_name").click(function(){ loadPopup("give_name"); });  

	//CLOSING POPUP  
	//Click out event!  
	$("#backgroundPopup").click(function(){  
		disablePopup();  
	}); 

	//Press Escape event  
	$(document).keypress(function(e){ 
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}  
	});  
});  

