// 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 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";
	}
}
function rounder(){
	roundDivs = gimme('.roundedCorners')
	for(i=0;i<roundDivs.length;i++){
		roundDivs[i].innerHTML+="<div class='tr'></div><div class='tl'></div><div class='br'></div><div class='bl'></div>";
	}
	
	roundButtons = gimme('.roundMe');
	for(i=0;i<roundButtons.length;i++){
		var wrapper = document.createElement('div'); 
		wrapper.appendChild(roundButtons[i].cloneNode(true)); 
		if(roundButtons[i].id == "searchButton"){	
			wrapper.setAttribute("id", "searchButtonWrapper");
		}
		wrapper.setAttribute("class", "yellowButton");
		wrapper.setAttribute("className", "yellowButton");
		roundButtons[i].parentNode.replaceChild(wrapper, roundButtons[i]);
		wrapper.innerHTML+="<div class='tr'></div><div class='tl'></div><div class='br'></div><div class='bl'></div>";
	}
}

function searchButton(){
	if(document.getElementById('searchButtonWrapper')){
		document.getElementById('searchButtonWrapper').onclick = function(){
			if(document.getElementById('useMultimap')){
				valid = checkForm(this, true);
			}else{
				valid = checkForm(this);
			}
			if(valid){
				document.getElementById('searchBoxForm').submit();
			}
		}
	}
}
yellAddEvent(window, 'load', searchButton);	



var w = 0;

function getBrowserWidth(){
	
	if (window.innerWidth){
		w = window.innerWidth;
	}else if (document.documentElement && document.documentElement.clientWidth != 0){
		w = document.documentElement.clientWidth;
	}else if (document.body){
		w = document.body.clientWidth;
	}		
	return w;
}

//Maps variable function
function changeM(){
	if (document.getElementById('useMultimap').checked) {
		document.forms[0].M.value = '1';
	}else {
		document.forms[0].M.value = '0';
	}
}	


function toggle800(){
	getBrowserWidth();
	if(document.getElementById('searchBoxForm')){
		if(w<931){
			document.getElementById('searchBoxForm').className="narrowRes";
		}else{
			document.getElementById('searchBoxForm').className="";
		}
	}
	
}
yellAddEvent(window, 'load', toggle800);	
yellAddEvent(window, 'resize', toggle800);	

//Validation variables
var pass;
var coNamePass;
var locPass;
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 specialCharsCatcher=new Array("`","#");



function checkForm(myform, mapCheck){
	//mapCheck is only included if the 'Show results on a map' checkbox is displayed otherwise it is an optional field
	if (typeof mapCheck == 'undefined' ) {
		mapCheck = false;
	}
	
	//Single character validation
	locVar = document.getElementById('location').value;
	if(locVar == "]" || locVar == "?" || locVar == "#"){
		document.getElementById('location').value = "";
	}		

	//sets pass variable to true. Do not remove.
	pass = true;
	coNamePass = true;
	hideErrors();	

	if(document.getElementById('keywordsInput') && document.getElementById('keywordsInput').value != '' ){
		for(i=0;i<specialCharsCatcher.length;i++){
			scRegexp = eval("/\\"+specialCharsCatcher[i]+"/g");
			document.getElementById('keywordsInput').value = document.getElementById('keywordsInput').value.replace(scRegexp, "");
		}
	}
	if(document.getElementById('companyName') && document.getElementById('companyName').value != '' ){
		for(i=0;i<specialCharsCatcher.length;i++){
			scRegexp = eval("/\\"+specialCharsCatcher[i]+"/g");
			document.getElementById('companyName').value = document.getElementById('companyName').value.replace(scRegexp, "");
		}
	}
	if(document.getElementById('location') && document.getElementById('location').value != ''){
		for(i=0;i<specialCharsCatcher.length;i++){
			scRegexp = eval("/\\"+specialCharsCatcher[i]+"/g");
			document.getElementById('location').value = document.getElementById('location').value.replace(scRegexp, "");
		}
	}	


	//Map application validation
	if(mapCheck && document.getElementById('useMultimap').checked==true && document.getElementById('location').value != '' &&(document.getElementById('keywordsInput').value == '' && document.getElementById('companyName').value == '' )){
		locationValidation(true);
	}else{
		//Ucs application validation
		//Blank keyword and company name validation
		if(document.getElementById('keywordsInput').value == '' && document.getElementById('companyName').value == '' ){
			document.getElementById('keywordError').style.display = "block";
			document.getElementById('companyNameError').style.display = "block";
			pass = false;
			coNamePass = false;
		}

		//Stopword validation for company name
		if(document.getElementById('companyName').value){
     			var companyName = document.getElementById('companyName').value;
      			var companyNameLowerCase = companyName.toLowerCase();
			for(i=0;i<companyNameWords.length;i++){
				if(companyNameLowerCase == companyNameWords[i]){
					document.getElementById('stopword').innerHTML = companyName;
					document.getElementById('stopwordError').style.display = "block";
					pass = false;
					coNamePass = false;
				}
			}
		}
		//location Validation
		locationValidation(false);
	}

	if(pass){return true}else{return false;}

}

function locationValidation(mapApp){
  //location Validation
  if(document.getElementById('location').value){
    locPass = true;
    var location = document.getElementById('location').value;
    var locationLowerCase = location.toLowerCase();
    for(i=0;i<locationWords.length;i++){
      if(locationLowerCase == locationWords[i]){
        document.getElementById('stopLocation').innerHTML = location;
        document.getElementById('locationStopwordError').style.display = "block";
        locPass = false;
        pass = false;
      }
    }
    if(locPass==true){
      if(mapApp){
        submitSearch();
        pass = false;
      }else{
		if ((document.getElementById('keywordsInput').value.length == "" && document.getElementById('companyName').value.length == "") || coNamePass==false){
			originalVal = document.getElementById('location').value;
		    newVal = '';
		    originalVal = originalVal.split(' ');
		    for(i=0; i<originalVal.length; i++) {
		        newVal += originalVal[i].substring(0,1).toUpperCase() +	originalVal[i].substring(1,originalVal[i].length);
		        if(i+1!=originalVal.length){
			        newVal += ' ';
		        }
		    }
			document.getElementById('locErrorLink').innerHTML = "view a map of <strong>"+newVal+"</strong>";
			document.getElementById('locErrorLink').href="http://maps.yell.com/client/yell/?qs="+document.getElementById('location').value+"&panel=business&submit=Show+map&js=true&intCam=intViewAMapOf";
			document.getElementById('locationError').style.display = "block";
			pass = false;
		}	      
      }
    }
  }
}

function submitSearch(){
	mapLocation = document.getElementById('location').value
	window.location = "http://maps.yell.com/client/yell/?qs="+mapLocation+"&panel=business&submit=Show+map&js=true&intCam=intViewAMapOf"
}	

function hideErrors(){
	document.getElementById('keywordError').style.display = "";
	document.getElementById('companyNameError').style.display = "";
	document.getElementById('stopwordError').style.display = "";
	document.getElementById('locationError').style.display = "";
	document.getElementById('locationStopwordError').style.display = "";	
}

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;}

