﻿jsoc = new JSOC();
var strSearch = "";
var selecColor = "#FFFFE0";
var unSelecColor = "#F8F8F8";
var strWidth = '250px';
var strUrl = '/';
//var strLan;
var iStationCount = 0;
var bSubmitKey = true;
    
function ShowList(str, listId, stationType, portalId, TSICtrl)
{
    if (str.length != 0){

        // Full name, dont search
        if ( str.indexOf(',') < 0)
        {
            document.getElementById(listId).style.display='block';
            //Get from client cache
            var stationsList = jsoc.get(str);

            if (stationsList != undefined){
                // Cache is in JSON, parse it 
                var stationsDiv = GenerateList(stationsList, listId, str, TSICtrl);
                document.getElementById(listId).innerHTML=stationsDiv;
            } else {
                // Not in cache... call the http to get them
                if (str.length==0)
                { 
                    document.getElementById("txtHint").innerHTML="";
                    return;
                }
                xmlHttp=GetXmlHttpObject();
                if (xmlHttp==null)
                {
                    alert ("Your browser does not support AJAX!");
                    return;
                } 
                
//                var url="/RetailWeb/GetStations.aspx";

                if (strUrl == undefined || strUrl == null){strUrl= '/';}

                var url=strUrl+"GetStations.aspx";
                url=url+"?q="+escape(str.toUpperCase());
                url=url+(stationType != '' ? "&type="+stationType : '');
                url=url+(portalId != '' ? "&portalid="+portalId : '');
                //url=url+(strLan != '' ? "&lan="+strLan : '');
                
                xmlHttp.onreadystatechange=function() {
                    if (xmlHttp.readyState==4)
                    { 
                        // JSON decode the response and put it in the div
                        var stationsDiv = GenerateList(xmlHttp.responseText, listId, str, TSICtrl);
                        document.getElementById(listId).innerHTML=stationsDiv;
                        //Add to client's cache, default cached time is 5 minutes...
                        jsoc.add(str,xmlHttp.responseText,{'ttl':'300000'}); 
                    }
                }
                
                xmlHttp.open("GET",url,true);
                xmlHttp.send(null);
       
            }
        } else {
            HideList();
        }
    }  else {
        ShowHelp(listId);
    }          
}

function SetUrl(vUrl){
    strUrl = vUrl;
}

//function SetLan(vLan){
//    strLan = vLan;
//}

function GetXmlHttpObject()
{
    var xmlHttp=null;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

//**************************************************************
//* Function that parse the JSON response to Generate the list  
//**************************************************************
function GenerateList(JsonStr, listId, str, TSICtrl){
    var resp = "";
    var desc = "";
    var iHeight;
    var iStation;
    var iPix;
    var iIframePix;
    var strPix;
    var iStrLength = str.length;
    var iPos;
    var iMaxStation = 9;
   
    stations = json_parse(JsonStr);
    
    for (var i = 0; i < stations.length; i++ ){
    
         desc = stations[i]['dFr'];
         
         if (desc == undefined){desc = stations[i]['dEn'];}
         
         iPos = desc.indexOf( str.toUpperCase(), 0 );
         
         if (iPos != -1){
            // Get the 3 string to insert <B></B>
            desc = desc.replace(str.toUpperCase(), '<b>' + str.toUpperCase() + '</b>');
         }
         
         resp = resp + 
          "<div pos=" + i +(i == 0 ? " style=\"font-weight:normal; background-color:" + selecColor + "; text-decoration:underline; \"" : " style=\"font-weight:normal;\"" )+
          " id='" + stations[i]['sc'] + "' " +
          " title='" + stations[i]['sn'] + ", " + stations[i]['pv'] + "'" +
          " onmouseover=\"ChangeBGColor('" + stations[i]['sc'] + "', '" + selecColor + "', '" + listId + "');\" " +
          " >" + desc + ", " + stations[i]['pv'] + "</div>";
    }
    
    strPix = document.getElementById(listId).style.top;
    iPix = parseInt(strPix.substr(0,2));
    // Set the station count for the scrollbar in keyup keydown
    iStationCount = stations.length;
    // Max 9 row
    
    if (TSICtrl == 'tsi')
    {
        iMaxStation = 4;
    }

    if (stations.length > iMaxStation)
    {
        iStation = iMaxStation;
        iHeight =  iStation* 18;
        document.getElementById(listId).style.height=iHeight.toString()+'px'; // Set the height of the div
        document.getElementById(listId).style.overflow ='auto' ; //add the y scrollbar
        document.getElementById(listId).style.overflowX ='hidden' ; //remove X scrollbar
        document.getElementById(listId).style.width = strWidth;
        iIframePix = iPix + 3 + iHeight;
        SetFrameDimension(iIframePix, strWidth,listId); // ie6 div/select bug patch
        document.getElementById(listId + 'select').style.display='block' ;
    }  else if (stations.length > 0) {
        iStation = stations.length;
        iHeight =  (iStation)* 18;
        document.getElementById(listId).style.height=iHeight.toString()+'px'; // Set the height of the div
        document.getElementById(listId).style.overflow ='hidden';
        document.getElementById(listId).style.width =strWidth ;
        iIframePix = iPix + 3 + iHeight;
        SetFrameDimension(iIframePix, strWidth,listId);
        document.getElementById(listId + 'select').style.display='block' ;
    } else {
        document.getElementById(listId + 'select').style.display='none' ;
    }
    document.getElementById(listId).setAttribute('class', 'listbox');
    document.getElementById(listId).setAttribute('className', 'listbox');
    document.getElementById(listId).style.cursor='pointer';
    bSubmitKey = true;
    return resp;
}

//**************************************************************
//* This function will only set the iframe dimension on ie6 
//* to correct the div/select bug.
//**************************************************************
function SetFrameDimension(height, strLength, listId){
    if (window.XMLHttpRequest){}
    else
    {
        var iHeight = height - 34;
        document.getElementById(listId + 'frame').style.marginTop = '34px';
        document.getElementById(listId + 'frame').style.height= iHeight.toString() + 'px';
        document.getElementById(listId + 'frame').style.width=strLength;
    }
}

//**************************************************************
//* Function to change the bgcolor onmouseover in the station list
//**************************************************************
function ChangeBGColor(elementid, color, listId)
{
    // First put all div bgcolor to the unselected color
    var item;
    
    for (var i = 0; i < document.getElementById(listId).childNodes.length; i++)
    {
        item = document.getElementById(listId).childNodes[i];
        var iType = item.nodeType;
        
        //****************************************************
        //* Firefox problem 
        //* Some node type are text(case 3) and not child(case 1)... 
        //* Dont process the text (case 3)
        //*****************************************************
        switch(iType){
            case 1: 
            {
                item.style.backgroundColor=unSelecColor;
                item.style.textDecoration='none';
                if (item.id == elementid)
                {
                    item.style.backgroundColor=color;
                    item.style.textDecoration='underline';
                }
            }
            case 3: break;
        }
    }
}

//**************************************************************
//* Function to put the station from the list to the input box
//**************************************************************
function SetStation(listId, input, nbrList)
{
    //First Set the station into the input
    var item;
    var bSet = false;
    for (var i = 0; i < document.getElementById(listId).childNodes.length; i++)
    {
        item = document.getElementById(listId).childNodes[i];
        var iType = item.nodeType;
        
        //****************************************************
        //* Firefox problem 
        //* Some node type are text(case 3) and not child(case 1)... 
        //* Dont process the text (case 3)
        //*****************************************************
        switch(iType){
            case 1: {
                if(item.style.textDecoration=='underline'){
                    
                    document.getElementById(input).value = item.title ;
                    document.getElementById(input + '_value').value = item.id;
                    bSet = true;
                    //HideList(nbrList); 
                }
                break;
            }
            case 3: break;
        }
    }
    if (!bSet  && (document.getElementById(input).value == '') )
    {
        document.getElementById(input + '_value').value = '';
    }
    
    //Hide the list since we lost the focus
    HideList(nbrList); 
}


//**************************************************************
//* Function to put the station from the list (view all station link) to the input box
//**************************************************************
function SetStationCallback(input, stationCode, stationName)
{
    //First Set the station into the input
    document.getElementById(input).value = stationName;
    document.getElementById(input + '_value').value = stationCode;
}

function KeyPress(){
    return bSubmitKey;
}
//**************************************************************
//* Function to move up in the stations list
//**************************************************************
function MoveUp(listId)
{
    var item;
    for (var i = 0; i < document.getElementById(listId).childNodes.length; i++)
    {
        item = document.getElementById(listId).childNodes[i];
        
        
        if((item.nodeType==1) &&( item.style.textDecoration=='underline')){
            
            // First item do nothing
            if ( i == 0){
            } else {
                item.style.backgroundColor=unSelecColor;
                item.style.textDecoration='none';
                item = document.getElementById(listId).childNodes[i-1];
                item.style.backgroundColor=selecColor;
                item.style.textDecoration='underline';
                break;
            }
        }
    }
    if (iStationCount > 9)
    {
        document.getElementById( listId ).scrollTop -= 18;
    }
}

//**************************************************************
//* Function to move down in the station list
//**************************************************************
function MoveDown(listId)
{
    var item;
    var i=0;
    var bLoop=true;
    while(bLoop == true)
    {
        item = document.getElementById(listId).childNodes[i];
        
        if (typeof(item) != "undefined"){
            var iType = item.nodeType;
            
            //****************************************************
            //* Firefox problem 
            //* Some node type are text(case 3) and not child(case 1)... 
            //* Dont process the text (case 3)
            //*****************************************************
            switch(iType){
                case 1: {
                    // Selected Item
                    if(item.style.textDecoration == 'underline'){
                        // Next item object
                        var nextItem = document.getElementById(listId).childNodes[i+1];
                        
                        // If the next item is undefine, we are in the end so do nothing
                        if (typeof(nextItem) != "undefined"){
                            item.style.backgroundColor=unSelecColor;
                            item.style.textDecoration='none';
                            
                            if(nextItem.nodeType == 3){ 
                                item.style.backgroundColor=selecColor;
                                item.style.textDecoration='underline';
                            } else {
                                nextItem.style.backgroundColor=selecColor;
                                nextItem.style.textDecoration='underline';
                            }
                        }
                        // Quit the loop
                        bLoop=false;
                    }
                    i++;

                    break;
                }		        
                case 3: i++; break;
            }
        } else {
            i++;
        }
        
        // We have process each element, get out of the loop
        if (i > document.getElementById(listId).childNodes.length){
            bLoop=false;
        }
    }
    if (iStationCount > 9)
    {
        document.getElementById( listId ).scrollTop += 18;
    }

}

//**************************************************************
//* Function to process the keydown event (enter key)
//**************************************************************
function KeyDownEv(str, e, listId, input, nbrList)
{
    if(str!=""){
        
        switch(e['keyCode']){
            // Enter key
            case 13:     bSubmitKey = false; SetStation(listId, input, nbrList); break;
            default : bSubmitKey = true;
        }   
    }
}

//**************************************************************
//* Function to process the onfocus event
//**************************************************************
function ListOnFocus(str, listId, nbrList, stationType ,portalId, input , TSICtrl)
{
    HideList(nbrList);
    //document.getElementById(input).style.border='solid 1px black';
    if (str == ""){
        ShowHelp(listId);
    } else {
        ShowList(str, listId, stationType, portalId, TSICtrl);
    }
    bSubmitKey = true;
}

function ListLostFocus(listId, input, nbrList)
{
    //document.getElementById(input).style.border='solid 1px grey';
    SetStation(listId, input); 
    HideList(nbrList);
}

//***************************************************************
//* Functions to correct the onblur event that 
//* fire for ie if the user click on the scrollbar
//***************************************************************
function InputLostFocus(listId, input, nbrList)
{
    var scroll = document.getElementById(listId).style.overflow;
    
    if (scroll != 'auto')
    {
        ListLostFocus(listId, input, nbrList)
    }  else {
        if (document.getElementById(listId).style.display=='block'){
            document.getElementById(listId).focus();
        }
    }
}

//**************************************************************
//* Hide the station list
//**************************************************************
function HideList(nbrList) 
{ 
    var item;
    var itemDivIe;
    
    for (var i = 0; i < nbrList; i++)
    {
        item = document.getElementById('divStation' + i);
        var iType = item.nodeType;
        
        //****************************************************
        //* Firefox problem 
        //* Some node type are text(case 3) and not child(case 1)... 
        //* Dont process the text (case 3)
        //*****************************************************
        switch(iType){
            case 1: 
            {
               itemDivIe = document.getElementById('divStation' + i + 'select');
               itemDivIe.style.display='none';
               item.style.display='none';
            }
            case 3: break;
        }
    }
}

//**************************************************************
//* These functions will add a delay on the keyup event
//**************************************************************
function KeyUp(str, e, listId, stationType, portalId, TSICtrl)
{
    strSearch = str;

    switch(e['keyCode']){
        // Up
        case 38: MoveUp(listId); break;
    	        
        // Down
        case 40: MoveDown(listId); break;
        
        // Enter, process on the keydown so do nothing
        case 13: break;
        
        case 09: break;
        
        default : setTimeout(function() { KeyUpGo(str, listId , str , stationType, portalId, TSICtrl)} , 150); break;
    } 
        
}

function KeyUpGo(str, listId, currSearch, stationType, portalId, TSICtrl)
{
   if(currSearch == strSearch)
   {
      count = "";
      ShowList(str, listId, stationType, portalId, TSICtrl);
   }
} 
