var stripchar = 2;  //No of charcters to skip.
var maxChar = 20;  //Max no of charcters supported by SnS API.

var _rf = document;
// Key codes to detect which key was pressed.
var UP = 38, DOWN = 40;
var LEFT= 37, RIGHT = 39;
var ENTER = 13, TAB = 9, ESC =27, BACKSPACE = 8;

var index = -1;    //Selected index
var init = 0;  // Is menu ready (inittialised).
var menuopen = 0;   //Status of suggestion. 0 = closed & 1 = open
var selectedRow = null, rows = null, pbox = "", nbox = "", tbox = "", oldtb = "";
var ecache = true;

//////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Common functions /////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////



function nuvalidate(stringToTrim){
	var nuString = stringToTrim.replace(/^\s+|\s+$/g,"");
	
	if(nuString.length>0){		
		nuString = nuString.replace(/\s+/g, " ");
		_rf.forms['query'].MT.value = nuString;
		return true;
	}else{
		return false;
	}
}

/* ************************* QnA iframe Loader  ********************************** */

function openiframe(){
	_rf.getElementById('socialsrch').src="http://qna.rediff.com/Main.php?do=socialsearch";
	return true;
}

function resizer(ht){
  i = _rf.getElementById('socialsrch');
  i.style.height = ht + 1 + "px";
}



/* ************************* Input element Reset  ********************************** */


function inputClear(obj,string){
	if (obj.value == string){
		obj.value="";
		obj.style.color="#000000";
		obj.style.fontWeight="bold";
	}
}

function inputReset(objId, string, flag){
	if (flag){
		if (_rf.getElementById(objId).value==""){
			_rf.getElementById(objId).value=string;
			_rf.getElementById(objId).style.color="#888888";
		}
	}else{
		_rf.getElementById(objId).value=string;
		_rf.getElementById(objId).style.color="#888888";
	}
}

_rf.onload = function (){
	if(_rf.getElementById && _rf.getElementById("queryTop")){
		_rf.getElementById("queryTop").focus();
	}
};




//////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Auto Suggest Code ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////


//var kHost = "http://" + window.location.host + "/ws/suggest.php?prefix=";
//var kHost = "http://" + window.location.host + "/js/new/stest.txt?prefix=";
//var kHost = "http://sns.rediff.com/ws/proxy.php?prefix=";
//var kHost = "http://sns.rediff.com:8001/suggest?prefix="; // Staging
var kHost = "http://cdnsns.rediff.com/suggest?prefix="; // Live
var counter = 0;
_cnt = 1000; // in milliseconds

//object for  caching
var Cache = {
    stack: {}, //Cache stack
    load: function(id){ //Load cache if found
        return (typeof(this.stack[id]) != 'undefined') ? this.stack[id] : false;
    },
	has: function(id){  //Check if data exists in cache
	    return (typeof(this.stack[id]) != 'undefined') ? true : false;
	},
    save: function(data,id){ //Cache data with unique id, if id exists then update it.
        this.stack[id] = data;
    },
    remove: function(id){//Remove cache for identifier
        if(typeof(this.stack[id]) != 'undefined'){
            delete this.stack[id];
		}
    }
};


var Suggestionr = {

	initr: function(nid,pid,textboxid,cachee) { 
		var el = _rf.getElementById(textboxid); 
		el.onfocus = function(){ Suggestionr.initsug(nid,pid,textboxid);  };
		el.onkeyup = function(e){ Suggestionr.showsug(e); };
		el.onkeydown = function(e){ Suggestionr.getkeys(e); };
		_rf.onclick = function(e){ Suggestionr.destroysug(); };
		this.initnext(nid,pid,textboxid,cachee);
		if (_rf.getElementById("snsSRC").value == "sugg"){
			_rf.getElementById("snsSRC").value = "web";
		}
	},

	initnext: function(nid,pid,textboxid,cachee){
		ecache=cachee;
		var wfield  = _rf.createElement('div');
		wfield.setAttribute('id',nid);
		_rf.getElementById(pid).appendChild(wfield);
	},

	initsug: function(newbox,parentbox,textbox){
		_rf.getElementById(parentbox).style.display = "none";
		pbox = parentbox;
		nbox = newbox;
		tbox = textbox;
		menuopen = 0;
		init = 1;
	},

	destroysug: function(){
		try{
			if(init){
				if(_rf.getElementById(nbox)){
					_rf.getElementById(pbox).removeChild(_rf.getElementById(nbox));
				}
				menuopen = 0;
				index = -1;
				selectedRow = null;
				rows = null;
				init=0;
			}
			_rf.getElementById(pbox).style.display = "none";
			_rf.getElementById(pbox).style.height = 0+"px";
		}catch(e){
			//alert(e.message);
		}
	},
	
	getlist: function(q){ 
		//	q = escape(q);
		//	var a = readtext(kHost+q);	//external
		
		if(ecache){
			txt = Cache.load(escape(q));
			if(txt == false){
				var a = _rf.createElement("script");
				a.setAttribute("id","r_sns");
				a.src = kHost+encodeURIComponent(q);
				var b = _rf.getElementById("r_sns"), d = _rf.getElementsByTagName("head")[0];
				if(b){
					d.removeChild(b);
				}
				d.appendChild(a);

				interval=setInterval(function(){  counter++;   },1);
				while(counter > _cnt){
					clearInterval(interval);
					_rf.getElementById(nbox).innerHTML = "";
					_rf.getElementById(nbox).style.display = "none";
					counter=0;
					break;
				}
				
				
			}else{
				_rf.getElementById(nbox).style.display = "block";
				_rf.getElementById(nbox).className = "suggbox";
				_rf.getElementById(nbox).innerHTML = txt;	
			}
		}else{
			var a = _rf.createElement("script");
			a.setAttribute("id","r_sns");
			a.src = kHost+encodeURIComponent(q);
			var b = _rf.getElementById("r_sns"), d = _rf.getElementsByTagName("head")[0];
			if(b){
				d.removeChild(b);
			}
			d.appendChild(a);
			
			interval=setInterval(function(){  counter++;   },1);
			while(counter > _cnt){
					clearInterval(interval);
					_rf.getElementById(nbox).innerHTML = "";								
					counter=0;
					break;
			}
		}

		return true;
		
	},

	IsNotIE: function() { // returns 'true' if browser is not ie
		return (navigator.appName == "Netscape");
	},

	show : function(myArray){
		var txt = "";
		var _kLoc = window.location.href;
		var _len = myArray.length;

		if(_kLoc.indexOf("dirsrch")==-1){
			if(_len>6){_len = 6}
		}
	
		//if(myArray[0] == _rf.getElementById(tbox).value){
			for(i=1;i<_len;i++){
				j=i-1;
				txt += "<div index='"+j+"' class='DefaultRowColor' onMouseOver='Suggestionr.over(this)' onClick='Suggestionr.select(this)'>"+myArray[i]+"</div>";
			}

			counter=0;	

			if(ecache == true){
				myArray[0] = escape(myArray[0]);
				Cache.save(txt,myArray[0]);
			}
		/*}else{
			this.destroysug();
			this.initsug(nbox,pbox,tbox);		
		}*/


		if(txt != ""){
			if(_rf.getElementById(nbox)) {
				_rf.getElementById(nbox).style.display="block";
				_rf.getElementById(nbox).className = "suggbox";
				_rf.getElementById(nbox).innerHTML = txt;
				menuopen=1; 
			}
		}else{
			if(_rf.getElementById(nbox)) _rf.getElementById(nbox).style.display="none";
		} 
		
	},

getkeys: function(e){

		if(window.event){ // IE
			if (!e) var e = window.event;
			keynum = e.keyCode;
		}else if(e.which) { // Netscape/Firefox/Opera
			keynum = e.which;
		}

		if(keynum === DOWN){
			if(menuopen != 0){
				this.MoveCursorDown();
				if(_rf.getElementById(nbox) && selectedRow != null){	
					if(this.IsNotIE()){
						_rf.getElementById(tbox).value = selectedRow.innerHTML;
					}else{
						_rf.getElementById(tbox).value = selectedRow.innerText;
					}
					_rf.getElementById("snsSRC").value = "sugg";
				}else{
					_rf.getElementById("snsSRC").value = "web";
				}
				return;
			}
		}
		else if(keynum === UP){
			this.MoveCursorUp();
			if(_rf.getElementById(nbox) && selectedRow != null){	
				if(this.IsNotIE()){
					_rf.getElementById(tbox).value = selectedRow.innerHTML;
				}else{
					_rf.getElementById(tbox).value = selectedRow.innerText;
				}
				_rf.getElementById("snsSRC").value = "sugg";				
			}else{
				_rf.getElementById("snsSRC").value = "web";
			}
			return;
		}
		else if(keynum == ENTER){
			if(selectedRow!=null){
				if(this.IsNotIE()){
					_rf.getElementById(tbox).value = selectedRow.innerHTML;
				}else{
					_rf.getElementById(tbox).value = selectedRow.innerText;
				}
			}
			this.destroysug();
			this.initsug(nbox,pbox,tbox);
			//As enter key was pressed then submit the form.
			return false;
		}
		else if(keynum === LEFT || keynum === RIGHT){
			if(selectedRow != null){
				if(this.IsNotIE()){
					_rf.getElementById(tbox).value = selectedRow.innerHTML;
				}
				else{
					_rf.getElementById(tbox).value = selectedRow.innerText;
				}
			}
			// dont return value. Let function go forward to show results. and reset the values
			index=-1;  selectedRow = null; rows = null;  init=1;
		}
		else if(keynum === ESC){
			_rf.getElementById(tbox).value = oldtb;
			this.destroysug();
			this.initsug(nbox,pbox,tbox);
            return;
		}
		else if(keynum == TAB){
			if(!_rf.getElementById(nbox)){
				this.initnext(nbox,pbox,tbox,ecache);
			}
			if(selectedRow != null){
				if(this.IsNotIE()){
					_rf.getElementById(tbox).value = selectedRow.innerHTML;
				}
				else{
					_rf.getElementById(tbox).value = selectedRow.innerText;
				}
			}
			this.destroysug();
		}
		else
		{
			//index=-1;  selectedRow = null; rows = null;  init=1; 
			return;
		}

},


showsug: function(e){  //function to traces keys and show lists
	if(window.event) {// IE
		if (!e) var e = window.event;
		keynum=e.keyCode;
	}else if(e.which) {// Netscape/Firefox/Opera
		keynum=e.which;
	}

	if(keynum === TAB || keynum === ESC || keynum === ENTER || keynum === UP || keynum === DOWN)return;
	selectedRow = null; rows = null;

	if(!(_rf.getElementById(nbox))){
		this.initnext(nbox,pbox,tbox,ecache);
	}

	if(_rf.getElementById(pbox)){
		_rf.getElementById(pbox).style.display = "block";
	}

	if((_rf.getElementById(tbox).value.length >= stripchar)&&(_rf.getElementById(tbox).value.length <= maxChar)){
		var q = _rf.getElementById(tbox).value;
		oldtb=_rf.getElementById(tbox).value;
		
		if(q == ""){
			_rf.getElementById(nbox).innerHTML = "";
			_rf.getElementById(nbox).style.display = "none";
			menuopen = 0;
		}else{
			this.getlist(q);
		}

	}else{
		this.destroysug();
	}
	
},

over: function(elem){
	listbox = _rf.getElementById(nbox);
	rows = listbox.getElementsByTagName('div');
	this.SetDefaultRowColor();
	elem.className = "HighlightRow";
	index=elem.getAttribute("index");
	selectedRow = rows[index];
},

select: function(elem){
	_rf.getElementById(tbox).value=elem.innerHTML;
	_rf.getElementById("snsSRC").value = "sugg";
	submitSearch();
	//_rf.getElementById('queryTop').submit();
	this.destroysug();
	this.initsug(nbox,pbox,tbox);
},

MoveCursorUp: function() // Moves the cursor upside
{
	listbox = _rf.getElementById(nbox);
	menuopen=1;
	if(listbox == null) return;
	rows = listbox.getElementsByTagName('div');

	if(index > 0)
	{
		index--;
		this.SetDefaultRowColor();
		selectedRow = rows[index];
		selectedRow.className = "HighlightRow";

	}
	else if(index == 0)
	{
	    this.SetDefaultRowColor();
		index--; selectedRow=null; 

	}
	else if(index < 0)
	{
		index = rows.length-1;
		this.SetDefaultRowColor();
		selectedRow = rows[index];
		selectedRow.className = "HighlightRow";	

	}

},
MoveCursorDown: function() // Moves cursor down
{
	selectedRow = null;
	listbox = _rf.getElementById(nbox);
	menuopen=1;
	if(listbox == null) return;

	rows = listbox.getElementsByTagName('div');

	//if(index < rows.length)
	//{
		if(index < rows.length -1)
		{index++;
		this.SetDefaultRowColor();
		selectedRow = rows[index];
		selectedRow.className = "HighlightRow";
		}
	//}
	else if(index == rows.length -1)
	{
	    this.SetDefaultRowColor();
		index++; selectedRow=null; 

	}
	else if(index > rows.length -1)
	{
		index = 0;
		this.SetDefaultRowColor();
		selectedRow = rows[index];
		selectedRow.className = "HighlightRow";	

	}
},
SetDefaultRowColor: function() // Set color for other rows, as they are not selected
{
	for(i=0;i<rows.length;i++){
		rows[i].className = "DefaultRowColor";
	}
}


};