var ie6	= $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);

// onload
$(function() {
	$("body").addClass("js");

	if(!($.browser.msie) || ($.browser.msie && $.browser.version > 5.5)){
		if($(".selectable").size() > 0){
			selectCityArea.init();
		}
		
		$(".tool li.area-chooser").openTab(false, function(){
			$(this).expand("#f2f2f2");
		});
		
		$(".elsewhere").fixPushes();

		$(".tabbed").handleTabbedListing();

		$(".tool li.contact").openTab(true, function(){
			$(this).handleContact(arguments[0]);
		});

		$(".tool li.report").openTab(true, function(){
			$(this).handleReport(arguments[0]);
		});

		$("a.page-anchor").pageAnchor();

		$("dl.qa").getQA();

		$("body").applyAdvancedCss();
		
		$("div.search").handleSearch();
		
		$("div.news-list").handleNews();

		$(".unit-type").handleServiceUnitType();
		
		$("ul.more").handleMoreListings();
		
	}
});
jQuery.fn.handleMoreListings = function(){
	this.find("li").hover(function(){
		$(this).addClass("hover");
		$(this).click(function(){
			document.location.href = $(this).find("a").attr("href");
		});
	},function(){
		$(this).removeClass("hover");
	});
};
jQuery.fn.handleServiceUnitType = function(){
	if(this.size() > 0){
		var height = (($(".unit-type").offset().top + $(".unit-type").height()) - $("#content").offset().top) / 10 + "em";
		if(($(".unit-type").offset().top + $(".unit-type").height())  > $("#content").height()){ 
			if(ie6){
				$("#content").css("height", height);
			}else{
				$("#content").css("min-height", height);
			}
		}
	}
	return this;
};
jQuery.fn.handleNews = function(){
	$(this).find("div").each(function(i){
		var href = $(this).find("h4 a");
		$(this).find("p").click(function(){
			document.location.href = href.attr("href");
		}).hover(
			function(){
				href.addClass("hover");
			},
			function(){
				href.removeClass("hover");
			}).addClass("clickable");
	});
	this.find("p[class^='image']:contains('')").addClass("no-text");
	return this;
};
jQuery.fn.handleSearch = function(){
	if(this.size() > 0){
		
		// div.search
		var cont = this;
		
		// find documents in searchresult and sets negative margin = dt.height
		cont.find("dd.icon").each(function(i){
			if($(this).prev("dt").height() > 23){
				$(this).css("margin-top", "-" + $(this).prev("dt").height()+ "px");
			}
		});
		
		cont.find("dd.special dd.map").not(".link").each(function(i){
			$(this).parent("dl").addClass("with-map");
			$(this).parent("dl").parent("dd").prev("dt").addClass("with-map");
			$(this).parent("dl").parent("dd").next("dd.date").addClass("with-map");
			$(this).css("margin-top", "-" + $(this).prev("dt").height()+ "px");
		});
		
		// talk between input
		var input = cont.find("input");
		var headInput = $("#head input");
		
		input.keyup(function(){
			headInput.val(input.val());
		});
		
		headInput.keyup(function(){
			input.val(headInput.val());
		});	
	}
	return this;
};
jQuery.fn.handleReport = function(href){
	var errors = $(this).checkForms();
	errors = $(this).checkCopySender(errors);
	$(this).submitForm(errors, href);
	$('html,body').animate({scrollTop: $(this).offset().top - 30}, 500);
};
jQuery.fn.handleContact = function(href){
	var errors = $(this).checkForms();
	errors = $(this).checkCopySender(errors);
	$(this).submitForm(errors, href);
};
jQuery.fn.openTab = function(expand, callback){
	if(this.size() > 0 || ($(this).find("a").size() > 0 && $(this).find("a").attr("href").indexOf("#"))){
		this.each(function(){
			var link = $(this).find("a");
			var href = link.attr("href");
			var target = href.substring(href.indexOf("#")+1);
			var hrefWithoutTarget = href.substring(0, href.indexOf("#"));
			var loadable = true;
			$(this, link).toggle(function(){
				if(loadable){
					link.addClass("open");
					loadable = false;
					$(document.createElement("div")).load(hrefWithoutTarget + "&"+ keyInternalNoContent +"= #"+ target, function(){
						
						var tabContent = $(this).children("div");
						link.parent("li").parent("ul").after(tabContent);
						
						selectCityArea.init();
						
						tabContent.find("button").removeAttr("onclick");
						tabContent.find("input:text").submitOnEnterClick();
						
						if(expand){
							if(target.indexOf("primary") === 0){
								tabContent.expand("#fff");
							}else{
								tabContent.expand("#f2f2f2");
							}
						}											
						callback.call(tabContent, hrefWithoutTarget + "&"+ keyInternalNoContent);						
					});
				}
				return false;
			}, function(){
				$("#" + target).collapse(0, true, function(){
					loadable = true;
					link.removeClass("open"); 
				});
				return false;
			});
		});
	}
	return this;
};
jQuery.fn.handleMap = function() {
	//var queryString = $(this).attr("src").replace(/^[^\?]+\??/,'');
	//var params = parseQuery( queryString );
    this.each(function() {
		var $cont = $(this);
		$cont.click(function(){
			$(this).thinMap(800, 500);
		});
	});
	return this;
};
jQuery.fn.handleSlideshow = function(){
	if(this.size() > 0 && this.css("overflow") === "hidden"){
		var con = this;
		var path = "/" + con.find("img").attr("src");
		con.height(con.height());
		$.getJSON(document.location.pathname +"?" + keyJson +"=&"+ keySlideShow +"=", function(data){
			$.each(data.SlideShowImages, function(i,item){

				// check if image is the first
				if(path != item.Path){

					// Create paragraph
					var p = $(document.createElement("p"))
						.css("opacity", "0")
						.text(item.Description)
						.appendTo(con);

					// Create image
					$(document.createElement("img"))
						.attr("src", item.Path)
						.attr("alt", item.AlternateText)
						.prependTo(p);
				}

			});
			con.cycle({ 
					fx:			'fade',
					speedIn:	600,
					speedOut:	600,
					speed:		(data.TimeOutSeconds * 1000),
					cleartype:	true
				});
		});
	}
	return this;
};
jQuery.fn.getFilter = function(){
	if(this.size() > 0){
		var cont = this;
		var elLocal = this.find("li.local :radio:last");
		if(!elLocal.is(":checked")){
			this.find("li.local div").hide();
		}
		elLocal.click(function(){
			if($(this).is(":checked")){
				$(this).parent("p").parent("li").find("div").expand("#fff");
			}
		});
		this.find("li.local :radio:first").click(function(){
			if($(this).is(":checked")){
				$(this).parent("p").parent("li").find("div").hide(200)
					.find(":checkbox").attr("checked", "");
			}
		});
		if($("li.local :checkbox:checked").size() === 0){
			$("li.local p").hide();
		}else{
			$("li.local p").expand("#fff");
		}
		this.find("li.local :checkbox").click(function(){
			if($(this).is(":checked")){
				$(this).parent("li").find("p").expand("#fff");
			}else{
				$(this).parent("li").find("p").hide(200);
				$(this).parent("li").find("p :checkbox").attr("checked", "");
			}
		});
		if($("li.category :radio:first").is(":checked")){
			this.find("li.category div").hide();
		}
		this.find("li.category :radio:first").click(function(){
			if($(this).is(":checked")){
				$(this).parent("p").siblings("div").hide(200)
					.find(":checkbox").attr("checked", "");
				cont.find("li.category :radio:last").removeClass("checked")
			}
		});
		this.find("li.category :radio:last").click(function(){
			if(!$(this).hasClass("checked")){
				$(this).addClass("checked");
				$(this).parent("p").siblings("div").expand("#fff");
			}
		});

		if($("li.secondary-category :radio:first").is(":checked")){
			this.find("li.secondary-category div").hide();
		}
		this.find("li.secondary-category :radio:first").click(function(){
			if($(this).is(":checked")){
				$(this).parent("p").siblings("div").hide(200)
					.find(":checkbox").attr("checked", "");
			}
		});
		this.find("li.secondary-category :radio:last").click(function(){
			if($(this).is(":checked")){
				$(this).parent("p").siblings("div").expand("#fff");
			}
		});
	}
	return this;
};
jQuery.fn.getQA = function(){
	if(this.size() > 0){
		this.find("dd").hide();
		this.find("dt a").toggle(function(){
			$(this).addClass("active");
			$(this).parent("dt").next("dd").slideDown(200);
			return false;
		},function(){
			$(this).removeClass("active");
			$(this).parent("dt").next("dd").slideUp(200);
		});
		// Check if a 
		var terms = getSearchTerms(document.referrer);
		$.each(terms, function(){
			var linksThatHasTerm = $("dd:containsNotSensitive("+decodeURI(this)+")").prev("dt").find("a");
			if(linksThatHasTerm.size() > 0){
				linksThatHasTerm.each(function(){
					if(!$(this).hasClass("active")){
						$(this).click();
					}
				});
				$('html,body').animate({scrollTop: linksThatHasTerm.eq(0).offset().top - 10}, 500);
			}			
		});
	}
	return this;
};
function getSearchTerms(url) {
	if (url.indexOf("?") == -1){
		return [];
	}
	var params = url.substr(url.indexOf("?") + 1).split("&");
	for (var p in params) {
		var param = params[p].split("=");
		if (param.length < 2){
			continue;
		}
		if (param[0] == "q" || param[0] == "p") { // q= for Google, p= for Yahoo
			var query = decodeURIComponent(param[1].replace(/\+/g, " "));
			if (query[0] == "!"){
				query = query.slice(1);
			}
			var terms = [];
			$.each(query.split(/(".*?")|('.*?')|(\s+)/), function() {
				term = this.replace(/^\s+$/, "");
				if (term.length) {
					terms.push(term.replace(/^['"]/, "").replace(/['"]$/, ""));
				}
			});
			return terms;
		}
	}
	return [];
}
var targetButton = {
	find: function(root){
		var button = root.find("button");
		if(button.size() > 0){
			return button;
		}
		return (typeof(root.parent()) == "undefined") ? null : targetButton.find(root.parent());
	}
};
jQuery.fn.submitOnEnterClick = function(){
	this.keypress(function(e){
		if(e.keyCode == "13"){
			var targetEl = targetButton.find($(this).parent());
			targetEl.trigger("click");
			return false;
		}
	});
	return this;
};
var fixHash = {
	init: function(){
		if(document.location.hash){
			if($(document.location.hash).size() > 0){
				$("a[href='"+document.location.hash+"']").click();
			}else{
				var cityArea = cityAreaFromQuery.fetch(location.toString().replace("#","?"));
				
				/*
				if(cityArea && ($.cookie(keyCityAreaFriendlyId) != cityArea)){
					cityAreaContent.load(location.toString().replace("#","?"));
				}
				*/
			}
		}
		/*
		if((location.toString().indexOf("?"+keyCityAreaFriendlyId) === -1) && ($.cookie(keyCityAreaFriendlyId)) && ($(".area-chooser").size() > 0)){
			document.location.hash = keyCityAreaFriendlyId + "=" +$.cookie(keyCityAreaFriendlyId);
		}
		*/
	}
};
jQuery.fn.getIndex = function(){
	if(this.size() > 0){
		var topLink = this.find("p").not(".skipper").slice(this.find("p").not(".skipper").size()-1);
		this.find("p").not(".skipper").not(topLink).remove();
		topLink.addClass("");
	}
	return this;
};
jQuery.fn.pageAnchor= function(){
	if(this.size() > 0){
		this.click(function(){	
			var link = $(this);
			$('html,body').animate({scrollTop: $($(this).attr("href")).offset().top}, 500, function(){
				document.location.hash = link.attr("href");
			});
			return false;
		});
	}
	return this;
};
jQuery.fn.log = function (msg) {
	if(console){
		console.log("%s: %o", msg, this);
	}
  return this;
};
jQuery.fn.submitForm = function(errorArr, target){
	var holder = this;
	this.find("button").click(function(){
		if(errorArr.length > 0){
			for(index in errorArr){
				var label = $(errorArr[index]);
				var attrFor = label.attr("for");
				label.fadeOut("fast", function(){
					var warning = $(this).attr("title");
					$(this)
						.text("")
						.html("<strong>"+warning+" *</strong>")
						.fadeIn("fast");
				});
				$("#"+attrFor).addClass("error");
			}
			$('html,body').animate({scrollTop: $(errorArr[0]).siblings(":input:first").offset().top - 30}, 500, function(){
				$(errorArr[0]).siblings(":input").get(0).focus();
			});
			return false;
		}
		$(this).attr("disabled","disabled");
		var confirm = $(document.createElement("div"))
			.attr("id", "confirm")
			.css("height", holder.height())
			.css("width", holder.width())
			.css("opacity","0")
			.html("<p class=\"indicator\">&nbsp;</p>");
		holder.prepend(confirm);
		if(target.indexOf("secondary") > -1){
			confirm.fadeTo("fast", 1);
		}else{
			confirm.fadeTo("fast", 0.95);
		}

		var keyValue = inputFields.fetch($(this));

		$(confirm).load(target+" p.message", keyValue, function(){
			var closeHolder = $(document.createElement("p"));
			var close = $(document.createElement("a"))
				.html(textClose)
				.attr("href", "#")
				.click(function(){
					holder.find("input, textarea").val("");
					confirm.fadeOut("slow", function(){
						holder.find("button").removeAttr("disabled");
						confirm.remove();
						holder.siblings(".tool").find("li").trigger("click");
					});
					return false;
				});
				confirm.append(closeHolder.append(close));
		});
		return false;
	});
};

/*
jQuery.fn.scrollToElement= function (){
	if(this.size() > 0){
		this.click(function(){
			var target = $(".index h3:contains(\""+$(this).text()+"\")");
			var href = $(this).get(0).href.substring($(this).get(0).href.indexOf("#"));
			$('html,body').animate({scrollTop: $(target).offset().top}, 400, function(){
				document.location.hash = href;
			});
			return false;
		});
	}
	return this;
};
*/
jQuery.fn.handleTabbedListing = function(){
	if(this.size() > 0){
		this.find("div").each(function(i){
		
			// Find all h4
			if($(this).find("h4, h4.fn").size() > 0){

				// Create firstlevelUl
				var firstLevelUl = $(document.createElement("ul"));
				$(this).find("h4[id],h4.fn").each(function(i){
					var h4 = $(this);
					var firstLevelLi = $(document.createElement("li"));

					var aOne = $(document.createElement("a"));
					aOne.attr("href", "#"+h4.attr("id"));
					aOne.attr("id", h4.attr("id"));
					aOne.text(h4.text());
					firstLevelLi.append(aOne);
					firstLevelUl.append(firstLevelLi);
					aOne.toggle(function(){
						$(this).toggleClass("active");
						$(this).siblings("ul").slideDown(function(){
							$(this).find("li").show(200);
							if(!$(this).hasClass("history")){
								$(this).addClass("history");
								$(this).parent().find(".selected a").not($(this).parent().find(".selected div a")).trigger("click");
							}
						});
						return false;

					},function(){
						$(this).toggleClass("active");
						$(this).parents("li").find("li").parent("ul").slideUp("fast");
						return false;
					});

					if(h4.parent("div").find("h5").not(h4.parent("div").find("div h5")).size() > 0){
						var secondLevelUl = $(document.createElement("ul"));
						h4.parent("div").find("h5").not(h4.parent("div").find("div h5")).each(function(i){
							var h5 = $(this);
							var secondLevelLi = $(document.createElement("li")).hide();
							var aTwo = $(document.createElement("a"));
							aTwo.text(h5.text());
							aTwo.attr("href","#");
							secondLevelLi.append(aTwo).append(h5.siblings("div").get(0));
							secondLevelLi.find("div").css("opacity", "0");
							secondLevelUl.append(secondLevelLi);
							secondLevelUl.appendTo(firstLevelLi);
							h5.remove();
							var firstHeight = firstLevelUl.height();
							secondLevelUl.find("li:first").addClass("selected").addClass("first-child");
							aTwo.click(function(){
									$(this).parent("li").parent("ul").find("li.selected").removeClass("selected").find("div").animate({opacity: 0},100);
									var liHeight = firstHeight + $(this).parent("li").find("div").height() + $(this).height() + 20 + "px";
									$(this).parent("li")
										.addClass("selected")
										.parent("ul").animate({height: liHeight},100, function(){
											$(this).find(".selected div").fadeTo(400, 1);
											$(this).find(".selected div").css("top", $(this).find(".selected").height());
										});
										
								return false;
							});
							
						});
					}
					h4.remove();
				});
				$(this).append(firstLevelUl);
			}
		});
		this.applyAdvancedCss();
		this.find("ul ul div h5").each(function(i){
			$(this).replaceWith("<h4>"+$(this).text()+"</h4");	
		});
		this.find("ul ul div h6").each(function(i){
			$(this).replaceWith("<h5>"+$(this).text()+"</h5");	
		});
	}
	return this;
};
jQuery.fn.fixPushes = function(){
	if(this.size() > 0){
		this.each(function(i){
			$(this).find("div:even").addClass("even");

			$(this).find("div").each(function(y){
				if($(this).find(".href a, .image a").size() > 0){
					var attrHref = $(this).find(".href a, .image a").attr("href");
					$(this).find(":header").click(function(){
						document.location.href = attrHref;
					})
					.addClass("clickable");
				}
			});
			if($(this).parent().is("#primary")){
				var divs = $(this).find("div").size();
				for(i = 0; i < divs; i = i + 2){
					$(this).find("div").not(".wrap").slice(i, i+2).wrapAll("<div class=\"wrap\"></div>");
				}
			}
			$(this).find("div:first").addClass("first-child");
			$(this).find("div:last").addClass("last-child");
			if($(this).prev().hasClass("related")){
				$(this).find(".wrap:first").addClass("after-related");
			}
		});
	}
	return this;
};
jQuery.fn.renderSelect = function(){
	// Create elements
	var selElm		  = $(document.createElement("select"));
	var firstOptionElm  = document.createElement("option");

	// Set id for label TODO: Take height for multiple area-choosers
	selElm.attr("id", "area-chooser-select");

	// First option is heading on area-chooser
	var firstOptionText = this.find(".first-choice").text();
	// Append first option
	$(firstOptionElm).attr("value", "-1").append(firstOptionText).appendTo(selElm);

	// Loop through links in ul
	this.find("a").each(function(i){
		// Create option
		var optElm  = $(document.createElement("option"));

		// Add attributes and append to select
		$(optElm).attr("value", $(this).attr("href")).append($(this).text());
		if($(this).hasClass("selected")){
			optElm.get(0).selected = true;
		}
		if($(this).hasClass("disabled")){
			optElm.addClass("disabled");
		}
		$(optElm).appendTo(selElm);
	});
	// Remove holder
	$(".selectable").remove();
	
	return $(selElm);
};
jQuery.fn.applyAdvancedCss = function(){

	if($.browser.msie && ($.browser.version == 6.0 || $.browser.version == 7.0)){	
			
		// addClass
		this.find(".loaded-content h2 + p").addClass("publisher");

		// css
		/*this.find("h3 + p, h3 + ul, h3 + ol").css("margin-top", "0.3em");*/

		/*this.find(".news-list h3 + ul").css("margin-top", "0");*/

		this.find(".loaded-content p:first, .loaded-content h4:first-child").css("margin-top","1em");

		this.find(".tabbed ul li li div").each(function(i){
			$(this).find("p:first").css("margin-top","1em");
		});
		// content
		/*this.find(".href a, .related li a, .more a, .all a").append("<span class=\"after\">&nbsp;&raquo;</span>");
		this.find(".local + div.has-important-news, .article + div.has-important-news").css("border-top", "1px solid #D1D2D4");*/
	}
	return this;
};

jQuery.fn.expand = function(background){
	this.hide();
	this.children().css("opacity", "0");
	this.slideDown(500,function(){
		$(this).children().animate({opacity:1, "backgroundColor": background}, "fast");
	});
	return this;
};

jQuery.fn.collapse = function(height, jremove, callback){
	$(this).children().animate({opacity:0}, 300, function(){
		$(this).parent().slideUp(300);
		$(this).parent().queue(function(){
			if(!jremove){
				if(jQuery.isFunction(callback)){
					callback.apply($(this));
				}
				return $(this).parent();
			}else{
				$(this).remove();
				if(jQuery.isFunction(callback)){
					callback.apply($(this));
				}
			}
		});
	});
};
var selectCityArea = {
	init: function(){
		var timeout = null;
		// Create paragraph that wraps the select
		var pElm		= $(document.createElement("p"));

		if($(".selectable h3").attr("title")){
			var labelElm	= $(document.createElement("label"));
			labelElm.text($(".selectable h3").attr("title"));
			pElm.prepend(" ").prepend(labelElm);
		}

		pElm.insertBefore(".selectable")
			.append($(".selectable").renderSelect());
		if(labelElm){
			labelElm.attr("for", $("#area-chooser select").attr("id"));
		}
		// Attatch event on select
		pElm.find("select").change(function(){
			selectCityArea.change($(this), null);
		});

		$(".address-chooser input").attr("autocomplete", "off");

		// Attatch event on textbox
		$(".address-chooser input").keypress(function(event){
			switch(event.keyCode){
				case 38: // arrow up
					if($("#suggester li.selected a").text() != $("#suggester li:first a").text()){
						$("#suggester li.selected").removeClass("selected").prev().addClass("selected");
					}
					break;
				case 40: // arrow down
					if($("#suggester li.selected a").text() != $("#suggester li:last a").text()){
						$("#suggester li.selected").removeClass("selected").next().addClass("selected");
					}
					break;
				case 9: //tab
					break;
				case 39:
					break;
				case 37:
					break;
				case 13:
					if($(this).val().length > 1){
						if($("#suggester li.selected a").size() > 0){
							var href = $("#suggester li.selected a").attr("href");
							$("#suggester").empty().hide();
							$("#area-chooser input").val("");
							cityAreaContent.load(href);
							if($("#area-chooser select").find("option[value$="+cityAreaFromQuery.fetch(href)+"]").size() > 0){
								$("#area-chooser select").find("option[value$="+cityAreaFromQuery.fetch(href)+"]").attr("selected", "selected");
							}else{
								$("#area-chooser select").find("option:first").attr("selected", "selected");
							}
							$(".area-chooser a").get(0).focus();
						}
					}
					return false;
				default:
					if (timeout){
						clearTimeout(timeout);
					}
					timeout = setTimeout(selectCityArea.keydown, 250);
					break;
			}
		});
		if($.browser.msie){
			$(".address-chooser input").keydown(function(event){
				switch(event.keyCode){
					case 38: // arrow up
					if($("#suggester li.selected a").text() != $("#suggester li:first a").text()){
						$("#suggester li.selected").removeClass("selected").prev().addClass("selected");
					}
					break;
				case 40: // arrow down
					if($("#suggester li.selected a").text() != $("#suggester li:last a").text()){
						$("#suggester li.selected").removeClass("selected").next().addClass("selected");
					}
					break;
				}
			});
		}
		$("#area-chooser input").blur(function(){
			timeout = setTimeout(function(){
				$("#suggester").hide();
			}, 250);
		});
		$("#area-chooser input").focus(function(){
			timeout = setTimeout(function(){
				if($("#suggester").css("display") === "none"){
					$("#suggester").show();
				}
			}, 250);
		});
		
	},
	keydown: function(){
		var input = $("#area-chooser input");

		if(input.val().length > 0){
			if(!$("#suggester").size() > 0){
				$(document.createElement("div"))
					.attr("id", "suggester")
					.css("width", input.width()+2)
					.appendTo(input.parent());
			}
			input.addClass("thinking");

			var buttonid = $("#area-chooser noscript").attr("id").replace(/noscript_/, "").replace(/_/g, "$");
			var button = $(document.createElement("button")).
				attr("name", buttonid);
			var AreaChooserkeyValue = inputFields.fetch(button);

			var formAction = $("form").attr("action");

			if($("form").attr("action").indexOf("?") > 0){
				formAction = formAction.substring(0, formAction.indexOf("?"));
			}

			$("#suggester").load(formAction + "?" + keyCityAreaFriendlyId + "=&" + keyInternalNoContent + "= ul#city-area-list", AreaChooserkeyValue, function(responseText){
				var html = $("<div/>")
					.append(responseText.replace(/<script(.|\s)*?\/script>/g, ""));

				var errorMes = html.find("#area-chooser .errors p");

				if(errorMes){
					$("#suggester")
						.append(errorMes)
						.show();
				}

				$("#suggester li:first").addClass("selected");
				$("#suggester li a").click(function(){
					$("#area-chooser input").val("");	
					cityAreaContent.load($(this).attr("href"));
					if($("#area-chooser select").find("option[value$="+cityAreaFromQuery.fetch($(this).attr("href"))+"]").size() > 0){
						$("#area-chooser select").find("option[value$="+cityAreaFromQuery.fetch($(this).attr("href"))+"]").attr("selected", "selected");
					}else{
						$("#area-chooser select").find("option:first").attr("selected", "selected");
					}

					$(".area-chooser a").get(0).focus();
					return false;
				});
				$("#suggester li").hover(function(){
					$("#suggester li.selected").removeClass("selected");
					$(this).toggleClass("selected");
				},function(){
					$(this).toggleClass("selected");
				});
				input.removeClass("thinking");
				$("#suggester").show();
			});
		}else{
			$("#suggester").empty().hide();
		}
	},
	change: function(elem, href){
		var selElm = elem.find("option:selected");
		if(href !== null){
			selElm = elem.find("option[value$="+cityAreaFromQuery.fetch(href)+"]").attr("selected", "selected");
		}
		if(selElm.val() != elem.find("option:first-child").val()){
			cityAreaContent.load(selElm.val());
		}
	}
};
var inputFields = {
	fetch: function(jqButton){
		var obj = new Object();
		$(":input").not($("button")).add(jqButton).each(function(i){
			var elType = $(this).attr("type");
			switch(elType){
				case "button":
					obj[$(":hidden[name$='EVENTTARGET']").attr("name")] = $(this).attr('name');
					obj[$(":hidden[name$='EVENTARGUMENT']").attr("name")] = '';
					obj[$(this).attr('name')] = '';
					break;
				case "checkbox":
					if($(this).is(":checked")){
						obj[$(this).attr('name')] = $(this).val(); 
					}
					break;
				default:
					obj[$(this).attr('name')] = $(this).val();
					break;
			}
		});
		return obj;
	}
};
var cityAreaFromQuery = {
	fetch: function(href){
		var getQueryTerm = "[\?|&]" + keyCityAreaFriendlyId + "=(.*?)($|&)";
		var pattern = new RegExp(getQueryTerm);
		var m = pattern.exec(href);	
		if(m === null){
			return false;
		}else{
			return m[1];
		}
	}
};
var title = {
	text: null,
	fetch: function(html){
		if(html.find("title").size() > 0){
			this.text = html.find("title").text();
		}else{
			this.text = html.find("meta[name='DC.Title.Alternative']").attr("content");	
		}
		return this.text;
	}
};
var cityAreaContent = {
	load: function(href){
		$("#secondary h2 span").addClass("loading");
		var cityArea = cityAreaFromQuery.fetch(href);
		var toolExists = true;
		if($("#secondary .tool .area-chooser").size() === 0){
			$("#area-chooser").collapse(0);
			toolExists = false;
		}else{
			if($("#secondary .tool .area-chooser a").hasClass("open") && (location.toString().indexOf("?"+keyCityAreaFriendlyId) > -1)){
				$.cookie(keyCityAreaFriendlyId, cityArea, {expires: 30});
				document.location.href = $("#secondary .tool .area-chooser a").attr("href");
				return false;
			}
			if($("#secondary .tool .area-chooser a").hasClass("open") && (location.toString().indexOf("?"+keyCityAreaFriendlyId) <= 0)){
				$("#secondary .tool .area-chooser").trigger("click");
			}
		}

		var loadedcontent = $(document.createElement("div")).load(href + " .loaded-content", function(responseText){		
			var html = $("<div/>")
				.append(responseText.replace(/<script(.|\s)*?\/script>/g, ""));
			var newTitle = title.fetch(html);

			var name = html.find("#secondary h2:first").text();

			$("#skip a[href='#secondary']").text(html.find("#skip a[href='#secondary']").text());

			$(".tool li.contact a").attr("href", html.find(".tool li.contact a").attr("href")); 

			if(!toolExists){
				var tool = html.find("#secondary ul.tool:first")
					.css({"opacity": "0"})
					.insertAfter($("#secondary h2"))
					.animate({opacity:1}, 300);
					tool.find("li.area-chooser").openTab(false, function(){
						$(this).expand("#f2f2f2");
						selectCityArea.init();
					});
			}
			if(newTitle !== null){
				document.title = newTitle;
			}
			if(document.location.href.indexOf("?"+keyCityAreaFriendlyId) === -1){
				document.location.hash = keyCityAreaFriendlyId +"="+cityArea;
			}
			var content = loadedcontent.children().children();
			$(".loaded-content")
				.empty()
				.append(content)
				.children().fixPushes();

				$(".loaded-content").expand("#f2f2f2");
				$("#secondary .tabbed").handleTabbedListing();
				$(".loaded-content").applyAdvancedCss();
				$(".loaded-content .tool li.report").openTab(true, function(){
					$(this).handleReport(arguments[0]);
				});
				$("#secondary h2 span").text(name);
				$("#secondary span").removeClass("loading");
				if($(".tool li.contact a").hasClass("open")){
					$(".tool li.contact").trigger("click");
					$(".tool li.contact, .tool li.contact a").unbind("click");
					$(".tool li.contact").openTab(true, function(){
						$(this).handleContact(arguments[0]);
					});
				}else{
					$("#primary-contact").remove();
					$(".tool li.contact, .tool li.contact a").unbind("click");
					$(".tool li.contact").openTab(true, function(){
						$(this).handleContact(arguments[0]);
					});
				}
			$("#secondary .tool .area-chooser a").get(0).focus();
		});
	}
};
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
jQuery.fn.checkCopySender = function(errArr){
	var holder = $(this);
	var checkboxLabelText = holder.find(".with-checkbox label").text();
	holder.find(":checkbox").change(function(){
		var label = holder.find("label[for="+$(this).attr("id")+"]");	
		if($(this).is(":checked") && (holder.find("label.email strong").size() > 0 || holder.find("#"+$("label.email").attr("for")).val() === "")){
			$(this).addClass("error");
			holder.find("label[for="+$(this).attr("id")+"]").fadeOut("fast", function(){
				$(this)
					.text("")
					.html("<strong>"+$(this).attr("title")+"</strong>")
					.fadeIn("fast");
			});
			errArr.push(label);
		}else{
			if(holder.find("label[for="+$(this).attr("id")+"]").find("strong").size() > 0){
				$(this).removeClass("error");
				holder.find("label[for="+$(this).attr("id")+"]").fadeOut("fast", function(){
					$(this)
						.children().remove();
					$(this)
						.text(checkboxLabelText)
						.fadeIn("fast");
				});
				for(index = 0; index < errArr.length; index++){
					if(errArr[index].attr("for") == label.attr("for")){
						errArr.splice(index, 1);
					}
				}
			}
		}
	});
	holder.find("label.email").each(function(i){
		var label = $(this);	
		var labelhtml = label.html();
		var warning = label.attr("title");
		var attrFor = label.attr("for");
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		$("#"+attrFor).blur(function(){
			if($(this).val().length > 0 && !filter.test($(this).val())){
				$(this).addClass("error");
				label.fadeOut("fast", function(){
					$(this)
						.text("")
						.html("<strong>"+warning+" *</strong>")
						.fadeIn("fast");
				});
				var found = false;
				for(index = 0; index < errArr.length; index++){
					if(errArr[index] == label){
						found = true;
					}
				}
				if(!found){
					errArr.push(label);
				}
			}else{
				if($(this).hasClass("error")){
					$(this).removeClass("error");
					label.fadeOut("fast", function(){
						$(this)
							.html(labelhtml)
							.removeClass("error")
							.fadeIn("fast");
					});
				}
				for(index = 0; index < errArr.length; index++){
					if(errArr[index] == label){
						errArr.splice(index, 1);
					}
				}
				if(holder.find(".with-checkbox label").find("strong").size() > 0){
					holder.find(".with-checkbox input").removeClass("error");
					holder.find(".with-checkbox label").fadeOut("fast", function(){
						$(this)
							.children().remove();
						$(this)
							.text(checkboxLabelText)
							.fadeIn("fast");
					});
					for(index = 0; index < errArr.length; index++){
						if(errArr[index].attr("for") === holder.find(".with-checkbox label").attr("for")){
							errArr.splice(index, 1);
						}
					}
				}
			}
		});
	});
	return errArr;
};
jQuery.fn.checkForms = function(){
	var requiredArray = new Array();
	
	this.find("label.required").each(function(i){
		var label = $(this);
		requiredArray.push(label);
		var labelhtml = label.html();
		var warning = label.attr("title");
		var attrFor = label.attr("for");
		$("#"+attrFor).blur(function(){
			if($(this).val().length === 0){
				$(this).addClass("error");
				label.fadeOut("fast", function(){
					$(this)
						.text("")
						.html("<strong>"+warning+" *</strong>")
						.fadeIn("fast");
				});
				var found = false;
				for(index = 0; index < requiredArray.length; index++){
					if(requiredArray[index] == label){
						found = true;
					}
				}
				if(!found){
					requiredArray.push(label);
				}
			}else{
				if($(this).hasClass("error") > -1){
					$(this).removeClass("error");
					label.fadeOut("fast", function(){
						$(this)
							.html(labelhtml)
							.removeClass("error")
							.fadeIn("fast");
					});
				}
				for(index = 0; index < requiredArray.length; index++){
					if(requiredArray[index] == label){
						requiredArray.splice(index, 1);
					}
				}
			}
		});
		$("#"+attrFor).keyup(function(){
			if($(this).val().length > 0){
				if(this.className.indexOf("error") > -1){
					$(this).removeClass("error");
					label.fadeOut("fast", function(){
						$(this)
							.html(labelhtml)
							.removeClass("error")
							.fadeIn("fast");
					});
				}
				for(index = 0; index < requiredArray.length; index++){
					if(requiredArray[index] == label){
						requiredArray.splice(index, 1);
					}
				}
			}
		});
	});
	this.find("label.email").each(function(i){
		var label = $(this);
		var labelhtml = label.html();
		var warning = label.attr("title");
		var attrFor = label.attr("for");
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		$("#"+attrFor).blur(function(){
			if($(this).val().length > 0 && !filter.test($(this).val())){
				$(this).addClass("error");
				label.fadeOut("fast", function(){
					$(this)
						.text("")
						.html("<strong>"+warning+" *</strong>")
						.fadeIn("fast");
				});
				var found = false;
				for(index = 0; index < requiredArray.length; index++){
					if(requiredArray[index] == label){
						found = true;
					}
				}
				if(!found){
					requiredArray.push(label);
				}
			}else{
				if(this.className.indexOf("error") > -1){
					$(this).removeClass("error");
					label.fadeOut("fast", function(){
						$(this)
							.html(labelhtml)
							.removeClass("error")
							.fadeIn("fast");
					});
				}
				for(index = 0; index < requiredArray.length; index++){
					if(requiredArray[index] == label){
						requiredArray.splice(index, 1);
					}
				}
			}
		});
	});
	return requiredArray;
};
jQuery.extend(jQuery.expr[':'], {
	containsNotSensitive : "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0"
});

/* helper functions */
var siteHelper = {
	stopEvent: function(e) {
		e = e ? e : window.event;
		if(e.stopPropagation){
			e.stopPropagation();
		}
		if(e.preventDefault){
			e.preventDefault();
		}
		e.cancelBubble = true;
		e.cancel = true;
		e.returnValue = false;
		return false;
	},
	parseQuery: function(query){
		var Params = {};
		if(!query ){// return empty object
			return Params;
		}
		var Pairs = query.split(/[;&]/);
		for(var i = 0; i < Pairs.length; i++ ){
			var KeyVal = Pairs[i].split('=');
			if(!KeyVal || KeyVal.length != 2 ){
				continue;
			}
			var key = unescape( KeyVal[0] );
			var val = unescape( KeyVal[1] );
			val = val.replace(/\+/g, ' ');
			Params[key] = val;
		}
		return Params;
	}
}