/* Author: Chapel Studios Communications Ltd - Dave Phipps

*/
 if(!addresses) var addresses = new Array();
addresses.push("20453 7331 15172 20231 2906 644 2110 4167 1539 15501 17074 2906 2110 4167 19211 10855 20231 2110 2110 20231 2906 8286 15172 20231 17378 20231 3742 2906 8286 15501 14164 15421 4167 14164 9236 13287"); //editor
addresses.push("20453 7331 15172 20231 2906 644 2110 4167 1539 20231 17074 17662 15501 19211 2110 2906 3743 2906 8286 17378 10855 20231 2110 2110 20231 2906 8286 15172 20231 17378 20231 3742 2906 8286 15501 14164 15421 4167 14164 9236 13287");//advertising
addresses.push("20453 7331 15172 20231 2906 644 2110 4167 1539 20231 17074 17662 15501 19211 2110 3743 10855 20231 2110 2110 20231 2906 8286 15172 20231 17378 20231 3742 2906 8286 15501 14164 15421 4167 14164 9236 13287");//adverts

function preQL(formData, jqForm, options) {
	$("#quicklinks").block({message:'<div class="quick-alert">Validating Code...</div>',css:{border: '0',backgroundColor:'transparent'}});
	return true;
	//return false; //testing phase - don't submit the form
}
// post-submit callback
function postQL(responseText, statusText)  {
   console.log(responseText);
	$("#quicklinks").unblock();
   if(statusText == "success" && isNaN(responseText)) {
		var errmessage = responseText.substring(7);
		$.blockUI({message: '<div class="quick-alert-error">An Error occurred:<br />' + errmessage +'<br /><input type="button" id="errok" value="OK" class="ui-state-default ui-corner-all" /></div>',css:{border: '0',backgroundColor:'transparent'}});
		$('#errok').hover(function(){$(this).addClass('ui-state-hover')},function(){$(this).removeClass('ui-state-hover')}).click(function() {
            $.unblockUI();
            return false;
        });
	} else {
		self.location = '/directory/' + responseText;
		$("#quicklinks").block({message: '<div class="quick-alert">Relocating to Directory</div>',css:{border: '0',backgroundColor:'transparent'}});
		return false;
	}
}

function preLogin(formData, $form, options) {
	return true;
}

function postLogin(responseText, statusText)  {
	//responseText contains the result
	//console.log(responseText);
	if(statusText == "success" && responseText.substring(1,6) == "error" ) {
		//#signin_menu p.remember append error
		$("p.remember","#signin_menu").append('<span class="loginerror">'+ responseText.substring(8) +'</span>');
	} else {
		window.location.reload();
	}
}

function preReg(formData, $form, options) {
	$.blockUI({message:'<div class="quick-alert">Registering...<br /><img src="/assets/images/loader.gif" alt="Loading..." /></div>',css:{border: '0',backgroundColor:'transparent'}});
	return true;
}

function postReg(responseText, statusText)  {
	$.unblockUI();
	//responseText contains the result
	//console.log(responseText);
	if(statusText == "success" && responseText.substring(1,6) == "error" ) {
		var errmessage = responseText.substring(8);
		$.blockUI({message: '<div class="quick-alert-error">An Error occurred:<br />' + errmessage +'<br /><input type="button" id="errok" value="OK" class="ui-state-default ui-corner-all" /></div>',css:{border: '0',backgroundColor:'transparent'}});
		$('#errok').hover(function(){$(this).addClass('ui-state-hover')},function(){$(this).removeClass('ui-state-hover')}).click(function() {
            $.unblockUI();
            return false;
        });
	} else {
		$.blockUI({message: '<div class="quick-alert">'+ responseText +'</div>',css:{border: '0',backgroundColor:'transparent'}});
		//setTimeout("$.unblockUI()",2000);
		var t=setTimeout("gotodir('')",2000);
	}
}

function preDir(formData, $form, options) {
	$.blockUI({message:'<div class="quick-alert">Saving Directory Listing...<br /><img src="/assets/images/loader.gif" alt="Loading..." /></div>',css:{border: '0',backgroundColor:'transparent'}});
	return true;
}

function postDir(responseText, statusText)  {
	//responseText contains the result
	//console.log(responseText);
	if(statusText == "success" && responseText.substring(1,6) == "error" ) {
		var errmessage = responseText.substring(8);
		$.blockUI({message: '<div class="quick-alert-error">An Error occurred:<br />' + errmessage +'<br /><input type="button" id="evok" value="OK" class="ui-state-default ui-corner-all" /></div>',css:{border: '0',backgroundColor:'transparent'}});
		$('#evok').hover(function(){$(this).addClass('ui-state-hover')},function(){$(this).removeClass('ui-state-hover')}).click(function(e) {
            $.unblockUI();
            e.preventDefault();
        });
	} else {
		$.blockUI({message: '<div class="quick-alert">The listing has been saved</div>',css:{border: '0',backgroundColor:'transparent'}});
		var dirid = Math.floor(responseText);
		//console.log(responseText);
		var t=setTimeout("gotodir("+dirid+")",2000);
	}
}

function preCalEvent(formData, $form, options) {
	$.blockUI({message:'<div class="quick-alert">Saving Event...<br /><img src="/assets/images/loader.gif" alt="Loading..." /></div>',css:{border: '0',backgroundColor:'transparent'}});
	return true;
}

function postCalEvent(responseText, statusText)  {
	//responseText contains the result
	//console.log(responseText);
	if(statusText == "success" && responseText.substring(1,6) == "error" ) {
		var errmessage = responseText.substring(8);
		$.blockUI({message: '<div class="quick-alert-error">An Error occurred:<br />' + errmessage +'<br /><input type="button" id="evok" value="OK" class="ui-state-default ui-corner-all" /></div>',css:{border: '0',backgroundColor:'transparent'}});
		$('#evok').hover(function(){$(this).addClass('ui-state-hover')},function(){$(this).removeClass('ui-state-hover')}).click(function(e) {
            $.unblockUI();
            e.preventDefault();
        });
	} else {
		$.blockUI({message: '<div class="quick-alert">The event has been saved</div>',css:{border: '0',backgroundColor:'transparent'}});
		var dirid = Math.floor(responseText);
		//console.log(responseText);
		var t=setTimeout("gotodir("+dirid+")",2000);
	}
}

function preNewsItem(formData, $form, options) {
	$.blockUI({message:'<div class="quick-alert">Saving News...<br /><img src="/assets/images/loader.gif" alt="Loading..." /></div>',css:{border: '0',backgroundColor:'transparent'}});
	return true;
}

function postNewsItem(responseText, statusText)  {
	//responseText contains the result
	//console.log(responseText);
	if(statusText == "success" && isNaN(responseText) ) {
		var errmessage = responseText.substring(8);
		$.blockUI({message: '<div class="quick-alert-error">An Error occurred:<br />' + errmessage +'<br /><input type="button" id="evok" value="OK" class="ui-state-default ui-corner-all" /></div>',css:{border: '0',backgroundColor:'transparent'}});
		$('#evok').hover(function(){$(this).addClass('ui-state-hover')},function(){$(this).removeClass('ui-state-hover')}).click(function(e) {
            $.unblockUI();
            e.preventDefault();
        });
	} else {
		$.blockUI({message: '<div class="quick-alert">The story has been saved</div>',css:{border: '0',backgroundColor:'transparent'}});
		var dirid = Math.floor(responseText);
		//console.log(responseText);
		var t=setTimeout("gotodir("+dirid+")",2000);
	}
}

function gotodir(dirid) {
	//console.log('/directory/'+dirid+'/#events');
	parent.location = '/directory/' + dirid;
}

$(function(){
	//$("#loginlnk").colorbox({width:"320px", height:"200px", iframe:true});
	//$("#reglnk").colorbox({width:"80%",height:"80%",iframe:true});
	if($("#slidebox").length > 0) {
		$('#s1,#s2').cycle({
		    fx:     'fade',
		    speed:   1500,
		    timeout: 5000,
		    pause:   1
		});
	}
	
	if($("#quicklinkfrm").length > 0) {
		$("#qlcode").focus(function(){
			if($(this).val() == 'Enter Quick Link Code') {
				$(this).val('').removeClass('blur').addClass('focus');
			}
		});
		$("#qlcode").blur(function(){
			if($(this).val() == '') {
				$(this).val('Enter Quick Link Code').removeClass('focus').addClass('blur');
			}
		});
		$("#quicklinkfrm").ajaxForm({
	        beforeSubmit:  preQL,  // pre-submit callback
	        success:       postQL,  // post-submit callback
			clearForm: true,
			resetForm: true,
			type: 'post',
			dataType: 'json'
	    });
	}
	
	if($("#schoolfinderfrm").length > 0) {
		$("#schoolfinderfrm").submit(function(e){
			e.preventDefault();
		});
		$("#organisation").focus(function(){
			if($(this).val() == 'Enter School name') {
				$(this).val('').removeClass('blur').addClass('focus');
			}
		});
		$("#organisation").blur(function(){
			if($(this).val() == '') {
				$(this).val('Enter School name').removeClass('focus').addClass('blur');
			}
		});
		$("#organisation").autocomplete({appendTo:"#schoolfinder",source: "/directory/organisations/",minLength: 2,select: function( event, ui ) {
			//$("#directoryid").val(ui.item.id);
			$.blockUI({message: '<div class="quick-alert">Loading Directory...</div>',css:{border: '0',backgroundColor:'transparent'}});
				var dirid = Math.floor(ui.item.id);
				//console.log(responseText);
				var t=setTimeout("gotodir("+dirid+")",1500);
			}
		});
	}
	
	if (!("autofocus" in document.createElement("input"))) {
      $("#loginfrmemail","#loginfrmcontainer").focus();
    }
	
	$("#loginlnk").click(function(e) {
		//console.log($(this).hasClass('menu-open'));
        if($("#loginlnk").hasClass('menu-open')){
        	$("#loginlnk").removeClass("menu-open");
            $("fieldset#signin_menu").hide();
        } else {
        	$("fieldset#signin_menu").toggle();
        	$("#loginlnk").toggleClass("menu-open");
        	$("#loginemail").focus();
        }
        e.preventDefault();
    });

    $("fieldset#signin_menu").mouseup(function() {
        return false
    });
    $(document).mouseup(function(e) {
        if($(e.target).parent("#loginlnk").length==0) {
            $("#loginlnk").removeClass("menu-open");
            $("fieldset#signin_menu").hide();
        }
        if($(e.target).parent("#loginlnk").length==0) {
            $("#accountlnk").removeClass("menu-open");
            $("div#account_menu").hide();
        }
    });
    
    $("#accountlnk").click(function(e){
    	if($("#accountlnk").hasClass('menu-open')){
        	$("#accountlnk").removeClass("menu-open");
            $("div#account_menu").hide();
        } else {
        	$("div#account_menu").toggle();
        	$("#accountlnk").toggleClass("menu-open");
        }
        e.preventDefault();
    });
    
    $("div#account_menu").mouseup(function() {
        return false
    });
    
    $("#logoutlnk").click(function(e){
    	var uri = $(this).attr('href');
    	$.get(uri,{},function(){
    		window.location.reload();
    	});
    	e.preventDefault();
    });
    if($("#register").length > 0) {
    	$("#parent_y").click(function(e){
    		if($("#parentbox").is(':hidden')){
    			$("#parentbox").slideDown('fast');
    		}
    	});
    	$("#parent_n").click(function(e){
    		if($("#parentbox").is(':visible')){
    			$("#postcode,#youngestchild").val('');
    			$("#son,#daughter,#day,#boarding").attr('checked', false);
    			$("#parentbox").slideUp('fast');
    		}
    	});
    	$("#staff_y").click(function(e){
    		if($("#staffbox").is(':hidden')){
    			$("#staffbox").slideDown('fast');
    		}
    	});
    	$("#staff_n").click(function(e){
    		if($("#staffbox").is(':visible')){
    			//clear the values
    			$("#directoryid,#organisation,#position").val('');
    			$("#authorised_y").attr('checked',false);
    			$("#authorised_n").attr('checked',true);
    			$("#staffbox").slideUp('fast');
    		}
    	});
    	$("#organisation").autocomplete({appendTo:"#staffbox",source: "/member/organisations/",minLength: 2,select: function( event, ui ) {
				$("#directoryid").val(ui.item.id);
			}
		});
    	var memberRegister = $("#register").validate({
	    	errorElement: 'span',
	    	errorPlacement: function(error, element) {
	   	     	error.appendTo( element.parent("div") );
	   	   },
			submitHandler: function(form) {
	    		$(form).ajaxSubmit({
	    			beforeSubmit: preReg,
	    			success: postReg,
	    			clearForm: false,
	    			resetForm: false,
	    			type: 'post'
	    		});
	    	},
	    		rules: {
	    			realname: {required: true},
	    			email: {required: true,email:true},
	    			pword:{required:true,minlength:6},
	    			postcode:{required:function(element) {
	    				return ($("#parent_y").is(':checked') && !$("#nonuk").is(':checked')) ? true : false ;//!$("#nonuk").is(':checked');
	    		      	}
	    			},
	    			organisation:{required: "#staff_y:checked"},
	    			position:{required: "#staff_y:checked"},
	    			antispam:{required:true}
	    		},
	    		messages: {
	    			realname: {required: "Please enter your name"},
	    			email: {required: "Please enter your email address",email:"Please check the email address"},
	    			pword:{required: "Please enter a password",minlength:"6 or more characters"},
	    			postcode: {required: "Please enter a postcode or check the non uk box"},
	    			organisation:{required: "Please select your school"},
	    			position: {required: "Please tell us your job title"},
	    			antispam: {required:"Please enter the anti spam text"}
	    		}
	    });
    }
    
    var memberLogin = $("#signin").validate({
    	submitHandler: function(form) {
			$(form).ajaxSubmit({
		        beforeSubmit:  preLogin,  // pre-submit callback
		        success:       postLogin,  // post-submit callback
				clearForm: false,
				resetForm: false,
				type: 'post'
		    });
		},
			rules: {
				email: {required:true,email: true}
				
			},
   			messages: {
   				email: {required: "Please enter your email address",email: "Please enter a valid email address"}
   				}
	});
    
    if($("#schoolfilter").length > 0) {
    	//load up a default table
    	$("#schoolfilter").submit(function(e){e.preventDefault()}).change(function(){
    		var pcode = $("#postcode").val(), categoryid = $("#categoryid").val(), child = $("#child").val(), distance = $("#distance").val(), tdata = '';
    		if(pcode.length == 0){
    			pcode = $("#postcode").attr('placeholder');
    		}
    		$("#schooldirectory tbody").empty().append('<tr><td colspan="5" align="center"><img src="/assets/images/loadingAnimation.gif" width="208" height="13" alt="Loading..."></td></tr>');
    		$.getJSON('/services/RemoteDirectoryService.cfc?method=directoryFilter&returnformat=json',{postcode:pcode,categoryid:categoryid,child:child,distance:distance},function(data){
        		//console.log(data);
        		//loop over the data array to populate the table
    			$("#schooldirectory tbody").empty();
    			jQuery.each(data, function(i, obj){
        			//console.log(obj);
    				org = obj.ORGANISATION;
        			if(org.length > 30){
        				org = org.substring(0,30) + '...';
        			}
    				if(obj.ACCOUNTLEVEL != 'basic') {
    					tdata = '';
    					tdata = '<tr><td colspan="5" style="padding:0;"><table border="0" cellpadding="0" cellspacing="0" class="featuredtable"><tbody><tr>';
    					tdata += '<td style="width: 200px;"><a href="/directory/'+ obj.DIRECTORYID +'/" title="'+obj.ORGANISATION+'">'+org+'</a></td>';
    					tdata += '<td style="width:60px;">'+obj.ORGTYPE+'</td>';
	        			tdata += '<td>'+obj.AREA+'</td>';
	        			if(obj.BOYSAGE_START != 0 && obj.GIRLSAGE_START == 0) {
	        				tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+')</td>';
	        			} else if(obj.GIRLSAGE_START != 0 && obj.BOYSAGE_START == 0) {
	        				tdata += '<td style="width:150px;">Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
	        			} else if(obj.BOYSAGE_START !=0 && obj.GIRLSAGE_START != 0){
	        				tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+'), Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
	        			} else {
	        				tdata += '<td style="width:150px;">&nbsp;</td>';
	        			}
	        			
	        			tdata += '<td style="text-align: center; width: 50px;">'+obj.DISTANCE+'</td></tr>';
	        			if(obj.DIRIMAGE.length > 0){
	        				tdata += '<tr><td><img src="' + obj.DIRIMAGE + '" width="190"></td>';
	        				tdata += '<td colspan="4">'+ obj.INTROTEXT + '</td></tr>';
	        			}
    					tdata += '</tbody></table></td></tr>';
    				} else {
	    				tdata = '';
    					tdata = '<tr>';
	        			tdata += '<td style="width: 200px;"><a href="/directory/'+ obj.DIRECTORYID +'/" title="'+obj.ORGANISATION+'">'+org+'</a></td>';
	        			tdata += '<td style="width:60px;">'+obj.ORGTYPE+'</td>';
	        			tdata += '<td>'+obj.AREA+'</td>';
	        			//tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+'), Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
	        			if(obj.BOYSAGE_START != 0 && obj.GIRLSAGE_START == 0) {
	        				tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+')</td>';
	        			} else if(obj.GIRLSAGE_START != 0 && obj.BOYSAGE_START == 0) {
	        				tdata += '<td style="width:150px;">Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
	        			} else if(obj.BOYSAGE_START !=0 && obj.GIRLSAGE_START != 0){
	        				tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+'), Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
	        			} else {
	        				tdata += '<td style="width:150px;">&nbsp;</td>';
	        			}
	        			tdata += '<td style="text-align: center; width: 50px;">'+obj.DISTANCE+'</td>';
	        			tdata += '</tr>';
    				}
        			$("#schooldirectory > tbody").append(tdata);
        		});
    			$("#schooldirectory > tbody > tr:odd").addClass('odd');
    			$("#schooldirectory > tbody > tr:even").addClass('even');
    		});
        	
    	});
    	var pcode = $("#postcode").attr('placeholder'), categoryid = $("#categoryid").val(), child = $("#child").val(), distance = $("#distance").val();
    	$.getJSON('/services/RemoteDirectoryService.cfc?method=directoryFilter&returnformat=json',{postcode:pcode,categoryid:categoryid,child:child,distance:distance},function(data){
    		//console.log(data);
    		$("#schooldirectory tbody").empty();
			jQuery.each(data, function(i, obj){
    			//console.log(obj);
				org = obj.ORGANISATION;
    			if(org.length > 30){
    				org = org.substring(0,30) + '...';
    			}
				if(obj.ACCOUNTLEVEL != 'basic') {
					tdata = '';
					tdata = '<tr><td colspan="5" style="padding:0;"><table border="0" cellpadding="0" cellspacing="0" class="featuredtable"><tbody><tr>';
					tdata += '<td style="width: 200px;"><a href="/directory/'+ obj.DIRECTORYID +'/" title="'+obj.ORGANISATION+'">'+org+'</a></td>';
					tdata += '<td style="width:60px;">'+obj.ORGTYPE+'</td>';
        			tdata += '<td>'+obj.AREA+'</td>';
        			//tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+'), Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
        			if(obj.BOYSAGE_START != 0 && obj.GIRLSAGE_START == 0) {
        				tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+')</td>';
        			} else if(obj.GIRLSAGE_START != 0 && obj.BOYSAGE_START == 0) {
        				tdata += '<td style="width:150px;">Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
        			} else if(obj.BOYSAGE_START !=0 && obj.GIRLSAGE_START != 0){
        				tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+'), Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
        			} else {
        				tdata += '<td style="width:150px;">&nbsp;</td>';
        			}
        			tdata += '<td style="text-align: center; width: 50px;">'+obj.DISTANCE+'</td></tr>';
        			if(obj.DIRIMAGE.length > 0){
        				tdata += '<tr><td><img src="' + obj.DIRIMAGE + '" width="190"></td>';
        				tdata += '<td colspan="4">'+ obj.INTROTEXT + '</td></tr>';
        			}
					tdata += '</tbody></table></td></tr>';
				} else {
					tdata = '';
					tdata = '<tr>';
        			tdata += '<td style="width: 200px;"><a href="/directory/'+ obj.DIRECTORYID +'/" title="'+obj.ORGANISATION+'">'+org+'</a></td>';
        			tdata += '<td style="width:60px;">'+obj.ORGTYPE+'</td>';
        			tdata += '<td>'+obj.AREA+'</td>';
        			//tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+'), Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
        			if(obj.BOYSAGE_START != 0 && obj.GIRLSAGE_START == 0) {
        				tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+')</td>';
        			} else if(obj.GIRLSAGE_START != 0 && obj.BOYSAGE_START == 0) {
        				tdata += '<td style="width:150px;">Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
        			} else if(obj.BOYSAGE_START !=0 && obj.GIRLSAGE_START != 0){
        				tdata += '<td style="width:150px;">Boys ('+obj.BOYSAGE_START+'-'+obj.BOYSAGE_END+'), Girls ('+ obj.GIRLSAGE_START + '-' + obj.GIRLSAGE_END+')</td>';
        			} else {
        				tdata += '<td style="width:150px;">&nbsp;</td>';
        			}
        			tdata += '<td style="text-align: center; width: 50px;">'+obj.DISTANCE+'</td>';
        			tdata += '</tr>';
				}
    			$("#schooldirectory > tbody").append(tdata);
    		});
			$("#schooldirectory > tbody > tr:odd").addClass('odd');
			$("#schooldirectory > tbody > tr:even").addClass('even');
		});
    }
    
    if($("#opendayfilter").length > 0) {
    	$("#opendayfilter").submit(function(e){e.preventDefault()}).change(function(){
    		var pcode = $("#postcode").val(), categoryid = $("#categoryid").val(), child = $("#child").val(), distance = $("#distance").val(), tdata = '';
    		if(pcode.length == 0){
    			pcode = $("#postcode").attr('placeholder');
    		}
    		$("#schoolopenday tbody").empty().append('<tr><td colspan="5" align="center"><img src="/assets/images/loadingAnimation.gif" width="208" height="13" alt="Loading..."></td></tr>');
    		$.get('/opendays/site/filter/',{postcode:pcode,categoryid:categoryid,child:child,distance:distance},function(data){
    			$("#schoolopenday tbody").empty();
    			$("#schoolopenday tbody").append(data);
    		});
    	});
    	var pcode = $("#postcode").attr('placeholder'), categoryid = $("#categoryid").val(), child = $("#child").val(), distance = $("#distance").val();
    	$.get('/opendays/site/filter/',{postcode:pcode,categoryid:categoryid,child:child,distance:distance},function(data){
			$("#schoolopenday tbody").empty();
			$("#schoolopenday tbody").append(data);
		});
		$("#schoolopenday > tbody > tr:odd").not('.daterow').addClass('odd');
		$("#schoolopenday > tbody > tr:even").not('.daterow').addClass('even');
    }
    
    if($("#dirtabs").length > 0){
    	$( "#dirtabs" ).tabs();
    }
    
    if($("a.calevent").length > 0){
    	$("a.calevent").colorbox({ 
    		data: {ajax:true},
    		width: 640,
			height: 480,
			iframe: true
		});
    }
    if($("a.newsitem").length > 0){
    	$("a.newsitem").colorbox({ 
    		data: {ajax:true},
    		width: 640,
			height: 580,
			iframe: true
		});
    }
    
    if($("#dirfrm").length > 0) {
    	$("input[id$='_start'],input[id$='_end']").blur(function(){
			if($("input[id$='_start'],input[id$='_end']").val() == '' || isNaN($("input[id$='_start'],input[id$='_end']").val())){
				$(this).val(0);
			}
		});
		$("#addphotobtn").hover(function(){$(this).addClass('lnkhover')},function(){$(this).removeClass('lnkhover')}).click(function(e){
			e.preventDefault();
			var strPIndex = $("#photoindex").val();
			var arrIndex = strPIndex.split(',');
			var lastIndex = arrIndex.pop();
			var nextIndex = parseInt(lastIndex) + 1;
			var containerID = 'photouploadcontainer_' + nextIndex;
			arrIndex.push(lastIndex);
			arrIndex.push(nextIndex);
			if(arrIndex.length == 6){
				$("#addphotolnk").hide();
			}
			if(arrIndex.length < 7){
				$("#photouploadcontainer_").clone().insertBefore($("#addphotolnk")).attr("id",containerID);
				$("#photoindex").val(arrIndex.join());
				var dirimgid = 'dirimage_' + nextIndex;
				$("#" + containerID + " label[for='dirimage_']").attr('for',dirimgid);
				$("#" + containerID + " input[id='dirimage_']").attr('id',dirimgid);
				$("#" + containerID + " input[name='dirimage_']").attr('name',dirimgid);
			} else {
				$.blockUI({message: '<div class="quick-alert-warning">A maximum of 6 photos may be uploaded.<br /><input type="button" id="photobtnok" value="OK" class="ui-state-default ui-corner-all" /></div>',css:{border: '0',backgroundColor:'transparent'}});
				$('#photobtnok').hover(function(){$(this).addClass('ui-state-hover')},function(){$(this).removeClass('ui-state-hover')}).click(function(evt) {
	            $.unblockUI();
	            evt.preventDefault();
	        });
			}
		});
    	
    	var dirForm = $("#dirfrm").validate({
    		submitHandler: function(form) {
    			$(form).ajaxSubmit({
    				url: $("#dirfrm").attr('action') + '?ajax=true',
			        beforeSubmit:  preDir,  // pre-submit callback
    		        success:       postDir,  // post-submit callback
    				clearForm: false,
    				resetForm: false,
    				type: 'post'
    		    });
    		},
    		rules: {
    			organisation: {required: true,minlength: 4},
				address1: {required: true, minlength: 4},
				postcode: {required: true, minlength: 5},
				contactemail: {required: true, email: true},
				website: {required: true},
				boysage_start: {required: false,digits: true},
				boysage_end: {required: false, digits: true},
				girlsage_start: {required: false,digits: true},
				girlsage_end: {required: false, digits: true}
			},
			messages: {
				organisation: {required: "Please enter the School name.", minlength: "Please enter a minimum of 4 characters"},
				address1: {required: "Please enter the first line of the address.", minlength: "Please enter a minimum of 4 characters"},
				postcode: {required: "Please enter the full postcode", minlength: "Please enter the full postcode (min 5 characters)"},
				contactemail: {required: "Please enter an email address",email: "Please check the email address"},
				website: {required: "Please enter your website address"},
				boysage_start: {digits: "Please enter a number only"},
				boysage_end: {digits: "Please enter a number only"},
				girlsage_start: {digits: "Please enter a number only"},
				girlsage_end: {digits: "Please enter a number only"}
			}
    	});
    }
    
    if($("#eventfrm").length > 0){
    	var calEdit = $("#eventfrm").validate({
        	submitHandler: function(form) {
    			$(form).ajaxSubmit({
    				url: $("#eventfrm").attr('action') + '?ajax=true',
			        beforeSubmit:  preCalEvent,  // pre-submit callback
    		        success:       postCalEvent,  // post-submit callback
    				clearForm: false,
    				resetForm: false,
    				type: 'post'
    		    });
    		},
    		rules: {
				eventstartdate: {required: true},
				eventstarttime: {required: true},
				eventtitle: {required: true}
			},
			messages: {
				eventstartdate: {required: "Please enter the event date in dd/mm/yy format."},
				eventstarttime: {required: "Please enter the event starttime in 24h (HH:mm) format"},
				eventitle: {required: "Please enter an event title"}
			}
    	});
    	
    	$("#closefbox,#cancelfrm").click(function(){
			parent.$.colorbox.close();
	        return false;
		});
		
		//var date = Date.parse($("#eventstartdate,#eventenddate").val());
		$("#eventstartdate,#eventenddate").addClass("calbg").datepicker({dateFormat:"dd/mm/yy"});
	}
    if($("#storyfrm").length > 0){
    	$("a.movie_box").colorbox({
			width : 770,
			height : 550,
			iframe: true
		});
    	
    	var newsEdit = $("#storyfrm").validate({
        	submitHandler: function(form) {
    			$(form).ajaxSubmit({
    				/*url: $("#storyfrm").attr('action') + '?ajax=true',*/
			        beforeSubmit:  preNewsItem,  // pre-submit callback
    		        success:       postNewsItem,  // post-submit callback
    				clearForm: false,
    				resetForm: false,
    				type: 'post',
    				dataType:'json'
    		    });
    		},
    		rules: {
				
			},
			messages: {
				
			}
    	});
    	
    	$("#closefbox,#cancelnewsfrm").click(function(){
			parent.$.colorbox.close();
	        return false;
		});
		
		//var date = Date.parse($("#eventstartdate,#eventenddate").val());
		$("#newsdate,#displayfrom").addClass("calbg").datepicker({dateFormat:"dd/mm/yy"});
		
		$("#addphotobtn").click(function(){
			var strPIndex = $("#photoindex").val();
			var arrIndex = strPIndex.split(',');
			var lastIndex = arrIndex.pop();
			var nextIndex = parseInt(lastIndex) + 1;
			var containerID = 'photouploadcontainer_' + nextIndex;
			arrIndex.push(lastIndex);
			arrIndex.push(nextIndex);
			if(arrIndex.length == 4){
				$("#addphotolnk").hide();
			}
			if(arrIndex.length < 5){
				$("#photouploadcontainer_").clone().insertBefore($("#addphotolnk")).attr("id",containerID);
				$("#photoindex").val(arrIndex.join());
				var newsimgid = 'newsimage_' + nextIndex;
				var captionid = 'caption_' + nextIndex;
				$("#" + containerID + " label[for='newsimage_']").attr('for',newsimgid);
				$("#" + containerID + " input[id='newsimage_']").attr('id',newsimgid);
				$("#" + containerID + " input[name='newsimage_']").attr('name',newsimgid);
				$("#" + containerID + " label[for='caption_']").attr('for',captionid);
				$("#" + containerID + " input[id='caption_']").attr('id',captionid);
				$("#" + containerID + " input[name='caption_']").attr('name',captionid);
			} else {
				$("#newsformcontainer").block({message: '<div class="quick-alert-warning">A maximum of 4 photos may be uploaded.<br /><input type="button" id="ok" value="OK" class="ui-state-default ui-corner-all" /></div>',css:{border: '0',backgroundColor:'transparent'}});
				$('#ok').hover(function(){$(this).addClass('ui-state-hover')},function(){$(this).removeClass('ui-state-hover')}).click(function() {
	            $("#newsformcontainer").unblock();
	            return false;
	        });
			}
			return false;
		});
	}
 }); 
