/* NAVIGATIONAL FUNCTIONS */
function NavigationOpen() {
	//cookiesManager.SetVariable( "NavigationState", "opened" );
	document.getElementById( "NavigationOpened" ).style.display = "";
	document.getElementById( "NavigationClosed" ).style.display = "none";
}

function NavigationClose() {
	//cookiesManager.SetVariable( "NavigationState", "closed" );
	document.getElementById( "NavigationOpened" ).style.display = "none";
	document.getElementById( "NavigationClosed" ).style.display = "";
}

function RestoreNavigationWindow() {
	/*
	var opened = cookiesManager.GetValue( "NavigationState" );
	if( opened != "opened"  ) {
		document.getElementById("NavigationClosed").style.display = "";
	} else {
		document.getElementById("NavigationOpened").style.display = "";
	}
	*/
} 
function NavigationExpandAll() {
	//alert( "Write Code for NavigationExpandAll() " );
}
function NavigationCollapseAll() {
	//alert( "Write Code for NavigationCollapseAll() " );
}

//RestoreNavigationWindow();



function toggleElement( oCode )
{
	var oElm = document.getElementById( oCode );

	if(oElm.style.display == 'none') {
		oElm.style.display = '';
	}else {
		oElm.style.display = 'none';
	}
}


function OpenNewWindow(theURL,winName,features) 
{
	window.open(theURL,winName,features);
}

function postBackHiddenField(hiddenFieldID) 
{
	var hiddenField = $get(hiddenFieldID);
	
	if (hiddenField) 
	{
		hiddenField.value = (new Date()).getTime();		
		__doPostBack(hiddenFieldID,'');
	}
}

/*
Cancel Async Post Back
This would help in killing the ajax calls on a page by users call
var prm = Sys.WebForms.PageRequestManager.getInstance();
*/
function CancelAsyncPostBack()
{
	/*
	if(confirm("Are you sure you want to cancel the background transaction(s)?"))
	{
		if (prm.get_isInAsyncPostBack())
		{
		  prm.abortPostBack();
		}
	}
	*/
}



//============FUNCTION ADDED BY SANTOSH==========================
/*
Added on 08 Jan 2008
Function Export Table/Grid data to Excel,
Just pass the ID of control to this function
*/
 function ExportToExcel(obj)
    {
        var detailsTable = document.getElementById(obj); 
        var oExcel = new ActiveXObject("Excel.Application");
        //alert('hi ji');
        oExcel.UserControl = true;
        var oExcelPage = oExcel.Workbooks.Add;
        var oExcelSheet = oExcelPage.Worksheets(1);
        for (var y=0;y<detailsTable.rows.length;y++)
        // detailsTable is the table where the content to be exported is
        {   for (var x=0;x<detailsTable.rows(y).cells.length;x++)
            {   
               oExcelSheet.Cells(y+1,x+1) = detailsTable.rows(y).cells(x).innerText;           
            }
        }
        oExcel.Visible = true;
        return false
    }
    
/*
Added on 25 April 2008
Show Message at the time of Modify a Record by an Unathorized User
*/
function ModifyMessage()
{
    alert("You don't have Modification rights for this page");
}

//ADDED ON 3RD MAY 2008
// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}


//Function Handle the Ajax Post Back and check Either the Internet connected or not
function EndRequestHandler(sender, args)
{
   if (args.get_error() != undefined)
   {
       if ((args.get_response().get_statusCode() == '12007') || (args.get_response().get_statusCode() == '12029'))
       {
       alert('Please make sure you are connected to internet');
       args.set_errorHandled(true); 
       }
   }
}
//Function show alert for session expiry time
function WarnUserTimeout()
{
    if (window.confirm('Your session will expire in 5 minutes. Do you want to continue working?\nNow:'+ Date() ))
    {
        window.history.go(0);
    }
}

function DoUserLogout()
{
    alert('Dear user,\nThe system noticed that you have been non-interactive on this page for a long period, hence you are been logged-out. \nPlease click OK to continue and Re-Login.');
    document.location.href='/logoutuser.aspx?signout=yes';
}


//MESSAGEBOX FUNCTION FOR CODE BEHIND

function ShowMessage(str)
{
    alert(str);
}

//FUNCTION RESTRICT OTHER CHARS EXCEPT DIGITS
function Restrict2Digits(oElm)
{
	if (window.event.keyCode < 46 || window.event.keyCode > 57) 
		window.event.keyCode = 0;
}
//========================END==================================


function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}



//============================================================================================================================
//FUNCTION TO OPEN THE CRYSTAL REPORT IN A NEW WINDOW ========================================================================
var popUpWinReport=0;
var jsGenerateTokenID=false;
function js_InitializeCrystalReportServer( prm_ServerPath, prm_ReportURL, prm_Height, prm_Width)
{
   //Return false statment just used for stop crystal report at this time.
   //return false;
    //'vReturnValue = window.showModalDialog(sURL [, vArguments] [, sFeatures])
    var l_ReportURL = prm_ServerPath + prm_ReportURL;
	
	if ( jsGenerateTokenID==true )
	{
	    var l_NewTokenID = jsfunc_GenerateReportToken();
	    l_ReportURL = l_ReportURL + "&tnk=" + l_NewTokenID;
	}
	
    //window.showModalDialog( l_ReportURL ,'','dialogHeight:'+prm_Height+'; dialogWidth:'+prm_Width+';');
    //window.open( l_ReportURL ,'','Height:'+prm_Height+'; Width:'+prm_Width+';');
	var left=0;
	var top=0;
	prm_Height = 600;
	prm_Width = 800;
	
	if(popUpWinReport)
  	{
    	if(!popUpWinReport.closed) popUpWinReport.close();
  	}
	
 	popUpWinReport = open(l_ReportURL, 'popUpWinReport', 'fullscreen=no,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width='+prm_Width+',height='+prm_Height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}
//========================END==================================


// ajax functions for report token generation
//var url="assets/scripts/ajax/gen_rep_token.aspx?sid="+Math.random(); //xmlHttp.onreadystatechange=callTime;

var gl;
function jsfunc_GenerateReportToken()
{
	//alert('am called');
    GenerateToken();    

    return gl;  
}

function ChangedInfo() 
{ 	
	//alert('ChangedInfo');
	if (xmlHttp.readyState==4 || xmlHttp.readyState=='complete')
	{
		gl = xmlHttp.responseText;
	}
}

function GenerateToken()
{ 
	//alert('GenerateToken');
	var url			= "/assets/scripts/ajax/gen_rep_token.aspx?sid=" + Math.random();
	xmlHttp			= GetXmlHttpObject(ChangedInfo);
	xmlHttp.Open("GET", url , false);
	xmlHttp.send(null);
} 

function GetXmlHttpObject(handler)
{ 
	//alert('GetXmlHttpObject');
	var objXmlHttp=null;
	
	if (navigator.userAgent.indexOf("MSIE")>=0)
	{ 
		var strName="Msxml2.XMLHTTP";
		if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
		{
			strName="Microsoft.XMLHTTP";
		} 
		try
		{ 
			objXmlHttp=new ActiveXObject(strName);
			objXmlHttp.onreadystatechange=handler;
			return objXmlHttp;
		} 
		catch(e)
		{ 
			alert("Error. Scripting for ActiveX might be disabled");
			return;
		} 
	} 
	if (navigator.userAgent.indexOf("Mozilla")>=0)
	{
		objXmlHttp=new XMLHttpRequest();
		objXmlHttp.onload=handler;
		objXmlHttp.onerror=handler;
		return objXmlHttp;
	}
}
//============================================================================================================================







//BRING THE POPUP WINDOW TO FOCUS AND TO THE CENTER OF DISPLAYED SCREEN
function jsScreenCenter( prm_WinWidth, prm_iWinHeight )
{
    window.focus();
    var iWinWidth 	= prm_WinWidth;
    var iWinHeight 	= prm_iWinHeight ;
    window.moveTo( eval((screen.width-eval(iWinWidth))/2), eval((screen.height-eval(iWinHeight))/2) );  
}


var jsHelpTopic='';
function showHelp()
{
    if ( jsHelpTopic=='' ){
        alert('Help is currently unavaliable.');
    }
    else{
        alert('Show Help for code: ' + jsHelpTopic);
    }
}
// Keep user from entering more than maxLength characters
		function doKeypressMaxLength(source,maxLength){
			if(!isNaN(maxLength)){
				maxLength = parseInt(maxLength);
				var oTR = document.selection.createRange();
				// Allow user to type character if at least one character is selected
				if(oTR.text.length >= 1)
					event.returnValue = true;
				else if(source.value.length > maxLength-1)
					event.returnValue = false;
			}
		}
		// Cancel default behavior
		function doBeforePasteMaxLength(){
				event.returnValue = false;
		}
		// Cancel default behavior and create a new paste routine
		function doPasteMaxLength(source,maxLength){
			if(!isNaN(maxLength)){
				event.returnValue = false;
				var oTR = document.selection.createRange();
				var iInsertLength = maxLength -  source.value.length+oTR.text.length;
				var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
				oTR.text = sData;
			}
		}

function js_FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)

        /**********************************************************************
        IN:
        NUM - the number to format
        decimalNum - the number of decimal places to format the number to
        bolLeadingZero - true / false - display a leading zero for numbers between -1 and 1
        bolParens - true / false - use parenthesis around negative numbers
        bolCommas - put commas as number separators.

        RETVAL:
        The formatted number!
        **********************************************************************/

{ 

        if (isNaN(parseInt(num))) return "NaN";

        var tmpNum = num;
        var iSign = num < 0 ? -1 : 1;		// Get sign of number

        // Adjust number so only the specified number of numbers after
        // the decimal point are shown.
        tmpNum *= Math.pow(10,decimalNum);
        tmpNum = Math.round(Math.abs(tmpNum));
        tmpNum /= Math.pow(10,decimalNum);
        tmpNum *= iSign;					// Readjust for sign


        // Create a string object to do our formatting on
        var tmpNumStr = new String(tmpNum);

        // See if we need to strip out the leading zero or not.
        if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
        if (num > 0)
            tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
        else
            tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);

        // See if we need to put in the commas
        if (bolCommas && (num >= 1000 || num <= -1000)) {
            var iStart = tmpNumStr.indexOf(".");
            if (iStart < 0)
                iStart = tmpNumStr.length;

            iStart -= 3;
            while (iStart >= 1) {
                tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length);
                iStart -= 3;
            }		
        }

        // See if we need to use parenthesis
        if (bolParens && num < 0)
            tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

        return tmpNumStr;		// Return our formatted string!
}

       