var req;
var isIE;
var names;
var nameRow;
var nowIndex = 0;
var idField;
var menu;
var timeCount;
var autorow;
var isHide = readCookie("Suggest");
var str_show = "Show Suggestions";
var str_hide = "Hide Suggestions";
var suggestIframe;
var suggestURL = "/plugins/querySuggest.php"; // service URL of ajax requested 
var domainName = "http://www.couponmountain.com";

if(typeof XmlHttpRequest =="undefined"){
	isIE=true;
}
if (window.XMLHttpRequest) {
}else if (window.ActiveXObject) {
	isIE=true;
}

isIE = getBrowser() == 1 ? true : false;

function getBrowser()
{
   if(navigator.userAgent.indexOf("MSIE")>0)return 1;;
   if(isFirefox=navigator.userAgent.indexOf("Firefox")>0)return 2;;
   if(isSafari=navigator.userAgent.indexOf("Safari")>0)return 3;;
   if(isCamino=navigator.userAgent.indexOf("Camino")>0)return 4;;
   if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0)return 5;;
   return 0;;
}


function init_search(){
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	}else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	initWindow();
}

function initWindow(){
	idField = document.getElementById("searchKey");
	menu = document.getElementById("searchKey");
	autorow = document.getElementById("menupopup");
	suggestIframe = document.getElementById("suggestbg");
	if ( isIE )
	{
		autorow.style.top = window.suggest_ie_top;// + parseInt(getElementY(menu));			//define the top of the div
		autorow.style.left = window.suggest_ie_left;// + parseInt(getElementX(idField));		//define the left of the div 
//		suggestIframe.style.top = window.suggest_ie_top;
		suggestIframe.style.left = 0;//window.suggest_ie_left;
//		autorow.style.width = parseInt(idField.clientWidth) + window.suggest_width;		//define the width of the div
	}
	else
		ptable = document.getElementById("ptable");
}

window.onresize=function(){
	initWindow();
}

function showSuggest()
{
	suggestIframe.style.display = "block";
	autorow.style.visibility = "visible";
	ptable.style.visibility = "visible";
}

function hideSuggest()
{
	suggestIframe.style.display = "none";
	autorow.style.visibility = "hidden";
	ptable.style.visibility = "hidden";
}

document.onmouseup = function (){
	try {
		if((isIE)?(names && names.rows && names.rows.length!=0):(names && names.childNodes && names.childNodes.length!=0)){
			hideSuggest();
		}
	} catch (e) {}
}

document.onkeydown = function (e){
	if((isIE)?(event.keyCode == 9):(e.which ==9)){
		try {
			if((isIE)?(names&&names.rows.length!=0):(names.childNodes.length!=0)){
				hideSuggest();
			}
		} catch (e) {}
	}
	if(names&&((isIE)?(names.rows.length!=0):(names.childNodes.length!=0))&&(autorow.style.visibility == "visible")){
		if ((isIE)?(event.keyCode == 38):(e.which ==38)){
			if (nowIndex>=0){
				nowIndex=(nowIndex!=0)?nowIndex - 1:0;
				makeTableWhite();
				changeTableColor(nowIndex);
				fillText();
			}
		}
		else if ((isIE)?(event.keyCode == 40):(e.which==40)){
			if (nowIndex>=-1&&nowIndex < ((isIE)?(names.rows.length-1):(names.childNodes.length-1))){
				nowIndex = nowIndex + 1;
				makeTableWhite();
				changeTableColor(nowIndex);
				fillText();
			}
		}
	}
}

function fillText(){
	if(isIE){
		var getTr = names.rows[nowIndex];
		var valueTd = getTr.getElementsByTagName("td");
		var keyword = valueTd[0].innerText;
	}else{
		var getTr =names.childNodes[nowIndex];
		if (getTr) {
			var valueTd = getTr.childNodes[0];
			var keyword = valueTd.childNodes[0].childNodes[0].innerHTML;
		}
	}
	// Modified By James 
	// don't display encoded string
	document.searchForm.searchKey.value = keyword.replace('&amp;', '&');
	// Modified End
}

function changeTableColor(rowIndex){
	makeTableWhite();
	if (isIE) {var getTr = names.rows[rowIndex];}else{var getTr = names.childNodes[rowIndex];}
	if (getTr) {
		getTr.className = "mouseOver";
		nowIndex = rowIndex;
		getTr.childNodes[0].childNodes[0].childNodes[0].className="mouseOverFont";
		getTr.childNodes[1].childNodes[0].className="mouseOverFont";	
	}
}

function makeTableWhite(){
	if(isIE){var getTr = names.rows;}else{var getTr = names.childNodes;}
	for (i=0 ;i<getTr.length; i++){
		if(i%2==0){getTr[i].className = "initTr";}else{getTr[i].className = "initTr1";}
		getTr[i].childNodes[0].childNodes[0].childNodes[0].className="mouseOutFont";
		getTr[i].childNodes[1].childNodes[0].className="mouseOutRight";
	}
}

function getElementX(element){
	var targetLeft = 0;
	if(element.offsetParent){
		while (element.offsetParent){
			targetLeft = targetLeft + element.offsetLeft;
			element = element.offsetParent;
		}
	}else if(element.x){
		targetLeft+=element.x;
	}
	return targetLeft;
}

function getElementY(element){
	var targetTop = 0;
	if (element.offsetParent) {
		while (element.offsetParent) {
			targetTop += element.offsetTop;
			element = element.offsetParent;
		}
	}else if(element.y){
		targetTop = targetTop+element.y;
	}
	return targetTop;
}

function validate(e){
	(e==null)?key=45:key=e.keyCode;
	timeCount=key;
	window.setTimeout("validate1("+key+")",100);
}


function validate1(e){
	if(!isHide){
		if(key==timeCount){
			if (key>=48 && key<=90 || key==8 || key==32 || key== 45 || key==46){
				if(window.idField == null || (!window.idField)) idField = document.getElementById("searchKey");
				if(window.req == null) init_search();
				if(window.idField && window.req){
					try {
						var url = suggestURL + "?id=" + encodeURI(idField.value);
						req.open("GET", url, true);
						req.onreadystatechange = processRequest;
						req.send(null);
					} catch (e) {}
				}
			 }
		}
	}
}

function processRequest(){
	if(req.readyState==4){
		try {
			if(req.status==200){
				parseMessages();
			}else{
				clearTable();
				hideSuggest();
			}
		} catch (e) {}
	}
}

function parseMessages(){
	if(!names) names = document.getElementById("names");
	clearTable();
	try {
		var products = eval("(" + req.responseText +")");
		var tableLength = products.length>10?10:products.length;
		for (loop=0;loop<tableLength;loop++){
			var product = products[loop];
			var productname = product.pname.value;
			var productnumber = product.pnumber.value;
			appendProduct(productname, productnumber,loop);
		}
		suggestIframe.style.height = tableLength * 14 + 2;
	} catch (e) {}
	if(isHide==true){
		hideSuggest();
	}
	else{
		showSuggest();
	}
	nowIndex=-1;
	if((isIE)?(names.rows.length!=0):(names.childNodes.length!=0)){
		makeTableWhite();
	}
	if ((isIE)?(names.rows.length<1):(names.childNodes.length<1)){
		hideSuggest();
	}
}

function clearTable(){
	if (names) {
		for (loop = names.childNodes.length -1; loop >= 0 ; loop--) {
			names.removeChild(names.childNodes[loop]);
		}
	}
}

function format( number )
{
	if ( number == '1' )
		return "1 result";
	
	for ( var i = 9; i > 0; i -= 3 )
		if ( number.length > i )
			number = number.substr( 0, number.length - i ) + " " + number.substr( number.length - i, i );
	
	return number + " results";
}

function appendProduct(fnameId,fnumberId,loopNo) {
	var nameCell;
	var nameCellRight;
	if (isIE) {
		nameRow = names.insertRow(names.rows.length);
		nameCell = nameRow.insertCell(0);
		nameCellRight = nameRow.insertCell();
	}else{
		nameRow = document.createElement("tr");
		nameCell = document.createElement("td");
		nameCellRight = document.createElement("td");
		nameRow.appendChild(nameCell);
		nameRow.appendChild(nameCellRight);
		names.appendChild(nameRow);
	}
	
	if(loopNo%2!=0){nameRow.className = "initTr";}else{nameRow.className = "initTr1";}
	nameRow.setAttribute("border", "0");
	nameCell.setAttribute("border", "0");
	nameCell.setAttribute("align", "left");
	nameCell.setAttribute("rowNumber",loopNo);
//	var slid=document.getElementById("slid");
	// Modified By James 
	// encode twice for apache rewrite
	nameRow.setAttribute("goHref", domainName + "/coupon-codes--se-" + encodeURIComponent(encodeURIComponent(fnameId)) + '.html');
	// Modified End
	var linkElement = document.createElement("a");
	linkElement.setAttribute("href","#" );
	if(isIE){linkElement.setAttribute("className","link_word" );}else{linkElement.setAttribute("class","link_word" );}
	
	var nameFontElement = document.createElement("font");
	nameFontElement.setAttribute("style", "font-size: 12px;");
	nameFontElement.setAttribute("color", "black");
	nameFontElement.appendChild(document.createTextNode(fnameId));
	nameCell.onmouseover= function(){ 
		try{changeTableColor(this.getAttribute("rowNumber"));
			this.childNodes[0].childNodes[0].className = "mouseOverFont";
			this.parentElement.childNodes[1].childNodes[0].className="mouseOverFont";
		} catch (e) {}
	};
	nameCell.onmouseout= function(){//this.parentElement.className="initTr";
		try{makeTableWhite();
			this.childNodes[0].childNodes[0].className = "mouseOutFont";
			this.parentElement.childNodes[1].childNodes[0].className = "mouseOutRight";
		} catch (e) {}
	};
	
	var nameFontElementRight = document.createElement("font");
	nameFontElementRight.setAttribute("size", "2");
	nameFontElementRight.setAttribute("color", "#006600");
	nameFontElementRight.appendChild(document.createTextNode(""));//format(fnumberId)));
	nameCellRight.setAttribute("align", "right");
	nameCellRight.setAttribute("rowNumber",loopNo);
	nameCellRight.appendChild(nameFontElementRight);
	nameCellRight.onmouseover= function(){changeTableColor(this.getAttribute("rowNumber"));
									this.parentElement.childNodes[0].childNodes[0].childNodes[0].className="mouseOverFont"
									this.childNodes[0].className="mouseOverFont";};
	nameCellRight.onmouseout= function(){//this.parentElement.className="initTr";
									makeTableWrite();
									this.parentElement.childNodes[0].childNodes[0].childNodes[0].className="mouseOutFont"
									this.childNodes[0].className="mouseOverRight";};

	nameRow.onmousedown = function (){
									if(isIE){
										window.location.href = this.goHref;
										var getRow = names.rows[nowIndex];
										var valueTd = getRow.getElementsByTagName("td");
										var keyword = valueTd[0].innerText;
									}else{
										window.location.href=this.getAttribute("goHref");
										var getRow = names.childNodes[nowIndex];
										var valueTd=getRow.childNodes[0];
										var keyword = valueTd.childNodes[0].childNodes[0].innerHTML;
									}
									// Modified By James 
									// don't display encoded string
									document.searchForm.searchKey.value = keyword.replace('&amp;', '&');
									// Modified End
									}
	linkElement.appendChild(nameFontElement);
	nameCell.appendChild(linkElement);
}

function hS(){
	hs = document.getElementById("hsb");
	if(isHide==false){
		isHide=true;
		if(isIE){hs.setAttribute("innerHTML",str_show);}
		else{hs.innerHTML=str_show;}
		hideSuggest();
		writeCookie("Suggest",isHide,null);
	}
	else{
		isHide=false;
		if(isIE){hs.setAttribute("innerHTML",str_hide);}
		else{hs.innerHTML=str_hide;}
		clearTable();
		validate(null);
		showSuggest();
		if(!names){
			hideSuggest();
		}
		else if((isIE)?(names.rows.length<1):(names.childNodes.length<1)){
			hideSuggest();
		}
		writeCookie("Suggest",isHide,null);
	}
}

function readCookie(name){
	var cookieValue = "";
	var search = name + "=";
	if(document.cookie.length > 0){ 
		offset = document.cookie.indexOf(search);
		if (offset != -1){ 
			offset += search.length;
			end = document.cookie.indexOf(";", offset);
			if (end == -1) end = document.cookie.length;
			cookieValue = unescape(document.cookie.substring(offset, end))
		}
	}
	if (cookieValue.toUpperCase()=="TRUE")
	{
		return true;
	}
	else 
	{
		return false;
	}
}

function writeCookie(name, value, hours){
	var expire = "";
	if(hours != null){
		expire = new Date((new Date()).getTime() + hours * 3600000);
		expire = "; expires=" + expire.toGMTString();
	}
	document.cookie = name + "=" + escape(value) + expire + "; path=/";
}

document.writeln("<style>");
document.writeln(".mouseOver {background: #0066FF;	color: #FFFAFA; cursor:hand}");
document.writeln(".mouseOutFont{color: #000000;}");
document.writeln(".mouseOutRight{color: #006600;}");
document.writeln(".mouseOverFont{color: #ffffff;}");
document.writeln(".initTr{ color: #000000;}");
document.writeln(".initTr1{ color: #000000;}");
document.writeln("a.link_word:link{text-decoration:none;font-weight:normal;padding-left:3px;}");
document.writeln("a.link_word:visited{text-decoration:none;font-weight:normal;padding-left:3px;}");
document.writeln("a.link_word:active{text-decoration:none;font-weight:normal;padding-left:3px;}");
document.writeln("a.link_word:hover{text-decoration:none;font-weight:normal;padding-left:3px;}");
document.writeln("a.link_font:link{color: white;text-decoration:none;font-weight:normal;padding-left:3px;}");
document.writeln("a.link_font:active{color: black;text-decoration:none;font-weight:normal;padding-left:3px;}");
document.writeln("a.link_font:visited{color: white;text-decoration:none;font-weight:normal;padding-left:3px;}");
document.writeln("a.link_font:hover{color: black;text-decoration:none;font-weight:normal;padding-left:3px;}");
document.writeln("</style>");

function get_autorow_window_html()
{
	return '<div id="menupopup" style="position: absolute; background:transparent; z-index:100; top:' + suggest_ff_top + 'px; left:' + suggest_ff_left + 'px; " >' + "\n" + 
			'<table id="ptable" class="suggestmenu" border="0" cellpadding="0" bgcolor="#566175" cellspacing="1" style="visibility:hidden;border-left:1px solid #535f75">'  + "\n" + 
			'  <tr>' + "\n" + 
			'    <th bgcolor="#FFFFFF" scope="row" style="border-left:1px solid #404040;">' + "\n" + 
			'         <table id="names" width="100%" border="0" cellpadding="0" cellspacing="0">' + "\n" + 
			'			</table>' + "\n" + 
			'	</th>' + "\n" + 
			'  </tr>' + "\n" + 
			'</table>' + "\n" + 
			'<iframe id="suggestbg" style=" display:none; top:0; left:10px; background:transparent; position: absolute; z-index:-2; " src="about:blank" frameBorder=0 scrolling=no >' + "\n" +
			'</iframe>' + "\n" + 
			'</div>';
}


var suggest_ff_top = 39;
var suggest_ff_left =0;




var browserie = navigator.userAgent.toLowerCase();
if (browserie.indexOf("msie 6") > 0){
var suggest_ie_top = 39;
var suggest_ie_left = 0;
}else{
var suggest_ie_top = 39;
var suggest_ie_left = 0;
}

window.se_offset_top = 20;
window.se_offset_left = 0;
window.se_offset_width = 80;
