// JScript File

// Popup Array which keeps count of all popup open
var popUpArr = new Array();
var oComm=null;         //flash communication object
var strOCVersion="";    //To store OCVersion
var strOCToken="";      //To store sessionId
var bMultipleOC=false;  //multiple oc flag
var sClientIPAddr="";
var iConsoleTimeOut=0;  //To store consolelock timeout value
var iUserLoginMode=1;   //By default set to refresh mode
var bConsoleTimeOut=false;

// adds the popup window instance to the Popup Array if it is not already availble
function addPopUp(obj)
{
    var iLength = popUpArr.length;
    for(var iCounter=0; iCounter<iLength;iCounter++)
    {
        if(popUpArr[iCounter]==obj)
            return;
    }
    popUpArr[popUpArr.length] = obj;
}

// removes the popup window instance from the Popup Array
function removePopUp(obj)
{
   for(var i=0; i< popUpArr.length; i++)
   {
        if(popUpArr[i] == obj)
        {
            popUpArr.splice(i,1);
            break;
        }
   }
}

// checks if the same popup is already open and returns a refrence to that popup
function SearchPopup(strPageName)
{
    var objPopup = null;
    for(var i=0; i< popUpArr.length; i++)
    {
        // this is checked bcos remove popup is not called...
        // when called does not give the desired result
        if(popUpArr[i].closed == false)
        {
            if(popUpArr[i].name == strPageName)
            {
                objPopup = popUpArr[i];
                break;
            }
        }
    }
    return objPopup;
}

// opens popup and adds the window instance to the internal popup array to keep count of all popups
// @param name- unique name of the window to restrict no. of popups
// @param property - property of the new window
function callPopUp(url,name,property,bModal)
{
    if (!bConsoleLock)
    {
        if(name=='undefined')
            name='';
        if(property=='undefined')
            property='scrollbars=no,toolbar=no,menubar=no,location=no';
        if(bModal=='undefined')
            bModal= false;
            
        if(name != '')
            name = name.split('-').join('');
        if (!bModal)
        {
            var xwin = SearchPopup(name);
            if(xwin == null)
            {
                name = name.replace('-', '');
                name = name.replace('@', '');
                name = name.replace('&', '');
                name = name.replace('<','');
                name = name.replace('>','');
                xwin = window.open(url,name,property);
            }
            else
            {
                // Special condition added for IndexDetails as previously two popups were opening for the 
                // same page, one from top index and another from menu
                // To eliminate that, i.e to open one popup always, this condtion is added
                // which will close the previoulsy open popup and open a new popup
                if (xwin.name == "IndexDetails")
                    xwin = window.open(url,name,property);
                if(xwin.name == "ScripInfo")
                    xwin = window.open(url,name,property);
                if(xwin.name == "BestFive")
                    xwin = window.open(url,name,property);
                if(xwin.name == "MarketMovement")
                    xwin = window.open(url,name,property);
                if(xwin.name == "OCXChart")
                    xwin = window.open(url,name,property);
            }
            xwin.focus();
            xwin.name = name;
            addPopUp(xwin);
        }        
    }
}


// for sending broadcast request irrespective of refresh/Streaming mode & single/multiple oc
// In case of refresh it will make an ajax call & on success of ajax it calls CheckMultipleResponse function
// In case of streaming if socketconnection is available request is written in socket else it works as refresh
function SendRequest(strRequest)
{
    if(bConsoleLock != null && !bConsoleLock)//sends request only if console is not locked
    {
        var bSocketState;
        if(window.parent)
            bSocketState = window.parent.bBroadCastSocket;
        else
            bSocketState = bBroadCastSocket;
            
        if(iUserLoginMode==1 || (iUserLoginMode==2 && bSocketState==C_V_SOCKET_DISCONNECTSTATE))
        {
            var strData = "param=" + strRequest;
            $.ajax({
                   type: "POST",
                   url: AJAXDATAFETCHER_URL,
                   cache: false,
                   dataType: "text",
                   data: strData,
                   success: CheckAjaxMultipleResponse,
                   error: HandleAjaxError
             });
        }
        else if(iUserLoginMode==2 && bSocketState==C_V_SOCKET_CONNECTSTATE)
        {
            if(oComm)
            {
                if(!bMultipleOC)
                    oComm.sendRequest(strRequest);
                else
                    oComm.sendBCRequest(strRequest);
            }
        }
    }
}

// executed if ajax page call fails 
function HandleAjaxError(XMLHttpRequest, textStatus, errorThrown)
{
    //Yet to be implemented fully;
    //input parameters will remain same as they come from jquery
    alert(textStatus);
}

//on receiving oc response, it triggers the event
function ProcessMessage(strResponse) 
{
    if(bConsoleTimeOut==false)//Not to trigger the events after console timeout is reached
    {
        if(strResponse.length != 0 && strResponse.toString() != "")
        {   
            try {
                thisDocument.trigger('OC_RESPONSE',strResponse);
            } catch(e) {}
           
            // trigger the events on all the frames present on the page
            for(var i=0; i< window.frames.length; i++)
            {
                try {
                    window.frames[i].triggerEvent('OC_RESPONSE', strResponse);
                } catch(e) {}
            }
           
            // trigger the events on all the popup open
            for(var j=0; j< popUpArr.length; j++)
            {
                try {
                    popUpArr[j].triggerEvent('OC_RESPONSE', strResponse);
                } catch(e) {}
            }
        }
    }
}

// to check if the response string contains more than 1 response
// which is the case for Market Watch and Index
function CheckAjaxMultipleResponse(strResponse)
{
    //Following function is invoked for Session Maangement.
    //In case Session has expired then the AJAX page would return Session Expiry code
    //as response
    if(!ValidateSession(strResponse))
        return false;
    if(bConsoleTimeOut==false)//Not to trigger the events after console timeout is reached
    {
        //if market watch response then the spliting part is done in Market watch frame (Market watch.js)
        if(C_V_MSGCODES_MW_RESPONSE == FindValue(strResponse.split(FD), C_V_TAG_MSGCODE))
        {
            window.frames.fraNetNet.CheckMultipleResponse(strResponse);
        }
        else
        {
            var strRespArr = '';
            if(strResponse.length != 0 && strResponse.toString() != "")
            {
                if(strResponse.indexOf(MULTIRESP_D) != -1)
                {
                    strRespArr = strResponse.split(MULTIRESP_D);
                    
                    for(idx = 0; idx < strRespArr.length; idx++)
                    {
                        if(Trim(strRespArr[idx]) != '')
                        {
                            ProcessMessage(strRespArr[idx]);
                        }
                    }
                }
                else
                {
                    ProcessMessage(strResponse);
                }
            }
        }
    }
}

// To start/stop Autorefresh in UI which expects interactive response irrespective of single/multi oc
function setAutoRefresh(bStartStop)
{
    thisDocument.trigger('handle_AutoRefresh',bStartStop);
    
    // trigger the events on all the frames present on the page
    for(var i=0; i< window.frames.length; i++)
    {
        try {
            window.frames[i].triggerEvent('handle_AutoRefresh', bStartStop);
        } catch(e) {}
    }
      
    // trigger the events on all the popup open
    for(var j=0; j< popUpArr.length; j++)
    {
        try {
            popUpArr[j].triggerEvent('handle_AutoRefresh', bStartStop);
        } catch(e) {}
    }
}

// To start/stop Autorefresh in UI which expects broadcast response irrespective of single/multi oc
function setBroadCastAutoRefresh(bStartStop)
{
    thisDocument.trigger('handle_BroadCastAutoRefresh',bStartStop);
    
    // trigger the events on all the frames present on the page
    for(var i=0; i< window.frames.length; i++)
    {
        try {
            window.frames[i].triggerEvent('handle_BroadCastAutoRefresh', bStartStop);
        } catch(e) {}
    }
      
    // trigger the events on all the popup open
    for(var j=0; j< popUpArr.length; j++)
    {
        try {
            popUpArr[j].triggerEvent('handle_BroadCastAutoRefresh', bStartStop);
        } catch(e) {}
    }
}

//to trigger the event on click of refresh link
function RefreshPage()
{
    if(bBroadCastSocket==C_V_SOCKET_CONNECTSTATE)
    {
        window.showModalPopup('NewNetNet', 'Already connected through socket. Refresh option is not required', null);
        return;
    }
    thisDocument.trigger('handle_PageRefresh');
    
    // trigger the events on all the frames present on the page
    for(var i=0; i< window.frames.length; i++)
    {
        try {
            window.frames[i].triggerEvent('handle_PageRefresh');
        } catch(e) {}
    }
      
    // trigger the events on all the popup open
    for(var j=0; j< popUpArr.length; j++)
    {
        try {
            popUpArr[j].triggerEvent('handle_PageRefresh');
        } catch(e) {}
    }
}

//To close popup if any when the main window closes    
$(window).unload(function(){
   closePopUps();
});

function closePopUps()
{
 for(var j=0; j< popUpArr.length; j++)
    {
        popUpArr[j].close();
    }
}

//sets flash Communication object
function setOComm(objComm)
{
    oComm = objComm;
}

//for setting sessionId & OCVersion
function setOCDetails(strVersion, strSession)
{
    strOCVersion=strVersion;
    strOCToken=strSession;
}

// for setting multiple oc flag
function setMultipleOC(bflag)
{
    bMultipleOC=bflag;
}

//creates complete request that can be send to ajax & flash
//Adding the HTTP header for socket request is handled inside flash
function CreateRequest(iMsgCode, strRequest)
{
    var strData="";
    var strHeader="",strTempData="",strMsgLength="";
    var iMsgLength=0,index=0;
    strHeader=CreateHeader(iMsgCode);
    strTempData=strTempData.concat(strHeader+strRequest);
    iMsgLength=strTempData.length;
    strMsgLength=iMsgLength.toString();
    iMsgLength=iMsgLength+strMsgLength.length-1;
    index=strTempData.indexOf("#");
    strData=strTempData.substring(0, index);
    strData=strData+iMsgLength;
    strData=strData+strTempData.substring(index+1);
    return strData;
}

// generates request header string for the message code
function CreateHeader(iMsgCode)
{
    var strData = "";
    strData=strData.concat(C_V_TAG_MSGVERSION+ND+strOCVersion+FD);
    strData=strData.concat(C_V_TAG_MSGCODE+ND+iMsgCode+FD);
    strData=strData.concat(C_V_TAG_MSGLENGTH+ND+"#"+FD);
    strData=strData.concat(C_V_TAG_MSGTIME+ND+GetCurrentTime()+FD);
    strData=strData.concat(C_V_TAG_SESSIONID+ND+strOCToken+FD);
    return strData;
}

// get current time in hh:mm:ss format
function GetCurrentTime()
{
    var CurrentDate=new Date();
    var strTime="";
    var hr,min,sec;
    hr=CurrentDate.getHours();
    min=CurrentDate.getMinutes();
    sec=CurrentDate.getSeconds();
    if(hr<10)
        hr="0"+hr;
    if(min<10)
        min="0"+min;
    if(sec<10)
        sec="0"+sec;
    strTime=hr+":"+min+":"+sec;
    return strTime;
}

//to write js & as error message in log4net through ajax call
function WriteError(sClass,sFunction,sError)
{
    var sData = 'sClass='+sClass+FD+'sFunction='+sFunction+FD+'sError='+sError;
    var sRequest=CreateRequest(C_V_WRITEERROR,sData);
    var strData = "param="+sRequest;
    $.ajax({
        type: "POST",
         url: AJAXDATAFETCHER_URL,
        cache: false,
        dataType: "text",
        data: strData,
        success: function(sResponse){},
        error: HandleAjaxError
    });
}

//To set the console lock timeout value
function setConsoleLockTimeOut(iTimeOut)
{
    iConsoleTimeOut=parseInt(iTimeOut, 10);
}

function setUserLoginMode(iMode)
{
    iUserLoginMode=iMode;
}

//if console gets locked checks for console lock status after console timeout value
function HandleConsoleLock()
{
    setTimeout('CheckConsoleTimeout()',iConsoleTimeOut);
}

function CheckConsoleTimeout()
{
    if(bConsoleLock != null && bConsoleLock==true)
    {
        bConsoleTimeOut=true;
        handleConsoleTimeout();
    }
}

//to handle consolelock timeout
//sends marketwatch stop request if socket is connected
function handleConsoleTimeout()
{
    var sTouchLineStop = ''; 
    sTouchLineStop = SendTouchLineRequest(aScripMap, C_V_MARKETWATCH_STOP);
    if(sTouchLineStop != null && Trim(sTouchLineStop)!='')
    {
        if(bBroadCastSocket==C_V_SOCKET_CONNECTSTATE)
        {
            if(!bMultipleOC)
                oComm.sendRequest(sTouchLineStop);
            else
                oComm.sendBCRequest(sTouchLineStop);
        }
    }
}

//if console is unlocked check for console timeout flag. Based upon the flag send touchline start request
function HandleConsoleUnlock()
{   
    if(bConsoleTimeOut && iUserLoginMode == 2)
    {
        SendTouchLineRequest(aScripMap, C_V_MARKETWATCH_START);
    }
    bConsoleTimeOut=false;
}

//For creating complete login request
function CreateLoginReq(iMsgCode, sRequest)
{
    var strData = "";
    var strRequest='';
    strData=strData.concat(C_V_TAG_MSGVERSION+ND+strOCVersion+FD);
    strData=strData.concat(C_V_TAG_MSGCODE+ND+iMsgCode+FD);
    strData=strData.concat(C_V_TAG_MSGLENGTH+ND+"#"+FD);
    strData=strData.concat(C_V_TAG_MSGTIME+ND+GetCurrentTime()+FD);
    strData=strData+sRequest;
    var iMsgLength=strData.length;
    var strMsgLength=iMsgLength.toString();
    iMsgLength=iMsgLength+strMsgLength.length-1;
    var index=strData.indexOf("#");
    strRequest=strData.substring(0, index);
    strRequest=strRequest+iMsgLength;
    strRequest=strRequest+strData.substring(index+1);
    return strRequest;
}

//Login request for single oc
//Interactive login request for multi oc.
function sendLoginReq(strGroupId,strClientId,strSession)
{
    //Modified for session id change in Login request
    var strData='';
    strData=strData+C_V_TAG_USER_ID+ND+strClientId+FD+C_V_TAG_PASSWORD+ND+''+FD+C_V_TAG_SESSIONID+ND+strSession+FD;
    strData=strData+C_V_TAG_GROUPID+ND+strGroupId+FD+C_V_TAG_CONNECTION_TYPE+ND+'4'+FD+C_V_TAG_IPADDRESS+ND+sClientIPAddr;
    var sRequest=CreateLoginReq(C_V_MSGCODES_INTERACTIVE_LOGIN_REQUEST, strData);
    oComm.sendRequest(sRequest);
}

function sendOrderReq()
{
    //oComm.sendRequest(CreateRequest(C_V_MSGCODES_ORDERDOWNLOAD_REQUEST,""));
}

function KeepAlive(boolOn)
{
    if(boolOn)
    {
        oComm.startKeepAlive(CreateRequest(C_V_MSGCODES_KEEPALIVE_REQUEST,''));
    }
}    

function sendBCLoginReq(strGroupId,strClientId,strSessionId,strNewPass)
{
    var strData='';
    strData=strData+C_V_TAG_USER_ID+ND+strClientId+FD+C_V_TAG_SESSIONID+ND+strSessionId+FD;
    strData=strData+C_V_TAG_GROUPID+ND+strGroupId+FD+C_V_TAG_CONNECTION_TYPE+ND+'4'+FD+C_V_TAG_IPADDRESS+ND+sClientIPAddr;
    var sRequest=CreateLoginReq(C_V_MSGCODES_BROADCAST_LOGIN_REQUEST, strData);
    oComm.sendBCRequest(sRequest);
}
