
function quick_alert(body, modal) 
{
	body += "<div class=\"ruler\"></div>";
	body += "<div style=\"float:right; width: 50px; padding-top:10px;\" >";
	body += "<div id=\"action_ok\" style=\"width:50px;\"><div onclick=\"$('#dialog').dialog('close');\" class=\"ok_button_unlit\"> Ok </div></div>";
	body += "</div>";

	$("#dialog").dialog('option', 'buttons', "");
	$("#dialog").dialog('option', 'modal', modal);
	$("#dialog").dialog('option', 'title', "<span class=\"\">Alert</span>");
	$("#dialog").html(body).dialog("open");
	
	$("#action_ok").hover(	
				function ()	{  $(".ok_button_unlit").addClass("ok_button_lit"); },
   				function ()	{  $(".ok_button_unlit").removeClass("ok_button_lit");
   			});
}


function quick_confirm(body, modal, action) 
{
	body += "<div class=\"ruler\"></div>";
	body += "<div style=\"float:right; width: 150px; padding-top:10px;\" >";
	body += "<div id=\"action_ok\" style=\"width:50px;float:left;\"><div onclick=\"$('#dialog').dialog('close');eval(action);\" class=\"ok_button_unlit\"> Ok </div></div>";
	body += "<div id=\"action_cancel\" style=\"width:50px;float:left;\"><div onclick=\"$('#dialog').dialog('close'); return false;\" class=\"ok_button_unlit\"> Cancel </div></div>";
	body += "</div>";

	$("#dialog").dialog('option', 'buttons', "");
	$("#dialog").dialog('option', 'modal', modal);
	$("#dialog").dialog('option', 'title', "<span class=\"\">Confirm</span>");
	$("#dialog").html(body).dialog("open");
	
	$(".ok_button_unlit").hover(	
				function ()	{  $(this).addClass("ok_button_lit"); },
   				function ()	{  $(this).removeClass("ok_button_lit");
   			});

	$(".ok_button_unlit").hover(	
				function ()	{  $(this).addClass("ok_button_lit"); },
   				function ()	{  $(this).removeClass("ok_button_lit");
   			});
   	return false;
}


function quick_find(input) 
{
	var body;
		
	body  = "<div><input type=\"text\" style=\"width:265px\" id=\"find_box\"/></div>";
	body += "<div style=\"float:right; padding-top: 10px;\" onclick=\"find_user($('#find_box').val(),'" + input + "')\">";
	body += "<div class=\"button_left\"></div>";
	body += "<div class=\"button_mid\">Find</div>";
	body += "<div class=\"button_find\"></div>";
	body += "</div>";
	body += "<div id=\"found_list\" style=\"width:200px; height: 50px;\"> Search results appear here.";
	body += "</div>";
	
	/*$("#dialog").dialog('option', 'buttons', { "Ok": function () { 	$(this).dialog("close"); } });*/
	$("#dialog").dialog('option', 'modal', false);
	$("#dialog").dialog('option', 'title', "Find member");
	$("#dialog").html(body).dialog("open");
}

function find_user(username, input)
{
	var htm, uname;
	
	$("#found_list").html("<img src='/asset/images/aload.gif' alt='spinner' /> Searching...");

	$.getJSON("/email/address_book/" + username +"/", function (json){
		htm = "";
		json.sort();
		if (typeof(json[0]) === "undefined") {
			$("#found_list").html("Not found");
		}				
		else 
		{ 
			for (uname in json) {
				if (json.hasOwnProperty(uname)) {
					htm += "<a href=\"#\" title=\"Click to insert\" class=\"found_users\" onclick=\"insert_name('" + json[uname] + "','" + input + "') \">" + json[uname] + "</a> &nbsp;";
					$("#found_list").html(htm);
				}
			}
		}
	});
}

// location helpers.

function insert_name(username, input)
{
	$("#"+input).val( $("#"+input).val() + username + ", ");	
}

function fcl_show_error(code) 
{
	var title, body, help;

	help = ["Error: That title is too short. It should be at least three letters.",
			"Error: That title is too long: maximum of 80 characters",
			"Error: Your subtitle is too long: maximum of 80 characters",
			"Error: An \"offered\" ad should have a value in limes.",
			"Error: A \"wanted\" ad requires a value in limes that you will surrender.",
			"Error: When offering something for \"Take My Stuff\" you need to enter your offer in limes.",
			"Error: Swaps cannot have a value."
			];

	title = help[code].substring(0,help[code].indexOf(":"));
	body =  help[code].substring(help[code].indexOf(":")+1);			
	
	$("#dialog").dialog('option', 'buttons', { "Ok": function () { $(this).dialog("close"); } });
	$("#dialog").dialog('option', 'modal', true);
	$("#dialog").dialog('option', 'title', title);

	body += "<div class=\"ruler\"></div>";
	body += "<div style=\"float:right; width: 120px; padding-top:10px;\" >";
	body += "<div id=\"action_cancel\"><div class=\"cancel_button_unlit\">Cancel</div></div>";			
	body += "<div id=\"action_ok\"><div onclick=\"$('#dialog').dialog('close');\" class=\"ok_button_unlit\"> Ok </div></div>";
	body += "</div>";

	$("#dialog").dialog('option', 'buttons', "");
	$("#dialog").dialog('option', 'modal', true);
	$("#dialog").html(body).dialog("open");
	
	$("#action_ok").hover(	
				function ()	{  $(".ok_button_unlit").addClass("ok_button_lit"); },
   				function ()	{  $(".ok_button_unlit").removeClass("ok_button_lit");
   			});
   			
	$("#action_cancel").hover(	
				function ()	{  $(".cancel_button_unlit").addClass("ok_button_lit"); },
   				function ()	{  $(".cancel_button_unlit").removeClass("ok_button_lit");
   			});
	$("#dialog").html(body).dialog("open");
}


function do_reject_advert()
{
									
	reason = parseInt($('input[name="reason_code"]:checked').val(), 10);
	explain = $('input[name="explain_why"]').val();
	$("#dialog").dialog("close");
	
	if (typeof(reason) === "undefined" || isNaN(reason))  
	{
		quick_alert("You must select one of the options or fill in a reason this advert should be rejected!", true);
		return false;
	}
	
	if (reason === 4 && explain.length < 10) 
	{
		quick_alert("Reason for removing this advert should be more detailed (up to 160 characters). Please try again.", true);
		return false;
	}

	if (reason === 4 && explain.length > 160) 
	{
		quick_alert("Your reason for removing this ad was truncated.", true);
		explain = explain.substr(0,160);
	}
	
	if (explain.length === 0)
	{
		explain = "Not given";
	}									
	window.open(encodeURI("/moderate/reject/" + earwigo + "/" + reason+ "/" + explain + "/" + mode), "_self");
}

function fcl_moderate_reject(earwigo, mode) {
	var reason, explain, html;
		
	$("#dialog").dialog('option', 'buttons',""); 
	$("#dialog").dialog('option', 'modal', true);
	$("#dialog").dialog('option', 'title', "Reject");
	html  = "<div>Rejecting an advert is a serious action that will be logged and visible to site admistrators! ";
	html += "Rejecting an advert without good reason may result in your account being terminated. Please give your reason:</div>";
	html += "<div class=\"radio_float\"><input type='radio' name='reason_code' value='1' /></div><div class=\"reason_float\">Advert appears to be spam. i.e. adult content, prescriptions, russian brides or simply meaningless text.</div><div style=\"clear:left;\"></div>";
	html += "<div class=\"radio_float\"><input type='radio' name='reason_code' value='2' /></div><div class=\"reason_float\">Contains offensive/racist/threatening language</div><div style=\"clear:left;\"></div>";
	html += "<div class=\"radio_float\"><input type='radio' name='reason_code' value='3'/></div><div class=\"reason_float\">Contains banned/illegal/unsuitable items</div><div style=\"clear:left;\"></div>";
	html += "<div class=\"radio_float\"><input type='radio' name='reason_code' value='4'/></div><div class=\"reason_float\">Other (specify)</div><div style=\"clear:left;\"></div>";
	html += "<div>Explain: <input type='text' name='explain_why' /></div>";
	html += "<div class=\"ruler\"></div>";
	html += "<div style=\"float:right; width: 120px; padding-top:10px;\" >";
	html += "<div id=\"action_cancel\"><div onclick=\"$('#dialog').dialog('close');\" class=\"cancel_button_unlit\">Cancel</div></div>";			
	html += "<div id=\"action_ok\"><div onclick=\"do_reject_advert();\" class=\"ok_button_unlit\"> Ok </div></div>";
	html += "</div>";

	$("#dialog").dialog('option', 'buttons', "");
	$("#dialog").html(html).dialog("open");
	
	$("#action_ok").hover(	
				function ()	{  $(".ok_button_unlit").addClass("ok_button_lit"); },
   				function ()	{  $(".ok_button_unlit").removeClass("ok_button_lit");
   			});
   			
	$("#action_cancel").hover(	
				function ()	{  $(".cancel_button_unlit").addClass("ok_button_lit"); },
   				function ()	{  $(".cancel_button_unlit").removeClass("ok_button_lit");
   			});
	return false;
}


function fcl_moderate_pass(earwigo) {
	var html;
	
	$("#dialog").dialog('option', 'buttons', 

					{"Everything is good. Make it live.": function () {	
								$(this).dialog("close");
								window.open("/moderate/pass/" + earwigo, "_self");
							},

							"No, forget it.": function () { 
							$(this).dialog("close");
							}
					}); 

	$("#dialog").dialog('option', 'modal', true);
	$("#dialog").dialog('option', 'title', "Activate Advert?");
	html  = "<div><strong>Are you absolutely sure?</strong><br /><br />This action will be logged and visible to site administrators - only activate adverts that are completely within the rules.";
	html += " Activating <strong>any</strong> advert that clearly contravenes site rules may render your liable to temporary account suspension, loss of Fairtrust or a complete ban. If unsure, don't take any action.</div>";	
	$("#dialog").html(html).dialog("open");
	return false;
}

function validate_login() {
	// stub function
}

function validate_locale()
{
	var street, town, district, postcode, name, county, country;
	$('#street').removeClass("ref_highlight");
	$('#town').removeClass("ref_highlight");
	$('#postcode').removeClass("ref_highlight");
	$('#name').removeClass("ref_highlight");
	$('#district').removeClass("ref_highlight");
	$('#county').removeClass("ref_highlight");
	
	name = $("#name").val();
	street = $("#street").val();
	town = $("#town").val();
	postcode = $("#postcode").val();
	country = $("#country").val();
	district = $("#country").val();
	county = $("#country").val();

	if (name.length < 2 || name.length > 120) 
	{
		quick_alert("Username should be at least 5 and no more than 120 letters", true);
		$('#name').addClass("ref_highlight");
		return false;
	}

	if (street.length < 3 || street.length > 120) 
	{
		quick_alert("Street name should be at least 3 and no more than 120 letters", true);
		$('#street').addClass("ref_highlight");
		return false;
	}

	if (town.length < 3 || town.length > 120)
	{
		quick_alert("Town name should be at least 3 and no more than 60 letters", true);
		$('#town').addClass("ref_highlight");
		return false;
	}

	if (district.length > 120)
	{
		quick_alert("District name should be at least 3 and no more than 120 letters", true);
		$('#district').addClass("ref_highlight");
		return false;
	}

	if (county.length > 60)
	{
		quick_alert("Count name should be at least 3 and no more than 60 letters", true);
		$('#county').addClass("ref_highlight");
		return false;
	}
/*
	if (country === "GB")
	{
		postcode = validate_postcode(postcode);
		if ( ! postcode)
		{
			quick_alert("Postcode does not appear to be valid", true);
			$('#postcode').addClass("ref_highlight");
			return false;		
		}
		$("#postcode").val(postcode);
	}

	if (country === "US")
	{
		if ( ! validate_zip(postcode) )
		{
			quick_alert("Zipcode does not appear to be valid", true);
			$('#postcode').addClass("ref_highlight");
			return false;		
		}
	}
*/	
	return true;
}

function validate_registration()
{
	var email, password1, password2, question, answer, username;
	$('#username').removeClass("ref_highlight");
	$('#email').removeClass("ref_highlight");
	$('#password1').removeClass("ref_highlight");
	$('#password2').removeClass("ref_highlight");
	$('#question').removeClass("ref_highlight");
	$('#answer').removeClass("ref_highlight");
	$('#accept_terms').removeClass("ref_highlight");


	username = $("#username").val();
	email = $("#email").val();
	password1 = $("#password1").val();
	password2 = $("#password2").val();
	question = $("#question").val();
	answer = $("#answer").val();
	
	if (username.length < 5 || username.length > 20) 
	{
		quick_alert("Username should be at least 5 and no more than 20 letters", true);
		$('#username').addClass("ref_highlight");
		return false;
	}
	
	if ( ! validate_email(email))
	{
		quick_alert("I don't recognise that email address.", true);
		$('#email').addClass("ref_highlight");
		return false;
	}

	if (password1.length < 6 || password2.length < 6 || (password1 !== password2)) 
	{
		quick_alert("passwords should match and be at least 6 characters", true);
		if (password1.length < 6)
		{
			$('#password1').addClass("ref_highlight");
		}
		if (password2.length < 6)
		{
			$('#password2').addClass("ref_highlight");
		}
		if ((password1 !== password2))
		{
			$('#password1').addClass("ref_highlight");
			$('#password2').addClass("ref_highlight");
		}
		return false;
	}

	if (question.length < 10) 
	{
		quick_alert("That question does not appear detailed enough. Please use longer one!", true);
		$('#question').addClass("ref_highlight");
		return false;
	}
	
	if (answer.length < 5) 
	{
		quick_alert("Your answer should be at least 5 letters or longer", true);
		$('#answer').addClass("ref_highlight");
		return false;
	}
	
	if ( ! $("[#terms]:checkbox").attr('checked')) {
		quick_alert("You must agree to the terms before registering for the site.", true);		
		$('#accept_terms').addClass("ref_highlight");
		return false;
	}

	return true;
}

function validate_advert()
{

	var limes, type;
	
	limes = parseInt($('#limes').val(), 10);
	type = parseInt($('input[name=type]:checked').val(), 10);
	
	$("#condition").val(parseInt(faircycle.stars.substr(4,1),10)+1);
		
	if ($('#title').val().length < 3) 
	{
		fcl_show_error(0);
		return false;
	}

	if ($('#title').val().length > 80) 
	{
		fcl_show_error(1);
		return false;
	}

	if ($('#subtitle').val().length > 80) 
	{
		fcl_show_error(2);
		return false;
	}


	if (type < 3 && limes <= 0) {
		fcl_show_error(type + 3);
		return false;
	}
	
	if (type === 3 && limes !== 0) {
		fcl_show_error(type + 3);
		return false;			
	}
	return true;
}

function updateChkd()
{
	// Count how many items are currently checked.
	var id;
	faircycle.checked = 0;
	
	$(":checkbox").each( function () {
		if ($(this).attr('checked'))
		{	
			id = $(this).attr('id');
			if (id.indexOf("all") === -1) {

				(faircycle.checked++);
				id = id.slice(id.indexOf("_cbx")+4);
				faircycle.emailID = parseInt(id,10);
			}
		}
	});	
}

function mark_email(status_code)
{
	var id;
	$(":checkbox").each( function () {
		if ($(this).attr('checked'))
		{	
			id = $(this).attr('id');
			if (id.indexOf("all") === -1) {
				id = parseInt(id.slice(id.indexOf("_cbx")+4),10);	// get the actual NUMBER attached to the code.
				faircycle.emailID = id;
				if (! isNaN(faircycle.emailID)) {								
					$.ajax({
					  type: "GET",
					  url: "/email/mark_mail/" + id + "/" + status_code,	//send command to delete (silent fail!)
					  dataType: "text"
					});				
					$("#email_tr" + id).effect("pulsate",{},300,function () {
																			$("#email_sbj" + id).html("");
																			$("#email_usr" + id).html("");																																										$("#email_dte" + id).html("");
																			});
					$(this).attr('checked', false);
				}
			}
		}
	});
}

function member_options(member_id, screen_name)
{
	var html;
	screen_name = "<span class='nice_screen_name'>" +screen_name+ "</span>" 
	$("#dialog").dialog('option', 'buttons', 
										{ 										
										"Cancel": function () { $(this).dialog("close"); },
										"Buddy": function () { 	$(this).dialog("close");
																quick_alert("Added " + screen_name + " as a contact.", true);
															 },
										"Block": function () { $(this).dialog("close");
																quick_alert("Added " + screen_name + " to your block list<br/>They will not be able to contact you.", true);
															}
										});
	html  = "Here's what you can do:";
	html += "<ul><li>Add "+screen_name+" as a contact</li>";
	html += "<li>Block "+screen_name+" from contacting you</li>";
	html += "<li>or press cancel for no action</li></ul>";
	
	$("#dialog").dialog('option', 'modal', false);
	$("#dialog").dialog('option', 'title', "Quick view: " + screen_name);
	$("#dialog").html(html).dialog("open");


}

function initialise()
{
	var tmp, oops, id;
	
	document.Browser = {
        bigblueE:     navigator.userAgent.indexOf('MSIE') > -1,
        Opera:  navigator.userAgent.indexOf('Opera') > -1,
        WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
        Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
        MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/),
        Safari:navigator.userAgent.indexOf('Safari') > -1,
        Firefox:navigator.userAgent.indexOf('Firefox') > -1
      };
      
	$("body").attr("background", "/asset/images/background.png");
	$("body").attr("backgroundColor", "#4f9bfc");
	$("body").attr("backgroundRepeat", "repeatX");
	
	faircycle = {"ajaxcount" : 0, // namespace for globals.
				"email" : 0,
				"checked" : 0,
				"stars" : "stars1",
				"loaded" : true
				};	
				
	if (typeof(document.getElementById("#submit_button")) !== "undefined") { 
		$("#action_submit").removeClass("hide_div").click(function() {document.fcl_form.submit();});
		$("#form_submit").addClass("hide_div");		
	}
	
	$("#registration").submit(function() {
		return validate_registration();
	});
	
	$("#locale_setting").submit(function() {
		return validate_locale();
	});
	
	
	$(".general_button_unlit").hover(	
				function ()	{  $(this).addClass("general_button_lit"); },
   				function ()	{  $(this).removeClass("general_button_lit");
   			});

	
	$("#accordion-online, #accordion-offline").accordion({ header: "h3"});

    $('.mid-menu-unlit').hover(		function ()	{  $(this).addClass("mid-menu-lit"); },
   									function ()	{  $(this).removeClass("mid-menu-lit");   
   								}); 

    $('.right-menu-unlit').hover(	function ()	{  $(this).addClass("right-menu-lit"); },
   									function ()	{  $(this).removeClass("right-menu-lit");   
   								}); 

    $('.left-menu-unlit').hover(	function ()	{  $(this).addClass("left-menu-lit"); },
   									function ()	{  $(this).removeClass("left-menu-lit");   
   								}); 


    $('.div_button').hover(	function ()	{  $(this).addClass("div_button_lit"); },
   									function ()	{  $(this).removeClass("div_button_lit");   
   								}); 


	$('.mail_section, .exp_menu, .faq_section').hover(	function () 	{  $(this).addClass("go_green");},
    													function () 	{  $(this).removeClass("go_green");
    													});
    													
    $('.faq_section').click(function () {  
    									var title = $(this).attr("rel"); 
    									$("#main_section").slideUp(100);
    									$("#main_section").load("/info/message/" + title,"",function () {$("#main_section").slideDown(500);});
    									return false;
    									});
    									
    
    
	$('.helpme').click(function() {return false;}); 
     
	$('.helpme').each(function () 
	{
      $(this).qtip(
      	{
	 	   content: {
				url: '/member/help/' + $(this).attr('rel'),
				data: { },
				method: 'get',
				title: '<div class="helper_lime"></div><div style="height:25px;"></div>'
			},
	 	   
	 	   show: {solo: true, effect: { type: 'fade', length: '400' } },
	 	   style: {
	 	   		background: '#f1f2f6',
		 	    width: { min: 250 },
		 	    color: 'black',
	            border: { width: 1, radius: 3, color: 'green' }
			},
			
			position: {
				corner: {
					target: 'topRight',
					tooltip: 'bottomLeft'
				}
			}
	 	   
      	 }
      );	
	});

	if (typeof(document.getElementById("#ad_location")) !== "undefined") {
		$("#ad_location").click(function () {
				return confirm("Location data is very approximate - do not use it for route planning! Contact the member if you are making a special trip."); 
			});
	}
	
	
	if (typeof(document.getElementById("#select_all")) !== "undefined") {

		$(":checkbox").each( function () { $(this).attr('checked', false);}); // CLEAR ALL selected checks on page reload!
	
		$("#select_all").click( function () {
			$(":checkbox").each( function () {
				faircycle.checked = 0;
				if ($("#select_all").attr('checked'))
				{
					$(this).attr('checked', true);
					(faircycle.checked++);
				}
				else 
				{
					$(this).attr('checked', false);			
				}
			});	
		});
	}	
    
    if (typeof(faircycle_general_error) !== "undefined") { fcl_show_error(faircycle_general_error); }
    if ($('.advert_error').html()) {alert($('.advert_error').html());}
    $("#dialog").dialog({ autoOpen: false });


	// star rating system
	
	if (document.getElementById("condition") !== "undefined") 
	{ 		
		var n;		
		for (n = 0; n < 6; n++) 
		{
			$("#star" + n).hover(	function () {showstars(this.id)}, 
									function () {showstars(faircycle.stars);}
								);
								
			$("#star" + n).click(function () 
				{
					faircycle.stars = this.id; 
					$("#condition").val(parseInt(this.id.substr(4,1),10)); 
				});
		}
	}

	function showstars(count)
	{		
		var n,x;
		x = parseInt(count.substr(4,1),10);
		
		for (n = 0; n < 6; n++)
		{
			$("#star" + n).removeClass("brite_star_lit");
			$("#star" + n).addClass("brite_star_unlit");			
		}
		
		for (n = 0; n < x+1; n++) 
		{
			$("#star" + n).addClass("brite_star_lit");
		}
	}

						

	//advert pages.
	
	$('.tmb_advert_box').hover(
			function() 	{  $(this).addClass("tmb_ad_expose");},
			function () {  $(this).removeClass("tmb_ad_expose");
    					});

	// moderation helpers

    $('.mod_disabled').click(function () {fcl_show_error(18);});
    
   	$('.mod_row').hover(function () 	{  $(this).addClass("mod_highlight");},
    					function () 	{  $(this).removeClass("mod_highlight");
    							});

    $('.mod_reject').click(function () {	var earwigo = this.id;
    									fcl_moderate_reject(earwigo,5);
    									return false;});							

    $('.mod_full_reject').click(function () {	var earwigo = this.id;
    											fcl_moderate_reject(earwigo,4);
    											return false;
    										});							

    $('.mod_pass').click(function () {	var earwigo = this.id;
    									fcl_moderate_pass(earwigo);
    									return false;});							

    $('.mod_sub, .exp_menu').qtip({ show: {solo: true, effect: { type: 'fade', length: '400' } }, style: {background: '#f1f2f6', width: { min: 250 },color: 'black',border: { width: 1, radius: 3, color: 'green' }} });
    
    // editors 


	if (document.getElementById("u_have_mail") !== null)
	{		
		quick_alert("You have new mail!", false);
	}


	if (document.getElementById("ck_editor") !== null)
	{	
		//CKEDITOR.replace( 'fcl_editor' );
	}
	
	// email functionality


	if ( (document.getElementById("mail_inbox") !== null) )
	{	
		oops = "Oops! You need to select an email first!";
		
		$(".email_row").click( function () { 

											if (faircycle.emailID) {
												$("#email_cbx" + faircycle.emailID).attr('checked', false);	// clear old one..
											}
											updateChkd();
											faircycle.emailID = $(this).attr("rel");
											$("#mail_preview").html("Loading...").slideDown("normal");
											$("#mail_preview").load("/email/preview_mail/" + faircycle.emailID,"",
																function ()
																			{
																				$(".from_name").click( 			// this displays the member options like BLOCK and BUDDY
																								function() {
																											tmp = $(this).attr("id");
																											member_options(parseInt(tmp.slice(3),10), $(this).attr("rel"));																											
																											return false;
																											}); 
																			});
																			
											$("#email_cbx" + faircycle.emailID).attr('checked', true);									
											tmp = ($("#email_img" + faircycle.emailID).html());	
											if (tmp.indexOf("newmail"))
											{
												$("#email_img" + faircycle.emailID).html("<img src='/asset/images/blank.gif' width='15' height='15' />");
											}										
											return false;										
										});
										
		$(".trash_email_button").click( function () {
												updateChkd();
												if (faircycle.checked === 0)
												{
													quick_alert(oops,true);
												}
												else
												{
													mark_email("T");	// mark all checked items for TRASH! (Not actually deleted).
													$("#mail_preview").fadeOut("slow");					
													faircycle.emailID = 0;
												}
												return false;										

											});
											
		$(".fwd_email_button").click( function () {
												updateChkd();
												if (faircycle.emailID === 0)
												{
													quick_alert(oops,true);
													
												}
												else
												{
													faircycle.emailID = 0;
												}
												return false;
											});
											
		$(".rply_email_button").click( function () {
												updateChkd();
												if (faircycle.emailID === 0)
												{
													quick_alert(oops,true);
												}
												else
												{
													faircycle.emailID = 0;
												}
												return false;
											});
											
		$("#to_inbox").click( function () {
										updateChkd();
										if (faircycle.emailID === 0)
										{
											quick_alert(oops,true);
										}
										else
										{
											mark_email("E");	// mark all checked items as READ!
											$("#mail_preview").fadeOut("slow");					
											faircycle.emailID = 0;
										}
									});

		$(".empty_trash").click( function () {
										$("#dialog").dialog('option', 'buttons', { "Cancel": function () { $(this).dialog("close"); },											
																				   "Ok":     function () { 
																						mark_email("X");	// delete all emails...
																						$("#mail_preview").fadeOut("slow");	
																						$(this).dialog("close"); 
																				   }
																				 });

										$("#dialog").dialog('option', 'modal', true);
										$("#dialog").dialog('option', 'title', "REALLY DELETE?");
										$("#dialog").html("This will permanently delete these emails!<br />Are you sure?").dialog("open");										
										faircycle.emailID = 0;
										return false;
									});


	}

}

/*
// Postcode validator v3.0 by John Gardner (www.braemoor.co.uk)
// Rights of the author are acknowledged.
*/

function validate_postcode (postCode) {
	var alpha1 = "[abcdefghijklmnoprstuwyz]";
	var alpha2 = "[abcdefghklmnopqrstuvwxy]";
	var alpha3 = "[abcdefghjkstuw]";
	var alpha4 = "[abehmnprvwxy]";
	var alpha5 = "[abdefghjlnpqrstuwxyz]";
	var valid = false;  
	var pcexp = new Array ();
	pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
	pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
	pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
	pcexp.push (/^(GIR)(\s*)(0AA)$/i);
	pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
	pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
	pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);
	for ( var i=0; i<pcexp.length; i++) {
		if (pcexp[i].test(postCode)) {
			pcexp[i].exec(postCode);
			postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
			postCode = postCode.replace (/C\/O\s*/,"c/o ");
			valid = true;
			break;
		}
	}
	if (valid) {
		return postCode;
	} 
	return false;
}



function validate_refer()
{
	var n, email, errors;
	errors = 0;
		
	for (n = 1; n < 11; (n++))
	{
		email = $('#email' + n).val();
		if ( email.length > 0 && (! validate_email(email))) {
			$('#email' + n).addClass("ref_highlight");
			(errors++);
		}
		else 
		{
			$('#email' + n).removeClass("ref_highlight");
		}
	}

	if (errors)
	{
		quick_alert(errors + " of the addresses you have supplied don't appear to be valid and I\'ve highlighted them for you. Please correct or remove them before pressing send again. Thanks.");
		return false;
	}
	return true;	
}

function validate_zip(zip)
{
	//http://geekswithblogs.net/MainaD/archive/2007/12/03/117321.aspx
	var re = new RegExp("(^\\d{5}(-\\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\\d{1}[A-Z]{1} *\\d{1}[A-Z]{1}\\d{1}$)");
	return zip.match(re);
}

function validate_email(email)
{
	//http://www.regular-expressions.info/email.html
	var re = new RegExp(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
	return email.match(re);
}
