
function quick_alert(body, modal) 
{
	$("#dialog").dialog('option', 'buttons', { "Ok": function () { $(this).dialog("close"); } });
	$("#dialog").dialog('option', 'modal', modal);
	$("#dialog").dialog('option', 'title', "Alert");
	$("#dialog").html(body).dialog("open");
}

function quick_find(input) 
{
	var body;
		
	body  = "<div>";
	body += "<input type=\"text\" style=\"width:200px\" id=\"find_box\"/>";
	body += " <input type=\"button\" id=\"find_button\" value=\"find\" onclick=\"find_user($('#find_box').val(),'" + input + "')\"/>";
	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);
	$("#dialog").html(body).dialog("open");
}

function fcl_moderate_reject(earwigo, mode) {
	var reason, explain, html;
	
	$("#dialog").dialog('option', 'buttons', 

					{"I'm sure - reject it!": function () {													
								$(this).dialog("close");
								reason = parseInt($('input[name="reason_code"]:checked').val(), 10);
								explain = $('input[name="explain_why"]').val();

								$(this).dialog("close");
								if (typeof(reason) !== "undefined") 
								{
									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,159);
									}
									
									if (explain.length === 0)
									{
										explain = "Not given";
									}									
									window.open(encodeURI("/moderate/reject/" + earwigo + "/" + reason+ "/" + explain + "/" + mode), "_self");
								} 
								else 
								{
									quick_alert("You must select one of the options or fill in a reason this advert should be rejected!", true);
								}
							},

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

	$("#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</div>";
	html += "<div>Please give your reason: <br /></div>";
	html += "<div><input type='radio' name='reason_code' value='1' />Advert is obviously spam</div>";
	html += "<div><input type='radio' name='reason_code' value='2' />Contains offensive/racist/threatening language</div>";
	html += "<div><input type='radio' name='reason_code' value='3'/>Contains banned/illegal/unsuitable items</div>";
	html += "<div><input type='radio' name='reason_code' value='4'/>Other (specify)</div>";
	html += "<div>Explain: <input type='text' name='explain_why' /></div>";
	
	$("#dialog").html(html).dialog("open");
	return false;
}

function fcl_moderate_pass(earwigo, mode) {
	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 showstars(count)
{
	var n;
	faircycle.stars = count;
	
	for (n = 1; n < parseInt(count,10) + 1; (n++)) 
	{
		$("#star" + n).attr("src","/asset/images/lit-star.gif");
	}

	for (n = n + 0; n < 6; (n++)) 
	{
		$("#star" + n).attr("src","/asset/images/unlit-star.gif");
	}

}

function validate_login() {
	// stub function
}


function validate_email() {
	if ($('#to').val().length < 6 && $('#cc').val().length < 6) 
	{
		fcl_show_error(22);
		return false;
	}
	
	if ($('#to').val().length > 80 || $('#cc').val().length > 80) 
	{
		fcl_show_error(23);
		return false;
	}

}

function validate_advert()
{
	var limes, type;
	
	limes = parseInt($('#limes').val(), 10);
	type = parseInt($('input[name=type]:checked').val(), 10);
	
	$("#condition").val(faircycle.stars);
		
	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;

	$("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" : 0				
				};	
	
	$("#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').each(function () 
	{
      $(this).qtip(
      	{
	 	   content: {
				url: '/member/help/' + $(this).attr('rel'),
				data: { },
				method: 'get',
				title: 'Help'
			},
	 	   
	 	   show: {solo: true, effect: { type: 'fade', length: '400' } },
	 	   style: {
		 	    width: { min: 250 },
	            tip: true, 
	            name: 'green',
	            border: { width: 1, radius: 3 }
			}	 	   
      	 }
      );	
	});
	
	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 (typeof(faircycle_star_rating) !== "undefined") { showstars(faircycle_star_rating); }
    if ($('.advert_error').html()) {alert($('.advert_error').html());}
    $("#dialog").dialog({ autoOpen: false });


	// star rating system
	
	$('.condition').hover(	
							function () 
							{
								showstars($(this).attr("rel"));		
							},
							
							function () 
							{
								if (typeof(faircycle_star_rating) !== "undefined") 
								{ 
									showstars(faircycle_star_rating); 
								}
								else 
								{
									showstars(1);
								}
							}
						);

	$('.condition').click(	
							function () 
							{
								faircycle_star_rating = $(this).attr("rel");
								return false;
							}
						);
						


	// 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).attr("rel");
    									fcl_moderate_reject(earwigo,5);
    									return false;});							

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

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

    $('.mod_title, .mod_sub, .exp_menu').qtip({ show: {solo: true, effect: { type: 'fade', length: '400' } }, style: { name: 'green', tip: true } });
    
    // 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("new_email") !== 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, re;
	errors = 0;
		
	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])?/);
				
	for (n = 1; n < 11; (n++))
	{
		email = $('#email' + n).val();
		if ( email.length > 0 && (! email.match(re))) {
			$('#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;	
}
