/// JAVASCRIPT CODE USED IN /UserControls/PageHeader.ascx ///

var glb_bUseFixedNavigation = true;
var glb_bForceLargeStylesheet = true;
var bPrintPreview = false;

window.onscroll = cancelScroll;
window.setInterval("cancelScroll()", 2000); // also every 2 seconds, just for fun

function cancelScroll () {
	var iScreenWidth = (document.body) ? document.body.clientWidth : self.innerWidth;

	if (glb_bUseFixedNavigation)
	{
		if (document.body != null && iScreenWidth >= 1020 && (document.body.scrollTop > 0 || document.body.scrollLeft > 0))
		{
			window.scroll(0,0);
		}
	}
}

function isDefined(variable)
{
	return eval("(typeof("+variable+") != 'undefined');");
}

function initializePage (bUseFixedNavigation, bSetProperNavigationStylesheet, bForceLargeStylesheet)
{
	if (typeof (bUseFixedNavigation) == "boolean") {
		glb_bUseFixedNavigation = bUseFixedNavigation;
	}
		
	if (typeof (bForceLargeStylesheet) == "boolean") {
		glb_bForceLargeStylesheet = bForceLargeStylesheet;
	}

	if (bUseFixedNavigation)
	{
		if (bSetProperNavigationStylesheet)
		{
			setProperNavigationStylesheet();
		}
		setDivHeights();

		// Run after 1/2 second to ensure browser scrollbars get accounted for
		window.setTimeout("setDivHeights()", 500);
	}
	else
	{
		setDivHeightsForOtherBrowsers();
	}
	
	StoreScreenSizeCookies();
}

document.glb_PageLayout_ScreenStyle = "unknown";
function setProperNavigationStylesheet ()
{
	var iScreenWidth = (document.body) ? document.body.clientWidth : self.innerWidth;
	var sProperNavStyle = "Navigation_Huge";
	
	if (iScreenWidth < 1260)
	{
		sProperNavStyle = "Navigation_Large";
	}

	/*	
	if (iScreenWidth < 1000 && !glb_bForceLargeStylesheet)
	{
		sProperNavStyle = "Navigation_Small";
	}
	*/
	
	document.glb_PageLayout_ScreenStyle = sProperNavStyle;
	
	var i, objLinkElement;
	for (i = 0; objLinkElement = document.getElementsByTagName('link')[i]; i++)
	{
		var sCurrentCSSFile = objLinkElement.getAttribute('href');
		
		if (sCurrentCSSFile.indexOf("Navigation_") != -1)
		{
			if (sCurrentCSSFile.indexOf(sProperNavStyle) != -1)
			{
				objLinkElement.disabled = false;
			}
			else
			{
				objLinkElement.disabled = true;
			}
		}
	}
}

function setDivHeights() {

	var iMinBodyHeight = 200;
	
	// Get DOCUMENT BODY div (Note: this DIV wraps 'divDocumentBody' and 'divRightNavigation')
	var objDocumentBody = document.getElementById('divDocumentBody');

	if (objDocumentBody == null) {
		return;
	}

	// Get PAGE BODY div
	var objPageBody = document.getElementById('divPageBody');

	if (objPageBody == null)
	{
		objPageBody = document.getElementById('divPageBodyLong');
	}

	// Get LEFT NAV div
	var objLeftNav = document.getElementById('divLeftNavigation');

	// The user's brower width is >= 1000 pixels
	//alert(document.body.clientWidth);
	
	if (document.body.clientWidth >= 1020 || glb_bForceLargeStylesheet)
	{
		// Resize PAGE BODY div
		if (objPageBody != null)
		{
			var iNewHeight = Math.max(document.body.clientHeight - (objPageBody.offsetTop + objDocumentBody.offsetTop), iMinBodyHeight);
			objPageBody.style.height = iNewHeight + 'px';
		}

		// Resize LEFT NAV div
		if (objLeftNav != null)
		{
			var iNewHeight = Math.max(document.body.clientHeight - objLeftNav.offsetTop, iMinBodyHeight);
			objLeftNav.style.height = iNewHeight + 'px';
		}

		// Get RIGHT NAV div
		var objRightNav = document.getElementById('divRightNavigation');
		var objRightNavContent = document.getElementById('divRightNavContent');
		var objSecondaryLogo = document.getElementById('divSecondaryLogo');

		// Resize RIGHT NAV div
		if (objRightNav != null)
		{
			var iNewRightNavHeight = 0;
			iNewRightNavHeight = Math.max(document.body.clientHeight - (objRightNav.offsetTop + objDocumentBody.offsetTop), iMinBodyHeight);
			objRightNav.style.height = iNewRightNavHeight + 'px';

			if (objSecondaryLogo != null)
			{
				var iNewRightNavContentHeight = 0;
				iNewRightNavContentHeight = iNewRightNavHeight - 91; //objSecondaryLogo.offsetHeight;
				objRightNavContent.style.height = iNewRightNavContentHeight + 'px';
			}
			else
			{
				objRightNavContent.style.height = iNewRightNavHeight + 'px';
			}
		}
	}

	// The user's brower width is <= 800 pixels
	else
	{
		// Resize LEFT NAV div
		if (objDocumentBody != null && objLeftNav != null)
		{
			var iNewHeight = Math.max(document.body.clientHeight, objDocumentBody.offsetHeight);
			objLeftNav.style.height = iNewHeight + 'px';
		}
	}
}

function setDivHeightsForOtherBrowsers()
{
	// Get DOCUMENT BODY div (Note: this DIV wraps 'divDocumentBody' and 'divRightNavigation')
	var objDocumentBody = document.getElementById('divDocumentBody');

	// Get PAGE BODY div
	var objPageBody = document.getElementById('divPageBody');
	if (objPageBody == null)
	{
		objPageBody = document.getElementById('divPageBodyLong');
	}

	// Get LEFT NAV div
	var objLeftNav = document.getElementById('divLeftNavigation');

	// Get RIGHT NAV div
	var objRightNav = document.getElementById('divRightNavigation');

	// Get brower window height
	var iWindowHeight = self.innerHeight;

	// Resize LEFT NAV div
	if (objPageBody != null && objLeftNav != null)
	{
		var iNewHeight = Math.max(iWindowHeight, objDocumentBody.offsetHeight + objPageBody.offsetHeight);
		objLeftNav.style.height = iNewHeight + 'px';

		iNewHeight = Math.max(iWindowHeight, objPageBody.offsetHeight);
		objRightNav.style.height = iNewHeight + 'px';
	}
}

function RemoveAutoScrollFromRightNav ()
{
	var divRightNavContent = document.getElementById("divRightNavContent");
	if (divRightNavContent != null)
	{
		divRightNavContent.style.overflow = "visible";
	}
}

// NOTE: This function is called in "<body onload>" from the code-behind file
function ScrollBodyToCoords()
{
	window.setTimeout("DelayInitialScroll()", 50);
}


function DelayInitialScroll ()
{
	try
	{
		var div = document.getElementById("divPageBody");

		if (document.body.clientWidth < 1000)
		{
			div = document.body;		        
		}

		// Uncomment if we ever want to scroll horizontally as well.
		//div.scrollLeft = parseInt(document.frmBrowseToc.xCoordHolder.value);

		var iDeltaY = parseInt(document.getElementById("yCoordHolder").value);
		if (iDeltaY > 0)
		{   
			div.scrollTop = iDeltaY;
		}

		CaptureBodyCoords();
	}
	catch(e)
	{
		/* this takes care of any script errors in case the element is not found (most pages) */
	}
}

function CaptureBodyCoords()
{
	try
	{
		var div = document.getElementById("divPageBody");
		if (document.body.clientWidth < 1000) {
			div = document.body;		        
		}

		document.getElementById("xCoordHolder").value = div.scrollLeft.toString();
		document.getElementById("yCoordHolder").value = div.scrollTop.toString();
		window.setTimeout("CaptureBodyCoords()", 200);
	}
	catch(e) { }
}

function StoreSessionTrackerState()
{            
	if (isDefined("bIsTrackerOn") && bIsTrackerOn)
	{
		var stCookie = "";           
		var myDate = new Date();                                    

		stCookie = "sessiontracker=" + iSTCurrentSessionId + "&client=" + iSTCurrentClient + "&stTimer=" + document.getElementById("sessionTrackerTimer").firstChild.nodeValue + "&clientTime=" + myDate;
		myDate.setDate(myDate.getDate() + 30);
		stCookie += "; path=/";

		document.cookie = stCookie;                   
	}
	else
	{
		// destroy cookie
		var myDate=new Date();
		myDate.setDate(myDate.getDate()-30);
		document.cookie = "sessiontracker=; expires=" + myDate.toGMTString() + "; path=/";                
	}            
}

function GetSessionTrackerState()
{                  
	if (isDefined("bIsTrackerOn"))
	{            
		var cookies = document.cookie.split(';');
		var iTimeElapsed = 0;
		var sTimerValue = "";     
		var bTrackerIsNotExpired = false;  

		for (var i=0; i<cookies.length; i++)
		{                                    
			if (cookies[i].indexOf("sessiontracker") != -1)
			{                            
				bTrackerIsNotExpired = true;                                                            
				var stCookieValues = cookies[i].split('&');                                                

				for (var j=0; j<stCookieValues.length; j++)
				{
					if (stCookieValues[j].indexOf("clientTime") != -1)
					{
						var dtLastPage = new Date(stCookieValues[j].split('=')[1]);
						var dtCurrentPage = new Date();   

						// time elapsed from previous page unload to current page load             
						iTimeElapsed = Math.round((dtCurrentPage - dtLastPage) / 1000);                                                                
					}
					else if (stCookieValues[j].indexOf("stTimer") != -1)
					{
						sTimerValue = stCookieValues[j].split('=')[1];
					}
					else if (stCookieValues[j].indexOf("sessiontracker") != -1)
					{
						iSTCurrentSessionId = stCookieValues[j].split('=')[1];
					}
					else if (stCookieValues[j].indexOf("client") != -1)
					{                               
						iSTCurrentClient = stCookieValues[j].split('=')[1];
					}
				}    
				break;                                            
			}
		}
		
		if (bTrackerIsNotExpired)
		{
			var hours, mins, secs, timerValues;

			timerValues = sTimerValue.split(':');

			hours = parseInt(timerValues[0]);
			mins = parseInt(timerValues[1]);
			secs = parseInt(timerValues[2]);

			// counteract the secs++ in UpdateTimer()
			iTimeElapsed = iTimeElapsed - 1;

			var iTimeElapsedMin = parseInt(iTimeElapsed/60);

			if (iTimeElapsedMin > 0)
			{
				mins += iTimeElapsedMin;
				iTimeElapsed = iTimeElapsed - iTimeElapsedMin * 60;

				var iTimeElapsedHour = parseInt(iTimeElapsedMin/60);

				if (iTimeElapsedHour > 0)
				{
					hours += iTimeElapsedHour;
					iTimeElapsedMin = iTimeElapsedMin - iTimeElapsedHour * 60;
				}                                      
			}

			UpdateTimer(hours, mins, secs);

			document.getElementById("SessionPlayStop").src = imgStopSrc;
			bIsTrackerOn = true;

			var spanCurrentClient = document.getElementById("spanCurrentClient");

			spanCurrentClient.firstChild.firstChild.nodeValue = document.getElementById("spanClientName_" + iSTCurrentClient).firstChild.nodeValue;                    

			GetSessionComment();
		}
	}
}

function openCopyrightDetailsWindow (sText, sCloseText, sSitePrefix)
{
	var w = 400;
	var h = 150;
	if (screen)
	{
		var l = (screen.width - w) / 2;
		var t = (screen.height - h) / 2;
	}
	else
	{
		var l = 300;
		var t = 350;
	}
	
	var s = "<html><head><title>&nbsp;</title><link rel=STYLESHEET type=text/css href='" + sSitePrefix + "_IncludeFiles/Styles/Main_KNOTIA.css'></head><body bgcolor='#dedede'><table cellpaddding=0 cellspacing=10 border=0><tr><td><p>" + sText + "</p></td></tr></table><p class=nopadding><span style=font-size:4pt>&nbsp;</span></p><p align=center class='normalText'><a href='javascript:self.close()'>" + sCloseText + "</a></p></body></html>";
	var xWin = window.open("", "xWin", "width=" + w + ",height=" + h + ",top=" + t + ",left=" + l);
	xWin.document.write(s);
	xWin.document.close();
}

// This function checks if a frameset is defined and, if it is, the page reloads WITHOUT the frameset
function RemoveFrameSet ()
{
    if (top.frames.length > 0)
    {
        top.location = self.location;
    }
}

function StoreScreenSizeCookies ()
{
   	var iScreenX = (document.body) ? document.body.clientWidth : self.innerWidth;
    CreateCookie("ScreenXSize", iScreenX, 7);

   	var iScreenY = (document.body) ? document.body.clientHeight : self.innerHeight;
    CreateCookie("ScreenYSize", iScreenY, 7);
}

function CreateCookie (sName, sValue, iDays)
{
    var sCookieText = "";
    var sExpires = "";
    
    if (iDays > 0)
    {
        var dExpiryDate = new Date();
		dExpiryDate.setTime(dExpiryDate.getTime() + (iDays*24*60*60*1000));
		sExpires = "expires=" + dExpiryDate.toGMTString() + "; ";
    }
    document.cookie = sName + "=" + sValue + "; " + sExpires + "path=/";
}

function InitializePrint() {
    //var container = document.getElementById("divDocumentBody");
    //alert(container.innerHTML);
}
/* PRINTING FUNCTIONS */

function PrettyPrintDisable()
{
	document.getElementById("divPagePrint").className="hide_Print";
	document.getElementById("divOuterDiv").className="";
	document.getElementById("divDocumentBody").className="";
}

function PrettyPrintEnable() 
{
	document.getElementById("divPagePrint").className="show_PrintPrettyOnly";
	document.getElementById("divOuterDiv").className="hide_PrintPrettyOnly";
	document.getElementById("divDocumentBody").className="hide_PrintPrettyOnly";
}


function format(str)
{
  for(i = 1; i < arguments.length; i++)
  {
    //str = str.replace('{' + (i – 1) + '}', arguments[i]);
    str = str.replace("{" + (i-1) + "}",arguments[i]);
  }
  return str;
}

function OpenPrintDialog(sSiteRoot, sPrintThisWindowJavascriptFunctionName) 
{
    
		
    
   
   
    var siteRoot = "k3";
    var printDialog = "\<form name='formPrintDialog' id='formPrintDialog'>\
                        <p class='small' id='elPrintDocument'>\
                        <input type='radio' name='iPrintWhat' value='0' checked>\
                        <a onclick='document.formPrintDialog.iPrintWhat[0].checked = true;'>{0}</a>\
                        </p>\
                        \
                        <p class='small' id='elPrintSelectedText'>\
                        <input type='radio' name='iPrintWhat' value='1'>\
                        <a onclick='document.formPrintDialog.iPrintWhat[1].checked = true;'>{1}\
                        </a>\
                        </p>\
                        \
                        <p class='small' id='elPrintCheckedBoxes'>\
                        <input type='radio' name='iPrintWhat' value='2'>\
                        <a onclick='document.formPrintDialog.iPrintWhat[2].checked = true;'>{2}\
                        </p>\
                        \
                        <p class='small' id='elPrintSearchResultDocuments'>\
                        <input type='radio' name='iPrintWhat' value='3'>\
                        <a onclick='document.formPrintDialog.iPrintWhat[3].checked = true;'>{3}\
                        </p>\
                        \
                        <p class='small' id='elPrintTaggedRecords'>\
                        <input type='radio' name='iPrintWhat' value='4'>\
                        <a onclick='document.formPrintDialog.iPrintWhat[4].checked = true;'>{4}\
                        </a>\
                        </p><br>\
                        \
                        \
                        <input id='btnPrintPreview' type='button' class='small' value=' &nbsp;{6}&nbsp; ' onclick='printPreview()'>  \
                        <input id='btnPrint' type='button' class='small' value=' &nbsp; &nbsp; {7} &nbsp; &nbsp; ' onclick='doPrint()'>\
                        <p class='small' style='diplay:none'id='elProcessingRow'> &nbsp; &nbsp; &nbsp; &nbsp; <img src='/Images/ProcessingYourRequest.gif' border='0' align='texttop'> Processing ... </p>\
                        \
                        \
                        </form>\
                    ";
        printDialog = format(printDialog,GetString("str_Print_PrintThisDocument"),GetString("str_Print_PrintSelectedText"),GetString("str_Print_PrintCheckedBoxes"),GetString("str_Print_PrintSearchResultDocuments"),GetString("str_Print_PrintTableOfContents"),GetString("str_Print_PrintTaggedParagraphs"),GetString("str_Print_Preview"),GetString("str_Print_Print"));
        
        
        
        
        var div= createCenteredPopupDiv(printDialog,true,GetString("str_Print_PrintOptions"));
        
        initWindowDialog();
        
}

function printPreview() 
{
    bPrintPreview=true;
    // OPEN WINDOW
   
    printTarget = window.open ("",  "printPreview","toolbar=no,scrollbars=yes,resizeable=yes,location=0,status=no");

    var PrintButton = "<table align='center' width='100%'><tr><td align='center'><input id='btnPrint' type='button' class='small' value='&nbsp; &nbsp; &nbsp; " + GetString("str_Print_Print") + " &nbsp; &nbsp; &nbsp;' onclick=\"print()\"> <input id='btnClose' type='button' class='small' value='&nbsp; &nbsp; &nbsp; " + GetString("str_Print_Close") + " &nbsp; &nbsp; &nbsp;' onclick='window.close()'></td></tr></table>"
    
    
    printTarget.document.write(PrintButton);

    // ADD STYLESHEETS
    for (var i=0;document.styleSheets!=null && i<document.styleSheets.length;i++) 
    {
        if (document.styleSheets[i].href !=null && document.styleSheets[i].href.toLowerCase().indexOf("fixednavigation_") < 0 )
            printTarget.document.write(format("<link rel='stylesheet' type='text/css' href='{0}' media='all'>",document.styleSheets[i].href));                        
    }
    
    // WRITE TEXT
    getPrintText();

    bPrintPreview=false;
    
    printTarget.document.close();
    
}

function CleanDoc(doc) 
{
    var cleanedDoc = doc.replace(/<script[^>]*>.*<\/script>/gi,"");
    cleanedDoc = cleanedDoc.replace(/onmouseover=/gi,"nothing=");
    cleanedDoc = cleanedDoc.replace(/onmouseout=/gi,"nothing=");
    cleanedDoc = cleanedDoc.replace(/onmousedown=/gi,"nothing=");
    cleanedDoc = cleanedDoc.replace(/onclick=/gi,"nothing=");
    cleanedDoc = cleanedDoc.replace(/onmouseup=/gi,"nothing=");
    return cleanedDoc ;
}   

function doPrint() 
{
    getPrintText();
}

function initWindowDialog()
{
	if (testSelectedText())
	{
		document.formPrintDialog.iPrintWhat[1].checked = true;
	}
	else
	{
		document.getElementById("elPrintSelectedText").style.color = "#A1A192";
		document.formPrintDialog.iPrintWhat[1].disabled = true;
	}
    
	document.getElementById("elPrintCheckedBoxes").style.color = "#A1A192";
	document.formPrintDialog.iPrintWhat[2].disabled = true;
	
	document.getElementById("elPrintSearchResultDocuments").style.color = "#A1A192";
	document.formPrintDialog.iPrintWhat[3].disabled = true;
	
	document.getElementById("elPrintTaggedRecords").style.color = "#A1A192";
	document.formPrintDialog.iPrintWhat[4].disabled = true;
	
	document.getElementById("elProcessingRow").style.display = "none";
	
}

function getPrintText() 
{
    if (document.formPrintDialog.iPrintWhat[1].checked) 
    {
       getSelectedText();
    }
    else 
    {
        getDocumentText();
    }

}

function testSelectedText()
{
	if (document.selection) 
	{
	    var r = document.selection;
		if (r.type == "Text")
		{
			var r = r.createRange();
			if (r.htmlText.length !=0 ) 
		    {
		        return true;
		    }
			
		}
		
	}

    else if (window.getSelection())	
    {
		var r = window.getSelection();
        if (r.anchorNode != r.focusNode || r.anchorOffset != r.focusOffset) 
        {
            return true;
        }
    }
	
	return false;
}

function getSelectedText()
{
    
	if (document.selection)
	{
		var r = document.selection;
		if (r.type == "Text")
		{
			
			var r = r.createRange();
			if ( bPrintPreview) 
			{
			    printTarget.document.write(r.htmlText)
			    
			}
			else 
			{
			 
			    var CopyrightHTML = document.getElementById("divCopyright").innerHTML;
			    PrettyPrintEnable();
			    document.getElementById("divPagePrint").innerHTML = r.htmlText + CopyrightHTML;
			    removeButtonPopup();  
			    window.print();
			    PrettyPrintDisable();
			}
			
		}
	}
	else if (window.getSelection())
	{
		var sel = window.getSelection();
		var html = "";
		for (var i=0;i<sel.rangeCount;i++)
		{
			var d = document.createElement("span");
			var r = sel.getRangeAt(i);
			d.appendChild(r.cloneContents());
			html += d.innerHTML;
		}
	
		if (bPrintPreview) 
			{
			    printTarget.document.write(html)
			}
			else 
			{
			    document.getElementById("divPagePrint").innerHTML = html;
			    removeButtonPopup();  
			    window.print();
			}
	}

}


function getDocumentText() 
{
    var BodyHtml="";
    if ( document.getElementById("divPageBody") == null)
    {
       BodyHtml = CleanDoc(document.getElementById("divPageBodyLong").innerHTML);
    }
    else
    {
       BodyHtml = CleanDoc(document.getElementById("divPageBody").innerHTML);
    }
    
    if ( bPrintPreview ) 
    {
        printTarget.document.write(BodyHtml);
    }
    else 
    {
        document.getElementById("divPagePrint").innerHTML = BodyHtml;
        removeButtonPopup();  
        window.print();
    }
}


function CountryOfInvestmentChanged(sCountryID /*ddlCountries*/) {
	//var sCountryID = ddlCountries.options[ddlCountries.selectedIndex].value;

	if (sCountryID == "0") {
		CreateCookie("GWTR_CountryOfInvestment", sCountryID, -1);
		window.location = "/GWTR/Home.aspx";
	}
	else {
		CreateCookie("GWTR_CountryOfInvestment", sCountryID, 1);
		window.location = "/GWTR/CountryHome.aspx";
	}
}


function ClearCountryOfInvestment() {
	/*$("#ddlCountryOfInvestment").selectedIndex = 0;*/
	var divRightNavInvestorCountry = document.getElementById("divRightNavInvestorCountry");
	if (divRightNavInvestorCountry != null) {
		divRightNavInvestorCountry.innerHTML = "Choose....";
	}
	CreateCookie("GWTR_CountryOfInvestment", "0", -1);
}


function GetWordSave(productID, bookID, documentID) {
	document.frmHiddenForSave.lsDocumentItems.value = productID + "," + bookID + "," + documentID;
	document.frmHiddenForSave.method = "post";
	document.frmHiddenForSave.action = "/Knowledge/" + "GetWordDocument.aspx";
	document.frmHiddenForSave.submit();
}
