$(document).ready(function() {
	reveal.init();
	refineForms.init();
	metroCityMapLink.init();
	fixMapPosition.init();
	$('img.helpIcon').ToolTipDemo();
	$('#FrmSubmit').click(function(){generateGUID();return checkSearchFrm(); });
	
	QueryString_Parse();
	if (QueryString('phrase')!=null) {document.getElementById('FrmWho').value = unescape(decodeURI(QueryString('phrase')).replace(/\+/g, ' '));};
	if (QueryString('where') != null) {document.getElementById('FrmWhere').value = unescape(decodeURI(QueryString('where')).replace(/\+/g, ' '));};
	
	// if the page uses SEFU urls QueryString_Parse() will not populate search boxes with values
	// from the querystring. On pages that use this format "/Driving+Schools/in/Bedford/3/453466/"
	// we will extract the values and prefill the input boxes.
		var path = window.location.pathname;
		var parts = path.split("/");
		var hd = removeURLFormatting(parts[1]);		
		if(parts[3]){var lc = removeURLFormatting(parts[3])};
		// check first because static SEO index page will error, parts[3] does not exist. 
		if(hd != "search" && hd != null && typeof hd != undefined && lc != null && typeof lc != undefined)
			{document.getElementById('FrmWhere').value = lc;document.getElementById('FrmWho').value = hd;};
	
	//tradeAssoc.init();
	// removed to be in page to save waiting for other content to be written to page
});

function removeURLFormatting(text)
{
	var out;
	out = text.replace(/\+/gi," ");
	out= out.replace(/%26/gi,"&");
	out= out.replace(/---/gi," - ");
	//console.log(out);
	out= out.replace(/([a-z])-/gi,"$1 ");
	//console.log(out);

	out= out.replace(/&-/gi,"& ");
	out= out.replace(/%20/gi," ");
	out= out.replace(/%2c/gi,",");
	//console.log(out);

	return out;
};

var fixMapPosition = 
{
    map : document.getElementById("mapWrapper"),
    init: function()
    {
        if(fixMapPosition.map != null )
       { 
        setInterval(fixMapPosition.checkPosition, 300);
       }
    },
    
    checkPosition: function()
    {
         var currP;
         if (window.innerHeight)
	        {
	            currP = window.pageYOffset
	        } 
	        else if (document.documentElement && document.documentElement.scrollTop)
	        {
	            currP = document.documentElement.scrollTop
	        };
    	
           if(currP > 240)
            {    
               fixMapPosition.map.style.position = "fixed"; 
               fixMapPosition.map.style.top = "0px";            

               var iw = ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth );

               if(document.body.clientWidth > 970)
               {
                  fixMapPosition.map.style.left = iw/2 + 25 + "px"; 
               }
               else
               {
                  fixMapPosition.map.style.left = "514px"; 
               }
           }
           else
           {
               //alert('left=0');
               fixMapPosition.map.style.position = "relative"; 
               fixMapPosition.map.style.left = "0px"; 
           };
   }
  
 }




var metroCityMapLink = {
	init: function(){
		$('#mapClose').click(function(){$('#metrocity').hide();});
		// create the 'show metro map' element and add it to the DOM
		var p = document.createElement("p");
		// give it an id
		p.id = 'showMetroMap';
		var a = document.createElement("a");
		a.href = "";
		// and create a text node
		var cl = document.createTextNode('View a map of districts');
		// append it to the span
		a.appendChild(cl);
		p.appendChild(a);
		$('#metrocity').before(p);
		$('#showMetroMap a').click(function(){ $('#metrocity').toggle();return false;});
	}
}

var tradeAssoc = {

	init: function(){
	   $(".etc a").click(function() {
         var tradeList = $(this).parent().parent().parent();
         tradeList.animate({height: (tradeList.height() != 40) ? '40px' : '100%'}, 500 );
	      $(this).text($(this).text() == "more..." ? "close" : "more...");
	   });
	}
};

function checkSearchFrm(){
		
	var frm = document.getElementById("SearchForm");
  // matches any alpha numeric. 
  var alphaNum = /\w/.test(frm.FrmWho.value);

/* if no who or what is entered create a prompt */
	if(frm.FrmWho.value == "" || alphaNum == false){
		if(document.getElementById("err"))return false;
			var div = document.createElement("div");
			div.id = 'err';
			var t = document.createTextNode('Please enter \'Who\' or \'What\' to search for.');
			div.appendChild(t);
			div.className = 'error';
			$('#SearchForm fieldset').before(div);
			$('#search form').css('height','7em');
	return false;
	}
	if(frm.FrmWhere.value == ""){frm.FrmWhere.value = "United Kingdom";return true;}; return true;
};

var refineForms = {

	init: function(){
	/* the submit buttons are now hidden immediately via script in the page head section */
	//$("#frmServeBase input:last").hide();
	//$("#frmNamesType input:last").hide();
	var frmServeBase = document.getElementById("frmServeBase");
	var frmNamesType = document.getElementById("frmNamesType");
	$('#serveArea').click(function(){frmServeBase.submit();});
	$('#basedInArea').click(function(){frmServeBase.submit();});
	$('#busNames').click(function(){frmNamesType.submit();});
	$('#busType').click(function(){frmNamesType.submit();});
	
	// create the help icon and insert it in the h4
	$('.hasHelp').each(function(i) {
		$(this).html( $(this).html() + "<img height='15px' width='15px' alt='' src='http://images.thomsonlocal.com/tlc/helpIcon.gif' class='helpIcon' />" );
		});
	}
};

var reveal = {

	init: function(){
	   // similar headings
	   $('#showSimHds').click(function(){$('#moreSimHds').fadeIn(500);reveal.revealMore(this);return false;});
	   $('#hideSimHds').click(function(){$('#moreSimHds').fadeOut(500);reveal.hideMore(this, 'simHdsUL', 'showSimHds');return false;});
	   // related headings
	   $('#showRelHds').click(function(){$('#moreRelHds').fadeIn(500);reveal.revealMore(this);return false;});
	   $('#hideRelHds').click(function(){$('#moreRelHds').fadeOut(500);reveal.hideMore(this, 'relHdsUL', 'showRelHds');return false;});
	   // similar locations
	   $('#showCloseLoc').click(function(){$('#moreCloseLoc').fadeIn(500);reveal.revealMore(this);return false;});
	   $('#hideCloseLoc').click(function(){$('#moreCloseLoc').fadeOut(500);reveal.hideMore(this, 'closeLocUL', 'showCloseLoc');return false;});
	   // expand locations
	   $('#showLocPar').click(function(){$('#moreLocPar').fadeIn(500);reveal.revealMore(this);return false;});
	   $('#hideLocPar').click(function(){$('#moreLocPar').fadeOut(500);reveal.hideMore(this, 'locParUL', 'showLocPar');return false;});
	   
	   // reduce locations
	   $('ul#locChildUL li.more:first').before('<li id="showLocChild"><a href="">show all &gt;&gt;</a></li>');
	   $('ul#locChildUL li.more:last').after('<li id="hideLocChild"><a href="">hide extras &gt;&gt;</a></li>').hide();
	   $('#showLocChild a').click(function() {$(this).parent().hide();$('ul#locChildUL li.more').fadeIn('slow');$('li#hideLocChild').show();return false;});
	   $('#hideLocChild a').click(function() {$(this).parent().hide();$('ul#locChildUL li.more').fadeOut('fast');$('li#showLocChild').show();return false;});
	},

	revealMore: function(t){
		var p = t.parentNode.parentNode;
		$(p).addClass("ulNoBorder");
		var u = t.parentNode;
		$(t).hide('fast');
		},
		
	hideMore: function(t, firstULID, showLink){
		$('#'+firstULID).removeClass("ulNoBorder");
		$('#'+showLink).show('fast');
		}
};
/*
 * Copyright (c) 2006 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * @author   Sam Collett (http://www.texotela.co.uk)
 */
$.fn.ToolTipDemo = function()
{
	this.mouseover(
		function(e)
		{
			// get mouse coordinates
			// based on code from http://www.quirksmode.org/js/events_properties.html
			var mouseX = e.pageX || (e.clientX ? e.clientX + document.body.scrollLeft : 0);
			var mouseY = e.pageY || (e.clientY ? e.clientY + document.body.scrollTop : 0);
			mouseX += 10;
			mouseY += 10;
			// if there is no div containing the tooltip
			if(!this.tooltipdiv)
			{
				// create a div and style it
				var div = document.createElement("div");this.tooltipdiv = div;var p = document.createElement("p");$(p).html((this.parentNode.title || this.parentNode.alt));$(div).addClass('helpBubble');this.parentNode.title = "";this.parentNode.alt = "";$("body").append(div);div.appendChild(p);this.tooltipset = true;
			};
			$(this.tooltipdiv).show().css({left: mouseX + 10 +"px", top: mouseY + -20 + "px"});})
.mouseout(function(){if(this.tooltipdiv){$(this.tooltipdiv).hide();}});return this;}
