var PubRepublik = {
	MyAccount : {
		Entertainer : {
			ValidateLogoStep1:function() {
				if($("imageLogo").value.blank()) {
					PubRepublik.HighlightAndFocus("imageLogo");
					return false;
				}
				if(!$("imageLogo").value.toLowerCase().endsWith(".jpg")) {
					alert("Only JPG images are allowed");
					return false;
				}
				$("imageSubmit").hide();
				$("LightBoxHolder").update("<img src='images/lightbox/loading.gif' width='32' height='32' alt='' border='0'> Working....");	
				MFLightbox.showBoxByID( "LightBoxHolder", 80, 80, false );
				return true;
			},
			ValidateNameSummary:function() {
				if($("entertainerName").value.blank()) {
					PubRepublik.HighlightAndFocus("entertainerName");
					return false;
				}
				if($("entertainerSummary").value.blank()) {
					PubRepublik.HighlightAndFocus("entertainerSummary");
					return false;
				}
				return true;
			},
			ValidateContactDetails:function() {
				if($("entertainerTelephone").value.blank()) {
					PubRepublik.HighlightAndFocus("entertainerTelephone");
					return false;
				}
				if($("entertainerEmailAddress").value.blank()) {
					PubRepublik.HighlightAndFocus("entertainerEmailAddress");
					return false;
				}
				return true;
			},
			ValidateFullDescription:function() {
				if($("entertainerDescription").value.blank()) {
					PubRepublik.HighlightAndFocus("entertainerDescription");
					return false;
				}
				return true;
			},
			ToggleCategory:function(id,entertainerId) {
				var cMaxCategories = 3;
				var selected = 0;
				var cbs = $("entertainmentTypes").select("input");
				for(i=0;i<cbs.length;i++) {
					if(cbs[i].checked) {
						selected++;
					}
				}
				if(selected>cMaxCategories) {						
					$("et"+id).checked = false;
					alert("You can only choose a maximum of " + cMaxCategories + " categories to be listed in");
				} else {
					if($("et"+id).checked) {
						$("li"+id).addClassName("on");
						var url = "index.cfm?action=Entertainer_ToggleCategory&id="+id+"&eId="+entertainerId+"&t=on";
					} else {
						$("li"+id).removeClassName("on");
						var url = "index.cfm?action=Entertainer_ToggleCategory&id="+id+"&eId="+entertainerId+"&t=off";;
					}						
					new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PubRepublik.MyAccount.Entertainer.ToggleCategory_onSuccess, onFailure:errFunc});
				}
			},
			ToggleCategory_onSuccess:function(t) {
				z = parseJSON(t.responseText);									
			}
		},
		ValidateDetails:function(){
			if($("regFirstName").value.blank()) {
				PubRepublik.HighlightAndFocus("regFirstName");
				return false;
			}
			if($("regLastName").value.blank()) {
				PubRepublik.HighlightAndFocus("regLastName");
				return false;
			}
			if($("regAddress1").value.blank()) {
				PubRepublik.HighlightAndFocus("regAddress1");
				return false;
			}
			if($("regCounty").selectedIndex==0) {
				alert("Please choose the county you reside in");
				return false;
			}			
			if($("regMobileNumber").value.blank() || !isMobileNumber($("regMobileNumber").value)) {
				PubRepublik.HighlightAndFocus("regMobileNumber");
				return false;
			}
			if($("regEmailAddress").value.blank()) {
				PubRepublik.HighlightAndFocus("regEmailAddress");
				return false;
			}
			if($("newPassword2").value != $("newPassword").value) {
				PubRepublik.HighlightAndFocus("newPassword2");
				return false;
			}
			return true;
		}
	},
	Login : {
		ValidateLogin:function() {
			if($("loginEmail").value.blank()) {
				PubRepublik.HighlightAndFocus("loginEmail");
				return false;
			}
			if($("loginPassword").value.blank()) {
				PubRepublik.HighlightAndFocus("loginPassword");
				return false;
			}
			return true;
		},
		ValidateLogin_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			if(z.result) {
				document.location=z.targetURL;
			} else {
				$("btnLogin").show();
			}
		},
		ForgotPass:function() {
			new Effect.SlideUp("existingUsersHolder");
			$("forgotPassSending").hide();
			$("forgotPassEmail").value = $("loginEmail").value;
			$("forgotPassHolder").show();
			$("forgotPassEmail").focus();
		},
		CancelForgotPass:function() {
			$("forgotPassHolder").hide();
			$("existingUsersHolder").show();
			$("forgotPassBut").show();
		},
		SendForgotPass:function() {
			if($("forgotPassEmail").value.blank()) {
				PubRepublik.HighlightAndFocus("forgotPassEmail");
			} else {
				$("forgotPassDetailsHolder").show();
				$("forgotPassSending").hide();
				$("forgotPassBut").hide();
				var url = "index.cfm?action=Login_SendForgottenPass&e="+escape($("forgotPassEmail").value);
				new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PubRepublik.Login.SendForgotPass_onSuccess, onFailure:errFunc});
			}
		},
		SendForgotPass_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			if(z.result) {
				PubRepublik.Login.CancelForgotPass();
				$("regMobileNumber").value=z.n;
				$("regMobilePrefix").value=z.p;
				PubRepublik.HighlightAndFocus("regPassNumber");
			} else {
				$("forgotPassPhoneDetailsHolder").show();
				$("forgotPassBut").show();
			}
		},
		ForgotPIN:function() {
			new Effect.SlideUp("existingUsersHolder");
			$("forgotPINPhoneSending").hide();
			$("forgotPINHolder").show();
		},
		CancelForgotPIN:function() {						
			$("forgotPINHolder").hide();
			$("existingUsersHolder").show();
			$("forgotPINPhoneDetailsHolder").show();
			$("forgotPINBut").show();
		},
		SendForgotPIN:function() {
			var cNumber = $("forgotMobileNo").value;
			var cPrefix = $("forgotMobilePrefix").value;
			if(cNumber.blank()) {
				PubRepublik.HighlightAndFocus("forgotMobileNo");
			} else {
				$("forgotPINPhoneDetailsHolder").hide();
				$("forgotPINPhoneSending").show();
				$("forgotPINBut").hide();
				var url = "index.cfm?action=Login_SendForgotPIN&n="+escape(cNumber)+"&p="+escape(cPrefix).replace('+','%2B');
				new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PubRepublik.Login.SendForgotPIN_onSuccess, onFailure:errFunc});
			}
		},
		SendForgotPIN_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			if(z.result) {
				PubRepublik.Login.CancelForgotPIN();
				$("regMobileNumber").value=z.n;
				$("regMobilePrefix").value=z.p;
				PubRepublik.HighlightAndFocus("regPINNumber");
			} else {
				$("forgotPINPhoneDetailsHolder").show();
				$("forgotPINBut").show();
			}
		}
	},
	Registration : {
		ValidateStep1:function() {	
			if($("regFirstName").value.blank()) {
				PubRepublik.HighlightAndFocus("regFirstName");
				return false;
			}
			if($("regLastName").value.blank()) {
				PubRepublik.HighlightAndFocus("regLastName");
				return false;
			}
			if($("regAddress1").value.blank()) {
				PubRepublik.HighlightAndFocus("regAddress1");
				return false;
			}
			if($("regCounty").selectedIndex==0) {
				alert("Please choose the county you reside in");
				return false;
			}			
			if($("regMobileNumber").value.blank() || !isMobileNumber($("regMobileNumber").value)) {
				PubRepublik.HighlightAndFocus("regMobileNumber");
				return false;
			}
			if($("regEmailAddress").value.blank()) {
				PubRepublik.HighlightAndFocus("regEmailAddress");
				return false;
			}
			if($("regPassword2").value != $("regPassword").value) {
				alert("Passwords must match");
				PubRepublik.HighlightAndFocus("regPassword2");
				return false;
			}
			return true;
		}
	},
	Finder : {
		Events : {
			Initialise:function() {
				PubRepublik.Finder.Events.datePickObj = new PubRepublicDatePicker({
					relative	: 'eventDate',
					language	: 'en',
					keepFieldEmpty : true,
					topOffset : 0,
					leftOffset : (document.all?200:110),//IE7 acting the maggot
					enableCloseonchange : true,
					dateFormat : [ ["dd", "mm", "yyyy"], "/" ],
					enableShowEffect : false,
					showEffect	: 'appear',
					showDuration: .1,
					enableCloseEffect : false,
					closeEffect	: 'appear',
					closeDuration: .1,
					disablePastDate:false,
					cellCallback:PubRepublik.Finder.Events.OnChooseDate
				});
				PubRepublik.Finder.Events.eventDateSelect_initOptionsLen = $("eventDateSelect").options.length;
			},
			OnChangeLocation:function(val){
				var url = "index.cfm?action=getPubSubLocationList&parentLocationId="+val;
				new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PubRepublik.Finder.Events.OnChangeLocation_onSuccess, onFailure:errFunc});
			},
			OnChangeLocation_onSuccess:function(t){
				var z = eval('(' + t.responseText + ')');
				var data = z.locations.data;
				var o = $("eventLocation");
				o.options.length = 1;
				for( var i=0; i<data.locationid.length; i++ ){
					o.options[ o.options.length ] = new Option( data.locationname[i]+" ("+data.pubcount[i]+")", data.locationid[i] )
				}
			},
			OnChooseDate:function(o,dd,mm,yyyy){
				var df;
				if( o != null ){
					df = PubRepublik.Finder.Events.datePickObj._df;
					var d = o.id.sub('eventDate-', '');
					dd = parseInt( d.substring( 0, 2 ) );
					mm = parseInt( d.substring( 3, 5 ) );
					yyyy = parseInt( d.substring( 6, 10 ) );
				}
				else df = new DatePickerFormatter();
				//restore back to original length
				$("eventDateSelect").options.length = PubRepublik.Finder.Events.eventDateSelect_initOptionsLen;
				$("eventDateSelect").options[ $("eventDateSelect").options.length ] = new Option( df.date_to_string( yyyy, mm, dd ), ""+yyyy+"-"+mm+"-"+dd);
				$("eventDateSelect").options.selectedIndex = $("eventDateSelect").options.length-1;
				$("eventFinderForm").submit();
			}
		},
		Pubs : {
			OnChangeLocation:function(val){
				var url = "index.cfm?action=getPubSubLocationList&parentLocationId="+val;
				new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PubRepublik.Finder.Pubs.OnChangeLocation_onSuccess, onFailure:errFunc});
			},
			OnChangeLocation_onSuccess:function(t){
				var z = eval('(' + t.responseText + ')');
				var data = z.locations.data;
				var o = $("pubLocation");
				o.options.length = 1;
				for( var i=0; i<data.locationid.length; i++ ){
					o.options[ o.options.length ] = new Option( data.locationname[i]+" ("+data.pubcount[i]+")", data.locationid[i] )
				}
			}			
		}
	}
	,HighlightAndFocus:function(id) {
		new Effect.Highlight($(id));
		$(id).focus();
	}
	,CloseLightBox:function() {
		Element.hide('box');
		Element.hide('overlay');
	}
	,InitSignUpForm:function(){
		new LiveValidation('regEmailAddress',{validMessage:"OK"}).add( Validate.Email );
		new LiveValidation('regMobileNumber',{validMessage:"OK"}).add( Validate.Numericality, {notANumberMessage:"Must be a valid phone number"} );
		new LiveValidation('regPassword',{validMessage:"OK"}).add( Validate.Length, { minimum: 4 } );
		new LiveValidation('regPassword2',{validMessage:"OK"}).add( Validate.Length, { minimum: 4 } );
	}
	,InitLoginForm:function(){
		new LiveValidation('loginEmail',{validMessage:"OK"}).add( Validate.Email );
	}
} 

String.prototype.isEmail = function () { 
	var rx = new RegExp("\\w+([-+.\’]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); 
	var matches = rx.exec(this); 
	return (matches != null && this == matches[0]); 
}

function isNumeric(str) { 
	var y=parseInt(str); 
	if (isNaN(y)) {
	   return false; 
	} else {
		return true;
	}
} 

function isMobileNumber(str) {
	var result = false;
	var phonenumber=RegExp(/^[0-9]+$/);
	if(phonenumber.test(str)) {
		if(str.length==7) {
			result = true;
		}
	}
	return result;
}

function LoadingAjax(txt) {
	if(typeof(txt)=="undefined") {
		txt = "Loading...";
	}
	return "<div class='ajaxMsg' id='widgetAjaxMsg'> "+txt+"</div>";
}

function parseJSON( json ){
	var o = eval('(' + json + ')');
	if( o.redirectURL )
	{
		document.location = o.redirectURL;
		return;
	}
	
	if( o.errMsg )
	{
		if( o.errMsgTitle == null ) o.errMsgTitle = "Error";
		alert( (o.errMsgTitle?(o.errMsgTitle + '\r'):"") + o.errMsg );
		return o;
	}
	if( o.msgTitle || o.msg || o.message )
	{
		if( o.message ) o.msg = o.message;
		alert( (o.msgTitle?(o.msgTitle + '\r'):"") + o.msg );
	}
	return o;
}

var errFunc = function(t) {
	var win = window.open("", "win", "width=1024,height=700,resizable=yes,scrollbars=yes,status=no"); // a window object
	win.document.open("text/html", "replace");
	win.document.write( "<html><body style='margin:0'><div style='border-bottom:1px solid #222;background:#666;padding:10px;'><h1 style='color:#FFF;margin:0;padding:0;'>Digital Crew Ajax Error</h1></div><div style='padding:10px;'>"+t.responseText.replace(/^\s+|\s+$/, '') + "</div></body></html>" );
	win.document.close();
	win.focus();
}