//$Id: util.js,v 1.22 2007/11/12 05:01:02 dilliganesh Exp $


var monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

//Registering for mouse click
document.onclick = mouseClick;

//Stores last mouse click X
var lastMouseClickX = 0;
//Stores last mouse click Y
var lastMouseClickY = 0;

function getAPIKey()
{
    //***** TODO::: Will be changed later****
    return "bf4c055702f27b7fa9b80d6af65578fc";
}

function getNewDoc(type)
{
    var urll = contextPath + "/getDocsList.do?method=getNewDoc&docType="
               +type+"&apiTicket="+getTicketIDFromCookie();
    window.open(urll,"_top");
}

//Returns XMLHTTPRequest Object with the TICKETID as its parameter
function getXMLHTTPRequest()
{
    var xmlObject = null;
    if(document.all) 
    {
        if (window.XMLHttpRequest)
        { // check for IE7
            xmlObject = new XMLHttpRequest();
        }
        else
        {
            if(xmlObject == null) 
            {
                try 
                {
                    xmlObject = new ActiveXObject('Msxml2.XMLHTTP');
                } 
                catch(e) {}
            }
            if(xmlObject == null) 
            {
                try 
                {
                    xmlObject = new ActiveXObject('Microsoft.XMLHTTP');
                } 
                catch(e) 
                {
                    throw new Exception('Browser does not support Ajax calls.  Please check your browser settings.');
                }
            }
        }
    } 
    else 
    {
        xmlObject = new XMLHttpRequest();
    }
    return xmlObject;
}

function appendTicketID(urll)
{
    var ticketID = getTicketIDFromCookie();
    var ticketParameter = "&apiTicket="+ticketID;
    urll = urll+ticketParameter;
    var timeinms = (new Date()).getTime();
    urll = urll+"&ttimems="+timeinms;
    return urll;
}

function sendAsyncAJAXRequest( type, urll , callbackFn)
{
    try
    {
        if(!handleCookies())
        {
            window.open(signinurl,"_top");
            return;
        }
        urll = appendTicketID(urll);
        var xmlhttp = getXMLHTTPRequest();
        xmlhttp.onreadystatechange = function(){ callbackFn(xmlhttp) };
        xmlhttp.open(type,urll,true);
        xmlhttp.send(null);
    }
    catch(e)
    {
        alert("Unable to process the request");
    }
}

//Sends synchronous request.And returns response.
//If responseType is "XML", fetches the XML response from
//the XMLHTTPRequest object and returns the same.
//Else returns Text response.
function sendSyncAJAXRequest(type, urll , responseType)
{
    var response = "";
    try
    {
        if(!handleCookies())
        {
            window.open(signinurl,"_top");
            return;
        }
        urll = appendTicketID(urll);
        var xmlhttp = getXMLHTTPRequest();
        xmlhttp.open(type,urll,false);
        xmlhttp.send(null);
        if(responseType == "XML")
        {
            reposonse = xmlhttp.responseXML;
        }
        else 
        {
            response = xmlhttp.responseText;
        }
    }
    catch(e)
    {
        alert("Unable to process the request ");
    }
    return response;
}
    

function getTicketIDFromCookie()
{
    //Need to get the ticketid from Cookie
    //var ticketId = "13e0f6185f29b52fbad7ee5f5572d9e3";
    //return ticketId;
    //**************** Need to be revised**********
    return getCookieValue(readCookie('EATICKET')); 
}

function getCurrentTimeInMillis()
{
    var ddate = new Date();
    return ddate.getTime();
}

function popupNewWindow(urll)
{
    var newwindow=window.open(urll,null,'location=no,toolbar=no,scrollbars=yes');
}


function findPosX(obj)
{
    var curleft = 0;
    if (document.getElementById || document.all)
    {
        curleft += document.body.offsetLeft;
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    }
    else if (document.layers)
    {
        curleft += obj.x;
    }
    return curleft;
}


function findPosY(obj)
{
    var curtop = 0;
    if (document.getElementById || document.all)
    {
        curtop += document.body.offsetTop;
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    else if (document.layers)
    {
        curtop += obj.y;
    }
    return curtop;
}

function trim(s)
{
    return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

//Replaces str1 with str2 in the given str,globally
function replaceStr(str,str1, str2)
{
    var regx = new RegExp(str1,"g");
    var s = str.replace(regx,str2);
    return s;
}

//Used in passing names with specail character across functions.
function wrapUnwrapSplChar(str,type)
{
    if(type == "wrap")
    {
        if(str.indexOf("'") != -1)
        {
            str = handleSpecialChar(str,"'");
        }
        if(str.indexOf("\"") != -1)
        {
            str = handleSpecialChar(str,"\"");
        }
    }
    else if(type == "unwrap")
    {
        //If unwrapping feature needs for ' and ",
        // the same can be captured here
    }
    return str;
}

//
function isValidString(str)
{
    var regExp = /^[a-z-a-z0-9_\-\.\'\@\$\"\ ]{0,100}$/i;
    if (!regExp.test(str)) 
    {
        return false;
    }
    return true;
}

function handleSpecialChar(s,spl)
{
    var tmp = s;
    if(tmp.indexOf(spl) != -1)
    {
        var strArray = s.split(spl);
        tmp = strArray[0];
        for(var i = 1 ; i < strArray.length ; i++ )
        {
            var val = "\\"+spl;
            tmp = tmp+val+strArray[i];
        }
    }
    //log("replaceDollar:IncomingStr:"+s+"*Resultant:"+tmp);
    return tmp;
}

//This method is used in Bookmarks module
//************ Has to be replaced with handleSpecialChars() in bookmarks module ****************
function replaceSpecialChars(s)
{
    var tmp = s;
    if(tmp.indexOf("'") != -1)
    {
        var strArray = s.split("'");
        tmp = strArray[0];
        for(var i = 1 ; i < strArray.length ; i++ )
        {
            tmp = tmp+"\\'"+strArray[i];
        }
    }
    log("replaceSpecialChars:IncomingStr:"+s+"*Resultant:"+tmp);
    return tmp;
}

function checkValue(val)
{
    val = trim(val);
    if(val == null || val == "" )
    {
        return false;
    }
    return true;
}

//return "month date"
function getMonthAndDate(timeInMillis)
{
    var datte = new Date();
    datte.setTime(timeInMillis);
    var yyear = datte.getFullYear();
    var mmonth = datte.getMonth();
    var dday = datte.getDate();
    var monthString = monthNames[mmonth];
    return (monthString+" "+dday);
}


//Returns equivalent time in milliseconds for the date with 
//format "yy-mm-dd hh:MM:ss"(2007-04-17 05:32:35)
function toTimeInMillis(ddate)
{
    var dateTime = new Array();
    dateTime = ddate.split(' ');
    var datee = new Array();
    datee = dateTime[0].split('-');
    var yyear = datee[0];
    var mmonth = datee[1];
    var dday = datee[2];
    var ttime = dateTime[1].split(':');
    var hhour = ttime[0];
    var mmin = ttime[1];
    var ssec = ttime[2];
    //alert("toDate::Date In String::"+ddate+"** year:"+yyear+"** month:"
    //+mmonth+"** day:"+dday+"** hour:"+hhour+"** minute:"+mmin+"** sec:"+ssec);
    var d = new Date();
    d.setYear(yyear);
    d.setMonth((mmonth - 1));
    d.setDate(dday);
    d.setHours(hhour);
    d.setMinutes(mmin);
    d.setSeconds(ssec);
    var timeInMillis = d.getTime();
    //alert("toDate:: In String::"+ddate+"*** InMillis::"+timeInMillis);
    return timeInMillis;
}


//Seperate windows for logging the message
function log(message)
{
    //console.log(message);
}

function removeSpecialChars(str)
{
    var tmp = str;
    if(str.indexOf("\\") != -1)
    {
        var strArray = str.split("\\");
        tmp = strArray[0];
        for(var i = 1 ; i < strArray.length; i++)
        {
            tmp = tmp+strArray[i];
        }
    }
    log("removeSpecialChars::InStr:"+str+"**OutStr:"+tmp);
    return tmp;
}

//Used in getting row color based on its index
function getRowColor(rowIndx)
{
    var rclass = ((rowIndx%2)==0)?"rowgrey":"rowclear";
    return rclass;
}

//Used in finding document's width
function getDocWidth(docEle)
{
    return 1024;
}

//Used in finding document's height
function getDocHeight(docEle)
{
    return 768;
}

//Need to do some logic changes in setting width and height
//Currently gives out the width ,height , x-coordinate and y-coordinate values
// of the divEle as it occupies the complete docEle with the given divPercentage.
// X and Y coordinates are used in displaying Upload window where resultant
//width and height of a div cannot suite anywhere in our requirements(as of now) 
function getRelativePos(docEle,divEle,divPercentage)
{
    var docWidth = getDocWidth(docEle);
    var docHeight = getDocHeight(docEle);
    var docXX = findPosX(docEle);
    var docYY = findPosY(docEle);
    log("Width:"+docWidth+"* docHeight:"+docHeight+"* docXX:"+docXX+"* docYY:"+docYY+"*");
    var docPrcntg = 100-divPercentage;
    docPrcntg = docPrcntg/2;
    var divWidth = docWidth*(divPercentage/100);
    var divHeight = docHeight*(divPercentage/100);
    var divXX = docXX+(docWidth*(docPrcntg/100));
    var divYY = docYY+(docHeight*(docPrcntg/100));
    log("divWidth:"+divWidth+"* divHeight:"+divHeight+"* divXX:"+divXX+"* divYY:"+divYY);
    var dimens = new Array();
    dimens[0] = divWidth;
    dimens[1] = divHeight;
    dimens[2] = divXX;
    dimens[3] = divYY;
    return dimens;
}

function cloneArray(arr)
{
    var tempArr = new Array();
    for(i in arr)
    {
       tempArr[i] = arr[i];
    }
    return tempArr;
}

//Used in moving the Div to top position when the scrolling is enabled
function moveTheDocDivToTop(divId)
{
    var docD = document.getElementById(divId);
    docD.scrollTop = "0";
}


function mouseClick(ev)
{
    ev           = ev || window.event;
    var mousePos = mouseCoords(ev);
    lastMouseClickX = mousePos.x;
    lastMouseClickY = mousePos.y;
}


function mouseCoords(ev){
    if(ev.pageX || ev.pageY){
        return {x:ev.pageX, y:ev.pageY};
    }
    return {x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y:ev.clientY + document.body.scrollTop  - document.body.clientTop };
}

function getUserIDFromCookie()
{
    //Yet to implement
    //return "1";
    return getCookieValue(readCookie('USERID'));
}

function truncateDisplayString(str,substrLength)
{
    var disFold = str;
    if(str.length > substrLength)
    {
        disFold = str.substring(0,(substrLength-3));
        disFold = disFold+"...";
    }
    return disFold;
}

function handleCookies()
{
    var ticketVal = getTicketIDFromCookie();
    //If cookies expired
    if(ticketVal == null || ticketVal == "" ||
        trim(ticketVal) == "")
    {
        return false;
    }
    else
    {
        extendExpiryTime();
    }
    return true;
}

function getOS()
{
    return navigator.platform ;
}

function isLinux()
{
    var os = getOS();
    if(os.indexOf('Linux') != -1)
    {
        return true;
    }
    return false;
}

function isWindows()
{
    var os = getOS();
    if(os.indexOf('Win') != -1)
    {
        return true;
    }
    return false;
}

function isJavaEnabled()
{
    return navigator.javaEnabled();
}

function removeControlMChars(str)
{
    // "%0D" is an equivalent encoded value for the control+M characher
    // So converting the incoming string to encoded value and 
    // then removing the "%OD" from the string and returning the
    // manipulated string in encoded format
    str = encodeURIComponent(str);
    if(str.indexOf("%0D") != -1)
    {
        str = replaceStr(str,"%0D","");
    }
    return str;
}

//Checks the e-mail id.
//Returns true, if the e-mail id is valid one.Else false.
function checkEMail( str )
{
    var testresults = false;
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    if (filter.test(str))
    {
        testresults=true;
    }
    return testresults;
}

