﻿
var arrAuctionIDs = new Array();
var returnURLLink = "Default.aspx"
var TimeNow = 0;
var smallTimerInterval = 1000; //1 Second
var largeTimerInterval = 60000; //1 Minute
var alertDisplayTime = 7000; //7 Seconds
var primaryAuctionIndex = 0;
var loadingAllAuctions = false;
var endingAnimationLength = 2000;

function loadAuctions(arrAuctions)
{
    arrAuctionIDs = arrAuctions;
    
    //Wait 2 seconds before starting the refreshing
    setTimeout("refreshAllAuctions();", 2000);
}

function refreshAllAuctions()
{
    loadingAllAuctions = true; //causes all auctions to be loaded (chained)
    refreshSingleAuction(0); //Start with the first item
}

function refreshSingleAuction(auctionIndex)
{
    getAuctionInfo(auctionIndex);
}

function getAuctionInfo(auctionIndex)
{
    //Testing... Remove
    //document.getElementById("auction_" + auctionIndex).style.border = "3px dotted #ff0000";
    
    J4T.Web.AjaxHandler.GetAuctionInfo(arrAuctionIDs[auctionIndex], auctionIndex, returnURLLink, getAuctionInfo_Callback);
}

function getAuctionInfo_Callback(result)
{
    if(result.error != null)
    {
        return;
    }
    
    var p = result.value;
    updateAuctionInfo(p.AuctionCountID, p);
    
    //Testing... Remove
    //setTimeout("document.getElementById('auction_" + p.AuctionCountID + "').style.border = '';", 2000);
    
    var d = new Date(p.EndTime);
    var now = new Date(p.CurrentTime);
    var diff = d - now;
    
    if(p.AuctionCountID == primaryAuctionIndex)
    {
        if(diff <= 0)
        {
            //The auction is over
            onAuctionEnded();
        }
        else if((diff / 1000) <= 120)
        {
            //The timer is under 2 minutes... Swith to realtime updating
            setTimeout('refreshSingleAuction(' + p.AuctionCountID + ')', smallTimerInterval);
        }
        else if((diff / 1000) <= 300)
        {
            //The Timer is under 5 minute... update a little more frequently
            setTimeout('refreshSingleAuction(' + p.AuctionCountID + ')', 20000); //20 secs
        }
        else
        {
            setTimeout('refreshSingleAuction(' + p.AuctionCountID + ')', largeTimerInterval);
        }
    }
    else
    {
        //This is NOT the primary auction
        
        if((diff / 1000) <= 300)
        {
            //The Timer is under 5 minute... update a little more frequently
            setTimeout('refreshSingleAuction(' + p.AuctionCountID + ')', 30000); //30 secs
        }
        else
        {
            setTimeout('refreshSingleAuction(' + p.AuctionCountID + ')', largeTimerInterval);
        }
        
    }
    
    if(loadingAllAuctions)
    {
        //If we are loading all of the auctions, update the next auction index (if any left)
        
        if(p.AuctionCountID < arrAuctionIDs.length - 1)
        {
            refreshSingleAuction(++p.AuctionCountID);
        }
        else
        {
            //No more auctions left, clear the loading flag.
            loadingAllAuctions = false
        }
    }
}

function onAuctionEnded()
{
    setTimeout("shrinkAndRemoveAuction('" + primaryAuctionIndex + "');", 4000);
    
    //setElementDisplay("auction_" + primaryAuctionIndex, "none");

    if(primaryAuctionIndex >= (arrAuctionIDs.length - 1))
    {
        //No more auctions
        setTimeout("document.location.reload();", 5000) // 3 seconds
    }
    else
    {
        //Delegate the next auction index as the primary auction
        primaryAuctionIndex++;
        
        //Move the next auction in line to the "A" position.
        //This should happen after the top auction has been removed.
        setTimeout("addToCssClass('auction_" + primaryAuctionIndex + "', 'apos');", 4000 + endingAnimationLength);
        
        refreshSingleAuction(primaryAuctionIndex);
    }
    
}

function updateAuctionInfo(auctionIndex, auc)
{
    TimeNow = Date.parse(auc.CurrentTime);
    var endTime = Date.parse(auc.EndTime);
    
    setTimeRemaining(auc.AuctionCountID, auc);
    setEndDate(auc.AuctionCountID, auc.EndTime, auc.OriginalEndTime);
    
    if(auctionIndex == primaryAuctionIndex)
    {
        var diff = endTime - TimeNow;
        //if((diff / 1000) <= 180)
        //    addToCssClass('auction_' + auctionIndex, 'apos');
    }
    else
    {
        //removeFromCssClass('aucion_' + auctionIndex, 'apos');   
    }
    
    UpdateSingleField("bidCount_" + auctionIndex, auc.NumberBids);
    
    if(auc.NumberBids == 0)
        UpdateSingleField("curBidLabel_" + auctionIndex, "Starting Bid:");
    else
        UpdateSingleField("curBidLabel_" + auctionIndex, "Current Bid:");
    
    UpdateSingleField("curBid_" + auctionIndex, CurrencyFormatted(auc.HighBid));
    
    if(auc.IsHighBidder)
    {
        setCssClass("highBidder_" + auctionIndex, "highbidder");
        UpdateSingleField("highBidder_" + auctionIndex, "You are the high bidder.", true);
        
        UpdateSingleField("minBidLabel_" + auctionIndex, "Proxy Bid:");
        UpdateSingleField("minBid_" + auctionIndex, CurrencyFormatted(auc.ProxyBid), false);
        document.getElementById('raiseProxy_' + auctionIndex).value = '1';
    }
    else
    {
        setCssClass("highBidder_" + auctionIndex, "nothighbidder");
        UpdateSingleField("highBidder_" + auctionIndex, "&nbsp;", false);
        
        UpdateSingleField("minBidLabel_" + auctionIndex, "Minimum Bid Amount:");
        UpdateSingleField("minBid_" + auctionIndex, CurrencyFormatted(auc.MinBid), false);
        document.getElementById('raiseProxy_' + auctionIndex).value = '0';
    }
    
    if(auc.IsSoldOnApproval)
    {
        //setElementDisplay("reserve_" + auctionIndex, "none");
        UpdateSingleField("reserve_" + auctionIndex, "&nbsp;");
    }
    else
    {
        setReserve(auctionIndex, auc.Reserve, auc.HighBid);
        //setElementDisplay("reserve_" + auctionIndex, "block");
    }
    
    //Administrator Info
    if(auc.IsAdmin)
    {
        UpdateSingleField("adminBidder1_" + auctionIndex, auc.Bidder1);
        UpdateSingleField("adminBidder2_" + auctionIndex, auc.Bidder2);
        UpdateSingleField("adminBidder3_" + auctionIndex, auc.Bidder3);
        UpdateSingleField("adminBidderComp1_" + auctionIndex, auc.BidderCompany1);
        UpdateSingleField("adminBidderComp2_" + auctionIndex, auc.BidderCompany2);
        UpdateSingleField("adminBidderComp3_" + auctionIndex, auc.BidderCompany3);
        UpdateSingleField("adminBidderProxy1_" + auctionIndex, CurrencyFormatted(auc.BidderProxy1));
        UpdateSingleField("adminBidderProxy2_" + auctionIndex, CurrencyFormatted(auc.BidderProxy2));
        UpdateSingleField("adminBidderProxy3_" + auctionIndex, CurrencyFormatted(auc.BidderProxy3));
    }
}



function setTimeRemaining(auctionIndex, auc)
{
	var d = Date.parse(auc.EndTime);
	var origEnd = Date.parse(auc.OriginalEndTime);
	var now = new Date(auc.CurrentTime);
	
	if(auctionIndex != primaryAuctionIndex && d > origEnd && d > now)
	    UpdateSingleField("remaining_" + auctionIndex, "Time Remaining: Extended");
	else	
	    UpdateSingleField("remaining_" + auctionIndex, "Time Remaining: " + CalculateTimeRemaining(d - TimeNow));
}

function setEndDate(auctionIndex, endTime, originalEndTime)
{
    var eTime = Date.parse(endTime);
    var origETime = Date.parse(originalEndTime);
    
    if (origETime - eTime < 0)
        UpdateSingleField('endTime_' + auctionIndex, "End Time: " + originalEndTime + " CST - Extended", true);
    else
	    UpdateSingleField('endTime_' + auctionIndex, "End Time: " + originalEndTime + " CST", true);
	
    //Not needed???
	UpdateSingleField('currentEndTime_' + auctionIndex, "End Time: " + endTime, true);
	
}

function displayAuctionMessage(auctionIndex, title, message, asError)
{
    UpdateSingleField("alertTitle_" + auctionIndex, title, false);
    UpdateSingleField("alertMessage_" + auctionIndex, message, false);
  
    if(asError)
        setCssClass("alert_" + auctionIndex, "alertneg");
    else
        setCssClass("alert_" + auctionIndex, "alertpos");
        
    setElementDisplay("alert_" + auctionIndex, "block");
    
    //if(!asError)
        setTimeout("setElementDisplay(\"alert_" + auctionIndex + "\", \"none\");", alertDisplayTime);
        
}

function UpdateSingleField(id, value, FlashOnChange)
{
	var field = document.getElementById(id);
	if (field)
	{
		if (field.innerHTML != value + '')
		{
			field.innerHTML = value;
			
			// make the field flash a different color by changing its css class?
			if (FlashOnChange)
			{
				//field.className = "BidBoxHighlighted";
				//setTimeout("ResetFieldFlash('" + id + "');", 1000);
			}
		}
	}
	else
	{
		//alert('Unable to locate field with id: ' + id);
	}
}



function setBid(auctionIndex)
{
    var isValid = true;
    var errors = new Array();
    
    if(checkMinBid(auctionIndex) == false)
    {
        errors.push("Your bid must meet the minimum bid requirements");
        
        isValid = false;
    }
   
    if(!isValid)
    {
        var ul = convertArrayToUL(errors);
     
        displayAuctionMessage(auctionIndex, "You must fix the following errors:", ul, true);   
    }
    
    if(isValid)
    {
        var field = document.getElementById('bidAmount_' + auctionIndex);
        setElementDisplay("bid_" + auctionIndex, "none");
        UpdateSingleField("confirmText_" + auctionIndex, "Place a bid of: " + CurrencyFormatted(field.value));
        //UpdateSingleField("confirmText_" + auctionIndex, "Place a bid in the amount of: " + CurrencyFormatted(field.value));
        setElementDisplay("confirmBid_" + auctionIndex, "block");
    }

}

function confirmBid(auctionIndex)
{
    var auctID = arrAuctionIDs[auctionIndex];
    var amount = document.getElementById('bidAmount_' + auctionIndex).value;
    var raiseProxy = document.getElementById('raiseProxy_' + auctionIndex).value;
    
    if (raiseProxy == '1')
       raiseProxy = true;
    else
       raiseProxy = false;

    J4T.Web.AjaxHandler.PlaceBid(auctID, amount, auctionIndex, raiseProxy, urlEncode(window.location), confirmBid_callback);
    
    //Clear the bid text box
    var field = document.getElementById('bidAmount_' + auctionIndex).value = "";
    
    //Hide the confirm bid box
    setElementDisplay("confirmBid_" + auctionIndex, "none");
    
    //Show the Bid box again
    setElementDisplay("bid_" + auctionIndex, "block");
}

function cancelBid(auctionIndex)
{
    setElementDisplay("confirmBid_" + auctionIndex, "none");
    setElementDisplay("bid_" + auctionIndex, "block");
}

function confirmBid_callback(result)
{
    var arrValues = result.value;
    
    if (arrValues[0] == 'LOGIN')
    {
        window.location.href = arrValues[1];
    }
    else
    {
        if (arrValues[2] == 'Success')
        {
            displayAuctionMessage(arrValues[0], "Bid Summary", arrValues[1], false);
        }
        else
        {
            displayAuctionMessage(arrValues[0], "Error Summary", arrValues[1], true);
        }
        
        var auctionIndex = arrValues[0];
        
        //Update this auctions
        refreshSingleAuction(auctionIndex);
        
        //Update the next auction (if present)
        if(auctionIndex < arrAuctionIDs.length - 1)
            refreshSingleAuction(auctionIndex + 1);
        
        //setTimeout("HideResults('" + arrValues[0] + "');", 10000);
    }
}

function setReserve(auctionIndex, reserve, currentBid)
{
    if (1 * reserve == 0)
    {
        UpdateSingleField('reserve_' + auctionIndex, "No Reserve", true);
    }
    else
    {
	    // multiple by 1 to assure the variables are integers (I h8 u javascript)
	    if ( (1 * currentBid) < (1 * reserve) )
	    {
		    UpdateSingleField('reserve_' + auctionIndex, "Reserve Not Met", true);
		    //TODO: Change css to make red
		    document.getElementById('reserve_' + auctionIndex).style.color = "";
	    }
	    else
	    {
		    UpdateSingleField('reserve_' + auctionIndex, "Reserve Has Been Met", true);
		    //TODO: Change css to make green
		    document.getElementById('reserve_' + auctionIndex).style.color = "#008000";
	    }
	}
}

function shrinkAndRemoveAuction(auctionIndex)
{
    var elem = document.getElementById("auction_" + auctionIndex);
    
    if(elem)
    {
        setTimeout("document.getElementById('auction_" + auctionIndex + "').style.display = 'none';", endingAnimationLength);
        
        opacity("auction_" + auctionIndex, 100, 0, 1500);
    }
}

function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 

    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
        for(var i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } else if(opacStart < opacEnd) { 
        for(var i = opacStart; i <= opacEnd; i++) 
            { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } 
} 

//change the opacity for different browsers 
function changeOpac(opacity, id) { 
    var object = document.getElementById(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
} 


function convertArrayToUL(arrItems)
{
    if(!arrItems)
        return "";
    
    var ret = "<ul>";
        
    for(var i = 0; i < arrItems.length; i++)
        ret += "<li>" + arrItems[i] + "</li>";

    ret += "</ul>";
    
    return ret;
}

function CalculateTimeRemaining(timeInSeconds)
{
	var Days = Math.floor(timeInSeconds / 86400000);
	
	var SecondsRemaining = timeInSeconds - Days * 86400000;
	
	var Hours = Math.floor(SecondsRemaining / 3600000);
	SecondsRemaining = SecondsRemaining - Hours * 3600000;
	
	var Minutes = Math.floor(SecondsRemaining / 60000);
	SecondsRemaining = (SecondsRemaining - Minutes * 60000) / 1000;
	
	if (timeInSeconds < 0)
	{
		return "Auction Over!";
	}
	else if (Days > 0)
	{
		return Days + " Days, " + Hours + " Hrs, " + Minutes + " Mins";
	}
	else if (Hours > 0)
	{
		return Hours + " Hrs, " + Minutes + " Mins";
	}
	else if (Minutes > 0)
	{
		return Minutes + " Mins, " + SecondsRemaining + " Sec";
	}
	else if (SecondsRemaining > 0)
	{
		return SecondsRemaining + " Sec";
	}
	else
	{
	    return "Auction Over!";
	}
	//return Days + " Days, " + Hours + " Hours, " + Minutes + " Minutes, " + SecondsRemaining + " Seconds";
}



//********************************************
// Start Validation Functions
//********************************************

function checkMinBid(auctionIndex)
{
   var bid = parseInt(document.getElementById('bidAmount_' + auctionIndex).value);
   if (isNaN(bid))
   {
       return false;
   }
   bid = parseInt(bid);
   
   var minBid = document.getElementById('minBid_' + auctionIndex).innerHTML;
   minBid = stringToInt(minBid);
   if (isNaN(minBid))
   {
       return false;
   }
   //minBid = stringToInt(minBid);
   if (minBid > bid)
   {
       return false;
   }

   return true;
}


//********************************************
// End Validation Functions
//********************************************




function setCssClass(id, newClass)
{
    var field = document.getElementById(id);
    
    if(field)
    {
        field.className = newClass;
    }
}

function addToCssClass(id, newClass)
{
    var field = document.getElementById(id);
    
    if(field)
    {
        var c = field.className;
        if(c)
        {
            if(c.length > 0)
            {
                if(c.indexOf(newClass) < 0)
                    c = c + ' ' + newClass;
            }
        }
        else
        {
            c = newClass
        }
        
        field.className = c;
    }
}

function removeFromCssClass(id, className)
{
    var field = document.getElementById(id);
    
    if(field)
    {
        var newClass = "";
        var c = field.className;
        var n = c.indexOf(className);
        
        if(n >= 0)
        {
            newClass = c.substr(0, n);
            
            if(c.length > (n + className.length))
                newClass = newClass + c.substr(n + className.length + 1, c.length - (n + className.length));
            
            field.className = newClass;
        }
    }
}

function setElementDisplay(id, display)
{
    var field = document.getElementById(id);
    
    if(field)
    {
        field.style.display = display;
    }
}


function stringToInt(s)
{
    if(!isNaN(s))
        return parseInt(s);
    
    if(s.length == 0)
        return 0;
    
    s = s.replace(/\$/, "");
    s = s.replace(/,/, "");
    
    return parseInt(s);   
}

/*	Currency formatting methods 
	Thanks to... Bontrager Connection, LLC */
function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	var s = new String(i);
	
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return "$" + CommaFormatted(s);
}

function CommaFormatted(amount)
{
	var delimiter = ",";
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	
	amount = minus + amount;
	return amount;
}
/* end currency formatting methods */


function urlEncode(url)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = new String(url);
	var encoded = "";
	
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
		
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

function urlDecode(url)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = new String(url);
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
	
   return plaintext;
}