// JavaScript Document

var lotObjs = [];
var auctionTimerIsRunning = false;


function displayLatest(){
lotObjs = [];
get_auction_data("php/get_auction_lots.php", true);
createMetaTags(1);
}

// called from EPG timer every minute
function getAuctionDataForUpdate(){
get_auction_data("php/get_auction_lots.php", false);
}

function get_auction_data(url, loadDOM){
	var ajaxRequest = setupAJAX();
  	var bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	ajaxRequest.open("GET",url+bustcacheparameter, true);
	//read returned data from server and place it in div
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
		if (ajaxRequest.status == 200) {
			var splits = ajaxRequest.responseText.split("**");
			var len = splits.length;
			
			// start countdown timer if we have any lots
					if(len > 1 && loadDOM){
					CD_Init(); // start countdown timer
					setTimeout(function(){ document.getElementById("countdownDiv").style.display = "block"; unlock_bid_buttons() },1000); // delay to allow timer to start
					}
					
			for (var i=0; i<len-1; i++){
				if(loadDOM){
				var thisLot = new lot_contructor(splits[i], i);
				lotObjs.push(thisLot);
				var auctionDiv = document.getElementById('auctionDiv');
				auctionDiv.appendChild(thisLot.wrapperDiv);
				}else{
				// just update existing fields
				updateAuctionData(splits[i], i);
				}
			 }
		   }
		  ajaxRequest = null; // ready for garbage collection
	      }
	    }
	   ajaxRequest.send(null); 
	  }
	  

function unlock_bid_buttons(){
	for (var i=0; i<lotObjs.length; i++){
		if(auctionTimerIsRunning) lotObjs[i].bidButton.disabled = false;
	}
	
	}


function sendBid(key){
lotObjs.currentKey = key; // pass key to lotObjs so it's global
var name = lotObjs[key].nameFieldDOM.value;
var nickname = lotObjs[key].nicknameFieldDOM.value;
var email = lotObjs[key].emailFieldDOM.value;
var bid = Number(lotObjs[key].bidFieldDOM.value);
var lotID = lotObjs[key].lot_id;
var wrapperDiv = lotObjs[key].wrapperDiv;
// checks
var incomplete = false;
if(name == "" || name == "Please give your name"){
lotObjs[key].nameFieldDOM.value = "Please give your name";
incomplete = true;
}
if(email == "" || email == "Please give your email address"){
lotObjs[key].emailFieldDOM.value = "Please give your email address";	
incomplete = true;
}
if(!checkEmail(lotObjs[key].emailFieldDOM)){
displayMessage(wrapperDiv, "Sorry, your e-mail address is malformed")
incomplete = true;
}
if(nickname == "") nickname = "Annon"; 

if(incomplete) return;

if(bid < lotObjs[key].resPrice){
var messageDiv = document.getElementById("auction_messageDiv");	
messageDiv.style.display = "block";	
messageDiv.innerHTML = "Sorry, you have not met the reserve price"
wrapperDiv.appendChild(messageDiv);
return;
}

// set up messageDiv
var messageDiv = document.getElementById("auction_messageDiv");	
messageDiv.style.display = "block";
wrapperDiv.appendChild(messageDiv);

// check for any higher bid that may have been made
var poststring = 'bid='+bid+'&lotID='+lotID;
var ajaxRequest = new XMLHttpRequest();
	ajaxRequest.open("POST", "php/check_highest_bid.php", true);
	ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajaxRequest.onreadystatechange = function() {
	if(ajaxRequest.readyState == 4){
		if (ajaxRequest.status == 200) {
			var highestBid = Number(ajaxRequest.responseText);
				if(bid <= highestBid){
				getAuctionDataForUpdate();
				messageDiv.innerHTML = "Sorry, your bid must be in exesses of the current highest"
				}else{
				// all clear to send new bid
				var sendstring = 'name='+name+'&nickname='+nickname+'&email='+email+'&bid='+bid+'&lotID='+lotID;
				post_data(sendstring, "php/send_auction_bid.php", "auction_messageDiv", "updateBidData()");	
				}
			
			}else{
            messageDiv.innerHTML = "Sorry, there was a server problem";			
            }
	      }
	    }
	ajaxRequest.send(poststring);

}

// called from callback when a bid is sucessfully sent
function updateBidData(){
// update screen with new values for Highest bid i.e. this one we've just sent and for Total Bids
var currentObj = lotObjs[lotObjs.currentKey];
var nickname = currentObj.nicknameFieldDOM.value;
if(nickname == "") nickname = "Annon"; 
currentObj.highestBidDOM.nodeValue = "Highest: £"+currentObj.bidFieldDOM.value+" ("+nickname+")";
var currentTotal = Number(currentObj.bidTotal); // this is just the number
currentTotal++;
lotObjs[lotObjs.currentKey].bidTotalDOM.nodeValue = "No. Bids: "+currentTotal;
}



function updateAuctionData(obj, key){
var splits = obj.split("|");
var highest_bid =  splits[6];
var nickname = (splits[7]);
var num_bids = splits[8];
var higestText = (nickname)?"Highest: £"+highest_bid+" ("+nickname+")" : "Highest: £"+highest_bid; // don't add brackets if nickname is blank
lotObjs[key].highestBidDOM.nodeValue = higestText;
lotObjs[key].bidTotalDOM.nodeValue = "No. Bids: "+num_bids;
}



function lot_contructor(obj, key){
var splits = obj.split("|");
this.lot_id = splits[0];
var lot_name = splits[1];
var lot_img = splits[2];
var lot_desc = splits[3];
var long_desc = splits[4];
var reserve_price = Number(splits[5]);
var highest_bid =  Number(splits[6]);
var nickname = (splits[7]);
var num_bids = splits[8];
// grab handles so we can update later
this.resPrice = reserve_price;
this.bidTotal = num_bids;
this.highestBid = highest_bid;
this.nickname = nickname;
this.longDesc = long_desc;
this.lotImg = lot_img;
// make DOM  wrapper div
var wrapperDiv = document.createElement("div");
wrapperDiv.setAttribute("class","lotDiv");
wrapperDiv.style.cssText = "position: relative; height: 200px; border-radius: .5em; -moz-border-radius: .5em; border: 2px solid #0066FF; padding: 15px; margin-bottom: 10px; background-color: #eee; font-size: 12px;";
// make bid button
var bidButton = document.createElement("input");
bidButton.disabled = true; // make sure button is disabled
this.bidButton = bidButton;
bidButton.setAttribute("type","button");
bidButton.setAttribute("class","bidButton");
bidButton.setAttribute("value","Send Bid");
bidButton.style.cssText = "position: absolute; right: 45px; bottom: 15px; cursor: pointer;";
bidButton.onclick=function(){sendBid(key);};
wrapperDiv.appendChild(bidButton);
// make top table
var table = document.createElement("table");
var tbody = document.createElement("tbody");
table.setAttribute("class","topStrip");
table.style.cssText = "table-layout: fixed; width: 100%; background-color: #CCCCCC; vertical-align: middle; padding-top: 2px; font-weight: bold; ";
// lot name
var tr = document.createElement("tr");
var cell = makeTableCell(lot_name, 230);
tr.appendChild(cell);
this.lot_nameNode = cell.firstChild;
tbody.appendChild(tr); // append to table row
// reserve price
var cell = makeTableCell("Reserve: £"+reserve_price, 100);
tr.appendChild(cell);
// Highest Bid
var higestText = (nickname)?"Highest: £"+highest_bid+" ("+nickname+")" : "Highest: £"+highest_bid; // don't add brackets if nickname is blank
var cell = makeTableCell(higestText);
tr.appendChild(cell);
this.highestBidDOM = cell.firstChild;
// Total Bids
var cell = makeTableCell("No. Bids: "+num_bids, 80);
cell.setAttribute("align","right");
tr.appendChild(cell);
this.bidTotalDOM = cell.firstChild;
tbody.appendChild(tr);
table.appendChild(tbody);

wrapperDiv.appendChild(table); // now append top strip to main wrapper
// make image
if(lot_img){
var img = new Image();
img.src = "images/lots/"+lot_img;
img.style.cssText="position: absolute; top: 36px; left: 15px; margin: 10px 0 10px 0;";
wrapperDiv.appendChild(img);
}
// make description panel
var descriptionDiv = document.createElement("div");
descriptionDiv.setAttribute("class","descriptionDiv");
descriptionDiv.style.cssText="position: absolute; left: 15px; top: 185px; width: 250px;";
descriptionDiv.innerHTML = lot_desc;
wrapperDiv.appendChild(descriptionDiv);
// make input field wrapper
var inputWrapperDiv = document.createElement("div");
inputWrapperDiv.setAttribute("class","input_wrapper");
inputWrapperDiv.style.cssText = "position: absolute; top: 60px; right: 15px; width: 430px;";
// make label for nickname field
inputWrapperDiv.appendChild(makeLabel("Bidder Name (public)"));
// nickname field
var nicknameField = makeInputField(250);
this.nicknameFieldDOM = nicknameField;
inputWrapperDiv.appendChild(nicknameField);
// make label for name field
inputWrapperDiv.appendChild(makeLabel("Your Name (private)"));
// name field
var nameField = makeInputField(250);
this.nameFieldDOM = nameField;
inputWrapperDiv.appendChild(nameField);
// make label for email field
inputWrapperDiv.appendChild(makeLabel("Email address (private)"));
// email input field
var emailField = makeInputField(250);
this.emailFieldDOM = emailField;
inputWrapperDiv.appendChild(emailField);
// make label for bid field
inputWrapperDiv.appendChild(makeLabel("Your Bid £"));
// bid input field
var bidField = makeInputField(50);
this.bidFieldDOM = bidField;
inputWrapperDiv.appendChild(bidField);

wrapperDiv.appendChild(inputWrapperDiv);

this.wrapperDiv = wrapperDiv;
	
}

function makeLabel(txt){
var label = document.createElement("label");
label.style.cssText = "float: left; width: 130px; text-align: right; padding-top: 4px;";
var textNode = document.createTextNode(txt);
label.appendChild(textNode);
return label;
}

function makeTableCell(txt, width){
var td = document.createElement("td");	
td.setAttribute("valign","top");
if(width) td.style.cssText = "width: "+width+"px; overflow: hidden; ";
var textNode = document.createTextNode(txt);
td.appendChild(textNode);
return td;
}

function makeInputField(width){
var field = document.createElement("input");
field.style.cssText = "margin-left: 10px; margin-bottom: 10px; width: "+ width +"px";
return field;	
}

// A generic function for checking to see if an input element
// looks like an email address
function checkEmail( elem ) {
    // Make sure that something was entered and that it looks like
    // a valid email address
    return !elem.value || /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test( elem.value );
}

// generic function to display message in current 'Lot' as defined by 'wrapperDiv'
function displayMessage(wrapperDiv, msg){
var messageDiv = document.getElementById("auction_messageDiv");	
messageDiv.innerHTML = msg;
messageDiv.style.display = "block";
wrapperDiv.appendChild(messageDiv);	
}

function auction_popup(num){
$('#auction_info_popupDiv').slideDown(200);
var div = document.getElementById("auction_info");
deleteprior(div);
var img = new Image();
img.src = "images/lots/"+lotObjs[num].lotImg;
img.style.cssText="float: left; width: auto; margin-right: 20px; border: 1px solid #000;";
div.appendChild(img);
var p = document.createElement("p");
p.innerHTML = lotObjs[num].longDesc;
div.appendChild(p);


}

function auction_popup_clear(){
$('#auction_info_popupDiv').slideUp(200);
}


