function createAppendReset(){
	var buttons = $("<p class='reset'/>");
	var reset = $("<a href='#' id='reset'>Start Over</a>").click(function(event){ // when the button is pressed
		RefreshScreenData();
		event.preventDefault();
	});
	$("#results").append(buttons.append(reset));
}
	
function RefreshScreenData(strQuery) {
	if (strQuery == null) {
		strQuery = '';
		$("#Find select").each(function(i){
			strQuery += (strQuery == '' ? '?' : '&') + this.name + '=0';
		})		
	}
	
	$("#loading").fadeIn(function(){ // after the loading gif appears
		$(".reset").fadeOut();
		$("#results").fadeOut(function(){ // fade out results. when faded out, initiate the ajax request
			var data_url = 'LocatorData.php' + strQuery;
			//$("#message").html(data_url);
			// tip for jerry, the above could be more elegant: $("<p id='message' />").html(data_url).appendTo("#locator");
			$.getJSON(data_url, function(data, textStatus) {
				$("#loading").fadeOut();
				if (textStatus != 'success') alert('Error receiving data:' + textStatus); // should this just output to #results?
				else {
					var len = data.length;
					if (len > 0) {
						for (var i=0; i<len; i++) {
							$('#' + data[i].key).html(data[i].html);
							if (data[i].key == 'results') {
								// if the city isnt selected, there are no results warranting reset button
								if ($("#City").val() != 0) createAppendReset(); 
								$("#results").fadeIn("slow");
							}
						}
					}
				}
			});		
		});
	});
}

$(function(){
	var bodyRe = /<body\b([^>]*?)>/;
	var attrRe = /(\w+)\s*?=\s*?"(.*?)"/;
	var phpRe=/(.*)?\/(.*)\.php([#|\?].*)?/;
	var hashRe=/([^\?#]*)?([#\?].*)?/;	
	var currentHash = '';
	var locHost = location.protocol+'//'+location.hostname;
	
	function crossFader(sel,fit,fot,pt,r){
		var els=$(sel);
		function swap(el){
			if(els.length>1){
				var current=jQuery.inArray(el,els);
				var next=(current+1);
				next = next%els.length;
				$(el).fadeOut(fot);
				$(els.get(next)).fadeIn(fit,function(){
					var self=this;
					setTimeout(
						function(){
							swap(self);
						},
						pt
					);
				});
			}
		}
		var start=0;
		if( r ){
			start = Math.floor(Math.random() * els.length);
		}
		start = start%els.length;
		els.hide().slice(start,start+1).show();
		setTimeout(
			function(){
				swap(els.get(start));
			},
			pt
		);
	};
	
	// set current location class for nav highlighting
	function markLocation(loc){
		loc = loc.replace(/pressRelease.php/, 'pressReleases.php');
		$('#nav a,#footer ul a').parents("li").not ($("div").parents()).removeClass("selected").add().children("a").removeClass("selected");
		$('#nav a,#footer ul a').each(function(){
			if(this.href === loc){
				$(this).parents("li").not ($("div").parents()).addClass("selected").add().children("a").addClass("selected");
			}
		});
	};			
	
	function sifrfy(){
		if(typeof sIFR.replaceElement == "function"){
			// replacement calls
			sIFR.replaceElement(named({
				sSelector:"h1",
				sFlashSrc:"scripts/sifr/cochinLtStd.swf",
				sWmode:"transparent",
				sColor:"#A75534"
			}));
			if ( !$("#pos, #reviews, #contact").length ) {	
				sIFR.replaceElement(named({
					sSelector:"h2",
					sFlashSrc:"scripts/sifr/cochinLtdStdItalic.swf",
					sWmode:"transparent",
					sColor:"#6C5D50"
				}));
			}
		};
	};
	
	function pageLoad( hash ){
		if( hash ){
			var url = unescape(hash).match(hashRe);
			var page = url[1];			
			page = '/' + page.replace(/:/g, '/') + '.php';
			markLocation(locHost+page);
			if( url[2] ){ page += url[2]; }
			$.get(page, function (res, status){
				if ( status == "success" || status == "notmodified" )	{
					var s = res.match(bodyRe)[1];
					var m;
					while( m = s.match(attrRe) ){
						$("body").attr(m[1],m[2]);
						s = s.replace(m[0], "");
					}
					// add and remove the selected class from the nav
					$("#body").replaceWith(
						$("<div/>")
							.append(res.replace(/<script(.|\s)*?\/script>/g, ""))
							.find("#body")
					);
					if ($("#container").css("display") === "none") {
						$(window).load(function () {
							sifrfy();
							$("#sidebar img").ifixpng();
							crossFader("#images img",1000,1000,1000,1);
							ajaxifyBody();
							if( url[2] && url[2].substring(0,1) === '#' ){
								var h = url[2];
								if( $(h).length !== 0 ){
									$.scrollTo($(h), 500);
								}
							}																		 
						});
					}
					else {
						sifrfy();
						$("#sidebar img").ifixpng();
						crossFader("#images img",1000,1000,1000,1);
						ajaxifyBody();
						if( url[2] && url[2].substring(0,1) === '#' ){
							var h = url[2];
							if( $(h).length !== 0 ){
								$.scrollTo($(h), 500);
							}
						}
					}
				}
			});
		}
	};
	
	function ajaxifyLinks( selector ){
		$(selector).click( function(){
			var m = this.href.match(phpRe);
			if( m && m.length === 4 && m[0].substring(0,locHost.length) === locHost && $(this).attr('target') !== '_blank' ){
				currentHash = unescape($.historyCurrentHash);
				var h = m[1].substring(locHost.length+1).replace(/\//g, ':');
				h += (h.length === 0)? m[2] : ':' + m[2];
				var cl = location.href.match(hashRe);
				var rl = $(this).attr('href').match(hashRe);
				if( m[3] ){
					h += escape(m[3]);
				}

				if( ( ( rl[1] && rl[1] === cl[1] ) || !rl[1] ) && ( rl[2] && rl[2].substring(0,1) === '#' ) ){
					h = m[3];
					if( h && $(h).length !== 0 ){
						$.scrollTo($(h), 500);
					}
				}
				else if( currentHash.substring(1) !== h ){
					$("#content").html("<p class='loading'>Loading: "+$(this).text()+"</p>");
					$("#content").css("background-image","none");
					$("#sidebar").html("");
					markLocation(this.href);
					$.historyLoad(h);
				}
				return false;
			}
			else{
				var cl = location.href.match(hashRe);
				var url = this.href.match(hashRe);
				if( url && cl && cl[1] == url[1] && url[1].substring(url[1].length-1) === '/' ){
					var h = url[2];
					if( h && $(h).length !== 0 ){
						$.scrollTo($(h), 500);
					}
					return false;
				}
			}
		});
	}
	
	function ajaxifyDistributor(){
		$("#dState").each( function(){
			this.onchange = null;
		})
		.change( function(){
			var state = this[this.selectedIndex].value;
			var m = unescape($.historyCurrentHash);
			if( !m ){
				var m = location.href.match(phpRe);
				m = m[1].substring(locHost.length+1).replace(/\//g, ':') + ':' + m[2];
				m = m + escape('?dState='+state);
				$.historyLoad(m);
			}
			else{
				if( m.substring(0,1) === '#' ){ m = m.substring(1); }
				m = m.match(hashRe);
				if( m[1] && state.length >= 0 ){
					m = m[1] + escape('?dState='+state);
					$.historyLoad(m);
				}
			}
		});		
	}
	
	function ajaxifyLocator()
	{
		$("#Find").append($("<img src='images/loading.gif' id='loading' alt='' />").hide()); // loading animation init
		
		// jquery replacement of UpdatePage() and inline change calls.
		$("#Find select").each(function(){ //use css selector to find element collection and loop through each.
			$(this).change(function(){ // attach onchange handler
				// generate the URL for the AJAX handler
				var strQuery = '';
				$("#Find select").each(function(i){
					strQuery += (strQuery == '' ? '?' : '&') + this.name + '=' + this.value;
				})
				RefreshScreenData(strQuery);
			});
		});

		RefreshScreenData();
	}
	
	function ajaxifyBody()
	{
		ajaxifyLinks("#body *[href]");
		ajaxifyDistributor();
		ajaxifyLocator();
	}

	$.historyInit(pageLoad);
	ajaxifyLinks("#nav a,#footer ul a");
	ajaxifyLinks("#title a");
	ajaxifyBody();
});

