
/*-----------------------------------------
* Global variables
*------------------------------------------*/
var myWindows = [];
var numWindows= 15;
var loggedin = false;
var myusername;
var bidsRemaining = 0;
var rootpath;
var singlewindow = 0;
var currentlybidding = false; //try to block duplicate bids
var connection_status = 1; // 1 = green, 2 = yellow, 3 = red

// set to true when an existing page goes from a live auction
// window to an empty one. triggers a page reload when the
// same page goes from an empty window to a live one.
// this only happens if singlewindow != 0;
var should_reload = 0;  

/*-----------------------------------------
* Setup heartbeat, load initial values etc
*------------------------------------------*/

// startup() function moved to index/index view

function startupZero(path) {
	rootpath = path;

	setInterval ( "winnerList()", 60000); //winner list doesn't need that frequent of an update
	//setInterval ( "bidsList()", 60000);
	
	winnerList(); //display initial list
	//bidsList();
}

function startupOne(path, i, auction_id) {
	rootpath = path;
	singlewindow = i;

	// Create blank auction windows
	for(i=0;i<numWindows;i++) {
		myWindows[i] = new AuctionWindow(i+1, loggedin);
	}

	//Setup regular window updates
	setInterval ( "heartBeat2()", 1000);	// this part has to run very quickly
	setInterval ( "userinfo()", 3000); //3 seconds refresh rate - trying to slightly reduce server load
	setInterval ( "winnerList()", 60000); //winner list doesn't need that frequent of an update
	//setInterval ( "bidsList()", 60000);
	setInterval ( "bidsList2()", 60000); //recent bids for this specific auction
	
	winnerList(); //display initial list
	//bidsList();
	bidsList2(auction_id);
}




/*-----------------------------------------
* Get auction window data via AJAX call
*------------------------------------------*/
function heartBeat() {

	//just in case, re-enable bidding - see bid()
	// - done here because this is run very frequently
	currentlybidding = false;

	// update auction windows
	//myPath = rootpath + "/cache/auction?rnd=" + anticache();
	//myPath = rootpath + "/public/gateway/getAuctionWindows.php?rnd=" + anticache();
	myPath = rootpath + "/public/gateway/getAuctionWindows.php"
	
	// save original status and starting time
	old_status = connection_status;
	start_time = get_unix_timestamp();
	
	$.ajaxSetup ({ cache: false});
	$.getJSON(myPath, function(data) {
		//alert(dump(data,0));
		// check how long it took to get the data
		end_time = get_unix_timestamp();
		duration = end_time - start_time;
		if(duration <= 1) {
			connection_status = 1;
		} else if(duration <= 2) {
			connection_status = 2;
		} else {
			connection_status = 3; //red = 2 or more seconds delay
		}
		if(data == null)
			connection_status = 3;
		if(old_status != connection_status) {
			render_status(connection_status);
		}
		
		updateAuctions(data);
	});
}

function heartBeat2() {

	//just in case, re-enable bidding - see bid()
	// - done here because this is run very frequently
	currentlybidding = false;

	i = (singlewindow - 1);

	// update auction windows
	//myPath = rootpath + "/cache/auction?rnd=" + anticache();
	//myPath = rootpath + "/public/gateway/getAuctionWindows.php?rnd=" + anticache();
	myPath = rootpath + "/public/gateway/getAuctionWindows.php";
	
	// save original status and starting time
	old_status = connection_status;
	start_time = get_unix_timestamp();
	
	$.ajaxSetup ({ cache: false});
	$.getJSON(myPath, function(data) {
		// check how long it took to get the data
		end_time = get_unix_timestamp();
		duration = end_time - start_time;
		if(duration <= 1) {
			connection_status = 1;
		} else if(duration <= 2) {
			connection_status = 2;
		} else {
			connection_status = 3; //red = 2 or more seconds delay
		}
		if(data == null)
			connection_status = 3;
		if(old_status != connection_status) {
			render_status(connection_status);
		}
		
		updateSingleAuction(data, i);
	});
}



function winnerList() {
	myPath = rootpath + "/public/gateway/winnerList.php";

	$.ajaxSetup ({ cache: false});
	$.getJSON(myPath, function(data) {
		updateTicker(data);
	});		
}

function updateHomepageMessage() {

	//myPath = rootpath + "/content/index/view/home_page_text/nolayout/1";
	myPath = rootpath + "/public/gateway/getAuctionCount.php";
	$.ajaxSetup ({ cache: false});
	$.get(myPath, function(data) {
		$('.numAuctions h4').html(data);
	});

	//TODO: hide the info bar if there's no message / display again if there is

}

function updatePromosBox() {
	myPath = rootpath + "/content/index/view/promotions/nolayout/1";
	myLink = '<p align="right"><a href="/content/index/view/promotions_details">&mdash; Read More</a></p>';
	$.ajaxSetup ({ cache: false});
	$.get(myPath, function(data) {
		$('#promotionsBox').html(data);
	});
}




function bidsList() {
	myPath = rootpath + "/public/gateway/recentBidsList.php";

	$.ajaxSetup ({ cache: false});
	$.getJSON(myPath, function(data) {
		updateBids(data);
	});		
}

function bidsList2(auction_id) {
	myPath = rootpath + "/public/gateway/recentBidsList.php?id=" + auction_id;

	$.ajaxSetup ({ cache: false});
	$.getJSON(myPath, function(data) {
		updateBids2(data);
	});		
}


function userinfo() {
	// update account info
	//myPath2 = rootpath + "/cache/user?rnd=" + anticache();
	//myPath2 = rootpath + "/public/gateway/getUserData.php?rnd=" + anticache();
	myPath2 = rootpath + "/public/gateway/getUserData.php"
	
	$.ajaxSetup ({ cache: false});
	$.getJSON(myPath2, function(data) {
	
		var bidcount = 0;
		var winnings = 0;
		var error = "";
		
		if(typeof(data) == 'object') {
			for (var item in data) {
				var value = data[item];
				
				if (item == 'bids_remaining') {
					bidcount = value;
				}
				if(item == 'winnings') {
					winnings = value;
				}
				if(item == 'error') {
					error = value;
				}
			}
		}
		
		// if person is currently logged in, and the user info returns that they are now
		// logged out, reload the page to provide a more reasonable view.
		if(loggedin == true) {
			if(error == "Please login to place bids") {
				window.location.reload();
				return true;
			}
		}
		
		
		$("#bidcount").html('<p>' + bidcount + '</p>');
		bidsRemaining = bidcount;

		if(winnings > 0) {
			wintxt = "Checkout (" + winnings + ")";
		} else {
			wintxt = "Checkout";
		}
		$("#checkout_count").html(wintxt);
	});
}




/*-----------------------------------------
* Display auction data in windows
*------------------------------------------*/
function updateAuctions(newWindows) {
	for(auc=0;auc<numWindows;auc++) {
		temp = newWindows[auc];
		//alert(dump(temp,0));
		windowUpdate(temp, auc);
	}
}

function updateSingleAuction(newWindows, auc) {
		temp = newWindows[auc];
		windowUpdate(temp, auc);
}

function windowUpdate(temp, auc) {
//alert(temp.aid);
	myWindows[auc].update(
			temp.aid, temp.st, temp.iid,
			temp.ina, temp.ipc, temp.sd,
			temp.et, temp.ta, temp.tr,
			temp.pr, temp.cbn, temp.lp, temp.at, temp.ic
		);
}


function updateTicker(data) {

	if(typeof(data) == 'object') {
		for (var item in data) {
			var value = data[item]; // value should be an array also
			winhtml = htmlWinner(value);
			$("#winnerlist").html(winhtml);
	
			break; // return true; //only show one
		}
	}
	
}


function updateBids(data) {
	//in theory this is an array
	
	//var html = "<ul class='bidlist' id='bidlist'>";
	var html = "<table class='bidlist' id='bidlist'>";

	if(typeof(data) == 'object') {
		for (var item in data) {
			var value = data[item]; // value should be an array also
			
			html = html + htmlBid(value);
		}
	}
	
	//html = html + "</ul>";
	html = html + "</ul>";
	
	//update the list on the layout
	$("#recentbids").html(html);
	
}


function updateBids2(data) {
	//in theory this is an array
	
	var html = "<table class='bidlist' id='bidlist2'>";

	if(typeof(data) == 'object') {
		for (var item in data) {
			var value = data[item]; // value should be an array also
			
			html = html + htmlBid2(value);

		}
	}
	
	html = html + "</table>";
	
	//update the list on the layout
	$("#recent_this_auction").html(html);
	
}

function htmlBid2(bid) {
/*
<div>
	<h3>100 Bids Bid Pack</h3>
	<p>$0.00 - username</p>
	<p>17-07-2010 @ 17:45</p>
</div>
*/
	html = "<div>";
	html += "<h3>" + bid["product_title"] + "</h3>";
	html += "<p>" + bid["price"] + " - " + bid["username"] + "</p>";
	html += "<p>" + bid["time_added"] + "</p>";
	html += "</div>";
	
	return html;
}

function htmlBid(bid) {

	html = "<tr>";
	html += "<td>";
	html += bid["product_title"] + "<br />";
	html += bid["price"] + " - " + bid["username"] + " - ";
	html += bid["time_added"];
	html += "</td>";
	html += "</tr>";
	
	return html;
}


// returns what a single winner looks like
function htmlWinner(winner) {

	html = '';
    html = html + '<div class="winners">';
    html = html + '<h3>' + winner["product_id"] + '</h3>';
    html = html + '<p class="finalPrice">' + winner["price"] + '</p>';
    html = html + '<p class="msrp">(MSRP ' + winner["list_price"] + ')</p>';
    html = html + '<p class="winningUser">' + winner["username"] + '</p>';
	html = html + '<p class="dateWon">' + winner["date_won"] + '</p>';
    html = html + '<p class="dateWon">Auction #' + winner["auction_id"] + '</p>';
    html = html + '</div>';
    html = html + '<div class="smThumb">';
    html = html + '<img src="' + rootpath + '/public/images/products/' + winner["photo"] + '" alt="' + winner["product_id"] + '" />';
        html = html + '<p><a href="/auction/completed">More Winners</a></p>';
    html = html + '</div>';
    html = html + '<div class="clear"></div>';

	return html;
}


function clearFlash(id) {
	$("#window_" + id + "_price").css('background-color:#fff;');
}

/*function button_click(id, onoff) {
	${"#window_" + this.id + "_button a").removeClass('bid').addClass('bidclick');
	setTimeout();
}*/


function winsAlert() {
	alert("Please note that you have met or exceeded your win limitations on this website.\n\nWin limits are based on 24 hour and 30 day rolling periods.");
}



