//Add hasJS class to HTML to tell the stylesheet that javascript is available
(function(){var a=document.documentElement;if(!a.className)a.className="hasJS dS";if(!a.className.match(/\bhasJS\b/))a.className+=" hasJS";if(!a.className.match(/\bdS\b/))a.className+=" dS";setTimeout(function(){a.className=a.className.replace(/(\s)?\bdS\b/,"")},2E3)}());


var _gaq = _gaq || [];//Initialising google analytics _gaq object
var today = new Date();
var todayDate = today.getDate();
var todayMonth = today.getMonth() + 1;
var todayYear = today.getFullYear();
var todayAsyyyyMMdd = (todayYear + ((todayMonth < 10)?"0":"") + todayMonth + ((todayDate < 10)?"0":"") + todayDate )*1;
//Regexes for matching urls
var urlMatch = {
	document: /^(http:\/\/www\.armadale\.wa\.gov\.au.*?|\/.*?|)\/files\/(\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-Z0-9]{12}\b)\/(.*?\.(pdf|docx|doc|xlsx|xls))((?=#)|$)/i,
	absoluteLink: /https?:\/\//i,
	armadaleDomain: /https?:\/\/[^\/]*\.armadale\.wa\.gov\.au/i,
	armadaleMainSite: /https?:\/\/www\.armadale\.wa\.gov\.au/i
}

clearCheckboxes = function(){
	$("input[type=radio], input[type=checkbox]").attr("checked", false);
}


$(document).ready(function(){
	/*
		Sometimes the "ready" event fires too soon and before the body element is available
		when viewing through an HTA in a kiosk environment. The following code, checks to 
		see if the body is available before continuing. If it isn't available yet, we use a 
		setTimeout to execute after 0 milliseconds (i.e. as soon as possible).
		This is a bug in mshta.exe - the body becomes available immediately after "readyState" 
		changes	to "interactive". In reality, it should be available before the onReadyStateChange.
		Note: this only applies when the IFRAME you are viewing the page through has the attribute
		application="no"
	*/
	if($("body").length == 0)
	{
		setTimeout(function(){	
			onBodyAvailable();
		}, 0);
	} else 
	{
		onBodyAvailable();
	}
});

function onBodyAvailable(){

	//Deprecated, will be removed when IE6 support is dropped
	menuFix();
	
	//Replace filesize labels with icons
	$("span.filesizeLabel").each(function(){
		text = $(this).html()+"";
		result = text.replace(/( \()|(\))/g, "");
		$(this).parent().attr("title", result);
		className = (result.substr(0, 3).toLowerCase());
		$(this).html('<div class="exticon ext_'+className+'">'+text+'</div>');
		$(this).addClass("asicon");
	});

	//Replace audio links with popup references
	$(".audioLink li a").bind("click", function(){
		popup($(this).attr("href"),'fixed',185,372);
		return false;									
	});
	
	//Make popable link items in the navigation pop
	$("div#linksThatPop_Meta a").each(function(){
	    var link = $(this).attr("rel");
	    $("div#leftNav a[href="+link+"]").addClass("jspopup").attr("target","_blank");		
	});
	
	$("a.jspopup").click(function(){
		popup(this.href,'fixed2',600,800);
		return false;
	});
	
	//Modify search form behaviour
	$("div#siteSearchHeader").each(function(){
		var keywords = $(".defaultValue input[type=hidden]", this).val();
		var container = this;
		$("input.searchbox", container).data("hasfocus", false);
		$(".hasFocus input[type=hidden]", container).val("false");	
		$("input.searchbox[value=]", container).val(keywords);
		$("input.searchbox", container).focus(function(){
			$(this).data("hasfocus", true);
			if($(this).val() == keywords){
				$(this).val("");
			}
		});
		$("input.searchbox", container).blur(function(){
			$(this).data("hasfocus", false);
			if($(this).val() == ""){
				$(this).val(keywords);
			}
		});
		$("label a", container).click(function(){
			if($("input.searchbox", container).val() != keywords && $("input.searchbox", container).val() != "" ){
				$("input.quickSearchBtn", container).click();
			} else {
				document.location = $(this).attr("href");	
			}
			return false;
		});
		$("input.quickSearchBtn", container).focus(function(){
			$(this).data("hasfocus", true);
		});
		$("input.quickSearchBtn", container).blur(function(){
			$(this).data("hasfocus", false);
		});
		
		$("input.quickSearchBtn", container).click(function(){	
			if(($("input.searchbox", container).val() == keywords || $("input.searchbox", container).val() == "") && $("input.searchbox", container).data("hasfocus") ){
				document.location = $("label a", container).attr("href");
				return false;
			} else if($("input.searchbox", container).data("hasfocus")){
				$(".hasFocus input[type=hidden]", container).val("true");			
			}
		});
		
		$("form").submit(function(){
			if(!$("input.searchbox", container).data("hasfocus") && !$("input.quickSearchBtn", container).data("hasfocus")){
				$("input.searchbox", container).val(keywords);
			}
		})
		
	});
	
	
	if(typeof(TJK_ToggleDL_enabled) != "undefined")TJK_ToggleDL();
	
	errors = new Array();
	$("ul.errorlist li").each(function(){
		html = $(this).html();
		result = html.match(/^(?:')[\s\S]*?(?:')/ig);
		if(result != null && result.length > 0){
			errors.push(result[0].replace(/'/g, "").toLowerCase());
		}
	});
	
	if($("ul.errorlist li").length > 0)
	{
		$("ul.errorlist").css({"paddingTop":5,"paddingBottom":5});
		$("ul.errorlist").before("<hr /><h4>Please correct the following errors</h4>");
	}
	
	//Mark failed CAPTCHA field
	if($("div.captchafail").size() > 0){
		errors.push("CAPTCHA fail");
		$("div.captcha input").addClass("error").val("");
	}
	
	$(".formTable").each(function(){
		$("tr", this).each(function(){
			labels = $("label", this);
			inputs = $("input, textarea", this);
			inputid = $(inputs).attr("name");
			$(inputs).attr("id", inputid);
			$(labels).attr("for", inputid);
			
			mainLabel = $(labels).eq(0).html();
			if(mainLabel != null){
				newMainLabel = mainLabel.replace(/\*/g, "");
				if(newMainLabel.length < mainLabel.length){
					$(labels).eq(0).html(newMainLabel);
					$(inputs).after('<span class="requiredField">*</span>');
				}
				$(".formTable input[type=text]").attr("size","40");
				strippedLabel = ($(".labeltext",this).html()||'').trim().toLowerCase();
				if($.inArray(strippedLabel,errors) > -1){
					$(inputs).addClass("error");
				}
			}
			
			$("textarea", this).each(function(){
				testa = ($("label", this.parentNode.parentNode).html()||'').toLowerCase().indexOf("message") >= 0;
				testb = ($("label", this.parentNode.parentNode).html()||'').toLowerCase().indexOf("comments") >= 0;
				if( testa || testb){
					$(this).attr({"cols":45,"rows":10});				
				} else {
					$(this).attr({"cols":40,"rows":5});
				}
			});
			
			
		});
		//Move "requiredField" labels on radio buttons and checkboxes
		$("td.answer", this).each(function(){
			if($("table span.requiredField",this).length > 0){
				$(this).prev("td").append('<span class="requiredField">*</span>');
			}
			$("table label", this).each(function(){
				html = $(this).html();
				$(this).siblings("input").wrap("<label></label>");
				$(this).siblings("label").append(html);
				$(this).remove();
			});
		});
		//Reset form values if no errors (i.e. this is the first time we've used the form)
		if($("ul.errorlist li",this).length == 0){
			clearCheckboxes();			
		}
		
		
		//Make modifications to the facilities for hire form if it exists
		if($('#facilitiesforhireenquiry').length)
		{
			var title = $('div.innerMainContent > h2:first-child').text()+"";
			$('span.ffh_enqtype').html('about '+title+' ');
			$('table.formTable tr:first-child').each(function(){
				if($('label',this).text()+"" == "Facility:")
				{
					$('input[type=text]',this)
						.val(title)
						.blur(function(){
							$(this).val($('div.innerMainContent > h2:first-child').text()+"");
						});
					$(this).css({
						position: 'absolute',
						left: -5000,
						zIndex: -1 
					});
				}
			});
		}
		
		
		
	});

	//Auto-Collapse accordian forms
	$("div.formAccordian").each(function(){
		if($("ul.errorlist li",this).length == 0){
			$(this).hide();
		} else {
			$(this).prev("div.formAccordianTrigger").hide();
		}
		$(this).prev("div.formAccordianTrigger").click(function(){
			$(this).next("div.formAccordian").slideDown(1000);
			$(this).slideUp(1000);
		});
	});
	
	
	if(errors.length > 0){
		formElement = $(".formTable, .surveyForm");
		if($(formElement).length > 0)
		{
			name = "#"+$(formElement).get(0).parentNode.id;
			$(name).prepend('<div><a name="'+name+'"></a></div>');
			document.location = name;
		}
	}
	
	//Find datemarkers and make them "new" if the date is correct...
	$("ul.audioLink li a span.datemarker").each(function(){
		fullClass = $(this).attr("class")+"";
		var myregexp = /d(\d{8})/i;
		var match = myregexp.exec(fullClass);
		if (match != null) {
			result = match[1] * 1;
			if(todayAsyyyyMMdd <= result){
				$(this).html(" (new)");
				$(this).addClass("isNew");
			}
		}

	});
	
	
	//Initialise Google Analytics code
	_gaq.push(['_setAccount', 'UA-1169654-1']);
	_gaq.push(['_trackPageview']);
	(function() {
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();
	
	
	//Google Analytics Click Tracking
	if($('.splashLayout').length > 0)
	{
		//Tracking for home page elements
		
		//What's new items
		$('#whatsNew .block a').click(function(){
			var header = $(this).parent().parent().find('.hdr a');
			var atext = $(header).text();
			var ahref = $(header).attr('href');
			_gaq.push(['_trackEvent','Home.WhatsNew.Clickthrus',atext,ahref]);
		});
		
		//Quicklinks
		$('#quicklinks ul li a').click(function(){
			var atext = $(this).text();
			var ahref = $(this).attr('href');
			_gaq.push(['_trackEvent','Home.Quicklinks.Clickthrus',atext,ahref]);
		});
		
		//Homepage ads 
		if($('.splashFeature a').length > 0)
		{			
			var adName = $('.splashFeature .splashFeatureName').text();
			var ahref = $('.splashFeature a').attr('href');
			_gaq.push(['_trackEvent','Home.Ads.Feature.Impressions',adName,ahref]);
			
			$('.splashFeature a').click(function(){
				_gaq.push(['_trackEvent','Home.Ads.Feature.Clickthrus',adName,ahref]);
			});
		}
		
		//Events
		$('#upComingEvents .block .hdr a').each(function(){
			var adName = $(this).text();
			var ahref = $(this).attr('href');
			_gaq.push(['_trackEvent','Home.Ads.Events.Impressions',adName,ahref]);			
		});		
		$('#upComingEvents .block .hdr a').click(function(){
			var adName = $(this).text();
			var ahref = $(this).attr('href');
			_gaq.push(['_trackEvent','Home.Ads.Events.Clickthrus',adName,ahref]);			
		});
		$('#upComingEvents .more a').click(function(){
			var adName = $(this).text();
			var ahref = $(this).attr('href');
			_gaq.push(['_trackEvent','Home.Ads.Events.Clickthrus',adName,ahref]);			
		});
		
		//Online Tools
		$('#onlineTools .block a').click(function(){
			var aTitle = $(this).attr('title');
			var ahref = $(this).attr('href');
			_gaq.push(['_trackEvent','Home.OnlineTools.Clickthrus',aTitle,ahref]);	
		});
		
		//Out for Comment
		$('#outForComment a').click(function(){
			var aTitle = $(this).text();
			var ahref = $(this).attr('href');
			_gaq.push(['_trackEvent','Home.OutForComment.Clickthrus',aTitle,ahref]);
		});
		
		//Media Releases
		$('#mediaReleases a').click(function(){
			var aTitle = $(this).text();
			var ahref = $(this).attr('href');
			_gaq.push(['_trackEvent','Home.MediaReleases.Clickthrus',aTitle,ahref]);	
		});			
	}
		
	//Google Analytics Documents and external links
	$('a').click(function(){
		var recordAnalytic = false;		
		var link = $(this).attr("href");
		var category = "";
		var action = "";
		var label = "";

		if (urlMatch.absoluteLink.test(link)) {
			//url is absolute
			if(!urlMatch.armadaleMainSite.test(link))
			{
				//url is not on the main www site
				if(urlMatch.armadaleDomain.test(link))
				{
					//This site is on our domain but is external to this one
					category = "Links.External.Armadale.Clicked";
				} else {
					//This is a link to an external site
					category = "Links.External.NonArmadale.Clicked";
				}
				action = link;
				label = $(this).text();
				recordAnalytic = true;
			}
		}			
		if(!recordAnalytic)
		{
			//Try match as a document
			var match = urlMatch.document.exec(link);
			if (match != null) {
				category = "Documents.Internal.Clicked";
				action = match[2];//GUID
				label = match[3];//Filename
				recordAnalytic = true;
			}
		}
		if(recordAnalytic)
		{
			_gaq.push(['_trackEvent',category,action,label]);	
		}	
	});
}



// Functions
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
String.prototype.titleCase = function () {
	var special_words = new Array('and',
					'the',
					'to',
					'for',
					'is',
					'in',
					'a',
					'at',
					'an',
					'from',
					'by',
					'if',
					'of');

	var str = "";
	var wrds = this.split(" ");
	for(keyvar in wrds)
	{
		keyvar = keyvar.toLowerCase();
		if(special_words.indexOf(keyvar) === false){
			str += ' ' + keyvar;
		} else {
			str += ' ' + wrds[keyvar].substr(0,1).toUpperCase()
			+ wrds[keyvar].substr(1,wrds[keyvar].length);
		}
	}
   return str;
}

refreshCaptchas = function(){
	if(typeof(document.captchaurl) == "undefined"){
		document.captchaurl = $(".captchaImage img").attr("src");
	}
	newURL = document.captchaurl + "?rand=" + Math.random();	
	$(".captchaImage img").attr("src", newURL);
	return false;
}

function popup(strURL,strType,strHeight,strWidth,winName) {
	var strOptions="";
	if (strType=="console") strOptions="resizable,height="+strHeight+",width="+strWidth;
	if (strType=="fixed") strOptions="status,height="+strHeight+",width="+strWidth;
	if (strType=="fixed2") strOptions="status,scrollbars,resizable,height="+strHeight+",width="+strWidth;
	if (strType=="fixed3") strOptions="status,scrollbars,height="+strHeight+",width="+strWidth;
	if (strType=="elastic") strOptions="toolbar,menubar,scrollbars,resizable,location,height="+strHeight+",width="+strWidth;
	window.open(strURL, winName, strOptions);
}

//Deprecated, will be removed when IE6 support drops off
function menuFix() {
	var sfEls = document.getElementById("leftNav");
	if(sfEls != null) sfEls = sfEls.getElementsByTagName("LI");
	if(sfEls != null){
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
			this.className+=(this.className.length>0? " ": "") + "sfhover";
			}
			// event added to keep menu items from disappearing
			sfEls[i].onMouseDown=function() {
			this.className+=(this.className.length>0? " ": "") + "sfhover";
			}
			// event added to keep menu items from disappearing
			sfEls[i].onMouseUp=function() {
			this.className+=(this.className.length>0? " ": "") + "sfhover";
			}
			sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp("( ?|^)sfhover\\b"), "");
			}
		}
	}
}
