/* ########################################################################### *
/* ***** MARKWINTERBOTTOM.COM - FLAJAX *************************************** *
/* ########################################################################### *
 * ##### DOCUMENT NAME:  global.js
 * ##### DOCUMENT INFO: 
 * ##### Original v1.0: 30/01/09 (Damian Keeghan, DMK Web Design)
/* ########################################################################### *
/* ########################################################################### *
/* ***** INDEX *************************************************************** *
/* ########################################################################### *
/* ##### GLOBAL VARIABLES
/* ##### INITIALISATION
/* ##### FLASH INTERFACE
/* ##### CONTACT FORM
/* ########################################################################### */

/* ########################################################################### *
/* ##### GLOBAL VARIABLES
/* ########################################################################### */

var DEBUG_MODE = false;
var ANIMATION_FADE_OUT = 250;
var ANIMATION_FADE_IN = 250;

var CURRENT_URL = "";

/* ########################################################################### *
/* ##### INITIALISATION
/* ########################################################################### */

$(document).ready(init);

function init(){
	init_scrollpane();
	init_errorMessage();
	
	if($("#admin").length==0){
		init_mainFlash();
		Flajax_Overlay_Close();
	} else {
		hide_loading();
		init_flashTitle(CURRENT_URL);
	}
}

function init_errorMessage(){
	$("#error").html("").hide();
	
	if($.browser.msie){
		if(parseFloat($.browser.version) < 7){
			display_errorMessage("<h2>You are using an obsolete browser (Internet Explorer 6). It might not be able to display this site correctly. Upgrade to <a href='http://www.microsoft.com/ie8' rel='external'>Internet Explorer 8</a> or <a href='http://www.firefox.com' rel='external'>Firefox 3</a>.</h2>");
		} else if(parseFloat($.browser.version) < 8){
			display_errorMessage("<h2>You are using an obsolete browser (Internet Explorer 7). Upgrade to <a href='http://www.microsoft.com/ie8' rel='external'>Internet Explorer 8</a> or <a href='http://www.firefox.com' rel='external'>Firefox 3</a>.</h2>");
		}
	} else if($.browser.mozilla){
		if(parseFloat($.browser.version) < 1.9){
			alert($.browser.version);
			display_errorMessage("<h2>You are using Firefox 2 which is no longer supported by the Mozilla Foundation. It might not be able to display this site correctly. Upgrade to <a href='http://www.firefox.com' rel='external'>Firefox 3</a> or <a href='http://www.microsoft.com/ie8' rel='external'>Internet Explorer 8</a>.</h2>");
		}
	} else {
		if(screen.width<=1000 && screen.height<=840){
			display_errorMessage("<h2>This site is designed for a larger resolution, you might not be seeing everything</h2>");
		}
	}
}

function display_errorMessage(str){
	$("#error").html(str).fadeIn('fast');
	init_relLinks();
}

function init_mainFlash(){
	var flashvars = {};
	flashvars.navigationXML = "/xml/navigation.php"
	var params = {};
	params.menu = "false";
	params.wmode = "transparent";
	params.allowscriptaccess = "always";
	params.base = "";
	var attributes = {};
	attributes.id = "MarkWinterbottom";
	attributes.name = "MarkWinterbottom_Name";
	attributes.styleclass = "flash";
	swfobject.embedSWF("/media/flash/markwinterbottom.swf", "flashContent", "990", "600", "9.0.0", null, flashvars, params, attributes);
	
	hide_loading();
}

function show_loading(){
	$("#loading, #loadingOverlay").fadeIn('fast');	
}

function hide_loading(){
	$("#loading, #loadingOverlay").fadeOut('fast');	
}

function init_scrollpane(){
	$(".scrollpane").jScrollPane({scrollbarWidth: 7});	
}

function init_flashTitle(url){
	var flaWidth = 860;
	var flaHeight = 25;
	
	if($("#overlay").hasClass("sponsor")){
		flaWidth = 470;
		flaHeight = 25;
	} else if($("#overlay").hasClass("oneColumn")||$("#overlay").hasClass("twoColumn")){
		flaWidth = 860;
		flaHeight = 25;
	}
	
	var flashvars = {};
	flashvars.navigationXML = "/xml/navigation.php";
	if($("#admin").length==0){
		flashvars.currentPage = SWFAddress.getValue();
	} else {
		flashvars.title = $("#header h1").text();
	}
	var params = {};
	params.menu = "false";
	params.wmode = "transparent";
	params.allowscriptaccess = "always";
	params.base = "";
	var attributes = {};
	attributes.id = "FlashHeader";
	attributes.name = "FlashHeader_Name";
	attributes.styleclass = "flash";
	swfobject.embedSWF("/media/flash/title.swf", "flashHeader", flaWidth, flaHeight, "9.0.0", null, flashvars, params, attributes);	
}

function init_flashMenu(url){
	var flashvars = {};
	flashvars.navigationXML = "/xml/navigation.php";
	if($("#admin").length==0){
		flashvars.currentPage = SWFAddress.getValue();
	} else {
		flashvars.title = $("#header h1").text();
	}
	var params = {};
	params.menu = "false";
	params.wmode = "transparent";
	params.allowscriptaccess = "always";
	params.base = "";
	var attributes = {};
	attributes.id = "FlashMenu";
	attributes.name = "FlashMenu_Name";
	attributes.styleclass = "flash";
	swfobject.embedSWF("/media/flash/menu.swf", "flashMenu", "245", "430", "9.0.0", null, flashvars, params, attributes);	
}

function init_relLinks(){
	$("a[rel='external']").each(function(){
		var href = $(this).attr("href");
		
		$(this).click(function(){
			window.open(href);
			return false;
		});
	});
	
	$("a[rel='image']").click(function(){
		var href = $(this).attr("href");
		
		var dimensions = "";
		if($(this).hasClass("portrait")){
			dimensions = "width=420, height=620";
		} else if($(this).hasClass("landscape")){
			dimensions = "width=620, height=420";	
		}
		
		window.open(href, "image", dimensions);
		return false;
	});
}

function init_backLink(){
	$("a.btn_back").click(function(){
		window.history.back(1);
		return false;							  
	});	
}

function init_upLink(){
	$("a.btn_up").click(function(){
		Flajax_UpLevel();
		return false;							  
	});		
}

function init_listIdentifiers(){
	$("ul").each(function(){
		$(this).find("li:first-child").addClass("first");
		$(this).find("li:last-child").addClass("last");
	});
}

function init_contactAvatars(){
	if($("#display_public").length>0){
		$("#display_public").bind("change", function(){
			if($(this).find("option:selected").val()=="private"){
				$("#avatarList").hide();	
			} else {
				$("#avatarList").show();	
			}
		});
	}
	
	if($("ul.avatarsList").length>0){
		$("ul.avatarsList li img").tooltip({
			bodyHandler: function(){
				return $("<img/>").attr("src", this.src);
			}, showURL: false				
		});
		
		$("ul.avatarsList li").click(function(){
			var avatarNum = $(this).find("img").attr("class");
			
			setCurrentlySelectedAvatar(avatarNum);
			$(this).parents(".ctrlHolder").find("input#avatar").val(avatarNum);					   
		});									 
	}
}

function setCurrentlySelectedAvatar(selected){
	$("ul.avatarsList li").each(function(){
		if($(this).find("img").attr("class")==selected){
			$(this).addClass("selected");
		} else {
			$(this).removeClass("selected");
		}
	});	
}

function loadRightColumnContent(url){
	//show loading
	show_loading();
	$("#overlay").find("#overlayContent #rightColumn").html("");
	
	$("#rightColumn").load(url+" #rightColumnContent", null, function(){
		var fragment = SWFAddress.getValue();
		if(fragment=="/"){
			Flajax_Overlay_Close()
		} else {
			if($("#FlashHeader").length>0){
				if($("#admin").length==0){
					try{
						getFlashMovieByName("FlashHeader").Flajax_Update(fragment);
					} catch(err) {
						
					}
				} else {
					try{
						getFlashMovieByName("FlashHeader").Flajax_Update($("#header h1").text());
					} catch(err) {
						
					}
				}
			}
			
			if($("#FlashMenu").length>0){
				try{
					getFlashMovieByName("FlashMenu").Flajax_Update(fragment);
				} catch(err) {
						
				}
			}
			
			afterContentLoad(url);
		}
	});
}

function init_listLinks(){
	if($("#overlay #rightColumn").find("ul.newsList li, ul.roundList li, ul.galleryList li").length>0){
		$("#overlay #rightColumn").find("ul.newsList li, ul.roundList li, ul.galleryList li").each(function(){
			$(this).click(function(){
				var fragment = $(this).find("div h2 a").attr("href");
				var fragArr = fragment.split("#");
				fragment = fragArr[fragArr.length-1];
				SWFAddress.setValue(fragment);
			});
		});	
	}
	
	if($("#overlay #rightColumn").find("a.btn_report").length>0){
		$("#overlay #rightColumn").find("a.btn_report").each(function(){
			$(this).tooltip({showURL: false});
			$(this).click(function(){
				var action = $(this).attr("href");
				var id = $(this).attr("rel");
				var aTag = $(this);
				
				if($.cookie('reported_'+id)=="true"){
					$(aTag).parent().html("<span class='report_error'>Sorry, you can only report a message once.</span>");
				} else {
					$.post(action, { 'id': id }, function(data){
							if (data.status == "success") {
								$.cookie('reported_'+id, "true", {expires: 999})					
								$(aTag).parent().html("<span class='report_success'>Thanks, the message has been reported.</span>");	
							} else {
								$(aTag).parent().html("<span class='report_error'>Sorry, the message wasn't reported.</span>");
							}									
						}, "json");
				}
				
				return false;
			});
		});
	}
}

function init_tableLinks(){
	if($("#overlay #rightColumn").find("table.results tbody tr").length>0){
		$("#overlay #rightColumn").find("table.results tbody tr").each(function(){
			$(this).tooltip({
				bodyHandler: function(){
					return "Click here to view the "+$(this).find("td.col_location a strong").text()+" round report";
				}, showURL: false				
			});
			
			$(this).click(function(){
				var fragment = $(this).find("td.col_location a").attr("href");
				var fragArr = fragment.split("#");
				fragment = fragArr[fragArr.length-1];
				SWFAddress.setValue(fragment);
			});
		});	
	}
}

function init_imageClick(){
	if($("ul.imageGrid li").length>0){
		$("ul.imageGrid li").each(function(){
			$(this).click(function(){
				return false;			   
			});
		});
	}
}

function init_internalLinks(){
	$(".updateFragment").click(function(){
		var fragment = $(this).attr("href");
		fragment = fragment.substring(2);
		SWFAddress.setValue(fragment);									
	});
}

function loadContent(url){
	//show loading
	show_loading();
	$("#overlay").find("#overlayContent").html("");
	
	$("#overlay").load(url+" #overlayContent", null, function(){
		var fragment = SWFAddress.getValue();
		if(fragment=="/"){
			Flajax_Overlay_Close()
		} else {
			afterContentLoad(url)	
		}
	});
}

function init_addHoverState(){
	$("ul.avatarsList li, ul.newsList li, ul.galleryList li, ul.roundList li, .ctrlHolder button, ul.imageList ul.imageGrid li, div.actions li, table.results tbody tr").hover(function(){
		$(this).addClass("hover");
	}, function(){
		$(this).removeClass("hover");
	});	
}

function init_calendar(){
	if($("#calendar").length>0){
		
	}
}

function init_inputClasses(){
	if($("#leftColumn form").length>0){
		$("#leftColumn form").find("input[type='text'], input[type='password']").each(function(){
			$(this).addClass("short");																	
		});
		
		$("#leftColumn form").find("input[readonly='readonly']").each(function(){
			$(this).addClass("readonly");																	
		});
	}
	
	if($("#rightColumn form").length>0){
		$("#rightColumn form").find("input[type='text'], input[type='password']").each(function(){
			$(this).addClass("long");																	
		});
		
		$("#rightColumn form").find("input[readonly='readonly']").each(function(){
			$(this).addClass("readonly");																	
		});
	}
}

function afterContentLoad(url){
	CURRENT_URL = url;
	
	//hide loading
	hide_loading();
	
	//page contents initialisation
	init_listLinks();
	init_tableLinks();
	init_relLinks();
	init_backLink();
	init_upLink();
	init_imageClick();
	init_listIdentifiers();
	
	//contact
	init_contactAvatars();
	init_contact();
	init_inputClasses();
	
	//calendar
	init_calendar();
	
	//add hover class
	init_addHoverState();
	
	//page titles and scrollbars
	init_flashTitle(url);
	init_flashMenu(url);
	init_scrollpane();
}

/* ########################################################################### *
/* ##### FLASH INTERFACE
/* ########################################################################### */

// IE looks at swf files differently than everyone else
function getFlashMovieByName(movieName)
{
	var flashmovie = document.getElementById(movieName);
	return flashmovie;
}


// Allows tracing from flash for SWF Address based tracking and bugfixing
function Flajax_Alert(str){
	alert(str);	
}

function Flajax_Overlay_OpenInNew(url, type){
	$("#overlay").addClass(type);
	
	//show loading
	show_loading();
	$("#overlay").find("#overlayContent").html("");
	
	$("#overlay").load(url+" #overlayContent", null, function(){
		var fragment = SWFAddress.getValue();
		if(fragment=="/"){
			Flajax_Overlay_Close()
		} else {
			$("#overlay").show();
			afterContentLoad(url)
		}
	});
}

function Flajax_Overlay_OpenInExisting(url, type){
	if($("#overlay").hasClass()==type){
		loadContent(url)
	} else {
		Flajax_Overlay_Close();
		Flajax_Overlay_OpenInNew(url, type);
	}
}

function Flajax_Overlay_UpdateRightColumn(url){
	loadRightColumnContent(url);
}

function Flajax_Overlay_Close(){
	$("#overlay").removeClass("oneColumn").removeClass("twoColumn").removeClass("sponsor").hide();
	$("#overlay").html("<div id='overlayContent'></div>");
	CURRENT_URL = "";
	
	//hide loading
	hide_loading();
}

// Sets the URL Fragment
function Flajax_SetFragment(fragment){
	SWFAddress.setValue(fragment);	
}

function Flajax_UpLevel(){
	var newFragment = SWFAddress.getValue();
	newFragment = newFragment.substring(0, newFragment.lastIndexOf("/"));
	SWFAddress.setValue(newFragment);
}

/* ########################################################################### *
/* ##### CONTACT FORM
/* ########################################################################### */

function init_contact()
{
	if ($("#frm_contact").length>0){
		$("#frm_contact #btn_sendEmail").click(function(){
			$('#frm_contact .errors').removeClass('errors');
			var hasError = false;
			var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
			var errorMessages = "";
			var action = $("#frm_contact").attr("action");
			
			var nameVal = $("#name").val();
			if(nameVal == "") {
				errorMessages += "<li>Your name is required</li>";
				$("#name").parents(".ctrlHolder").addClass("errors");
				hasError = true;
			}
					
			var emailVal = $("#email_address").val();
			if(emailVal == '') {
				errorMessages += '<li>Your email address is required</li>';
				$("#email_address").parents(".ctrlHolder").addClass("errors");
				hasError = true;
			} else if(!emailReg.test(emailVal)) {	
				errorMessages += '<li>Please enter a valid Email Address</li>';
				$("#email_address").parents(".ctrlHolder").addClass("errors");
				hasError = true;
			}
							
			var messageVal = $("#message").val();
			if(messageVal == '') {
				errorMessages += '<li>Please enter a message</li>';
				$("#message").parents(".ctrlHolder").addClass("errors");
				hasError = true;
			}

			if(messageVal.length > 600) {
				errorMessages += '<li>Please limit your message to 600 characters</li>';
				$("#message").parents(".ctrlHolder").addClass("errors");
				hasError = true;
			}
							
			if(hasError == false) {
				var avatar = $("#avatar").val();
				var isPublic = ($("#display_public option:selected").val()=="public") ? true : false;
				
				$("#frm_contact").find("input, select, textarea, button").attr("disabled", "disabled");
				contact_loading(function(){
					// If in DEBUG_MODE then do not attempt to send via server side script, instead execute dummy client side test
					if (DEBUG_MODE)
					{
						setTimeout ( contact_success, 2000 );
					} else {
						$.post(action, { 'name': nameVal, 'email_address': emailVal, 'message': messageVal, "avatar": avatar, "public": isPublic }, function(data){
							if (data.status == "success") {
								contact_success(isPublic);	
							} else {
								contact_fail(isPublic, data.message);
							}									
						}, "json");
					}
				});
			} else {
				// If errors exist show the feedback
				$('#contactStatus').fadeOut("normal", function(){
					$('#contactStatus').html("<ul class='errors'>" + errorMessages + "</ul>").fadeIn("normal");														
				});
				return false;
			}
			
			return false;
		});
	}
	return false;
}

function contact_loading(callback)
{
	$('#contactStatus').fadeOut("normal", function(){
		$('#contactStatus').html("<p class='note'>Sending...</p>").fadeIn("normal");
		callback();
	});
}

function contact_success(isPublic)
{
	$("#frm_contact").fadeOut();
	$('#contactStatus').fadeOut("normal", function(){
		var messageText = (isPublic) ? "Your message has successfully been posted on the wall." : "Your email was sent successfully.";
		$('#contactStatus').html("<p class='success'>"+messageText+"</p>").fadeIn("normal");
		
		if(isPublic){
			Flajax_Overlay_UpdateRightColumn(CURRENT_URL);
		}													
	});
}

function contact_fail(isPublic, message)
{
	$("#frm_contact").find("input, select, textarea, button").removeAttr("disabled");
	
	$('#contactStatus').fadeOut("normal", function(){
		if(message==""||message==undefined){
			message = (isPublic) ? "Your message was unable to be posted on the wall, please try again." : "Your email was unable to be sent, please try again.";
		}
		
		$('#contactStatus').html("<p class='errors'>"+message+"</p>").fadeIn("normal");													
	});
}
