
var zXml={useActiveX:(typeof ActiveXObject!="undefined"),useDom:document.implementation&&document.implementation.createDocument,useXmlHttp:(typeof XMLHttpRequest!="undefined")};zXml.ARR_XMLHTTP_VERS=["MSXML2.XmlHttp.5.0","MSXML2.XmlHttp.4.0","MSXML2.XmlHttp.3.0","MSXML2.XmlHttp","Microsoft.XmlHttp"];zXml.ARR_DOM_VERS=["MSXML2.DOMDocument.5.0","MSXML2.DOMDocument.4.0","MSXML2.DOMDocument.3.0","MSXML2.DOMDocument","Microsoft.XmlDom"];;function zXmlHttp(){}zXmlHttp.createRequest=function(){if(zXml.useXmlHttp){return new XMLHttpRequest();}else if(zXml.useActiveX){if(!zXml.XMLHTTP_VER){for(var i=0;i<zXml.ARR_XMLHTTP_VERS.length;i++){try{new ActiveXObject(zXml.ARR_XMLHTTP_VERS[i]);zXml.XMLHTTP_VER=zXml.ARR_XMLHTTP_VERS[i];break;}catch(oError){;}}}if(zXml.XMLHTTP_VER){return new ActiveXObject(zXml.XMLHTTP_VER);}else{throw new Error("Could not create XML HTTP Request.");}}else{throw new Error("Your browser doesn't support an XML HTTP Request.");}};zXmlHttp.isSupported=function(){return zXml.useXmlHttp||zXml.useActiveX;};function zXmlDom(){}zXmlDom.createDocument=function(){if(zXml.useDom){var oXmlDom=document.implementation.createDocument("","",null);oXmlDom.parseError={valueOf:function(){return this.errorCode;},toString:function(){return this.errorCode.toString()}};oXmlDom.__initError__();oXmlDom.addEventListener("load",function(){this.__checkForErrors__();this.__changeReadyState__(4);},false);return oXmlDom;;}else if(zXml.useActiveX){if(!zXml.DOM_VER){for(var i=0;i<zXml.ARR_DOM_VERS.length;i++){try{new ActiveXObject(zXml.ARR_DOM_VERS[i]);zXml.DOM_VER=zXml.ARR_DOM_VERS[i];break;}catch(oError){;}}}if(zXml.DOM_VER){return new ActiveXObject(zXml.DOM_VER);}else{throw new Error("Could not create XML DOM document.");}}else{throw new Error("Your browser doesn't support an XML DOM document.");}};zXmlDom.isSupported=function(){return zXml.useDom||zXml.useActiveX;};var oMozDocument=null;if(typeof XMLDocument!="undefined"){oMozDocument=XMLDocument;}else if(typeof Document!="undefined"){oMozDocument=Document;}if(oMozDocument&&!window.opera){oMozDocument.prototype.readyState=0;oMozDocument.prototype.onreadystatechange=null;oMozDocument.prototype.__changeReadyState__=function(iReadyState){this.readyState=iReadyState;if(typeof this.onreadystatechange=="function"){this.onreadystatechange();}};oMozDocument.prototype.__initError__=function(){this.parseError.errorCode=0;this.parseError.filepos=-1;this.parseError.line=-1;this.parseError.linepos=-1;this.parseError.reason=null;this.parseError.srcText=null;this.parseError.url=null;};oMozDocument.prototype.__checkForErrors__=function(){if(this.documentElement.tagName=="parsererror"){var reError=/>([\s\S]*?)Location:([\s\S]*?)Line Number(\d+),Column(\d+):<sourcetext>([\s\S]*?)(?:\-*\^)/;reError.test(this.xml);this.parseError.errorCode=-999999;this.parseError.reason=RegExp.$1;this.parseError.url=RegExp.$2;this.parseError.line=parseInt(RegExp.$3);this.parseError.linepos=parseInt(RegExp.$4);this.parseError.srcText=RegExp.$5;}};oMozDocument.prototype.loadXML=function(sXml){this.__initError__();this.__changeReadyState__(1);var oParser=new DOMParser();var oXmlDom=oParser.parseFromString(sXml,"text/xml");while(this.firstChild){this.removeChild(this.firstChild);}for(var i=0;i<oXmlDom.childNodes.length;i++){var oNewNode=this.importNode(oXmlDom.childNodes[i],true);this.appendChild(oNewNode);}this.__checkForErrors__();this.__changeReadyState__(4);};oMozDocument.prototype.__load__=oMozDocument.prototype.load;oMozDocument.prototype.load=function(sURL){this.__initError__();this.__changeReadyState__(1);this.__load__(sURL);};Node.prototype.__defineGetter__("xml",function(){var oSerializer=new XMLSerializer();return oSerializer.serializeToString(this,"text/xml");});Node.prototype.__defineGetter__("text",function(){var sText="";for(var i=0;i<this.childNodes.length;i++){if(this.childNodes[i].hasChildNodes()){sText+=this.childNodes[i].text;}else{sText+=this.childNodes[i].nodeValue;}}return sText;});}function zXslt(){}zXslt.transformToText=function(oXml,oXslt){if(typeof XSLTProcessor!="undefined"){var oProcessor=new XSLTProcessor();oProcessor.importStylesheet(oXslt);var oResultDom=oProcessor.transformToDocument(oXml);var sResult=oResultDom.xml;if(sResult.indexOf("<transformiix:result")>-1){sResult=sResult.substring(sResult.indexOf(">")+1,sResult.lastIndexOf("<"));}return sResult;;}else if(zXml.useActiveX){return oXml.transformNode(oXslt);}else{throw new Error("No XSLT engine found.");}};function zXPath(){}zXPath.selectNodes=function(oRefNode,sXPath,sXmlNs){if(typeof XPathEvaluator!="undefined"){oXmlNs=oXmlNs||{};var nsResolver=function(sPrefix){return oXmlNs[sPrefix];};var oEvaluator=new XPathEvaluator();var oResult=oEvaluator.evaluate(sXPath,oRefNode,nsResolver,XPathResult.ORDERED_NODE_ITERATOR_TYPE,null);var aNodes=new Array;if(oResult!=null){var oElement=oResult.iterateNext();while(oElement){aNodes.push(oElement);oElement=oResult.iterateNext();}}return aNodes;}else if(zXml.useActiveX){if(oXmlNs){var sXmlNs="";for(var sProp in oXmlNs){sXmlNs+="xmlns:"+sProp+"="+oXmlNs[sProp]+" ";}oRefNode.ownerDocument.setProperty("SelectionNamespaces",sXmlNs);};return oRefNode.selectNodes(sXPath);}else{throw new Error("No XPath engine found.");}};zXPath.selectSingleNode=function(oRefNode,sXPath,oXmlNs){if(typeof XPathEvaluator!="undefined"){;oXmlNs=oXmlNs||{};var nsResolver=function(sPrefix){return oXmlNs[sPrefix];};var oEvaluator=new XPathEvaluator();var oResult=oEvaluator.evaluate(sXPath,oRefNode,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE,null);if(oResult!=null){return oResult.singleNodeValue;}else{return null;};}else if(zXML.useActiveX){if(oXmlNs){var sXmlNs="";for(var sProp in oXmlNs){sXmlNs+="xmlns:"+sProp+"="+oXmlNs[sProp]+" ";}oRefNode.ownerDocument.setProperty("SelectionNamespaces",sXmlNs);};return oRefNode.selectSingleNode(sXPath);}else{throw new Error("No XPath engine found.");}};function zXMLSerializer(){}zXMLSerializer.prototype.serializeToString=function(oNode){var sXml="";switch(oNode.nodeType){case 1:sXml="<"+oNode.tagName;for(var i=0;i<oNode.attributes.length;i++){sXml+=" "+oNode.attributes[i].name+"=\""+oNode.attributes[i].value+"\"";}sXml+=">";for(var i=0;i<oNode.childNodes.length;i++){sXml+=this.serializeToString(oNode.childNodes[i]);}sXml+="</"+oNode.tagName+">";break;case 3:sXml=oNode.nodeValue;break;case 4:sXml="<![CDATA["+oNode.nodeValue+"]]>";break;case 7:sXml="<?"+oNode.nodevalue+"?>";break;case 8:sXml="<!--"+oNode.nodevalue+"-->";break;case 9:for(var i=0;i<oNode.childNodes.length;i++){sXml+=this.serializeToString(oNode.childNodes[i]);}break;};return sXml;};

var oldTextboxValue
function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, 
                            oProvider /*:SuggestionProvider*/,
							sAction
							) {
	this.hideme = 0;
	this.submitme = 1;
	this.Action = sAction;
    this.cur /*:int*/ = -1;
    this.layer = null;
    this.provider /*:SuggestionProvider*/ = oProvider;
    this.textbox /*:HTMLInputElement*/ = oTextbox;
    this.timeoutId /*:int*/ = null;
    this.userText /*:String*/ = oTextbox.value;
    //initialize the control
    this.init();
    
}

AutoSuggestControl.prototype.autosuggest = function (aSuggestions, aRank, bTypeAhead) {
    
    //re-initialize pointer to current suggestion
    this.cur = -1;
    
    //make sure there's at least one suggestion
	if (aSuggestions) {
	    if (aSuggestions.length > 0) {
	        if (bTypeAhead) { this.typeAhead(aSuggestions[0]); }
	        this.showSuggestions(aSuggestions, aRank);
	    } else {
	        this.hideSuggestions();
	    }
	}
};

AutoSuggestControl.prototype.createDropDown = function () {

    //create the layer and assign styles
    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    this.layer.style.paddingLeft = "2px";    
    this.layer.style.paddingRight = "3px";  
	// Fix for Home input box which doesn't get its width info properly  - Keith
	if (this.textbox.id == "Home") {
		this.layer.style.width = 150;
	} else {
	    this.layer.style.width = this.textbox.offsetWidth;
	}

    document.body.appendChild(this.layer);    
    
    //when the user clicks on the a suggestion, get the text (innerHTML)
    //and place it into a textbox
    var oThis = this;
    this.layer.onmousedown = 
    this.layer.onmouseup = 
    this.layer.onmouseover = function (oEvent) {

        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;
        
		if(oldTextboxValue == null) {
			oldTextboxValue = oThis.textbox.value;
		}
		
        if (oEvent.type == "mousedown") {
		
            if (oTarget.getAttribute("RealVal") != "!@#$%^&*()" && oTarget.parentNode.getAttribute("RealVal") != "!@#$%^&*()") {
                oThis.textbox.value = oTarget.getAttribute("RealVal") || oTarget.parentNode.getAttribute("RealVal") || oldTextboxValue;
                oThis.hideSuggestions();
    			
			    if(oThis.Action == "GetKeywords") {
				    search.submit();
			    } else if (oThis.Action == "Big_GetKeywords") { 
				    Big_search.submit();
			    }
		    }	
		    
        } else if (oEvent.type == "mouseover") {
		
		    if (oTarget.getAttribute("RealVal") != "!@#$%^&*()" && oTarget.parentNode.getAttribute("RealVal") != "!@#$%^&*()") {
			    if (oTarget.parentNode.getAttribute("RealVal")) {
				    oThis.highlightSuggestion(oTarget.parentNode);
				    //oThis.textbox.value = oTarget.parentNode.getAttribute("RealVal") || oldTextboxValue;
			    } else {
				    oThis.highlightSuggestion(oTarget);
				    //oThis.textbox.value = oTarget.getAttribute("RealVal") || oldTextboxValue;
			    }
			    
		} else {
			oThis.textbox.value = oldTextboxValue;
		}
        } else {
            oThis.textbox.focus();
        }
		
    };
   
};

AutoSuggestControl.prototype.getLeft = function () /*:int*/ {

    var oNode = this.textbox;
    var iLeft = 0;
    
    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;        
    }
    
    return iLeft;
};

AutoSuggestControl.prototype.getTop = function () /*:int*/ {

    var oNode = this.textbox;
    var iTop = 0;
    
    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
    return iTop;
};

AutoSuggestControl.prototype.goToSuggestion = function (iDiff /*:int*/) {
    var cSuggestionNodes = this.layer.childNodes;
    
    if (cSuggestionNodes.length > 0 && this.userText.length > 0) {
        var oNode = null;
    	this.submitme = 0;
		
        if (iDiff > 0) {
            if (this.cur < cSuggestionNodes.length-1) {
                oNode = cSuggestionNodes[++this.cur];
            }        
        } else {
            if (this.cur > 0) {
                oNode = cSuggestionNodes[--this.cur];
            }    
        }
if(oldTextboxValue == null) {
	oldTextboxValue = this.textbox.value;
}
         if (oNode) {
            this.highlightSuggestion(oNode);
			if (oNode.getAttribute("RealVal") != "!@#$%^&*()" && oNode.parentNode.getAttribute("RealVal") != "!@#$%^&*()") {
            	this.textbox.value = oNode.getAttribute("RealVal");
			} else {
				this.textbox.value = oldTextboxValue;
			}
        }
    }
};

AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {
    switch(oEvent.keyCode) {
		case 9: //tab
            //this.goToSuggestion(1);
			this.hideme = 1;
			this.hideSuggestions();
            break;
        case 38: //up arrow
            this.goToSuggestion(-1);
            break;
        case 40: //down arrow 
            this.goToSuggestion(1);
            break;
        case 27: //esc
            this.textbox.value = this.userText;
            this.selectRange(this.userText.length, 0);
            /* falls through */
		case 13: //enter
			if (this.submitme != 1) {
				this.hideSuggestions();
				this.submitme = 1;
            	oEvent.returnValue = false;
            		if (oEvent.preventDefault) {
            	    oEvent.preventDefault();
            	}
			} else {
			this.hideSuggestions();
			}
        default:
			this.hideme = 0;
			break;
    }

};

AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {

    var iKeyCode = oEvent.keyCode;
    var oThis = this;
    
    //get the currently entered text
    this.userText = this.textbox.value;
    
    clearTimeout(this.timeoutId);

    //for backspace (8) and delete (46), shows suggestions without typeahead
    if (iKeyCode == 8 || iKeyCode == 46) {
        
        this.timeoutId = setTimeout( function () {
            oThis.provider.requestSuggestions(oThis, false);
        }, 10);
        
    //make sure not to interfere with non-character keys
    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
        //ignore
    } else {
        //request suggestions from the suggestion provider with typeahead
        this.timeoutId = setTimeout( function () {
            oThis.provider.requestSuggestions(oThis, true);
        }, 10);
    }
};

AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};

AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {

    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "current"
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};

AutoSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;
    
    //assign the onkeyup event handler
    this.textbox.onkeyup = function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyUp() method with the event object
        oThis.handleKeyUp(oEvent);
    };
    
    //assign onkeydown event handler
    this.textbox.onkeydown = function (oEvent) {

        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyDown() method with the event object
        oThis.handleKeyDown(oEvent);
    };
    
    //assign onblur event handler (hides suggestions)    
    this.textbox.onblur = function () {
        oThis.hideSuggestions();
    };
    
    //create the suggestions dropdown
    this.createDropDown();
};

AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iEnd /*:int*/) {

    //use text ranges for Internet Explorer
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iEnd - this.textbox.value.length);      
        oRange.select();
        
    //use setSelectionRange() for Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iEnd);
    }     

    //set focus back to the textbox
    this.textbox.focus();      
}; 

AutoSuggestControl.prototype.showSuggestions = function (aSuggestions, aRank) 
	{
    var oDiv = null;
    this.layer.innerHTML = "";  //clear contents of the layer

	if (this.Action == "GetKeywords" || this.Action == "Big_GetKeywords") {
	    var increment = 0;
		oDiv = document.createElement("div");
		oDiv.setAttribute("align", "right");
		oDiv.style.borderBottom = '2px solid black';
		oDiv.setAttribute("RealVal", "!@#$%^&*()");
	    this.layer.appendChild(oDiv);
		this.layer.childNodes[0].innerHTML = "<font style='COLOR: #006400; FONT-SIZE: 10pt; font-weight: bold;'>CATEGORY SUGGESTION</font>&nbsp;&nbsp;";	
		increment = increment + 1;

	} else {
		var increment = 0;
	}
	
    var what = this.textbox.value.split(" ");
	var matches = new Array();
	
    for (var i=0; i < aSuggestions.length; i++) {
	    matches[0]=[0];
	    matches[1]=[0];
		//Play with the Suggestion to highlight the words that macth words in our array splitting on spaces.
		var Suggestions = aSuggestions[i].split(" ");
		
		for (var j=0; j < what.length; j++) {
			for (var k=0; k < Suggestions.length; k++) {
				if (what[j] != "" && what[j].toLowerCase() == Suggestions[k].toLowerCase().substring(0,what[j].length) && (this.Action == "GetKeywords" || this.Action == "Big_GetKeywords")) //Only for keywords
					{
						matches[0][k] = 1;
						matches[1][k] = what[j].length;
					}
			}
    	}
    	
		var myhtml = "";
		
		for (var k=0; k < Suggestions.length; k++) {
		
			if (matches[0][k] == 1)
				{
					myhtml = myhtml + "<font style='color:#ff0000;FONT-WEIGHT:bold;'>" + Suggestions[k].substring(0,matches[1][k]) + "</font>" + Suggestions[k].substring(matches[1][k],Suggestions[k].length) + " ";
				}
				else
				{
				    if (k==Suggestions.length - 1) {
					    myhtml = myhtml + Suggestions[k]; 
				    }
				    else {
					    myhtml = myhtml + Suggestions[k] + " ";  
				    }
				}
			}

			oDiv = document.createElement("div");
			oDiv.style.borderBottom = '1px dotted Black';
			oDiv.style.paddingTop = '4px';
			oDiv.style.paddingBottom = '4px';
			oDiv.setAttribute("RealVal", aSuggestions[i]);
       		this.layer.appendChild(oDiv);
       		
            if (aRank != 'Where') {
 			
       		    myhtml = myhtml + '&nbsp;<span style="font-size:12px; color:Gray;">(' + aRank[i] + ')</span>';

            }
            
			this.layer.childNodes[i + increment].innerHTML = myhtml;
    }

    this.layer.style.left = this.getLeft() + "px";
    this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
	
	if (this.hideme != 1) {
    this.layer.style.visibility = "visible";
	}
};

AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {

    //check for support of typeahead functionality
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion; 
        this.selectRange(iLen, sSuggestion.length);
    }
};

function SuggestionProvider() {
    this.http = zXmlHttp.createRequest();
}

SuggestionProvider.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
                                                            bTypeAhead /*:boolean*/) {

    var oHttp = this.http;
	var DisplayZip = "";
    var Dupe = "";
    
    //cancel any active requests                          
    if (oHttp.readyState != 0) {
        oHttp.abort();
    }

	if(oAutoSuggestControl.Action.substring(0,4) == 'Big_') {
		Action = oAutoSuggestControl.Action.replace('Big_','');
		userLocation = document.getElementById("BigWhere").value;
	} else if (oAutoSuggestControl.Action.substring(0,4) == 'Zip_') {
		Action = oAutoSuggestControl.Action.replace('Zip_','');
		DisplayZip = "&DisplayZip=1";
		userLocation = document.getElementById("Where").value;
	} else {
		Action = oAutoSuggestControl.Action;
		userLocation = document.getElementById("Where").value;
	}

    //open connection to server
    if (oAutoSuggestControl.Action == "GetCityState" || oAutoSuggestControl.Action == "GetKeywords") {
        SetCookie('Radius','0')
        SetCookie('BoundaryType','1')
        oHttp.open("get", "/?Action=" + escape(Action) + DisplayZip + "&Word=" + escape(oAutoSuggestControl.userText) + "&Where=" + escape(userLocation) + "&BoundaryType=1", true);
    }
    else {
    
        for(var i = 0; i < document.getElementsByName('BoundaryType').length; i++) {
        
            if(document.getElementsByName('BoundaryType')[i].checked) {
                var BoundaryType = document.getElementsByName('BoundaryType')[i].value;
            }
        }

        SetCookie('Radius',document.getElementById('SelectDistance').value)
        SetCookie('BoundaryType',BoundaryType)
        
        oHttp.open("get", "/?Action=" + escape(Action) + "&Word=" + escape(oAutoSuggestControl.userText) + "&Where=" + escape(userLocation), true);
    }
    
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {
            //evaluate the returned text JavaScript (an array)
			var aSuggestions = eval(oHttp.responseText);

			oldTextboxValue = null;
			var bTypeAhead = false;

            if (Dupe != oHttp.responseText) {
            	Dupe = oHttp.responseText;

			    //provide suggestions to the control
			    if (Action == 'GetKeywords') {
			        oAutoSuggestControl.autosuggest(aSuggestions[0],aSuggestions[1], bTypeAhead);
			    }
			    else {
			        oAutoSuggestControl.autosuggest(aSuggestions,'Where', bTypeAhead);
			    }
                
            }
        }
    };
    
    //send the request
    oHttp.send("");
};

isIE=document.all;
isNN=!document.all&&document.getElementById;
isN4=document.layers;
isHot=false;

function ddInit(e){
  topDog=isIE ? "BODY" : "HTML";
  whichDog=isIE ? document.all.Questions : document.getElementById("Questions");  
  hotDog=isIE ? event.srcElement : e.target;  
  while (hotDog.id!="titleBar"&&hotDog.tagName!=topDog){
    hotDog=isIE ? hotDog.parentElement : hotDog.parentNode;
  }  
  if (hotDog.id=="titleBar"){
    offsetx=isIE ? event.clientX : e.clientX;
    offsety=isIE ? event.clientY : e.clientY;
    nowX=parseInt(whichDog.style.left);
    nowY=parseInt(whichDog.style.top);
    ddEnabled=true;
    document.onmousemove=dd;
  }
}

function dd(e){
	if (!ddEnabled) return;
	whichDog.style.left=isIE ? nowX+event.clientX-offsetx : nowX+e.clientX-offsetx; 
	whichDog.style.top=isIE ? nowY+event.clientY-offsety : nowY+e.clientY-offsety;
	return false;
	}

function ddN4(whatDog){
  if (!isN4) return;
  N4=eval(whatDog);
  N4.captureEvents(Event.MOUSEDOWN|Event.MOUSEUP);
  N4.onmousedown=function(e){
    N4.captureEvents(Event.MOUSEMOVE);
    N4x=e.x;
    N4y=e.y;
  }
  N4.onmousemove=function(e){
    if (isHot){
      N4.moveBy(e.x-N4x,e.y-N4y);
      return false;
    }
  }
  N4.onmouseup=function(){
    N4.releaseEvents(Event.MOUSEMOVE);
  }
}
document.onmousedown=ddInit;
document.onmouseup=function() {
	ddEnabled=false;
	}

function centerMain() {
	var centerBook = GetCookie('centerBook');
	var clientWidth = (document.body.clientWidth / 2) - (972/2);
	if (centerBook < (clientWidth) || centerBook > clientWidth ) {
		if (clientWidth > 25) {
			SetCookie('centerBook',clientWidth);
			document.getElementById('main').style.left=clientWidth;
		} else {
			SetCookie('centerBook','5');
			document.getElementById('main').style.left=5
		}
	}
}

function linkTo(url,AddressGroupID) {
	if(String(url).substring(0,7) == 'http://') { var prepend = ''; } else { var prepend = 'http://'; }

	var logLink = new Image(); 
	logLink.src = '/?Action=LogAction&Type=Link&AddressGroupID=' + AddressGroupID.toString() + '&url='+encodeMyHtml(url.toString());

	var win = null;
	win = window.open(prepend + url,"www", "width=750,height=500,status=1,toolbar=1,menubar=1,location=1,resizable=1,scrollbars=1");
	win.focus();
	}

function emailTo(url,AddressGroupID) {

	var logLink = new Image(); 
	logLink.src = '/?Action=LogAction&Type=Email&AddressGroupID=' + AddressGroupID.toString() + '&url='+encodeMyHtml(url.toString());

	window.location.href='mailto:' + url;
	}

function popad(AddressGroupID) {
	var logLink = new Image(); 
	logLink.src = '/?Action=LogAction&Type=Ad&AddressGroupID=' + AddressGroupID.toString() + '&url='+encodeMyHtml(window.location);
	
	var win = null;
	win = window.open("/PopAd.aspx?ImprintID=" + ImprintID.toString(),"ad", "width=215,height=200,status=0,toolbar=0,menubar=0,location=0");
	win.focus();
	}

function add2Gadet() {
	var logLink = new Image();
	logLink.src = '/?Action=LogAction&Type=add2Gadet&url='+encodeMyHtml(window.location);
	    SetCookie('Review','1');
		window.location = "http://fusion.google.com/add?moduleurl=http%3A%2F%2F' + location.hostname + '%2Fgadget%2Exml";
		
	}
function add2Toolbar() {
	var logLink = new Image(); 
	logLink.src = '/?Action=LogAction&Type=add2Toolbar&url='+encodeMyHtml(window.location);
			var toolbarURL = "http://" + location.hostname + "/toolbar.xml"
			window.location="http://toolbar.google.com/buttons/add?url=" + encodeMyHtml(toolbarURL);
			SetCookie('Review','1');
	}
	
function add2Bookmark() {
	var logLink = new Image(); 
		logLink.src = '/?Action=LogAction&Type=add2Bookmark&url='+encodeMyHtml(window.location);
		var title = 'The Online Yellow Pages'
		var url = 'http://' + location.hostname + '/?Source=Fav'
			if (window.sidebar) { // Mozilla Firefox Bookmark
				window.sidebar.addPanel(title, url,"");
			} else if( window.external ) { // IE Favorite
				window.external.AddFavorite( url, title);
			} else if(window.opera && window.print) { // Opera Hotlist
				return true;
			}
			SetCookie('Review','1');
	}

function closeSpan(name) {
 	document.getElementById(name).style.display='none';
	}

function GetData(i,AddressGroupID,Latitude,Longitude, ToFrom) {
	var logLink = new Image();
	if(String(window.location).indexOf("Action=map")==-1){
		logLink.src = '/?Action=LogAction&Type=Map&AddressGroupID=' + AddressGroupID.toString() + '&url=' + encodeMyHtml(window.location) + '&Lat=' + Latitude + '&Long=' + Longitude;
	} else {
		var objURL = new Object();
		window.location.search.replace(
			new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
				function( $0, $1, $2, $3 ) { 
					if($1 == 'URL') {
						logLink.src = '/?Action=LogAction&Type=Map&AddressGroupID=' + AddressGroupID.toString() + '&url=' + $3 + '&Lat=' + Latitude + '&Long=' + Longitude;
						}
				}
		);
	}
	GDownloadUrl('/?Action=GetThisData&AddressGroupID=' + AddressGroupID + '&ToFrom=' + ToFrom + '&i=' + i + '&' + Math.random(),
	    function (data,responseCode) { 
	        gmarkers[i].openInfoWindowHtml(data) 
        }
    )
}

function encodeMyHtml(str) {
	encodedHtml = escape(str);
	encodedHtml = encodedHtml.replace(/\//g,"%2F");
	encodedHtml = encodedHtml.replace(/\?/g,"%3F");
	encodedHtml = encodedHtml.replace(/=/g,"%3D");
	encodedHtml = encodedHtml.replace(/&/g,"%26");
	encodedHtml = encodedHtml.replace(/@/g,"%40");
	return (encodedHtml);
}

var timer = 0;
function startQuestions(bypass) {
	if (timer || bypass) {
		timer = 0;
		if(document.cookie.indexOf("Review=") == -1 || bypass) {
			var logLink = new Image();
			if(bypass) { var Type = 'Feedback'; } else { var Type = 'TimerQuestion'; }
			    document.getElementById("Questions").style.backgroundColor="#FFFFFF";
				document.getElementById('Questions').style.display='block';
				document.getElementById("Questions").style.top="75px";
				document.getElementById("Questions").style.left="110px";
				document.getElementById("Questions").style.width="700px";
				document.getElementById("Questions").style.height="466px";
				document.getElementById("QuestionsFrame").style.width="698px";
				document.getElementById("QuestionsFrame").style.height="443px";
				document.getElementById("QuestionsFrame").innerHTML="<iframe src='/Review.aspx' width='698' height='443' marginwidth='0' marginheight='0' align='top' scrolling='no' frameborder='0'></iframe>";
		}
	}
}

function getPage(input,output) {
	var getHttp = zXmlHttp.createRequest();
           getHttp.open("get", input, true);
               getHttp.onreadystatechange = function () {
                   if (getHttp.readyState == 4) {
                      document.getElementById(output).innerHTML = getHttp.responseText;
                   }    
               };
           getHttp.send("");
}

function SetCookie(cookieName,cookieValue) {
	var today = new Date();
	var expires_date = new Date( today.getTime() + (86400000 * 365) );
	document.cookie = cookieName + "=" + cookieValue + "; expires=" + expires_date.toGMTString() + "; path=/;";
}

function GetCookie(cookieName) {
	var start = document.cookie.indexOf( cookieName + "=" );
	var len = start + cookieName.length + 1;
	if ( ( !start ) && ( cookieName != document.cookie.substring( 0, cookieName.length ) ) ) { return null; }
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function keyPress(e) {
	if (e.keyCode == 13) {
		getHomeMarker();
	} else if (e.keyCode == 8 || e.keyCode == 46) {
	    if(document.getElementById("HomeMarkerAddress").value == '') {
		    setTimeout("MyLocation()",1);
		}
	}
}

function getHomeMarker() {
	if (document.getElementById("HomeMarkerAddress").value != '' && document.getElementById("HomeMarkerAddress").value != 'Street, City, State or Street and Zipcode' ) {
		geocoder.getLatLng(document.getElementById("HomeMarkerAddress").value,ShowHome );
	} else {
		alert('You need not give your true exact address.\r\nYou can give approximate address.\r\nYour location will be shown as a blue arrow and your search result locations will be shown on the map in red arrows so that you can see how far the search results are away from where you are.\r\nYou can zoom in on your blue arrow location to get a better look at which search results are closest to you. You can also drag your blue arrow to a new location.\r\nOur program will remember the last location of your blue arrow so that you do not have to enter your search location every time you search our pages.');
		return false;
	}
}

function CalcDist(dblLat1,dblLong1,dblLat2,dblLong2) {
	return (Math.acos(Math.cos(dblLat1 * Math.PI / 180) * Math.cos(dblLat2 * Math.PI / 180) * Math.cos(dblLong2 * Math.PI / 180 - dblLong1 * Math.PI / 180) + Math.sin(dblLat1 * Math.PI / 180) * Math.sin(dblLat2 * Math.PI / 180)) * 3963.1);
}

function MyLocation(UserHome) {
    if ( UserHome != '' ) {
		document.getElementById("HomeMarkerAddress").value = UserHome;
	} else {
		document.getElementById("HomeMarkerAddress").value = 'Street, City, State or Street and Zipcode';
		document.getElementById("HomeMarkerAddress").select();
	}
}

function OpenLink(URL) {
	var win = null;
	win = window.open(URL, 'PopUp', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=850,height=560');
	win.focus();
}

function divQuestions(TOP,LEFT,WIDTH,HEIGHT,HTML) {
	document.getElementById("Questions").style.display="block";
	document.getElementById("Questions").style.top=TOP + "px";
	document.getElementById("Questions").style.left=LEFT + 2 + "px";
	document.getElementById("Questions").style.width=WIDTH + 2 + "px";
	document.getElementById("Questions").style.height=HEIGHT + 20 + "px";
	document.getElementById("QuestionsFrame").style.width=WIDTH + "px";
	document.getElementById("QuestionsFrame").style.height=HEIGHT + "px";
	document.getElementById("QuestionsFrame").innerHTML=HTML;
}
    //Top,Left,Width,height
function How2UseUSYP() {
    var logLink = new Image(); 
	logLink.src = '/?Action=LogAction&Type=How2UseUSYP&url='+encodeMyHtml(window.location);
	document.getElementById("Questions").style.backgroundColor="#FFFFFF";
	//divQuestions(-50,410,500,500,"<table width='95%' border='0' cellspacing='2' cellpadding='2' align='center'><tr><td colspan='2' align='center'><b>How to Use?<\/b><\/td><\/tr><tr><td>1. Select the city or area in which you want to search by entering either your zip code or city and state combination in the &quot;Where:&quot; box.<br><br>2. Enter what you are looking for in the &quot;What:&quot; box, such as &quot;Flowers&quot; or &quot;Restaurants&quot; etc. Take advantage of our drop-down suggestions and click on the suggestions that closest match your search criteria.<br><br>3. Click on the link &quot;CLICK TO SEE MORE INFO&quot; that takes you to a profile page with more information such as a map and driving directions and opening hours and services offered by the business.<br><br>Tips:<br><li> When you do not immediately find what you are looking for, click on the links in the blue category heading.<\/li><br><li>Under the heading you can click on different choices for how to display the search results: A to Z, by distance and by user rating rank.<\/li><br>Click <a href=\"javascript:closeSpan('Questions');\"><img src='\/images\/xButton.gif' alt='Close' width='19' height='19' border='0'></a> to close.<\/td><\/tr><\/table>")
    var oHttp = zXmlHttp.createRequest();
        oHttp.open("get", "/HowToUse.aspx?" + Math.random(), true);
        oHttp.onreadystatechange = function () {
            if (oHttp.readyState == 4) {
                if(oHttp.responseText != '') {
                    divQuestions(-50,410,500,450,'<div style="margin:10px;">' + oHttp.responseText + '<br> click the <a href="javascript:closeSpan(\'Questions\');"><img src="/images\/xButton.gif" alt="Close" width="19" height="19" border="0"></a> to close</div>');
                }
            }
        };
        oHttp.send("");
    }

/*
Table sorting script  by Joost de Valk, check it out at http://www.joostdevalk.nl/code/sortable-table/.
Based on a script from http://www.kryogenix.org/code/browser/sorttable/.
Distributed under the MIT license: http://www.kryogenix.org/code/browser/licence.html .

Copyright (c) 1997-2007 Stuart Langridge, Joost de Valk.

Version 1.5.7
*/

/* You can change these values */
var image_path = "/images/";
var image_up = "arrow-up.gif";
var image_down = "arrow-down.gif";
var image_none = "arrow-none.gif";
var europeandate = false;
var alternate_row_colors = true;

/* Don't change anything below this unless you know what you're doing */
addEvent(window, "load", sortables_init);

var SORT_COLUMN_INDEX;
var thead = false;

function sortables_init() {
	// Find all tables with class sortable and make them sortable
	if (!document.getElementsByTagName) return;
	tbls = document.getElementsByTagName("table");
	for (ti=0;ti<tbls.length;ti++) { //"
		thisTbl = tbls[ti];
		if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
			ts_makeSortable(thisTbl);
		}
	}
}

function ts_makeSortable(t) {
	if (t.rows && t.rows.length > 0) {
		if (t.tHead && t.tHead.rows.length > 0) {
			var firstRow = t.tHead.rows[t.tHead.rows.length-1];
			thead = true;
		} else {
			var firstRow = t.rows[0];
		}
	}
	if (!firstRow) return;
	
	// We have a first row: assume it's the header, and make its contents clickable links
	for (var i=0;i<firstRow.cells.length;i++) {
		var cell = firstRow.cells[i];
		var txt = ts_getInnerText(cell);
		if (cell.className != "unsortable" && cell.className.indexOf("unsortable") == -1) {
		    cell.innerHTML = '<a href="#" class="sortheader" onclick="ts_resortTable(this, '+i+');return false;">'+txt+'<span class="sortarrow"></span></a>';
			// eric cell.innerHTML = '<a href="#" class="sortheader" onclick="ts_resortTable(this, '+i+');return false;">'+txt+'<span class="sortarrow">&nbsp;&nbsp;<img src="'+ image_path + image_none + '" alt="&darr;"/></span></a>';
		}
	}

}

function ts_resortTable(lnk, clid, NoCol, HeadingID, Filter) {

	var span;

	if (NoCol==1) lnk = lnk.childNodes[0];

	for (var ci=0;ci<lnk.childNodes.length;ci++) {
		if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
	}

	var spantext = ts_getInnerText(span);
	var td = lnk.parentNode;
	var column = clid || td.cellIndex;
	var t = getParent(td,'TABLE');
   
	// Work out a type for the column
	if (t.rows.length <= 1) return;
	var itm = "";
	var i = 0;

	while (itm == "" && i < t.tBodies[0].rows.length) {

		var itm = ts_getInnerText(t.tBodies[0].rows[i].cells[column]);
		itm = trim(itm);
		if (itm.substr(0,4) == "<!--" || itm.length == 0) {
			itm = "";
		}
		i++;
	}
	if (itm == "") return; 
	
	sortfn = ts_sort_caseinsensitive;

	if (itm.match(/^\d\d[\/\.-][a-zA-z][a-zA-Z][a-zA-Z][\/\.-]\d\d\d\d$/)) sortfn = ts_sort_date;
	if (itm.match(/^\d\d[\/\.-]\d\d[\/\.-]\d\d\d{2}?$/)) sortfn = ts_sort_date;
	if (itm.match(/^-?[£$€Û¢´]\d/)) sortfn = ts_sort_numeric;
	if (itm.match(/^-?(\d+[,\.]?)+(E[-+][\d]+)?%?$/)) sortfn = ts_sort_numeric;

	SORT_COLUMN_INDEX = column;
	var firstRow = new Array();
	var newRows = new Array();
	for (k=0;k<t.tBodies.length;k++) {
		for (i=0;i<t.tBodies[k].rows[0].length;i++) { 
			firstRow[i] = t.tBodies[k].rows[0][i]; 
		}
	}

	if (Filter==1) {
        var Result = ResultT.cloneNode(true);

	    for (k=0;k<Result.tBodies.length;k++) {
		    if (!thead) {
			    var g;
			    g = 0;
    			
			    // Skip the first row
			    for (j=1;j<Result.tBodies[k].rows.length;j++) { 
    			
			        if (Result.tBodies[k].rows[j].getAttribute('headingids').indexOf('*' + HeadingID) >= 0 || HeadingID==0)
			        {
			            newRows[g] = Result.tBodies[k].rows[j];
			            
			            g = g + 1;
			        } 
			    }
		    } else {
			    // Do NOT skip the first row
			    for (j=0;j<t.tBodies[k].rows.length;j++) { 
				    newRows[j] = t.tBodies[k].rows[j];
			    }
		    }
	    }
    }
    else {
    
	    for (k=0;k<t.tBodies.length;k++) {
		    if (!thead) {
			    // Skip the first row
			    for (j=1;j<t.tBodies[k].rows.length;j++) { 
				    newRows[j-1] = t.tBodies[k].rows[j];
			    }
		    } else {
			    // Do NOT skip the first row
			    for (j=0;j<t.tBodies[k].rows.length;j++) { 
				    newRows[j] = t.tBodies[k].rows[j];
			    }
		    }
	    }
    }

	newRows.sort(sortfn);
	
	var AddressGroupID;
    var AvgLat = 0;
    var AvgLong = 0;
    var Lat = 0;
    var long = 0;
    map.clearOverlays();
    
	//re-number the results to always be 1-9 asc.
	for (k=0;k<newRows.length;k++) {

	    if (k<9) {
	        AddressGroupID = parseInt(newRows[k].cells[2].getAttribute('AddressGroupID')); 
	        Lat = parseFloat(newRows[k].cells[2].getAttribute('Lat')); 
	        Long = parseFloat(newRows[k].cells[2].getAttribute('Long')); 
            AvgLat = ((AvgLat * k) + Lat) / (k + 1);
            AvgLong = ((AvgLong * k) + Long) / (k + 1);
            map.addOverlay(createMarker(1, AddressGroupID, Lat, Long, k + 1, 0));
	        newRows[k].cells[0].innerHTML = k + 1;
	    }
	    else {
	        newRows[k].cells[0].innerHTML = '';
	    }
	}   
	
    //Home
    CreateHome();
    map.setCenter(new GLatLng(AvgLat,AvgLong),MapZoomLvl);

	if (span.getAttribute("sortdir") == 'down') {
			ARROW = '';
			//eric ARROW = '&nbsp;&nbsp;<img src="'+ image_path + image_down + '" alt="&darr;"/>';
			newRows.reverse();
			span.setAttribute('sortdir','up');
	} else {
	        ARROW = '';
			//ARROW = '&nbsp;&nbsp;<img src="'+ image_path + image_up + '" alt="&uarr;"/>';
			span.setAttribute('sortdir','up');
	} 
	
    var m;
    m = t.tBodies[0].rows.length;
    
    for (i=1; i<m; i++) {
        t.tBodies[0].removeChild(t.tBodies[0].rows[1]);
    }
    
    for (i=0; i<newRows.length; i++) { 
		if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) {
			t.tBodies[0].appendChild(newRows[i]);
		}
	}
	
    // do sortbottom rows only
    for (i=0; i<newRows.length; i++) {
		if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) 
			t.tBodies[0].appendChild(newRows[i]);
	}
	// Delete any other arrows there may be showing
	var allspans = document.getElementsByTagName("span");
	/* eric
	for (var ci=0;ci<allspans.length;ci++) {
		if (allspans[ci].className == 'sortarrow') {
			if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
				allspans[ci].innerHTML = '&nbsp;&nbsp;<img src="'+ image_path + image_none + '" alt="&darr;"/>';
			}
		}
	}		
	*/
	span.innerHTML = ARROW;

}

function getParent(el, pTagName) {
	if (el == null) {
		return null;
	} else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) {
		return el;
	} else {
		return getParent(el.parentNode, pTagName);
	}
}

function sort_date(date) {	
	// y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
	dt = "00000000";
	if (date.length == 11) {
		mtstr = date.substr(3,3);
		mtstr = mtstr.toLowerCase();
		switch(mtstr) {
			case "jan": var mt = "01"; break;
			case "feb": var mt = "02"; break;
			case "mar": var mt = "03"; break;
			case "apr": var mt = "04"; break;
			case "may": var mt = "05"; break;
			case "jun": var mt = "06"; break;
			case "jul": var mt = "07"; break;
			case "aug": var mt = "08"; break;
			case "sep": var mt = "09"; break;
			case "oct": var mt = "10"; break;
			case "nov": var mt = "11"; break;
			case "dec": var mt = "12"; break;
			// default: var mt = "00";
		}
		dt = date.substr(7,4)+mt+date.substr(0,2);
		return dt;
	} else if (date.length == 10) {
		if (europeandate == false) {
			dt = date.substr(6,4)+date.substr(0,2)+date.substr(3,2);
			return dt;
		} else {
			dt = date.substr(6,4)+date.substr(3,2)+date.substr(0,2);
			return dt;
		}
	} else if (date.length == 8) {
		yr = date.substr(6,2);
		if (parseInt(yr) < 50) { 
			yr = '20'+yr; 
		} else { 
			yr = '19'+yr; 
		}
		if (europeandate == true) {
			dt = yr+date.substr(3,2)+date.substr(0,2);
			return dt;
		} else {
			dt = yr+date.substr(0,2)+date.substr(3,2);
			return dt;
		}
	}
	return dt;
}

function ts_sort_date(a,b) {
	dt1 = sort_date(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
	dt2 = sort_date(ts_getInnerText(b.cells[SORT_COLUMN_INDEX]));
	
	if (dt1==dt2) {
		return 0;
	}
	if (dt1<dt2) { 
		return -1;
	}
	return 1;
}
function ts_sort_numeric(a,b) {

	var aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
	var bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);

	aa = clean_num(aa);
	bb = clean_num(bb);

	return compare_numeric(aa,bb);
}

function ts_getInnerText2(el) {

	if (typeof el == "string") return el;

	var str = "";
alert('2');
	var cs = el.childNodes;
	var l = cs.length;
alert(cs);
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += ts_getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
alert(str);
	return str;
}

function ts_getInnerText(el) {

	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += ts_getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

function compare_numeric(a,b) {
	var a = parseFloat(a);
	a = (isNaN(a) ? 0 : a);
	var b = parseFloat(b);
	b = (isNaN(b) ? 0 : b);
	return a - b;
}
function ts_sort_caseinsensitive(a,b) {
	aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
	bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();

	if (aa==bb) {
		return 0;
	}
	if (aa<bb) {
		return -1;
	}
	return 1;
}
function ts_sort_default(a,b) {
	aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
	bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
	if (aa==bb) {
		return 0;
	}
	if (aa<bb) {
		return -1;
	}
	return 1;
}
function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// 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 {
		alert("Handler could not be removed");
	}
}
function clean_num(str) {
	str = str.replace(new RegExp(/[^-?0-9.]/g),"");
	return str;
}
function trim(s) {
	return s.replace(/^\s+|\s+$/g, "");
}
function Sort() {
    var SortVal;
    SortVal = document.getElementById('SortSelect').value;
    ts_resortTable(document.getElementById(SortVal), 0,1,0, 0);
}
function TurnCatOn(CatID, HeadingID) {
    
    var CatTotal;
    CatTotal = document.getElementById('CatTotal').value;

    // lets filter the recordset
    ts_resortTable(document.getElementById(document.getElementById('SortSelect').value), 0,1, HeadingID, 1);

    for (var i = 0; i <= CatTotal; i++) {
        
        if (CatID == i) {
            document.getElementById('Cat-' + i).className = 'CatOn';
            document.getElementById('CatCnt-' + i).className = 'CatCntOn';
        }
        else {
            document.getElementById('Cat-' + i).className = 'CatOff';
            document.getElementById('CatCnt-' + i).className = 'CatCntOff';   
        }
    }
    
}

function tdHover(a) {

    if (a.className.substring(a.className.length - 2) != 'On') {
        var id = a.getAttribute('id');
        document.getElementById('Cat-' + id.substring(id.indexOf('-') + 1)).className = 'CatHL';
        document.getElementById('CatCnt-' + id.substring(id.indexOf('-') + 1)).className = 'CatCntHL';
    }
}

function tdNoHover(a) {

    if (a.className.substring(a.className.length - 2) != 'On') {
        var id = a.getAttribute('id');
        document.getElementById('Cat-' + id.substring(id.indexOf('-') + 1)).className = 'CatNoHL';
        document.getElementById('CatCnt-' + id.substring(id.indexOf('-') + 1)).className = 'CatCntNoHL';            
    }
}  


function GetDirections(Type)
{
    document.getElementById("GetDirections").style.display="block";
    document.getElementById("GetDirGo").focus();
    
    if (Type=='To') {
        document.getElementById("ToFrom").innerHTML='<b>From:</b> '; 
        document.getElementById("ToLink").className = 'DrDirSelected';
        document.getElementById("FromLink").className = 'Directions';
    }
    else {
        document.getElementById("ToFrom").innerHTML='<b>To:</b> '; 
        document.getElementById("ToLink").className = 'Directions';
        document.getElementById("FromLink").className = 'DrDirSelected';
    }
}

function saveAddress(Address) {
    
	//SetCookie('saveAddress',Address);
	
	if (document.getElementById("ToLink").className=='DrDirSelected'){
        document.getElementById("daddr").value = document.getElementById("busaddr").value;
        document.getElementById("saddr").value = document.getElementById("addr").value;
	}
	else {
        document.getElementById("daddr").value = document.getElementById("addr").value;
        document.getElementById("saddr").value = document.getElementById("busaddr").value;
	}
}

//Top,Left,Width,height
function RecentlyViewedBusinesses() {
    var logLink = new Image();
    
	logLink.src = "/?Action=LogAction&Type=RecentlyViewedBusinesses&url="+encodeMyHtml(window.location);
    document.getElementById("Questions").style.backgroundColor="#FFFFFF";
    var RVs = GetCookie('RVs');
    var HTML = '';
    
	if (RVs != null) {	
	
	    if (RVs.lastIndexOf("ImprintID") > 0) {
	        SetCookie('RVs','')
	        HTML='<span style="font-size:12px;"><br /><br /><center>We have implemented a major upgrade to our system and we could not preserve your history.</center><br /><br /><center>We apologize for the incovenience.</center></span>';
	        
	    }

	    else if (RVs != '') {w
            var temp = new Array();
            temp = RVs.split('^');
            HTML = "<table width='100%'><tr><td>&nbsp;</td><td>";

            for (i = 0; i <= temp.length - 1; i++) 
            {
                var RV = temp[i].substring(0, temp[i].lastIndexOf("**"));
                var BN = temp[i].substring(temp[i].lastIndexOf("**") + 2, 300);

                HTML = HTML + "<b><font style='font-size:12px;'>" + BN + "</font></b><br>" + 
                    "<a class='MoreInfo' href='http://" + RV + "&PopMI=1&BN=" + escape(BN) + "' style='font-size:11px;'>View this business</a>" + 
                    " | " + 
                    "<a class='MoreInfo' href='http://" + RV + "&WR=1&BN=" + escape(BN) + "' style='font-size:11px;'>Write a review</a>" + 
                    "<hr>"
            }
            
            HTML = HTML + "</td><td>&nbsp;</td></tr></table>";
        }
    }
    else {

        HTML = "<br><center>No History</center>";
    }
        HTML = "<div style='POSITION:absolute;WIDTH:298px;height:418px;overflow:auto;'>" + HTML + "</div>";
    divQuestions(85,140,300,420,HTML);
}

// EditMode: 0 = none, 1 = edit, 2 = delete

var EditMode = 0;

function EditModeOff() {
      EditMode = 0;
      document.getElementById("EditModeActive").style.display = "none";
      document.getElementById("EditModeInactive").style.display = "inline";
      document.getElementById("DeleteModeActive").style.display = "none";
      document.getElementById("DeleteModeInactive").style.display = "inline";

}

function EditModeOn() {
      EditMode = 1;
      document.getElementById("EditModeActive").style.display = "inline";
      document.getElementById("EditModeInactive").style.display = "none";
      document.getElementById("DeleteModeActive").style.display = "none";
      document.getElementById("DeleteModeInactive").style.display = "inline";
}

function DeleteModeOn() {
      EditMode = 2;
      document.getElementById("EditModeActive").style.display = "none";
      document.getElementById("EditModeInactive").style.display = "inline";
      document.getElementById("DeleteModeActive").style.display = "inline";
      document.getElementById("DeleteModeInactive").style.display = "none";
}

function ListingHoverOn(element) {
      if (EditMode != 0) {
            element.style.border = "1px solid #FF0000";
            element.style.cursor = "crosshair";
      }
}

function ListingHoverOff(element) {
      if (EditMode != 0) {
            element.style.border = "none";
            element.style.cursor = "auto";
      }
}

function EditListing(ImprintID) {
      if (EditMode == 1) {
            window.location="/Listing/Edit/" + ImprintID
                            + "/?ReturnURL=" + encodeMyHtml(window.location);
      }
      else if (EditMode == 2) {
      
        var UserID = CheckLogin();
        var src = '';
        
        document.getElementById("Questions").style.backgroundColor="#515151";
        src = "<iframe src='";
        
        if(UserID == 0){
            src += "https://www.usyellowpages.com/Admin/Reg.aspx?ReturnURL=";
            src += encodeMyHtml('/DeleteListing.aspx?AddressGroupID=' + ImprintID);
        } else {
            src += "/DeleteListing.aspx?AddressGroupID=" + ImprintID;
        }
        
        src += "' name='Login' id='Login' width='500' height='420' marginwidth='0' marginheight='0' align='top' scrolling='no' frameborder='0'><\/iframe>";
        divQuestions(87,144,500,420,src)
        
        //window.location="/Listing/Delete/" + ImprintID;
                        //+ "/?ReturnURL=" + encodeMyHtml(window.location);
    }
}

function CreateListing() {
            window.location="/Listing/New/?ReturnURL=" + encodeMyHtml(window.location);
}

function NewListing() {
      window.open("/Listing/New/");
}

function MyListings() {
      window.open("/Listing/View/");
}

function CheckLogin() {
    var oHttp = zXmlHttp.createRequest();
        oHttp.open("get", "/?Action=CheckLogin&" + Math.random(), false);
        oHttp.send("");

        if (oHttp.readyState == 4) {
            return oHttp.responseText;
        } else {
            return 0;
        }            

}

function LogIn() {
    
    var UserID = CheckLogin();
    if(UserID == 0){
        document.getElementById("Questions").style.backgroundColor="#515151";
        var src = "<iframe src='";
            src += "https://www.usyellowpages.com/Admin/Reg.aspx?ReturnURL=/MyAccount/?goto=home&ReturnURL=";
            src += encodeMyHtml(window.location);
            src += "' name='Login' id='Login' width='500' height='420' marginwidth='0' marginheight='0' align='top' scrolling='no' frameborder='0'><\/iframe>";
        divQuestions(87,144,500,420,src)
    } else {
        window.location='/MyAccount/?ReturnURL=' + encodeMyHtml(window.location);
    }
}

function LogOut(ReturnURL) {
    var oHttp = zXmlHttp.createRequest();

    var URL = "/?Action=LogOut&" + Math.random();
    oHttp.open("get", URL, false);
    oHttp.send("");
    if(ReturnURL == null || ReturnURL == ''){
        window.location.reload(true);
    } else {
        window.location = ReturnURL;
    }
}

function AdvancedSearch() {
    window.location='/AS/?eWhere=' + document.getElementById("Where").value + '&What=' + document.getElementById("What").value;
}