/*
=======================================================================================
'
'	Filename:		main_template.asp
'	Description:	Main layout template
'	Author:			Joanna Araminta
'   CVS Info:       $Id: main.js,v 1.15 2007/08/27 07:15:55 victor Exp $
'	
'=======================================================================================
*/
	// Global Variables
	// keep track of the line # for the currently selected row
	var selectedRow = null;
	var selLotStatus = "";
	var selActivityStatus = "";
	var selCapacityStatus = "";
	var currentRound = 0;

	function MSIEHighlightRow( rowNumber )
	{
		var targetRow = document.getElementById("row" +rowNumber);
		targetRow.bgColor = "#FFFF9B";
	}

	function MSIEUnHighlightRow( rowNumber )
	{
	    var targetRow = document.getElementById("row" + rowNumber);
	    if (isSecondaryAuction)
	        targetRow.bgColor = "#ffffff";
	    else
		    targetRow.bgColor = "#F0F9DF";
	}

	function NetscapeHighlightRow( rowNumber )
	{
		var highlight = document.layers["highlightLayer"];
		// compute height of rows
		var height = highlight.clip.height;
		highlight.moveTo( 1, ( rowNumber * height ) );
		highlight.visibility="show";
	}

	function NetscapeUnHighlightRow( rowNumber )
	{
		var highlight = document.layers["highlightLayer"];
		highlight.visibility="hide";
	}

	// set functions according to browser type
	// assume only MSIE or Netscape for example purposes
	if( navigator.appName.search(  /Microsoft Internet Explorer/i ) > -1 )
	{
		HighlightRow = MSIEHighlightRow;
		UnHighlightRow = MSIEUnHighlightRow;
	}
	else
	{
		HighlightRow = NetscapeHighlightRow;
		UnHighlightRow = NetscapeUnHighlightRow;
	}

	// select the specified row
	function SelectRow(rowID)
	{
		// unhighlight the previously selected row, if any
		if( selectedRow != null ) {
			UnHighlightRow( selectedRow );
        }

		// highlight selected row
		HighlightRow( rowID );
		selectedRow = rowID;
	}


	// update the bid information panel.  
	// dynamically update the lot number and the target bid information
	function updatePanel(lotID, lotNum, lotStatus, activityStatus, capacityStatus)
	{

		if (lotID != "") {
		    if(document.getElementById('lotTB') != null)
			    document.getElementById('lotTB').innerHTML			= lotsArray[lotID]["target"];
			if (document.getElementById('lotOT') != null)
				document.getElementById('lotOT').innerHTML			= lotsArray[lotID]["option"];

			document.getElementById('lotNum').innerHTML			= lotNum;	
			document.getElementById('lotCB').innerHTML			= lotsArray[lotID]["ceiling"];	
            document.getElementById('autoSubmit').innerHTML		= lotsArray[lotID]["auto"];
            document.getElementById('lotReactivate').innerHTML = lotsArray[lotID]["reactivate"];
            if (!isSecondaryAuction) {
                document.getElementById('lotSB').innerHTML = lotsArray[lotID]["submitted"];
            }
            else {
                document.getElementById('lotSP').innerHTML = lotsArray[lotID]["settlementPrice"];
                document.getElementById('secondaryAuctionMDPLotValue').innerHTML = lotsArray[lotID]["lotMDPValue"];
                if(document.getElementById('lotSB') != null)
                    document.getElementById('lotSB').innerHTML = lotsArray[lotID]["submittedBidLotPrice"];
            }
			selectedRow	= lotID;
		}

		selLotStatus		= lotStatus;
		selActivityStatus	= activityStatus;
		selCapacityStatus	= capacityStatus;

	}

	function MM_preloadImages() { //v3.0
	  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
		var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
		if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
	}

	function MM_swapImgRestore() { //v3.0
	  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
	}

	function MM_findObj(n, d) { //v4.01
	  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	  if(!x && d.getElementById) x=d.getElementById(n); return x;
	}

	function MM_swapImage() { //v3.0
	  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
	}

    var server_time_diff = 0;
	var is_pushed_refresh = 0;
    
    function countdown(timeEnd, tagID) {
        if (timeEnd == "") {
            document.getElementById(tagID).innerHTML = "-";
            setTimeout("countdown('" + timeEnd + "', '" + tagID + "');", 1000);
            return;
        }
        var nowMs = new Date().getTime() + server_time_diff;
        var endMs = new Date(timeEnd).getTime();
        var timeLeft = Math.round((endMs - nowMs) / 1000);

		//if (timeLeft == -5 && is_pushed_refresh == 0)
		if (timeLeft == 0 && is_pushed_refresh == 0)
		{
			refresh(tagID);
			is_pushed_refresh = 1;
		}

        if(timeLeft < 0) {
            timeLeft = 0;
        }

        var hours = Math.floor(timeLeft / (60 * 60));
        timeLeft %= (60 * 60);
        var minutes = Math.floor(timeLeft / 60);
        timeLeft %= 60;
        seconds = timeLeft;

        document.getElementById(tagID).innerHTML =
            hours + 'h ' + minutes + 'm ' + seconds + 's';
    
        //Recursive call, keeps the clock ticking.
        setTimeout("countdown('" + timeEnd + "', '" + tagID + "');", 1000);
    }
    
    function upclock(tagID) {
        var dte = new Date(new Date().getTime() + server_time_diff);
        var hrs = (dte.getHours() < 10 ? "0" : "") + dte.getHours(); 
        var min = (dte.getMinutes() < 10 ? "0" : "") + dte.getMinutes(); 
        var sec = (dte.getSeconds() < 10 ? "0" : "") + dte.getSeconds(); 
        
        // For 12 Hour AM/PM time:
        //var hrs = dte.getHours();
        //var apm = hrs >= 12 ? "PM" : "AM";
        //hrs = (hrs == 0 ? 12 : (hrs > 12 ? hrs - 12 : hrs));
        //document.getElementById("serverTime").innerHTML = hrs + ":" + min + ":" + sec + " " + apm;

        document.getElementById(tagID).innerHTML = hrs + ":" + min + ":" + sec + " AEST";
    
        setTimeout("upclock('" + tagID + "');", 1000);
    }
    
    function refresh(tagID) {

		if (tagID == "regTimeRemaining" || tagID == "regTime")
		{
			location.href = "registration.asp";
		}
		
		else if (tagID == "bidSubmitRoundTimeRemaining")
		{
			location.href = unescape(window.location.pathname);
		}

		else if (tagID == "processingTimeRemaining")
		{
			location.href = "auctions.asp";
		}

		else if (tagID == "roundTimeRemaining" || tagID == "auctionTimeRemaining")
		{
			location.href = "auctions.asp?processing=y";
		}

		else if (tagID == "comboPrefTimeRemaining" || tagID == "comboCreateTimeRemaining")
		{
			location.href = "combinations.asp";
		}

		else {
	        location.href = (selectedRow == null ? "" : "?LotID=" + selectedRow + "&sortBy=" + sort + "&priorSortBy=" + prevSort);
		}

        setTimeout("refresh();", 10000);
    }

	//verify function to verify all inputs with a set pattern
	function verifyBidSubmit(sortString){

		var goAhead = 0;

		if (selLotStatus == "6.closed")
		{
			alert("The selected lot is now closed.  No more bids will be accepted for this lot.");
			return false;
		}
		else
			goAhead = 1;

		if (selLotStatus == "7.winner")
		{
			alert("You have won the selected lot.  Thank you for your participation.");
			return false;
		}
		else
			goAhead = 1;

		if (selLotStatus == "3.hidden")
		{
			alert("You have been de-activated for this Lot.  You can not enter bids for this lot.");
			return false;
		}
		else
			goAhead = 1;
		
		if (currentRound > 1) 
		{
				if (selLotStatus != "2.pending" && selLotStatus != "1.blank" && selLotStatus == "3.hidden" && selActivityStatus == "2.not_active")
				{
					alert("You are not qualified to submit bids for this lot in this round.");
					return false;
				}
				else
				{
					goAhead = 1;
				}
		}
		else
			goAhead = 1;
		
		if (selCapacityStatus == "2.no_capacity")
		{
			alert("You do not have enough Capacity to bid on this lot.");
			return false;
		}
		else
			goAhead = 1;
		
		if (currentRound == 0)
		{
			alert("The auction is currently paused.  No bids will be accepted until the start of the next round.");
			return false;
		}
		else
			goAhead = 1;

		if (goAhead > 0) 
        {
			location.href = "bid_breakdown.asp?lot_id=" + selectedRow + "&" + sortString;
		}		

	}	

	function clearPref(lotNum) {

		var thisElement = document.getElementById("reg[" + lotNum + "]");

		if (thisElement.checked)
		{
			// do nothing
		}
		else {
			document.getElementById("pref[" + lotNum + "]").value = "";
		}
	}

	function verifyForm() {

		var typeCheck = false;

		for (var i = 0; i<document.regForm.elements.length; i++)
		{

			if (document.regForm.elements[i].name == "trainingType") {

				if (document.regForm.training.checked)
				{
					for(counter = 0; counter < document.regForm.trainingType.length; counter++)	{
						if (document.regForm.trainingType[counter].checked) {
							typeCheck = true;
						}
					}
				}

			}

			else {
				if (document.regForm.elements[i].value.length == 0)
				{
					alert("All fields are mandatory.\n\nPlease populate all fields to proceed.");
					return false;
				}
			}

		}

		if (isNaN(document.regForm.postcode.value))
		{
			alert("Postcode must be positive numeric value.\n\nPlease try again.");
			return false;
		}

		if (document.regForm.training.checked && typeCheck == false)
		{
			alert("Please specify the training type required.");
			return false;
		}

	}

	function clearType() {

		var thisElement = document.getElementById("training");

		if (thisElement.checked)
		{
			// do nothing
		}
		else {
			for(counter = 0; counter < document.regForm.trainingType.length; counter++)	{

				document.regForm.trainingType[counter].checked = false;				
			}
		}

	}
    
    function verifyRegistration(frmElem){
        var regex, pattern, errmsg;
        var result;
        var index;
        var registered;
        var numLotsRegistered;
        var prefList;
        
        prefList = "";        
        numLotsRegistered = 0;

        
        //loop through all form elements
        for(var i = 0;i < frmElem.length ;i++){

            index = frmElem.elements(i).name.indexOf("reg[");

            if (!index) {
                
                if (frmElem.elements(i).checked) {
                 
                    numLotsRegistered = numLotsRegistered + 1;
                    
                    if (frmElem.elements(i+1).name.indexOf("pref[") >= 0) {
                        
                        if (frmElem.elements(i+1).value == "") {
                     
                            alert("You must assign preferences to all selected lot.\n\nPlease try again");
                            return false;
                        }
                        else if (frmElem.elements(i+1).value <= 0 || isNaN(frmElem.elements(i+1).value)) {
                            
                            alert("Preferences must be a positive value and greater than 0.\n\nPlease try again.");    
                            return false
                            
                        }
                        
                        prefList = prefList + "[" + frmElem.elements(i+1).value + "], ";
                        
						if ((i+3) <= frmElem.length)
						{
							if (prefList.indexOf("[" + frmElem.elements(i+3).value + "]") >= 0) {
							 
								   alert("Duplicate preference values are not allowed.\n\nPlease try again.");
								   return false;
							}

						}
                    }   
                }
            }
        }
        
        for(var k = 0;k < frmElem.length ;k++){

            index = frmElem.elements(k).name.indexOf("pref[");

            if (!index) {
                
                if (frmElem.elements(k).value > numLotsRegistered) {
                 
                    alert("There are only " + numLotsRegistered + " lots selected.  Preference value can not exceed this number.\n\nPlease try again.");                
                    return false;
                    
                }
            }
        }   

		var isValidate = 0;
		var myArgs = new Array(isValidate);
		var myArgs = window.showModalDialog("validate_registration.asp", myArgs, "dialogHeight=500px, dialogWidth=400px");
		if (myArgs != null)
		{
			isValidate = myArgs[0];
			//return true;
		}
		else
			return false;			
    }

    function verifyPreference(frmElem){
        var regex, pattern, errmsg;
        var result;
        var index;
        var registered;
        var numLotsRegistered;
        var prefList;
        
        prefList = "";        
        numLotsRegistered = 0;

        
        //loop through all form elements
        for(var i = 0;i < frmElem.length ;i++){

            index = frmElem.elements(i).name.indexOf("reg[");

            if (!index) {
                
                if (frmElem.elements(i).checked) {
                 
                    numLotsRegistered = numLotsRegistered + 1;
                    
                    if (frmElem.elements(i+1).name.indexOf("pref[") >= 0) {
                        
                        if (frmElem.elements(i+1).value == "") {
                     
                            alert("You must assign preferences to all selected lot.\n\nPlease try again");
                            return false;
                        }
                        else if (frmElem.elements(i+1).value <= 0 || isNaN(frmElem.elements(i+1).value)) {
                            
                            alert("Preferences must be a positive value and greater than 0.\n\nPlease try again.");    
                            return false
                            
                        }
                        
                        prefList = prefList + "[" + frmElem.elements(i+1).value + "], ";
                        
						if ((i+3) <= frmElem.length)
						{
							if (prefList.indexOf("[" + frmElem.elements(i+3).value + "]") >= 0) {
							 
								   alert("Duplicate preference values are not allowed.\n\nPlease try again.");
								   return false;
							}

						}
                    }   
                }
            }
        }
        
        for(var k = 0;k < frmElem.length ;k++){

            index = frmElem.elements(k).name.indexOf("pref[");

            if (!index) {
                
                if (frmElem.elements(k).value > numLotsRegistered) {
                 
                    alert("There are only " + numLotsRegistered + " lots selected.  Preference value can not exceed this number.\n\nPlease try again.");                
                    return false;
                    
                }
            }
        }   
    }	

	function trimAll(sString) 
	{
		while (sString.substring(0,1) == ' ')
		{
			sString = sString.substring(1, sString.length);
		}

		while (sString.substring(sString.length-1, sString.length) == ' ')
		{
			sString = sString.substring(0,sString.length-1);
		}
		return sString;
	}

	function verifyProfile() {

		var testResults;
		var str = trimAll(document.profileForm.email.value);
		var str2 = trimAll(document.profileForm.secondaryEmail.value);
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

		if (str != "")
		{
			if (filter.test(str))
				testresults=true;
			else{
				alert("Please enter a valid primary contact email address.");
				testresults=false;
			}
		}
		else {
			alert("Primary contact email address is mandatory.");
			testresults = false;
		}
		
		if (testresults == true) {

			if (str2 != "")
			{
				if (filter.test(str2))
					testresults=true;
				else{
					alert("Please enter a valid secondary contact email address.");
					testresults=false;
				}
			}		
		}

		return (testresults);
	}

	

	function verifyCapacity(qty, credit, uom) {

		var confirmText;
		var currQty;
		var currCredit;
		var displayQtyConfirmation = false;
		var displayCreditConfirmation = false;

		currCredit = document.capacityForm.creditLimit.value;
		currQty = document.capacityForm.qtyLimit.value;

		var newQty = qty;
		newQty = formatNumber(qty);

		var newCredit = credit;
		newCredit = formatNumber(credit);

		var newUom = uom
				
		if (document.capacityForm.qtyLimit.value == "" || document.capacityForm.qtyLimit.value == 0)
		{
			confirmText = "Empty or zero volume capacity limit is not allowed.  Your volume capacity limit will be reset to the default value of " + newQty + " " + uom + " p.a, as set by VicForests.";
			currQty = qty;

		}
        else if (document.capacityForm.qtyLimit.value > qty)
        {
			confirmText = "Your volume capacity limit cannot be higher than the amount set by VicForests.  Your volume capacity limit will be reset to the amount of " + newQty + " " + uom + " p.a, as set by VicForests.";
			currQty = qty;
        }
		else
		{
			displayQtyConfirmation = true;
		}

		if (document.capacityForm.creditLimit.value == "" || document.capacityForm.creditLimit.value == 0)
		{
			confirmText = "Empty or zero credit limit is not allowed.  Your credit limit will be reset to the default value of $" + newCredit + " p.a, as set by VicForests.";
			currCredit = credit;

		}
        else if (document.capacityForm.creditLimit.value > credit)
        {
			confirmText = "Your credit limit cannot be higher than the amount set by VicForests.  Your credit limit will be reset to the amount of $" + newCredit + " p.a, as set by VicForests.";
			currCredit = credit;

        }
		else
		{
			displayCreditConfirmation = true;
		}
		

		if (trimAll(confirmText) != "")
		{
			if (displayQtyConfirmation == true || displayCreditConfirmation == true)
			{
				//Display Messagebox
				alert(confirmText);
				document.capacityForm.creditLimit.value = formatNumber(currCredit);
				document.capacityForm.qtyLimit.value = formatNumber(currQty);


			}
		}
		
		

	}



	function confirmReactivation(lotStatus) {

		var confirmText;

		if (lotStatus == "6.closed" || lotStatus == "7.winner") {

			alert("This lot is now closed.  Reactivation setting can no longer be modified.");
			return false;

		}

		if (document.reactiveForm.reactivate_flag.value == 1)
		{
			confirmText = "You are about to enable reactivation for this lot.  Are you sure you wish to continue?";				
		}
		else
			confirmText = "You are about to disable reactivation for this lot.  Are you sure you wish to continue?";				
		

		var agree=confirm(confirmText);
		if (agree)
			return true ;
		else
			return false ;
	}

	function formatNumber(strValue)
	{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + dblValue + '.' + strCents);
	}

	

	

