/*
00001     9/07/2009         tejas   ShowSuggestions() updated to fix position of div 
*/
var textboxObj = null;
var divObj = null;
//var divContent;
//var tableElem;
var SelectedRowIndex = 0;
var MaxIndex = 15;
var TextBoxOldValue = "";
var numRows = 5;
var execQuery = "";
var rowHeight = 20;
var timerID = null;
var delay = 500;
//var outLength = 10;
//var numRows2 = 10;
var maxLength = 5;
var results = null;
var ResultLength= 0;
var DeepRet=true;
//var dragDropObj = new DHTMLgoodies_dragDrop() ;
var searchReq;

function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("Browser dosnt support");
    }
}
//function AdjustScroll()
//{
//	var currentSelected = SelectedRowIndex*rowHeight;
//	if ( currentSelected <= document.getElementById("DIV1").scrollTop )
//	{
//		divObj.scrollTop = currentSelected - rowHeight;
//	}
//	else if ( currentSelected > document.getElementById("DIV1").scrollTop + numRows*rowHeight )
//	{
//		divObj.scrollTop = currentSelected - numRows*rowHeight;
//	}
//}


function funcMouseOver(obj)
{
	SelectedRowIndex = obj.id.split("_")[1];
    //obj.style.backgroundColor='#94B684'	
    obj.firstChild.className="auto_hover";    
}

function funcMouseOver_feed(obj)
{
    obj.style.backgroundColor='#ffffff';	
}

function funcMouseOut(obj)
{
    //obj.style.backgroundColor='#ffffff';
    obj.firstChild.className="autotd";
}


function funcOnClick(obj)
{
	var indata=OldTextBoxValue()+document.getElementById(obj.id).firstChild.innerHTML;
	indata=indata.replace("<B>","");
	indata=indata.replace("</B>","");
    textboxObj.value = indata;
//	textboxObj.value = obj.firstChild.innerHTML+',';
//	TextBoxOldValue = textboxObj.value;
//	divObj.style.visibility = "hidden";
//	SelectedRowIndex = 0;
 // FocusOut();
}

var temp_rslt_id,fd_or_tag,succ_func ;



function startAutoSuggest(textbox,fd_or_tag1)
{
textboxObj =  document.getElementById(textbox);
textboxObj.onkeyup = keyReleased;
return DeepRet;	
}

function FocusOut()
{
    var strNewTextValue = "";
    if (divObj!=null)
    {
	    if(divObj.style.visibility == "visible" && SelectedRowIndex > 0)
	    {	
	        strNewTextValue = OldTextBoxValue();
	        if (document.getElementById("row_" + SelectedRowIndex)!=null)
		    //textboxObj.value = strNewTextValue + document.getElementById("row_" + SelectedRowIndex).firstChild.innerHTML + ',';
		    var indata = strNewTextValue + document.getElementById("row_" + SelectedRowIndex).firstChild.innerHTML ;
	        indata=indata.replace("<B>","");
	        indata=indata.replace("</B>","");		    
		    textboxObj.value=indata;
		    TextBoxOldValue = textboxObj.value;
		    document.search_box.submit();
	    
		}
	    else if( divObj.style.visibility == "visible" && SelectedRowIndex == 0)
	    {	
	        if (document.getElementById("row_1")!=null)
		    textboxObj.value = textboxObj.value;// + document.getElementById("row_1").firstChild.innerHTML + ',';
		    TextBoxOldValue = textboxObj.value;
	    }
	    divObj.style.visibility = "hidden";
	    divObj.style.display="none";
	}
	SelectedRowIndex=0;
}

function KeyPressed(e)
{
	var whichASC;
	
	DeepRet=true;
	if (navigator.appName == 'Netscape' )
		// This part will work for mozilla
		whichASC = e.which; // keys ASCII code
	else
		// This part will work for IE
		whichASC = event.keyCode;

	var TRNAME = "row_" + SelectedRowIndex;
    var strNewTextValue = OldTextBoxValue();
        
	switch(whichASC)
	{
		case 40:
		    /// For DownKeyPress    
		   
			if (divObj != null && divObj.style.visibility == "visible")
			{
			    
				if( SelectedRowIndex != 0 )
				{
				if (document.getElementById(TRNAME)!=null)
					document.getElementById(TRNAME).firstChild.className = "autotd";
				}
					
				if(SelectedRowIndex == MaxIndex)
				{
					textboxObj.value = TextBoxOldValue;
					SelectedRowIndex = maxLength-1;
				    break;
				}
				else
				{
					if(SelectedRowIndex == 0)
					{
						TextBoxOldValue = textboxObj.value;
					}
					    SelectedRowIndex++;
					    TRNAME = "row_" + SelectedRowIndex;
					    if(document.getElementById(TRNAME)!=null)
					    {
					    document.getElementById(TRNAME).firstChild.className = "auto_hover";
					    textboxObj.value = strNewTextValue + document.getElementById(TRNAME).firstChild.innerHTML;
					    }
/*					else if(SelectedRowIndex == maxLength)
					{
					    SelectedRowIndex=1;
					    TRNAME = "row_" + SelectedRowIndex;
					    if(document.getElementById(TRNAME)!=null)
					    {
					    document.getElementById(TRNAME).firstChild.className = "autotd";
					    ///
					    textboxObj.value = strNewTextValue + document.getElementById(TRNAME).firstChild.innerHTML;
					    }
					}*/
					
				}
				//AdjustScroll();
			}
			break;
			
			
		case 38:
		
		    /// For UPKeyPress 
			if (divObj != null && divObj.style.visibility == "visible")
			{
			    if (SelectedRowIndex <0)
			    {
			        divObj.style.visibility = "hidden";
			        break;
			    }
			
				if( SelectedRowIndex != 0 && SelectedRowIndex > -1 )
				{
				    if (document.getElementById(TRNAME)!=null)
					    document.getElementById(TRNAME).firstChild.className = "autotd";
				}
				else
				{
				if (SelectedRowIndex != 0)
					SelectedRowIndex = MaxIndex + 1;
				}
				
				if(SelectedRowIndex == 1)
				{
				    SelectedRowIndex = maxLength;
				    TRNAME = "row_" + SelectedRowIndex;
				    if (document.getElementById(TRNAME)!=null)
			        {
			            document.getElementById(TRNAME).firstChild.className = "autotd";
			            textboxObj.value = strNewTextValue + document.getElementById(TRNAME).firstChild.innerHTML;
			        }
				}
				else
				{
					if(SelectedRowIndex == MaxIndex + 1)
					{
						TextBoxOldValue = textboxObj.value;
					}

					if(SelectedRowIndex > 1 && SelectedRowIndex <= maxLength)
					{

					    SelectedRowIndex--;
       
					    TRNAME = "row_" + SelectedRowIndex;
					    if (document.getElementById(TRNAME)!=null)
					    {
					        document.getElementById(TRNAME).firstChild.className = "auto_hover";
					        textboxObj.value = strNewTextValue + document.getElementById(TRNAME).firstChild.innerHTML;
					    }
					}
				}
				//AdjustScroll();
			}
			break;
			
		case 27:
		    /// For Escape KeyPress 
		    if (divObj != null && divObj.style.visibility == "visible")
			{
			    if ( TextBoxOldValue != null )
				    textboxObj.value = TextBoxOldValue;
			    else
				    TextBoxOldValue = textboxObj.value;

			    divObj.style.visibility = "hidden";
			}
			break;
			
			
		case 44:
		    /// For comma KeyPress 
		    if (divObj != null && divObj.style.visibility == "visible")
			{
			    TextBoxOldValue = textboxObj.value;
			    divObj.style.visibility = "hidden";
			}
			break;
			
		
		case 13:
		    /// For Enter KeyPress 
		    if (divObj != null && divObj.style.visibility == "visible")
			{
			    TextBoxOldValue = textboxObj.value;
			    divObj.style.visibility = "hidden";
			}
			SelectedRowIndex=0;
			DeepRet=false;
			break;			
		default:
			break;
	}

}


function keyReleased(e)
{
	var whichASC;
	if (navigator.appName == 'Netscape' )
	    // This part will work for mozilla
		whichASC = e.which; // keys ASCII code
	else
		// This part will work for IE
		whichASC = event.keyCode;
    
	if ( ( whichASC >= 65 && whichASC <= 90 ) ||
		 ( whichASC >= 219 && whichASC <= 222 ) ||
		 ( whichASC >= 190 && whichASC <= 192 ) ||
		 ( whichASC >= 96 && whichASC <= 111 && whichASC != 108 ) ||
		 whichASC == 188 || whichASC == 8 )
	{
        TextBoxOldValue = textboxObj.value;
		if( whichASC == 8)		
			SelectedRowIndex = 0;			
		if( TextBoxOldValue == "" )
		{
			if(divObj){divObj.style.visibility = "hidden";}
			return;
		}		
		startTimer();
	}
}


function startTimer()
{
	if(timerID != null)
	{
		clearTimeout(timerID);
		timerID = null;
	}
	timerID = self.setTimeout("doQuery()", delay);
}


function doQuery()
{
searchReq = getXmlHttpRequestObject();
searchReq.open("GET", 'autosuggest/searchSuggest.php?search=' + textboxObj.value, true);
searchReq.onreadystatechange = ShowSuggestions; 
searchReq.send(null);   
}
function prepareTable()
{
	var tableStr = "<table cellSpacing=0 cellPadding=2>";
    var maxLength = 10;
/*    if(maxLength > ResultLength)
    {*/
        maxLength = ResultLength;
//    } 
    for( var i=1; i<=maxLength; i++ )
	{   
	    var innerResult = results[i-1].split("|");
		tableStr += "<tr id=";
		tableStr += "\"row_"+i+"\" ";
		tableStr += "style=\"height:20;\" onmouseover=\"funcMouseOver(this);\" onmouseout=\"funcMouseOut(this);\" class=\"autosuggesttd\" ><td class='autotd' align=\"left\" style='cursor:pointer' onclick='hide_results();' >";
		tableStr += "<a  href='"+innerResult[0]+"' style='color:black;'><b>";
		tableStr += innerResult[1];
		tableStr += "</b></a></td></tr>"
	}
	tableStr += "</table>";	
	return tableStr;
}
function hide_results()
{
	if(divObj!=null)
	{
	  divObj.style.visibility = "hidden";
	  divObj.style.display="none";
	}
}

function ShowSuggestions()
{
    if (searchReq.readyState == 4) 
	{
	   if (searchReq.status == 200) 
		{
		results = searchReq.responseText.split("||") ;
		 ResultLength= results.length - 1 ;
		 
	// Get the position for diaplying the DIV ---------------------------------
	var tag1 = textboxObj.offsetParent.tagName;
	var top1 = textboxObj.offsetTop;
	var left1 = textboxObj.offsetLeft;
	var height1 = textboxObj.offsetHeight;
	var a = textboxObj;
//    alert(tag1+"---"+top1+"---"+left1+"---"+height1);
	while(tag1 != "BODY")
	{
		a = a.offsetParent;
		tag1 = a.tagName;
		top1 = top1 + a.offsetTop;
		left1 = left1 + a.offsetLeft;
	}
	//-------------------------------------------------------------------------
	// Create the DIV element
    maxLength = 10;
    if(maxLength > ResultLength)
    {
        maxLength = ResultLength;
    } 
	if( divObj == null )
	{
		divObj = document.createElement("DIV");
	    divObj.innerHTML = "yahoo";
		divObj.style.position = "absolute";
		divObj.style.top = top1 + height1;
		//divObj.style.left = left1-71;
		//from above line - 71 is removed to display the list properly. by d		
		divObj.style.left = left1;
		
		SelectedRowIndex = 0;
//      divObj.style.width = textboxObj.offsetWidth ;		
		divObj.style.width =  "160px" ;	//here width also reduce  from 170  to 160, by d
		divObj.style.height =height1;
		divObj.style.overflow= "auto";
		divObj.style.zIndex = 100000 - 0;
		divObj.className = "autosuggest";
		divObj.id = "DIV1";
	    document.getElementById("input_search").appendChild(divObj);
//	document.body.appendChild(divObj);
	}
	else
	{
	    divObj.innerHTML = "";
		divObj.style.top = top1 + height1;
		divObj.style.left = left1 ;
	}
	//-------------------------------------------------------------------------
	// Set the content to display in the DIV
	//divObj.innerHTML = (divObj.id =="DIV1")? prepareTable() : dump_feeds_fun();
	divObj.innerHTML =  prepareTable() ;
    if( maxLength != 0 )
	{	
		rowHeight = divObj.firstChild.firstChild.firstChild.style.height.split("px")[0];	    
        if(rowHeight!="" || rowHeight!=0)
		divObj.style.height = maxLength*rowHeight;
		divObj.style.visibility = "visible";
    	divObj.style.display="block"; 
	}
	else
    	divObj.style.visibility = "hidden";
	
	SelectedRowIndex = 0;
	divObj.scrollTop = 0;
	}
}
}

function handleQueryError(req)
{
	if(req == currentRequest)
		alert('error occurred.');
}


/// This function use to preserve the old values of textbox. -N
function OldTextBoxValue()
{
    var strNewTextBoxValue="";
    var tempNew ="";
    if (TextBoxOldValue!="" || TextBoxOldValue!=" ")
        tempNew = TextBoxOldValue.substr(0 ,TextBoxOldValue.lastIndexOf(','));
    if (tempNew !="")
        strNewTextBoxValue = tempNew + ',';

    return strNewTextBoxValue;
}
function AutoDivRequestQuery(textbox,fd_or_tag1,target_div)
{
 var AutoDivRequest = getXmlHttpRequestObject(); 
    var textboxDiv =  document.getElementById(textbox);
    var divobjDiv = document.getElementById(target_div); 
function dump_feeds_fun() 
{
    if (AutoDivRequest.readyState == 4 ) 
	{
	   if (AutoDivRequest.status == 200) 
		{
		var divresult;		
		 divresult = AutoDivRequest.responseText.split("||") ;		 
         var tableStr = '<ul style="padding-left:1px;">';
         var  divresultinner ;
         var suggest ;
         tableStr = "" ;
       for(i=0; i < divresult.length - 1; i++) 
       {
      
                //Build our element string.  This is cleaner using the DOM, but
                  //IE doesn't support dynamically added attributes.
               divresultinner  = divresult[i].split("|");
                // suggest = '    <li style=\"list-style-type:none;vertical-align:middle;\"><div class=\"dragableBox\" id= \"sourceTag_'+divresultinner[1]+'\"><img src=\"images/folder_folder.gif\" style=\"vertical-align :middle;\" >&nbsp;&nbsp;&nbsp;'+divresultinner[0]+'</div></li>';
                   if (fd_or_tag1 == "feed")
                  {
                   suggest = '<div style="height:30px;">   <img src=\"images/rss.gif\" style=\"vertical-align :middle;\" >&nbsp;&nbsp;<a onclick="addDefaultFeed(this)" style="text-decoration:none;color:black;" href="javascript:void(0);" id="'+divresultinner[1]+'">'+divresultinner[0]+'</a></div>';
                    tableStr += suggest; 
                  }
                else
                {
                    suggest = '<div class=\"dragableBox\" id= \"sourceTag_'+divresultinner[1]+'\">   <img src=\"images/folder_folder.gif\" style=\"vertical-align :middle;\" >&nbsp;&nbsp;'+divresultinner[0]+'</div>';
                    tableStr += suggest;
                }        
      }
        divobjDiv.innerHTML = tableStr;
        
        if (fd_or_tag1 != "feed")
        {
         
            var j = 0 ;
            dragDropObj.dragDropSourcesArray = new Array();            
            for(j=0; j < divresult.length - 1; j++) 
            {
                   
            //Build our element string.  This is cleaner using the DOM, but
            //IE doesn't support dynamically added attributes.
            divresultinner = divresult[j].split("|");     
            dragDropObj.addSource('sourceTag_'+divresultinner[1],true);    
            }
            
          dragDropObj.init();   
        }
    }
    return;  
    }    
   return false;    
}       
  
   
    
          
    if (fd_or_tag1 == "feed")
        AutoDivRequest.open("GET", 'autosuggest/searchSuggest_feed.php?search=' + textboxDiv.value, true);
    else
        AutoDivRequest.open("GET", 'autosuggest/searchSuggest.php?search=' + textboxDiv.value, true);            
    AutoDivRequest.onreadystatechange = dump_feeds_fun ;     
    AutoDivRequest.send(null);
    
}
function AutoSuggestAjax(textbox,fd_or_tag1,target_div)
{  
	  startAutoSuggest(textbox,fd_or_tag1);        
}



function addtargetTag(obj_resp)
{
       if (obj_resp.readyState == 4 ) 
	{
	   if (obj_resp.status == 200) 
		{
        var divresult = obj_resp.responseText.split("||") ;		 
             var j = 0 ;
           
            dragDropObj.dragDropTargetArray = new Array();   
			if(document.getElementById('destTag_0'))
		        dragDropObj.addTarget('destTag_0','dropItems');                
            for(j=0; j < divresult.length - 1; j++) 
            { 
				if(document.getElementById('destTag_'+divresult[j]))
		            dragDropObj.addTarget('destTag_'+divresult[j],'dropItems');    
            }
           
          dragDropObj.init();   
          }
          }
}

function dropItems(idOfDraggedItem,targetId,x,y)
{

var c_or_state = document.getElementById('cntry_name').value;
idOfDraggedItem = idOfDraggedItem.replace('sourceTag_','');
targetId = targetId.replace('destTag_','');
AutoSuggestAjax('txtSearch','tag','dump_tags');
makeRequest('includes/modules/update_feed_directory.php?action=update&parentid='+ targetId +'&tagid='+ idOfDraggedItem +'&locationid='+c_or_state ,'addfeed_dirhandler','errors','POST');
}


	   
function addfeed_dirhandler(obj_resp)	   
{
      if (obj_resp.readyState == 4 ) 
	{
	   if (obj_resp.status == 200) 
		{
		  
	if(obj_resp.responseText==true || obj_resp.responseText=="true")
    {
        load_treeview(document.getElementById('cntry_name').value);       
    }
		}
	}
}
	
function delete_FeedDir(dir_ID, tag_Name)
{

if(confirm("Do you want to delete Feed "+ tag_Name +" ?"))
{
	makeRequest('includes/modules/update_feed_directory.php?action=delete&nodeid='+ dir_ID ,'delete_FeedDir_handler','errors','POST');
}
}
function delete_FeedDir_handler(obj_resp)
{

 load_treeview(document.getElementById('cntry_name').value);
 //alert("Feed Directory Successfully Delted");
}