// Global do-nothing function
var nullFunction = function(){};

// Sets up Yell logger for simple cross-browser logging
if (location.host.match(/^[a-z0-9_-]+(\.btyp)?$/i) || location.search.match(/[&?](debug|log)=true/i)) {
  var debugLevel = location.search.match(/[&?]debug=true/i);
  if (window.console) {
    window.logger = {
      debug: debugLevel ? function(message){ window.console.debug(message); } : nullFunction,
      info: function(message){ window.console.log(message); },
      warn: function(message){ window.console.warn(message); }
    };
  } else if (window.opera) {
    window.logger = {
      debug: debugLevel ? function(message){ window.opera.postError('[DEBUG] ' + message); } : nullFunction,
      info: function(message){ window.opera.postError('[INFO] ' + message); },
      warn: function(message){ window.opera.postError('### WARNING ###\n' + message); }
    };
  } else {
    // Log to the status bar
    var fullStatusLog = '';
    function statusLog(message) {
      fullStatusLog += message;
      fullStatusLog = (fullStatusLog.length <= 5000) ? fullStatusLog : fullStatusLog.substr(fullStatusLog.length - 5000);
      window.status = (fullStatusLog.length <= 120) ? fullStatusLog : fullStatusLog.substr(fullStatusLog.length - 120);
    }
    window.logger = {
      debug: debugLevel ? function(message){ statusLog(' :' + message + ':'); } : nullFunction,
      info: function(message){ statusLog(' [' + message + ']'); },
      warn: function(message){ statusLog(' |[' + message + ']|'); }
    };
  }
} else {
  // Set up a dummy logger (to prevent errors)
  window.logger = {
    debug: nullFunction,
    info: nullFunction,
    warn: nullFunction
  };
}
if (!window.console) {
  // Set up a cross-browser alternative to console.log
  window.console = { log: function(message) { alert('PLEASE USE YELL LOGGER INSTEAD\n' + message); } };
}
// Set up short-cut functions for easy logging
function log(message) {
  logger.info(message);
}
function debug(message) {
  logger.debug(message);
}
function warn(message) {
  logger.warn(message);
}

// Pauses script execution
function pause(milliseconds) {
  // Use for debug only, as this causes massive CPU usage.
  if (location.host.match(/^[a-z0-9_-]+(\.btyp)?$/i) || location.search.match(/[&?](debug|log)=true/i)) {
    var startDate = new Date();
    var now;
    log('PAUSE');
    do { now = new Date(); } while (now - startDate < milliseconds);
  }
}

// JavaScript Document
function yellAddEvent(elm, evType, fn, useCapture){
	// cross-browser event handling for IE5+, NS6 and Mozilla 
	// By Scott Andrew 
	if (elm.addEventListener) { 
		elm.addEventListener(evType, fn, useCapture); 
		return true; 
	} else if (elm.attachEvent) { 
		var r = elm.attachEvent('on' + evType, fn); 
		return r; 
	} else {
		elm['on' + evType] = fn;
	}
}
function removeEvent(obj, evType, fn, useCapture){
	if (obj.removeEventListener){
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.detachEvent){
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be removed");
	}
}

function getEl(e){
	var el = (window.event && window.event.srcElement) ? window.event.srcElement : (e && e.target)? e.target : null;
	if (!el){return}
	return el;
}

function gimme(id){
	if(id.indexOf('.') != -1){
		id = id.replace(/./,"");
		return getElementsByClassName(id);
	}else{
		return document.getElementById(id);
	}
}

function getElementsByClassName(classname){
    var a = [];
	var re = new RegExp('(^| )'+classname+'( |$)');
	var els = document.all?document.all:document.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
		if(re.test(els[i].className))
			a[a.length]=els[i]; //a.push(els[i]) is not ie 5 compatible
    return a;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}

function toggledisplay(obj){
	if(gimme(obj)){
		var type = typeof obj;
		var myObj;
		
		if(type == "object"){
			myObj = obj;
		}else if(type == "string"){
			myObj = gimme(obj);
		}
			if((myObj.style.display == 'none')||(myObj.style.display == '')){
			myObj.style.display = 'block';
		}else{
			myObj.style.display = 'none';
		}	
	}
}
function togglecontent(divId, defaultContent, otherContent){
	var type = typeof divId;
	var myObj;
	if(type == "object"){
		myObj = divId;
	}else if(type == "string"){
		myObj = gimme(divId);
	}
	if(myObj.innerHTML == defaultContent){
		myObj.innerHTML = otherContent;
	}else{
		myObj.innerHTML = defaultContent;
	}
}
function cPop(obj,popup,reldiv,offSetX,offSetY){
	if(!document.getElementById(popup+'copy')){
		var newdiv = document.createElement('div');
		newdiv.setAttribute('id', popup+'copy');
		newdiv.setAttribute('class','tip popUp');
		newdiv.innerHTML = document.getElementById(popup).innerHTML;
		obj.parentNode.insertBefore(newdiv,obj.nextSibling);
		showPopUp(obj,newdiv.id,reldiv,offSetX,offSetY);
	}else{
		showPopUp(obj,popup+'copy',reldiv,offSetX,offSetY);
	}
}
function showPopUp(clickedObj, tabName, relDiv, offSetX, offSetY){
	/*clickedObj = the link to show menu,
	tabName = the id of the div to show
	relDiv = if the div you are showing is contained within a relative div, name it here
	offSetX, offSetY = if the div has to be positioned above/below the link*/
	
	hideAllPopUps();
	
	var pos = findPos(clickedObj);
	var posRel = (!relDiv) ? [0,0] : findPos(document.getElementById(relDiv));
	var moveX = (!offSetX) ? 0 : offSetX;
	var moveY = (!offSetY) ? 0 : offSetY;
	
	var tabX = pos[0] - posRel[0] + moveX  ;
	var tabY = pos[1] - posRel[1] + moveY;
	var tabObj = document.getElementById(tabName);
	tabObj.style.left = tabX +"px";
	tabObj.style.top = tabY +"px";
	tabObj.style.display = "block";
}

function hideAllPopUps(){
	
	var allPopUps = getElementsByClassName('popUp');
	//alert("allPopUps: "+allPopUps.length);
	for (i=0;i<allPopUps.length;i++){
		allPopUps[i].style.display = "none";
	}
}
function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function getLocalData(name){
	if(window.localStorage){
		return window.localStorage.getItem(name);
	}else{
		return getCookie(name);
	}
}
function setLocalData(name,value,days){
	if(window.localStorage){
		return window.localStorage.setItem(name,value);
	}else{
		return setCookie(name,value,days);
	}	
}

function addAdvertHistory(advert) {
	$.ajax({
		method: "get",
		url: "/ucs/ManageHistory.do?addadvert="+advert+'&ajax=true',
		success: function(){}
		});
	
}

$(function(){
	$('.nat a').click(function(){
		natID = $(this).closest('.nat').attr('id');
		if(natID != ""){
			coName = $('#'+natID+' .coName').html();
			coAddress = $('#'+natID+' .mini-address').html();
			alphaUrl = $('#'+natID+' .expandLink').attr('href');
			classification = jQuery.trim($('#'+natID+' .classification').text());
			telNo = jQuery.trim($('#'+natID+' .small strong:first').text());
			newCookie =escape(coName+" -:- "+coAddress+" -:- "+alphaUrl+" -:- "+classification+" -:- "+telNo); 
			addAdvertHistory(newCookie);
		}

	});
});

function deleteAdvert(id) {
	//first, remove the cookie
	//this needs more work - can't just delete the cookie without renumbering the others
	deleteCookie(id);
	
	//then remove advert from screen
	//this does not seem to work, don't know why not
	document.getElementById('savedAdverts').removeChild(id);
}

function deleteCookie(name) {
	setCookie(name,"",-1);
}
function loadEstara(iframeID, estaraUrl){
	var cffDiv = iframeID.replace(/estaraFrame/,"makeCall");
	if(gimme(cffDiv).style.display =="block"){
		gimme(iframeID).src=estaraUrl;
	}else{
		gimme(iframeID).src="/yell/loading.html";
	}
}


var w = 0;

//Maps variable function
function changeM(){
	if (document.getElementById('useMultimap').checked) {
		document.forms[0].M.value = '1';
	}else {
		document.forms[0].M.value = '0';
	}
}	



function updateEGs(){
	//Set up event for validation on submit
	$('form#searchBoxForm').submit(function(){
		return validate3Search(this.id);
	});
	//Set up event to hide previous error messages
	$('form#searchBoxForm input[type=text]').keypress(function(){
		hideErrors();
	});		
	//Set up events to handle population and clearing of examples
	$('#keywordsInput, #companyName, #location').each(function(){
		$(this).parent().next().hide();
		setEG($(this),$(this).parent().next());
		$(this).focus(function(){
			checkEG($(this),$(this).parent().next());
		});
		$(this).blur(function(){
			setEG($(this),$(this).parent().next());
		});
	});
}

$(function(){
	$('form#searchBoxForm_bottom').submit(function(){
		return validate3Search(this.id);
	});
});


function setEG(formField,eg){
	if(formField.val()==""){
		formField.val(eg.html());
		formField.addClass('exampleInput');
	}
}
function checkEG(formField,eg){
	if(formField.val()==eg.html()){
		formField.val("");
		formField.removeClass('exampleInput');
	}
}

//Search Validation functionality


//Variables
var pass,coNamePass,locPass;
//Arrays for catching false search input
var companyNameWords=new Array("ltd","the","plc","co","in","at","and");
var locationWords=new Array("tba","c","h","d","a","p","r","t","u","k","f","o","y","i","v");
var specialChars=new Array("`","#","?","]","e.g. plumbers, florists","e.g. Yell","e.g. UK, town, postcode");

function hideErrors(){
	$('.vError').remove();
}

function specialCharsCatcher(fieldid){
	for(i=0;i<specialChars.length;i++){
				scRegexp = eval("/\\"+specialChars[i]+"/g");
				updatedField = $('#'+fieldid).val();
				updatedField = updatedField.replace(scRegexp, "");
				$('#'+fieldid).val(updatedField);
	}
}

function stopwordsCatcher(field, farray){
	var stopwordArray = eval(farray).slice();
	for(k=0;k<stopwordArray.length;k++){
		if(field.value.toLowerCase() == stopwordArray[k]){
			vErrorBuilder(field,'stopword',stopwordArray[k]);
			pass = false;
			return false;
		}
	}
}
function vErrorBuilder(vfield,vErrtype,vChar){
	var vposField = $("#"+vfield.id);
	var vpost = vposField.position().top + 25;
	var vposl = vposField.position().left;
	
	
	Err_Open = '<div class="vError" style="position:absolute; top:'+vpost+'px; left:'+vposl+'px; "><div class="upArrow"/>';
	Err_Close = '</div>';
	
	if(vErrtype == 'blank'){
		if(vfield.id == 'keywordsInput' || vfield.id == 'keywordsInput_bottom'){
			$('#'+vfield.id).after(Err_Open+'Please enter a product or a service.'+Err_Close);
		}
		if(vfield.id == 'companyName' || vfield.id == 'companyName_bottom'){
			$('#'+vfield.id).after(Err_Open+'<strong>AND/OR</strong> enter a company name.'+Err_Close);
		}
	}else if(vErrtype == 'stopword'){
		$('#'+vfield.id).after(Err_Open+'Sorry, but we will need a bit more than "'+vChar+'" to find you great results.'+Err_Close);
	}else if(vErrtype == 'mapsearch'){
		vfieldJs = "submitMapSearch('"+vfield.id+"');"
		$('#'+vfield.id).after(Err_Open+'<strong>OR </strong><a id="locErrorLink" href="#" onclick="'+vfieldJs+'">view a map of '+vfield.value+'</a>.'+Err_Close);
	}
}


function validate3Search(form){
	//Resets validation
	vqs = '';vkwrd = '';vcname = '';vloc = '';pass = true; mapsearch = false;
	hideErrors();

	validatefields = $('#'+form+' input[type=text]');

	//Loops through the submitted elements
	for(a=0;a<validatefields.length;a++){
		specialCharsCatcher(validatefields[a].id);
		if(validatefields[a].id == 'keywordsInput' || validatefields[a].id == 'keywordsInput_bottom'){vkwrd = validatefields[a];}
		if(validatefields[a].id == 'companyName' || validatefields[a].id == 'companyName_bottom'){vcname = validatefields[a];}
		if(validatefields[a].id == 'location' || validatefields[a].id == 'location_bottom'){vloc = validatefields[a];}
	}
	
	//Trim any whitespace from start and end of search term	
	vkwrd.value = jQuery.trim(vkwrd.value);
	vcname.value = jQuery.trim(vcname.value);
	vloc.value = jQuery.trim(vloc.value);
	
	//Check if maps search or not
	if($('#'+form+' #useMultimap:checked').length >=1 || (!vkwrd.value && !vcname.value && vloc.value)){
		mapsearch = true;
	};

	//Checks for empty fields
	if(vkwrd.value == '' && vcname.value == ''){
		if(vloc.value == ''){
			vErrorBuilder(vkwrd,'blank');
			vErrorBuilder(vcname,'blank');
			pass = false;
		}else{
			pass = false;
			if(stopwordsCatcher(vloc, 'locationWords')!= false){
				submitMapSearch(vloc.id);
			}
		}
	}else{
	//Validation if found text in search
		if(vcname.value != ''){
			stopwordsCatcher(vcname, 'companyNameWords');
		}
		if(vloc.value != ''){
			stopwordsCatcher(vloc, 'locationWords');
		}	

	}
	//Returns true or false to the submitting form

	if(pass){
    if(window.ajaxSearch == true){
      stateChanged({'mapSearchType':'yellSearch','keywords':$('#keywordsInput').val(),'companyName':$('#companyName').val(),'location':$('#location').val()});
      return false;
    }else{
		return true;
    }
  }else{
    return false;
  }
  
  
}


function submitMapSearch(vfield){
	mapLocation = $('#'+vfield)[0].value;
  if(window.ajaxSearch == true){
    stateChanged({'mapSearchType':'locSearch','location':mapLocation});
    return false;
  }else{
    window.location = "/maps/MapAction.do?location="+mapLocation+"&panel=poi&submit=Show+map&intCam=intViewAMapOf";
    return false;
  }
}

function changeSSMs(){
	if(placesMMIsSupportedBrowser()) {
		var hiddenInputs = document.getElementsByName('ssm');
		for(i=0;i<hiddenInputs.length;i++){
			hiddenInputs[i].value="0";
		}
	}
}

//  Multimap provided function
function placesMMIsSupportedBrowser(){if(document.attachEvent||document.addEventListener){if(typeof(document.doctype)=='\157\142\152\145\143\164'||typeof(document.media)=='\163\164\162\151\156\147'){if(document.getElementById){return true;}}}return false;};


//Start of homepage address book functionality
function updateSavedData(ajaxURL,returnTarget){
	$.ajax({
		method: "get",
		url: ajaxURL,
		success: function(html){
			$("#"+returnTarget).hide('fast',function(){
				$("#"+returnTarget).remove();
				if($('#saved-wrapper li').size()==0){
					$('#saved-wrapper').hide('fast',function(){
						$('#saved-wrapper').remove()
						$('body').hide().show(); //Fix for IE8 redraw error
					});
				}
				if($('#searchHistory li').size()==0){
					$('#searchHistory').hide('fast',function(){
						$('#searchHistory').remove()
						$('body').hide().show(); //Fix for IE8 redraw error
					});
				}
				if($('#advert-history li').size()==0){
					$('#advert-history').hide('fast',function(){
						$('#advert-history').remove()
						$('body').hide().show(); //Fix for IE8 redraw error
					});
				}
				$('body').hide().show(); //Fix for IE8 redraw error
			});
		}
	});
}

var acAjaxTimeout;
$(function(){
	$('.halfWidth li .delete').click(function(){
		ajaxURL = $(this).attr('href')+'&ajax=true';
		returnTarget = $(this).parent().attr('id');
		updateSavedData(ajaxURL,returnTarget);
		return false;
	});		
	$('.halfWidth h2 .delete').hover(
		function () { $(this).parent().parent().addClass('red'); }, 
		function () { $(this).parent().parent().removeClass('red');	}
	).click(function(){
		ajaxURL = $(this).attr('href')+'&ajax=true';
		returnTarget = $(this).parent().parent().attr('id');
		updateSavedData(ajaxURL,returnTarget);
		return false;
	});		
});

function initPromo(){
	$('#topics-list li').hide();
	var randomNum = Math.floor(Math.random() * $('#topics-list li').length);
	$('#topics-list li:eq('+randomNum+')').show();
	$('#topics-thumbs').show();
	$('#topics-thumbs li:eq('+randomNum+')').hide();
	$('#topics-thumbs li:visible:last').css({'padding-right':'0'});
	$('#topics-list').after($('#blog-promo h2'));
}

//End of homepage address book functionality


/* OnlineOpinion (S3tS,1424b) */
/* This product and other products of OpinionLab, Inc. are protected by U.S. Patent No. 6606581, 6421724, 6785717 B1 and other patents pending. */
var custom_var,_sp='%3A\\/\\/',_rp='%3A//',_poE=0.0, _poX=0.0,_sH=screen.height,_d=document,_w=window,_ht=escape(_w.location.href),_hr=_d.referrer,_tm=(new Date()).getTime(),_kp=0,_sW=screen.width;_d.onkeypress=_fK;function _fK(_e){if(!_e)_e=_w.event;var _k=(typeof _e.which=='number')?_e.which:_e.keyCode;if((_kp==15&&_k==12))_w.open('https://dashboard.opinionlab.com/pv_controlboard.html?url='+_fC(_ht),'PageViewer','height=529,width=705,screenX='+((_sW-705)/2)+',screenY='+((_sH-529)/2)+',top='+((_sH-529)/2)+',left='+((_sW-705)/2)+',status=yes,toolbar=no,menubar=no,location=no,resizable=yes');_kp=_k};function _fC(_u){_aT=_sp+',\\/,\\.,-,_,'+_rp+',%2F,%2E,%2D,%5F';_aA=_aT.split(',');for(i=0;i<5;i++){eval('_u=_u.replace(/'+_aA[i]+'/g,_aA[i+5])')}return _u};function O_LC(){_w.open('https://secure.opinionlab.com/ccc01/comment_card.asp?time1='+_tm+'&time2='+(new Date()).getTime()+'&prev='+_fC(escape(_hr))+'&referer='+_fC(_ht)+'&height='+_sH+'&width='+_sW+'&custom_var='+custom_var,'comments','width=535,height=192,screenX='+((_sW-535)/2)+',screenY='+((_sH-192)/2)+',top='+((_sH-192)/2)+',left='+((_sW-535)/2)+',resizable=yes,copyhistory=yes,scrollbars=no')};function _fPe(){if(Math.random()>=1.0-_poE){O_LC();_poX=0.0}};function _fPx(){if(Math.random()>=1.0-_poX)O_LC()};window.onunload=_fPx;function O_GoT(_p){_d.write('<a href=\'javascript:O_LC()\'>'+_p+'</a>');_fPe()};


// bgIrame plugin (fixes z-index issues by adding an iframe directly behind element)
(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);


/* Yell autoSuggest version 1.1, based on jSuggest Version: 1.0
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * 2008 Kean Loong Tan http://www.gimiti.com/kltan
 * Matt Tortolani
 */
(function($) {

	$.fn.autoSuggest = function(options) {
	return this.each(function() {
		// merge users option with default options
		var opts = new $.extend({}, $.fn.autoSuggest.defaults, options);		
		var ac_defaultData = opts.data;
	
		var autoComplete = "div.ac_contain";
		
		var ac_hoverSelectorS = "li.ac_hover";
		var ac_hover = "ac_hover";
		
		var ac_textVal = this.value;	
		
		var ac_textBox = this;
		var ac_textBoxId = $(ac_textBox).attr('id');
		
		var $acList = $('ul#acList_'+ac_textBoxId);
		var $acContain = $('div#ac_'+ac_textBoxId);
		
		// parse cookie to JSON object with source of "recent"
		function parse(ac_cookie){
			if (ac_cookie !== null && ac_cookie !== "") {
				var len = ac_cookie.length;
				myArray = [];
				for (var i in ac_cookie) {
					var obj = {
						name: ac_cookie[i],
						source: "recent"
					};
					myArray.push(obj);
				}
				return myArray;
			}
		}
		if (opts.cookie != null && getCookie(opts.cookie) != null && getCookie(opts.cookie) != '""' && getCookie(opts.cookie) != '') {
			var ac_cookieData = parse(unescape(getCookie(opts.cookie).replace(/\+/g, " ").replace(/^\|*(.*[^\|])\|*$/, "$1")).split('|'));
		}else{
			ac_cookieData = "";
		}
		
		$(autoComplete).hide();
		
		
		// on field focus 
		$(this).focus(function () {
			$acList.remove();
			//Check it's under the minchar, if so, it has focus
			if (this.value.length <= opts.minchar) {
			
				$acList.find('li:not(.recent)').remove();
				
				acBuild(ac_cookieData, this);
			}
			return false;
		});

		function moveSelect(step) {
			if (step == 1){
				if ($(ac_hoverSelectorS).length >= 1) {
					if (!$(ac_hoverSelectorS).next('li').hasClass(ac_hoverSelectorS)) {
					$(ac_hoverSelectorS).next().addClass(ac_hover);
					$(ac_hoverSelectorS).prev().removeClass(ac_hover);
					}
				}
				else {
					$acList.find('li:first-child').addClass(ac_hover);
				}
			}
			
			if (step === 0){
				if ($(ac_hoverSelectorS).length >= 1) {
					if (!$(ac_hoverSelectorS).prev('li').hasClass(ac_hoverSelectorS)) {
						$(ac_hoverSelectorS).prev().addClass(ac_hover);
						$(ac_hoverSelectorS).next().removeClass(ac_hover);
					}
				}
				else {
					$acList.find('li:first-child').addClass(ac_hover);
				}
			}
		return false;
		}

		
		function selectCurrent(selected) {
			// omniture
			inputName = ac_textBox.name;
		
			if ($acList.find('li.ac_hover').hasClass('recent')){
				if (inputName == "keywords"){kw = "kw_recent";}
				if (inputName == "companyName"){cn = "cn_recent";}
				if (inputName == "location"){lo = "lo_recent";}
			}else {
				if (inputName == "keywords"){kw = "kw";}
				if (inputName == "companyName"){cn = "cn";}
				if (inputName == "location"){lo = "lo";}
			}

			// make sure eg's are cleared
			checkEG($(ac_textBox),$(ac_textBox).parent().next());
			
			// set value
			$(ac_textBox).val($acList.find('li.ac_hover').text());
			
			$acList.find('li.ac_hover').removeClass('ac_hover');
			// remove
			$acList.remove();
			$acContain.hide();
			
			ac_textBox.focus();
			
			return false;
		}
		
		// Bindings

		// onclick of anywhere else in the document, remove the results and leave original val
		$(document).bind("click", function() {
			$acContain.hide();
			$acList.find(ac_hoverSelectorS).removeClass(ac_hover);
			$acList.remove();
		});
		
		function acBindMouse() {
			
			$acList.find('li').mouseover(function() {
				$acList.find(ac_hoverSelectorS).removeClass(ac_hover);
				$(this).addClass(ac_hover);
				return false;
			});
			
			$acList.find('li').click(function() {
				selected = $(this).text();
				selectCurrent(selected);
				return false;
			});

		}
	
		$('#searchBoxForm, #searchBoxForm_bottom').bind("keyup click", function(e) {
			selected = $acList.find('li.ac_hover').text();
				if (selected != ""){
					//IE fix
					selectCurrent(selected);
					return false;
				}
		});
		
		$(ac_textBox).bind("keyup click", function(e) {

			ac_textBox = this;
			ac_textVal = this.value;
			
				// escape (hide)
				if (e.keyCode == 27) {
					$(autoComplete).remove();
					return false;
				}
				
				// tab
				else if (e.keyCode == 9) {
					return false;
				}
				
				// up/down
				else if (e.keyCode == 40) {
					moveSelect(1);
				}
				else if (e.keyCode == 38) {
					moveSelect(0);
				}
				
			// select (if enter/left/right)
				else if (e.keyCode == 13 || e.keyCode == 37 || e.keyCode == 39) {
					selected = $acList.find('li.ac_hover').text();
					if (selected != ""){
						selectCurrent(selected);
						return false;
					}
				}

			// new query detected
				else if (ac_textVal.length >= opts.minchar) {
					term = ac_defaultData + "=" + ac_textBox.value;
					sendAjaxCall(term);	
				}
		
				else {
				// remove hover
					$(ac_hoverSelectorS).removeClass(ac_hover);
					
				// rebuild with the cookie data
					acBuild(ac_cookieData, ac_textBox);
				}
				
			// no bubbling, click is binded to ac_textBox to prevent document bind from firing
			return false;
		});
		
		function sendAjaxCall(term) {
			clearTimeout(acAjaxTimeout);

			acAjaxTimeout = setTimeout(function () {
				$.ajax({
				
					mode: "abort",
					type: opts.type,
					dataType: "json",
					url: opts.url,
					data: term,
					success: function(json) {				
						var ac_data = jQuery.makeArray(json);
						
						ac_ajax_data = [];
						
						$.merge(ac_ajax_data, ac_cookieData);
						$.merge(ac_ajax_data, ac_data);
					

						acBuild(ac_ajax_data, ac_textBox);
					}
				});

			}, opts.delay);
		
		}
		
		function stopAjaxCall(timeout) {
			clearTimeout(t);
		}
	
		function acRemoveHistory() {

			$acList.find('li.recent').append('<span class="ac_delete"></span>');
			
			$acList.find('li span.ac_delete').hover(
				   function(){ $(this).addClass('hover'); },
				   function(){ $(this).removeClass('hover'); }
			);

			// remove item from cookie onclick
			$acList.find('li span.ac_delete').click( function() {

				// get the removed term
				acTermEsc = escape($(this).parent('li').text()).replace(/\%20/g,"\+");

				function removeTerm(cookie,term) {
					var cookieArray = getCookie(cookie).split("|")
					for(var i=0; i<cookieArray.length;i++ ){
						if(cookieArray[i]===term)
							cookieArray.splice(i,1);
					}
				return cookieArray.join("|").toString();
				}
				
				var newCookie = removeTerm(opts.cookie, acTermEsc)
									
				setCookie(opts.cookie, newCookie, 200);
			
			
				$(this).parent('li').slideUp(600, function () {
					//$(this).remove();
				});
				
				// reset cookie data
				if (opts.cookie != null && getCookie(opts.cookie) != null && getCookie(opts.cookie) != '""' && getCookie(opts.cookie) != ''){
					ac_cookieData = parse(unescape(getCookie(opts.cookie).replace(/\+/g, " ")).split('|'));
				} else {
					ac_cookieData = "";
					$($acContain).hide();
				}
				
				return false;
			});
		
		}

		function acBuildList(ac_data, ac_textBox) {

			acListContent = [];
			if (ac_data != null){	
				var usedResult = [];
				for ( var i = 0, len = ac_data.length; i < len; i++ ) {
					if(usedResult[ac_data[i].name] && ac_data[i].source != "recent") {
							delete ac_data[i];
					} else {
						usedResult[ac_data[i].name] = ac_data[i].name;
					}
				}
			
				for ( var i = 0, len = ac_data.length; i < len; i++ ) {
				if (ac_data[i] != undefined && ac_data[i].name != ''){
						var acLiClass = ac_data[i].source;
						var acLiText = ac_data[i].name;
						var acInputTerm = ac_textBox.value;

						// stop giving class of "undefined"
						if (acLiClass != "recent"){
							acLiClass = "";
						}
						
						var highlightRegex =  RegExp("(?![^&;]+;)(?!<[^<>]*)(.?)(" + acInputTerm + ")(?![^<>]*>)(?![^&;]+;)(.?)", "gi");
						
						if (opts.highlight = "matchedCharacters") {		
						// highlight characters that match
							var acHighlightedText = acLiText.replace(highlightRegex, "$1<strong>$2</strong>$3");
						}else{
						// highlight characters that don't match
							var acHighlightedText = acLiText.replace(highlightRegex, "<strong>$1</strong>$2<strong>$3</strong>");
						}
						var acLiRelevance = highlightRegex.test(acLiText);
		
								li = '<li class="'+acLiClass+'">'+acHighlightedText+'</li>';
								acListContent.push(li);
					}
				}
			}
			return acListContent.join("");
		}	

		
		function acBuild(ac_data, ac_textBox){
			
			// clear existing results
			$(autoComplete).find(ac_hoverSelectorS).removeClass(ac_hover);
			$(autoComplete).remove();			
			
			// create a unique id for each container
			$acContain = $('div#ac_'+ac_textBoxId);
			if ($($acContain).size() === 0) {
				$('body').append('<div id="ac_'+ac_textBoxId+'"class="ac_contain"></div>');
				$acContain = $('div#ac_'+ac_textBoxId);
			}

			// & for each set of results
			$acList = $('ul#acList_'+ac_textBoxId);
			if ($($acList).size() === 0) {
					$('div#ac_'+ac_textBoxId).append('<ul id="acList_'+ac_textBoxId+'" class="results"></ul>');
					$acList = $('ul#acList_'+ac_textBoxId);
			}
		
			var offSet = $(ac_textBox).offset();
			$($acContain).css({
				position: "absolute",
				top: offSet.top + $(ac_textBox).outerHeight() + "px",
				left: offSet.left,
				width: $(ac_textBox).outerWidth()-2 + "px",
				zIndex: opts.zindex
			}).show();	


			acListHTML = acBuildList(ac_data, ac_textBox);
				$($acList).html(acListHTML);

				// videojug/z-index fix
				if ($.browser.msie && $.browser.version.substr(0,1)<7) {
					$('div.ac_contain').bgiframe();
				}
				else if ($('embed').size() >= 1) {
					$('div.ac_contain').bgiframe();
				}
		

				// remove recent items that are not relevant
				$acList.find('li.recent:not(:has(strong))').remove();
				
				// if there are ajax items, only show 2 recent
				if ($acList.find('li:not(.recent)').size() >= 1) {
					acNumberOfRecent = "2";
				}else{
					acNumberOfRecent = "9";
				}
				
				$acList.find('li.recent:gt('+acNumberOfRecent+')').remove();

			if ($acList.find('li.recent').size() >= 1) {
				acRemoveHistory();
			}

			acBindMouse();

			if ($acList.find('li').size() === 0) {
				$($acContain).hide();
			}
		
		}

	});


};
	var acAjaxDelay = 300;
	var acResultsHighlight = "matchedCharacters";
	
	$.fn.autoSuggest.defaults = {
		minchar: 2,
		zindex: 1000,
		delay: acAjaxDelay,
		url: "",
		type: "GET",
		data: "",
		cookie: "",
		highlight: acResultsHighlight,
		url:"/autocomplete/autoComplete.do"
	};

})(jQuery);

clearTimeout(acAjaxTimeout);

/*autocomplete global omniture variables*/
var cn = ""
var kw = ""
var lo = ""
		

/*
//initiate autocomplete
*/
$(function() {
	$('#keywordsInput').attr("autocomplete","off").autoSuggest({
		data: "type=keyword&value",
		cookie: "AUTOKWD"
	});
	
	$('#companyName').attr("autocomplete","off").autoSuggest({
		data: "type=company&value",
		cookie: "AUTOCN"
	});

	$('#location').attr("autocomplete","off").autoSuggest({
		data: "type=location&value",
		cookie: "AUTOLOC"
	});
	
	$('#keywordsInput_bottom').attr("autocomplete","off").autoSuggest({
		data: "type=keyword&value",
		cookie: "AUTOKWD"
	});
	
	$('#companyName_bottom').attr("autocomplete","off").autoSuggest({
		data: "type=company&value",
		cookie: "AUTOCN"
	});

	$('#location_bottom').attr("autocomplete","off").autoSuggest({
		data: "type=location&value",
		cookie: "AUTOLOC"
	});
	// ie6 focus fix
	$('#keywordsInput, #companyName, #location').blur();
	
/*
//Autocomplete Omniture tracking
*/
$('form#searchBoxForm, form#searchBoxForm_bottom').submit(function() {
	$('.ac_contain').remove();
		pass = false 
	
			//If the values aren't blank, append a hidden input to the form with the vars as the value
			if (!(!kw && !cn && !lo)){
				$(this).append('<input id="autocomplete" type="hidden" name="autocomplete" value="'+kw+''+cn+''+lo+'"/>');
			}

		pass = true	
		if(pass){return true;}else{return false;}	
	});

});


/*
//Togglelist plugin
*/
$.fn.togglelist = function(options) {
var defaults = {
   number: 5,
   showtext: "More",
   showtitle: "Show more",
   hidetext: "Less",
   hidetitle: "Show less",
   showonclick: ""
};
var options = $.extend(defaults, options);

//Get the id of the list the function is being ran on
var listid = $(this).attr('id');

//The initial show html
var togglehtml = '<a id="'+listid+'toggle" class="MoreLink" title="'+ options.showtitle +'" href="#" onclick="'+options.showonclick+'">'+ options.showtext +'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button></button></a>';

//The unique id of the show/hide html
var toggleselector = '#'+listid+'toggle';

//Find the nth children of the ul, hide them and store as 'hidden'
var hidden = $(this).children().slice(eval(options.number)).hide();

//Find the hidden li parent ul (to handle there being no hidden li) and insert show html after
hidden.parents('ul').after(togglehtml);

//Toggle the hidden li when the show html is clicked
$(toggleselector).click(function () {
	$(hidden).toggle();
		//If the hidden li are visible, update the "show" html with the hide title and text
		if ($(hidden).is(':visible')) {$(toggleselector).removeAttr("onclick").attr("title", ""+ options.hidetitle +"").attr("class","CloseLink").html(''+options.hidetext+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button></button>');}
		//Else, go back to the original show html
		else{$(toggleselector).attr("title", ""+ options.showtitle +"").attr("class","MoreLink").attr("onclick", ""+ options.showonclick +"").html(''+options.showtext+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button></button>');}
	return false;
});
	
};
function getUrlParam( name , myURL){
  //Grabs the url variables that you ask for and returns them
  var urlToMatch = myURL || document.location;
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( urlToMatch );
  if( results == null )
  return "";
  else
  return results[1];
}


/* Greybox Redux
 * Required: http://jquery.com/
 * Written by: John Resig
 * Based on code by: 4mir Salihefendic (http://amix.dk)
 * License: LGPL (read more in LGPL.txt)
 */
// removed the caption div & argument

var GB_ANIMATION = true;
var GB_DONE = false;
var GB_HEIGHT = 400;
var GB_WIDTH = 400;

function GB_show(url, height, width) {
  GB_HEIGHT = height || 400;
  GB_WIDTH = width || 400;
  if(!GB_DONE) {
    $(document.body)
      .append("<div id='GB_overlay'></div><div id='GB_window'>"
        + "<div id='GB_close'></div></div>");
    $("#GB_window #GB_close").click(GB_hide);
    $("#GB_overlay").click(GB_hide);
    $(window).resize(GB_position);
    GB_DONE = true;
  }
  $("#GB_frame").remove();
  $("#GB_window").append("<iframe id='GB_frame' src='"+url+"'></iframe>");
  $("#GB_overlay").show();
  GB_position();

  if(GB_ANIMATION)
    $("#GB_window").fadeIn("slow");
  else
    $("#GB_window").show();
}

function GB_hide() {
  $("#GB_window,#GB_overlay").hide();
}

function GB_position() {
  var w = $(window).width();
  var h = $(document).height();
  var scrollTop = $(window).scrollTop();
  $("#GB_window").css({width:GB_WIDTH+"px",height:GB_HEIGHT+"px", left: ((w - GB_WIDTH)/2)+"px", top: (scrollTop + 10)+"px" });
  $("#GB_frame").css("height",GB_HEIGHT+"px");
  $("#GB_overlay").css({height:h+"px", width:w+"px"});
}
// end of greybox

//JSON2 .js
if(!this.JSON)this.JSON={};
(function(){function k(a){return a<10?"0"+a:a}function n(a){o.lastIndex=0;return o.test(a)?'"'+a.replace(o,function(c){var d=q[c];return typeof d==="string"?d:"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function l(a,c){var d,f,i=g,e,b=c[a];if(b&&typeof b==="object"&&typeof b.toJSON==="function")b=b.toJSON(a);if(typeof j==="function")b=j.call(c,a,b);switch(typeof b){case "string":return n(b);case "number":return isFinite(b)?String(b):"null";case "boolean":case "null":return String(b);case "object":if(!b)return"null";
g+=m;e=[];if(Object.prototype.toString.apply(b)==="[object Array]"){f=b.length;for(a=0;a<f;a+=1)e[a]=l(a,b)||"null";c=e.length===0?"[]":g?"[\n"+g+e.join(",\n"+g)+"\n"+i+"]":"["+e.join(",")+"]";g=i;return c}if(j&&typeof j==="object"){f=j.length;for(a=0;a<f;a+=1){d=j[a];if(typeof d==="string")if(c=l(d,b))e.push(n(d)+(g?": ":":")+c)}}else for(d in b)if(Object.hasOwnProperty.call(b,d))if(c=l(d,b))e.push(n(d)+(g?": ":":")+c);c=e.length===0?"{}":g?"{\n"+g+e.join(",\n"+g)+"\n"+i+"}":"{"+e.join(",")+"}";
g=i;return c}}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+k(this.getUTCMonth()+1)+"-"+k(this.getUTCDate())+"T"+k(this.getUTCHours())+":"+k(this.getUTCMinutes())+":"+k(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var p=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
o=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,g,m,q={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},j;if(typeof JSON.stringify!=="function")JSON.stringify=function(a,c,d){var f;m=g="";if(typeof d==="number")for(f=0;f<d;f+=1)m+=" ";else if(typeof d==="string")m=d;if((j=c)&&typeof c!=="function"&&(typeof c!=="object"||typeof c.length!=="number"))throw new Error("JSON.stringify");return l("",
{"":a})};if(typeof JSON.parse!=="function")JSON.parse=function(a,c){function d(f,i){var e,b,h=f[i];if(h&&typeof h==="object")for(e in h)if(Object.hasOwnProperty.call(h,e)){b=d(h,e);if(b!==undefined)h[e]=b;else delete h[e]}return c.call(f,i,h)}p.lastIndex=0;if(p.test(a))a=a.replace(p,function(f){return"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)});if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){a=eval("("+a+")");return typeof c==="function"?d({"":a},""):a}throw new SyntaxError("JSON.parse");}})();
//

function shortlistToolbar() {
var slSwitch = getUrlParam("sl");
var omHeaderLinkSL = "s.tl(this,'o','SLIST:HEADER')";
	if(slSwitch == "on" && getLocalData("shortlistCookie")!==null){
		var cookieObject = JSON.parse(getLocalData("shortlistCookie"));
		
		if (cookieObject[0] !== undefined){

			if(cookieObject[0].ids.length !== 0){
				var adIds = new Array(); 
				var ids = cookieObject[0].ids;
				var idLength = ids.length;

				for (var i=0;i<idLength;i++){
					adIds.push(ids[i].id);
				}
				var shortlistUrl = '/ucs/ShortlistAction.do?ids='+adIds.toString();
				$('#shortlistLink').remove();
				$('#header #rightLinks').prepend('<li id="shortlistLink"><a href="'+shortlistUrl+'" onclick="'+omHeaderLinkSL+'">My Shortlist ['+idLength+']</a>&nbsp;&nbsp;|&nbsp;&nbsp;</li>');
			}
			else{
				$('#shortlistLink').remove();
			}
		}
		else{
			$('#shortlistLink').remove();
		}
		
	}
}

// onLoad
$(function() {
	shortlistToolbar();
});

