// ------------------------------------------------------------------
// This is a part of the In-Tend Software library.
// Copyright (c) 2002 
// All rights reserved.
//
// This source code is only intended as a supplement to the In-Tend
// Software Library and related electronic documentation
// provided with the library. See the sources for detailed
// information regarding the In-Tend Software Library product.
// ------------------------------------------------------------------
// IT-01261			AM		11/08/2009
// Changes to stop returns being made after start of o/c
// ------------------------------------------------------------------
// IT-00037			GM		26/11/2008
// Modified to record last time a contact viewed the document manage
// screen for an auction.
// ------------------------------------------------------------------
// IT-00038			AM		19/11/2008
// Removed '0' elements from countdown's
// ------------------------------------------------------------------
// IT-00035			GM		13/11/2008
// Fixed problem with uploading documents stopping the doc manage
// page from refreshing.
// ------------------------------------------------------------------
// IT-00035			GM		12/11/2008
// Slight change to suspended logic.
// ------------------------------------------------------------------
// IT-00035			GM		05/11/2008
// Modifed for setting the start date and time for an Auction.
// ------------------------------------------------------------------
// ITS01064	GM		22/09/2008
// Modified for language selection.
// ------------------------------------------------------------------
// ITS01064	GM		17/09/2008
// Modified for multiple language support.
// ------------------------------------------------------------------
// ITS01340	DR		10/09/2008
// Modified to deal with changes in client locale.
// ------------------------------------------------------------------
// ITS01064	GM		28/08/2008
// Modified for multiple language support.
// ------------------------------------------------------------------
// Build V2.6.0.18	GM	14/11/06
// Fixed problem with time remaining being too large on 31st of the
// month when close date is in a month with fewer than 31 days.
// ------------------------------------------------------------------
// Build V2.6.0.14	GM	10/08/06
// Removed GMT.
// ------------------------------------------------------------------
// Build V2.6	AM		19/07/06
// Safari compatibility
// ------------------------------------------------------------------
// Build 2.6.0.9	GM	18/07/06
// Added days to countdown.
// ------------------------------------------------------------------
// Build 2.6.0.9	GM	17/07/06
// Fixed bug with refreshing the screen when countdown reaches zero.
// ------------------------------------------------------------------
// Build 2.6.0.8	GM	17/07/06
// Modified refresh when countdown reaches zero.
// ------------------------------------------------------------------
// Build 2.6.0.6	GM	14/07/06
// Modified adding countdown till deadline.
// ------------------------------------------------------------------
// Build 2.6.0.6	GM	10/07/06
// Modified client call back function.
// Moved ServerTime function here.
// ------------------------------------------------------------------
// IT01593		AM		26/04/06
// Modified client call back function.
// Moved ServerTime function here.
// ------------------------------------------------------------------

//   Following functions written by:   Bill Dortch, hIdaho Design 
//   The following functions are released to the public domain. 

function FixCookieDate (date) { 
   var base = new Date(0); 
   var skew = base.getTime(); // dawn of (Unix) time - should be 0 
   if (skew > 0)   // Except on the Mac - ahead of its time 
      date.setTime (date.getTime() - skew); 
} 

function getCookieVal (offset) { 
   var endstr = document.cookie.indexOf (";", offset); 
   if (endstr == -1) 
      endstr = document.cookie.length; 
   return unescape(document.cookie.substring(offset, endstr)); 
} 

function GetCookie (name) { 
   var arg = name + "="; 
   var alen = arg.length; 
   var clen = document.cookie.length; 
   var i = 0; 
   while (i < clen) { 
      var j = i + alen; 
      if (document.cookie.substring(i, j) == arg) 
         return getCookieVal (j); 
      i = document.cookie.indexOf(" ", i) + 1; 
      if (i == 0) break; 
   } 
   return null; 
} 

function SetCookie (name, value) { 
   var argv = SetCookie.arguments; 
   var argc = SetCookie.arguments.length; 
   var expires = (argc > 2) ? argv[2] : null; 
   var path = (argc > 3) ? argv[3] : null; 
   var domain = (argc > 4) ? argv[4] : null; 
   var secure = (argc > 5) ? argv[5] : false; 
   if (expires!=null) FixCookieDate(expires); 
   document.cookie = name + "=" + escape (value) + 
      ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
      ((path == null) ? "" : ("; path=" + path)) + 
      ((domain == null) ? "" : ("; domain=" + domain)) + 
      ((secure == true) ? "; secure" : ""); 
} 


function GetXMLHttpRequest() 
{
	if (window.XMLHttpRequest) 
	{
		return new XMLHttpRequest();
	} 
	else 
	{
		if (window.XMLHttpRequestProgID) 
		{
			return new ActiveXObject(window.XMLHttpRequestProgID);
		} 
		else 
		{
			var progIDs = 
			[	
				"Msxml2.XMLHTTP.5.0", 
				"Msxml2.XMLHTTP.4.0", 
				"MSXML2.XMLHTTP.3.0", 
				"MSXML2.XMLHTTP", 
				"Microsoft.XMLHTTP"
			];
			
			for ( var i = 0; i < progIDs.length; ++i ) 
			{
				var progID = progIDs[i];
				try 
				{
					var httpReq = new ActiveXObject(progID);
					window.XMLHttpRequestProgID = progID;
					return httpReq;
				}
				catch (e) 
				{
				
				}
			}
		}
	}
	return null;
}

var vHelpWindow = null;
var vHelpSection = "";
function ShowHelp( vSection ) {
    vHelpWindow = window["onlinehelp"];
    if ( !vHelpWindow ) {
        vHelpWindow = window.open( "onlinehelp.asp?help=" + vSection, "onlinehelp", "height=500,width=500,scrollbars=yes,resizable=yes" );
    }
    vHelpWindow.focus();
}

function FinishLoadingPage() {
    if((obForm=document.pageloginform)){
        if(obForm.username){obForm.username.focus();}
        else if(obForm.email){obForm.email.focus();}
    }
    if((obForm=document.pageloginphraseform)){
        if(obForm.newpin){obForm.newpin.focus();}
        else if(obForm.newpassphrase){obForm.newpassphrase.focus();}
        else if(obForm.pin){obForm.pin.focus();}
        else if(obForm.phrasechar1){obForm.phrasechar1.focus();}
    }
    if((obForm=document.businessdetailsform)&&obForm.businesstypes){obForm.businesstypes.focus();}
    if((obForm=document.contactdetailsform)&&obForm.contact_title){obForm.contact_title.focus();}
    if((obForm=document.supplierdetailsform)&&obForm.companyname){obForm.companyname.focus();}
    if((obForm=document.recoveryform)&&obForm.email){obForm.email.focus();}
}

function UnloadingPage() {
    //if ( vHelpWindow != null ){vHelpWindow.close();}
}

document.onstop=StopPage;
function StopPage(){
    document.body.style.cursor = "default";
}

function EmailKeyPress(event){
    if(window.event)vKC=window.event.keyCode;
    else vKC=event.which;
	// 0=null, 8=backspace, 39=apostrophe ('), 45=hyphen (-), 95=underscore (_), 46=full stop (.), 64=At (@)
    if(vKC==0||vKC==8||vKC==39||vKC==45||vKC==95||vKC==46||vKC==64||AlphaNumKP(event,false))
    {return true;}else{return false;}
}       

function NumKP(event,vTE,vNeg,vDec){
    if(window.event)vKC=window.event.keyCode;
    else vKC=event.which;
    if(vKC==0||vKC==8||(vKC>=48&&vKC<=57)){return true;}
    if(vTE){
        if(vNeg){
            if(vKC==45&&vTE.value.indexOf("-")==-1){return true;}
        }
        if(vDec){
            if(vKC==46&&vTE.value.indexOf(".")==-1){return true;}
        }
        return false;
    }else{
        return false;
    }
}

function NumKPNegValid(vTE){
    if(vTE&&vTE.value.indexOf("-")>0)
    {window.alert("Incorrect negative number");vTE.select();}
}

function AlphaNumKP(event,vMakeCaps){
    if(window.event)vKC=window.event.keyCode;
    else vKC=event.which;
    if(vMakeCaps){
        if(vKC>=97&&vKC<=122)
        {vKC-=32;window.event.keyCode=vKC;}
        if(vKC==0||vKC==8||(vKC>=48&&vKC<=57)||(vKC>=65&&vKC<=90))
        {return true;}else{return false;}
    }else{
        if(vKC==0||vKC==8||(vKC>=48&&vKC<=57)||(vKC>=65&&vKC<=90)||(vKC>=97&&vKC<=122))
        {return true;}else{return false;}
    }
}

function IsIE() {
    return ( document.all != null );
}

function IsNetscape() {
    return ( document.layers != null );
}

var vAnyChanges=false;
function SetChange(){
vAnyChanges=true;
}

// Used to update the server clock on docmanage.asp
var timerObj;
var iCount = 1;
var dtServerTime = null;
var dtOpeningDate = null;
var dtClosingDate = null;
var dtPreviousOpeningDate = null;
var dtPreviousClosingDate = null;
var varPastDeadline;
var lTimeZoneOffset;
var lProductId = -1;
var lTendererId = -1;
var lContactId = -1;
var bBeforeStageStartDate = false;
var bAuction = false;
var bSuspended = false;
var bPreviousSuspended = null;
var bJustLoaded = true;
var bPreviousOCStarted = null;
var bOCStarted = false;

function ServerClock(
	vTimeZoneOffset,
	vProductId,
	vBeforeStageStartDate,
	vAuction,
	vTendererId, 
	vContactId )
{
	// If screen opended for first time/refreshed
	if ( bJustLoaded == true )
	{
		lTimeZoneOffset = vTimeZoneOffset;
		lProductId = vProductId;
		lTendererId = vTendererId;
		lContactId = vContactId;
		bBeforeStageStartDate = ( vBeforeStageStartDate == "True" ) ? true : false;
		bAuction = ( vAuction == "True" ) ? true : false;
		bJustLoaded = false;
	}

	var iRefreshInterval = 15;
	var objControl = document.getElementById( "ServerClock" ); 

	// If this is the server refresh cycle
	if ( iCount == 1 )
	{
		var url = "time.asp?productid=" + lProductId + "&tendererid=" + lTendererId + "&contactid=" + lContactId;
		var httpReq = window.GetXMLHttpRequest();
	
		httpReq.open("GET", url, true);
		httpReq.onreadystatechange = function() {
		    if (httpReq.readyState == 4) {
		        if (objControl != null) {
		            var strStageInfo = httpReq.responseText;

		            // Refresh the server time object with the data from the server
		            dtServerTime = GetDateFromString(strStageInfo, 0);
		            dtOpeningDate = GetDateFromString(strStageInfo, 19);
		            dtClosingDate = GetDateFromString(strStageInfo, 38);

		            // If the suspended string is True
		            bSuspended = (strStageInfo.charAt(57) == 'T');
		            bOCStarted = (strStageInfo.charAt(61) == 'T' || strStageInfo.charAt(62) == 'T');

		            // Adjust for any time zone requirements.
		            if (lTimeZoneOffset != 0) {
		                dtServerTime.setHours(dtServerTime.getHours() + lTimeZoneOffset);
		                dtOpeningDate.setHours(dtOpeningDate.getHours() + lTimeZoneOffset);
		                dtClosingDate.setHours(dtClosingDate.getHours() + lTimeZoneOffset);
		            }

		            if ((dtPreviousOpeningDate != null && dtPreviousOpeningDate.getTime() != dtOpeningDate.getTime()) ||
						 (dtPreviousClosingDate != null && dtPreviousClosingDate.getTime() != dtClosingDate.getTime()) ||
						 (bPreviousSuspended != null && bPreviousSuspended != bSuspended) ||
						 (bPreviousOCStarted != null && bPreviousOCStarted != bOCStarted)) {
		                RefreshDocumentManagePage();
		            }
		            else {
		                dtPreviousOpeningDate = dtOpeningDate;
		                dtPreviousClosingDate = dtClosingDate;
		                bPreviousSuspended = bSuspended;
		                bPreviousOCStarted = bOCStarted;

		                var strDateTimeIncremented =
							pad(dtServerTime.getDate()) + "/" +
							pad(dtServerTime.getMonth() + 1) + "/" +
							(dtServerTime.getFullYear()) + " " +
							pad(dtServerTime.getHours()) + ":" +
							pad(dtServerTime.getMinutes()) + ":" +
							pad(dtServerTime.getSeconds());

		                objControl.value = strDateTimeIncremented;

		                // If this is the first time through
		                if (varPastDeadline == null) {
		                    var iTimeLeft = dtClosingDate.getTime() - dtServerTime.getTime();

		                    if (iTimeLeft < 0) {
		                        varPastDeadline = true;
		                    }
		                    else {
		                        varPastDeadline = false;
		                    }
		                }

		                UpdateCountdown();
		                timerObj = setTimeout(ServerClock, 1000);
		            }
		        }
		    }
		}
		
		try
		{
			httpReq.send("");
		}
		catch(e){
			return;
		}
	}
	else
	{  
		if ( objControl != null )
		{
			dtServerTime.setTime( dtServerTime.getTime() + 1000 );
            
			var strDateTimeIncremented = pad( dtServerTime.getDate()) + "/" +
										 pad( dtServerTime.getMonth() + 1 ) + "/" +
										 ( dtServerTime.getFullYear() ) + " " +
										 pad( dtServerTime.getHours() ) + ":" +
										 pad( dtServerTime.getMinutes() ) + ":" +
										 pad( dtServerTime.getSeconds() );
			objControl.value = strDateTimeIncremented;
            
            UpdateCountdown();
			timerObj = setTimeout( ServerClock, ( 1000 ) )
		}
	}

	if ( iCount == iRefreshInterval )
	{
		// Go back to the server
		iCount = 1;
	}
	else
	{
		iCount++;
	}
}

function pad( iValue )
{
	return iValue = ( iValue < 10 ) ? "0" + iValue : iValue;
}

function UpdateCountdown() 
{
	var objControl = document.getElementById( "Countdown" ); 

	if ( objControl != null )
	{
		if ( bSuspended && bAuction )
		{
			objControl.value = GetTerminology("Auction Suspended");
		}
		else if ( dtOpeningDate != null && dtClosingDate != null && dtServerTime != null )
		{
			var iTimeLeft
			
			if ( bAuction && bBeforeStageStartDate )
			{
				iTimeLeft = dtOpeningDate.getTime() - dtServerTime.getTime();
			}
			else
			{
				iTimeLeft = dtClosingDate.getTime() - dtServerTime.getTime();
			}

			if ( iTimeLeft < 0 )
			{
				if ( varPastDeadline == false )
				{
					RefreshDocumentManagePage();
				}

				iTimeLeft = 0;
			}

			objControl.value = msToDHMS( iTimeLeft );
		}
	}
}

var msInSecond = 1000;
var msInMinute = msInSecond * 60;
var msInHour = msInMinute * 60;
var msInDay = msInHour * 24;

function msToDHMS( vNumMilliSeconds )
{
	var iWholeDays, iWholeHours, iWholeMinutes, iWholeSeconds;
    var strTime = "";

	if ( vNumMilliSeconds == 0 )
	{
		iWholeDays = 0;
		iWholeHours = 0;
		iWholeMinutes = 0;
		iWholeSeconds = 0;

		strTime = GetTerminology("Finished");
	}
	else
	{
		iWholeDays = calcQuotient( vNumMilliSeconds, msInDay );
		vNumMilliSeconds = vNumMilliSeconds - ( iWholeDays * msInDay )

		iWholeHours = calcQuotient( vNumMilliSeconds, msInHour );
		vNumMilliSeconds = vNumMilliSeconds - ( iWholeHours * msInHour )

		iWholeMinutes = calcQuotient( vNumMilliSeconds, msInMinute );
		vNumMilliSeconds = vNumMilliSeconds - ( iWholeMinutes * msInMinute )

		iWholeSeconds = calcQuotient( vNumMilliSeconds, msInSecond );

		if( Math.round( iWholeDays ) != 0 )
			strTime = Math.round( iWholeDays ) + " " + GetTerminology("Days") + " ";

		if( Math.round( iWholeHours ) != 0 )
			strTime = strTime + Math.round( iWholeHours ) + " " + GetTerminology("Hrs") + " "

		if( Math.round( iWholeMinutes ) != 0 )
			strTime = strTime + Math.round( iWholeMinutes ) + " " + GetTerminology("Mins") + " "

		strTime = strTime + Math.round( iWholeSeconds ) + " " + GetTerminology("Secs");
	}


	return strTime;
}

function calcQuotient( vNumerator, vDenominator )
{
	return ( vNumerator / vDenominator ) - ( (vNumerator % vDenominator) / vDenominator );
}

function RefreshDocumentManagePage()
{
	var strURL = document.URL;

	// If the url doesn't contain project/stage info
	// we need to explicitly add it.
	if ( strURL.search( /projectid/i ) == -1 )
	{
		var objProjectId = document.getElementById( "projectid" );
		var objProductId = document.getElementById( "productid" );

		if ( objProjectId != null && objProductId != null )
		{
			strURL += "?projectid=" + objProjectId.value +
					  "&productid=" + objProductId.value;
		}
	}

	// If a return document was uploaded/removed fix the URL
	strURL = strURL.replace( "#returnanchor", "" );

	// Reload the page
	window.location.replace( strURL );
}

function GetDateFromString( vDateTime, vOffSet )
{
	var dtExtractedDate = new Date();

	// Refresh the server time object with the data from the server
	dtExtractedDate.setFullYear(
		parseInt( vDateTime.slice( 6 + vOffSet, 10 + vOffSet ), 10 ),
		parseInt( vDateTime.slice( 3 + vOffSet, 5 + vOffSet ), 10 ) - 1,
		parseInt( vDateTime.slice( 0 + vOffSet, 2 + vOffSet ), 10 )
	);
	dtExtractedDate.setHours( parseInt( vDateTime.slice( 11 + vOffSet, 13 + vOffSet ), 10 ) );
	dtExtractedDate.setMinutes( parseInt( vDateTime.slice( 14 + vOffSet, 16 + vOffSet ), 10 ) );
	dtExtractedDate.setSeconds( parseInt( vDateTime.slice( 17 + vOffSet, 19 + vOffSet ), 10 ) );
	dtExtractedDate.setMilliseconds( 0 );

	return dtExtractedDate;
}

function GetTerminology( vKey )
{
	if( vKey && vTerminology )
	{
		var i;

		for( i = 0; i< vTerminology.length; i+=2 )
		{
			if ( vKey == vTerminology[i] )
			{
				return vTerminology[i+1]
			}
		}
	}

	return "Error: could not find " + vKey;
}

function SetLanguageCookie( vNewLanguage )
{
	var vCurrentLanguage = GetCookie( "DisplayLanguage" );

	if ( vCurrentLanguage != vNewLanguage )
	{
		SetCookie( "DisplayLanguage", vNewLanguage );

		// Refresh the page
		window.location.reload();
	}
}
