 // Function to update bidding history list with ajax
updatebiddinghistory = function(auctionid) {
	reqJSON("/ajaxcall.php", { call: "get_bidding_history", auction_id: auctionid }, function(json) {
		var winner = json.winning.username+', '+json.winning.town;
		if( winner.length > 20) {
			winner = winner.substring(0,17)+'...';
		}
		$('#winningbidder').text(winner);
		$('#bidcount').text(json.bidcount);
		$('#winningbidderavatar').attr('src',json.winning.avatar);
		$('#biddinghistory table tbody').html('');
		$('#personalbiddinghistory table tbody').html('');
		$.each(json.list, function() {
			if( this.bonus == 1) {
				paid = "Bonus Bid";
			} else {
				paid = '£'+this.bid;
			}
			$('#biddinghistory table tbody').append('<tr><td>'+this.username+', '+this.town+'</td><td>'+paid+'</td></tr>');
			if( this.personal == 1 ) {
				if( this.bonus == 1) {
					paid = '0.50';
				} else {
					paid = '£'+this.bid;
				}
				$('#personalbiddinghistory table tbody').append('<tr><td>'+this.bid+'</td><td>'+paid+'</td></tr>');
			}
		});
	}, ajaxerror);
}

// Function to update bidding history list with ajax
updatecredit = function() {
	reqJSON("/ajaxcall.php", { call: "get_user_credit" }, function(json) {
		$('#usercredit').html("£"+json.credit);
		if( json.credit < 1.00 ) {
			$('#usercredit').addClass('low');
		}
	}, ajaxerror);
}

// Function to update auction price and time remaining with ajax
updateauctionstatuses = function() {
	auction_id_list = [];
	$("div#[id^=auction_id_]").each(function() { 
		auction_id_list.push( (this.id).substring(11) ); 
	});
	if( auction_id_list.length > 0 ) {
		reqJSON("/ajaxcall.php", { call: "get_auction_statuses", auctions: auction_id_list.join(',') }, function(json) {
			$.each(json, function() {
				if( this.status != $('#last_status_'+this.aid).attr('value') ) {
					$('#auction_id_'+this.aid+' #stage_tabs a').css('color','gray');
					$('#auction_id_'+this.aid+' #stage1').css("background-image","url(/images/tab_off.jpg)");
					$('#auction_id_'+this.aid+' #stage2').css("background-image","url(/images/tab_off.jpg)");
					$('#auction_id_'+this.aid+' #stage3').css("background-image","url(/images/tab_off.jpg)");
					switch(this.status) {
						case 0:
							$('#state_indicator').css("display","none");
							$('#bid_'+this.aid).css("display","none");
							$('#auction_id_'+this.aid+' .statusribbon').css("display","none");
							$('#auction_id_'+this.aid+' #auction_stages').css("background-image","url(/images/auction-stages-bg.jpg)");
							$('#auction_id_'+this.aid+' #stage_tabs').tabs('select',0);
							$('#auction_id_'+this.aid+' #stage_tabs #stage1 a').css('color','green');
							$('#auction_id_'+this.aid+' #stage1').css("background-image","url(/images/tab_green.jpg)");
							$('#auction_id_'+this.aid+' .time_label').text('This Auction Begins At');
							break;
						case 1:
							$('#state_indicator').attr({className: 'stage1'});
							$('#bid_'+this.aid).css("display","inline");
							$('#auction_id_'+this.aid+' .statusribbon').css("display","block");
							$('#auction_id_'+this.aid+' .statusribbon').attr('src','/images/collect_ribbon.png');
							$('#auction_id_'+this.aid+' #auction_stages').css("background-image","url(/images/auction-stages-green-bg.jpg)");
							$('#auction_id_'+this.aid+' #stage_tabs').tabs('select',0);
							$('#auction_id_'+this.aid+' #stage_tabs #stage1 a').css('color','green');
							$('#auction_id_'+this.aid+' #stage1').css("background-image","url(/images/tab_green.jpg)");
							$('#auction_id_'+this.aid+' .startingin').css("display","none");
							$('#auction_id_'+this.aid+' .time_label').text('Time Remaining');
							$('#auction_id_'+this.aid+' .duration').css('display','none');
							break;
						case 2:
							$('#state_indicator').attr({className: 'stage2'});
							$(' #bid_'+this.aid).css("display","inline");
							$('#auction_id_'+this.aid+' .statusribbon').css("display","block");
							$('#auction_id_'+this.aid+' .statusribbon').attr('src','/images/use_ribbon.png');
							$('#auction_id_'+this.aid+' #auction_stages').css("background-image","url(/images/auction-stages-amber-bg.jpg)");
							$('#auction_id_'+this.aid+' #stage_tabs').tabs('select',1);
							$('#auction_id_'+this.aid+' #stage_tabs #stage2 a').css('color','orange');
							$('#auction_id_'+this.aid+' #stage2').css("background-image","url(/images/tab_amber.jpg)");
							$('#auction_id_'+this.aid+' .startingin').css("display","none");
							$('#auction_id_'+this.aid+' .time_label').text('Time Remaining');
							$('#auction_id_'+this.aid+' .duration').css('display','none');					
							break;
						case 3:
							$('#state_indicator').attr({className: 'stage3'});
							$('#bid_'+this.aid).css("display","inline");
							$('#auction_id_'+this.aid+' .statusribbon').css("display","block");
							$('#auction_id_'+this.aid+' .statusribbon').attr('src','/images/final_contdown_ribbon.png');
							$('#auction_id_'+this.aid+' #auction_stages').css("background-image","url(/images/auction-stages-red-bg.jpg)");
							$('#auction_id_'+this.aid+' #stage_tabs').tabs('select',2);
							$('#auction_id_'+this.aid+' #stage_tabs #stage3 a').css('color','red');
							$('#auction_id_'+this.aid+' #stage3').css("background-image","url(/images/tab_red.jpg)");
							$('#auction_id_'+this.aid+' .startingin').css("display","none");
							$('#auction_id_'+this.aid+' .time_label').text('Time Remaining');
							$('#auction_id_'+this.aid+' .duration').css('display','none');
							break;
						case 4:
							$('#state_indicator').css("display","none");	
							$('#bid_'+this.aid).css("display","none");
							$('#timeremaining_'+this.aid).addClass('finishing');
							$('#timeremaining_'+this.aid).html('Auction Finished!');
							$('#auction_id_'+this.aid+' .statusdot').css("display","none");
							$('#auction_id_'+this.aid+' #auction_stages').css("background-image","url(/images/auction-stages-bg.jpg)");
							if( $('#auction_id_'+this.aid).attr('class') == 'mainauction' ) {
								document.title = 'Finished';
								setTimeout("location.reload(true);",3000);
							}
							$('#auction_id_'+this.aid+' .duration').css('display','none');
							$('#auction_id_'+this.aid+' .startingin').css("display","none");					
							break;
					} //end switch

					if( $('#auction_id_'+this.aid).attr('class') == 'auction future' && ( $('#last_status_'+this.aid).attr('value') == 0 || $('#last_status_'+this.aid).attr('value') == -1) && this.status != 0 ) {
						$('#auction_id_'+this.aid).css('display','none');
					}
					$('#last_status_'+this.aid).attr('value',this.status);

				} // end if status changed
				time = seconds2dhms(this.time);
				if( this.status != 0 && this.status != 4 ) {
					if ( time[0] == 0 ) {   // if no days
						$('#timeremaining_'+this.aid).html(time[1]+':'+padzeros(time[2],2)+':'+padzeros(time[3],2));
						if( $('#auction_id_'+this.aid).attr('class') == 'mainauction' ) {
							document.title = time[1]+':'+padzeros(time[2],2)+':'+padzeros(time[3],2);
						}
					} else {
						$('#timeremaining_'+this.aid).html(time[0]+'d '+time[1]+':'+padzeros(time[2],2)+':'+padzeros(time[3],2));
						if( $('#auction_id_'+this.aid).attr('class') == 'mainauction' ) {
							document.title = time[0]+'d '+time[1]+':'+padzeros(time[2],2)+':'+padzeros(time[3],2);
						}
					}
				}
				if( this.time  < 15 ) {
					$('#timeremaining_'+this.aid).addClass('finishing');
					if( this.time <= 0) {
						$('#auction_id_'+this.aid+' #going').text('Gone');
					} else if( this.time <= 5) {
						$('#auction_id_'+this.aid+' #going').text('Going twice');
					} else if( this.time <= 10 ) {
						$('#auction_id_'+this.aid+' #going').text('Going once');
					} else {
						$('#auction_id_'+this.aid+' #going').text(' ');
					}
				} else {
					$('#timeremaining_'+this.aid).removeClass('finishing');
					$('#auction_id_'+this.aid+' #going').text('');
				}

				if( $('#auction_id_'+this.aid).attr('class') != 'mainauction' ) {
					$('#auction_id_'+this.aid+' .winningbidder').text(this.awb);
				}
				$('#bonus_bids_'+this.aid).html(this.abb);
				if( this.alb != $('#last_bid_id_'+this.aid).attr('value') ) {
					$('#last_bid_id_'+this.aid).attr('value',this.alb);
					$('#currentbid_'+this.aid).html(this.bid);
if( $.browser.msie ) {
	$.fx.off=false;
}

					$('#currentbid_'+this.aid).css("background-color","red")
					.delay(250).queue(function () {$(this).css({"background-color": "#fff"});$(this).dequeue();}) 

					if( $('#auction_id_'+this.aid+' #biddinghistory').length > 0 ) {
						updatebiddinghistory(this.aid);
					}
				}
			});
		}, ajaxerror);

	}
}

// Function to fetch password strength with ajax
updatepasswordstrength = function() {
	reqJSON("/ajaxcall.php", { call: "get_password_strength", password: $("#password").attr('value'), username: $('#username').attr('value'), email: $('#email').attr('value') }, function(json) {
		$('#password_strength').html(json);
		$('#password_strength_bar_fill').animate({width:json+'%'},100);
		$('#password_strength_bar_fill').removeClass();
		if( json < 40 ) {
			$('#password_strength_bar_fill').addClass('weak');
		} else if( json < 70 ) {
			$('#password_strength_bar_fill').addClass('ok');
		} else {
			$('#password_strength_bar_fill').addClass('strong');
		}
	}, ajaxerror );
}

// Function to add leading zero's to a number
padzeros = function(number, length) {
	var str = '' + number;
	while (str.length < length) {
		str = '0' + str;
	}
	return str;
}

// Function to convert seconds into an array of hours, minutes, seconds
seconds2dhms = function(seconds) {
	var dhms = Array();
	dhms[0] = parseInt(parseInt(seconds) / 86400); 
	dhms[1] = parseInt(parseInt(seconds % 86400) / 3600); 
	dhms[2] = parseInt((seconds / 60) % 60); 
	dhms[3] = parseInt(seconds % 60);
	return dhms;
}

// Function to send ajax request and return json
reqJSON = function(url, params, success, error) {
    var CallParams = {};
    CallParams.type = params.Method || "GET";
    CallParams.url = url;
    CallParams.processData = true;
    CallParams.data = params;
    CallParams.dataType = "json";
    CallParams.success = success;
	//CallParams.timeout = 900;
    if (error) {
        CallParams.error = error;
    }
    var q2b = $.ajax(CallParams);
}

ajaxerror = function (xhr, ajaxOptions, thrownError) {
	//jAlert('Failed','Ajax Call Failed');
}

$(document).ready( function() {	

	// Bid click event - place bid
	$("#[id^=bid_]").each(function() { 
		$(this).click( function() {
			var btn = this;
			if( $(btn).attr('class') == 'bid_button large' ) {
				$(btn).src = '/images/button-placed.jpg';
			} else {
				$(btn).src = '/images/button-placed-small.jpg';
			}
			reqJSON("/ajaxcall.php", { call: "place_bid", auction_id: (this.id).substring(4) }, function(json) {
				if( json.status == -1) {
					jAlert('<p>You must be logged in to place a bid</p><form id="login" action="/login.php?ref='+window.location.pathname+'" method="post" class="clearfix"><label for="email" class="lbl_txt">Email/Username: </label><input type="text" name="email" size="10" value="" /><br /><label for="password" class="lbl_txt">Password: </label><input type="password" name="password" size="10" value="password" /><br /><label for="submit"></label><input type="submit" name="submit" value="Login" /></form><p>Not joined us yet? <a href="/register.php">Register now</a> to start winning!<br />Have you <a href="/forgotten_password.php">Forgotten Your Password?</a></p>', 'Bid Failed');
				} else if( json.status == -2) {
					jAlert('<p>Sorry, this auction has finished - no more bids can be placed</p>', 'Bid Failed');
				} else if( json.status == 0) {
					jAlert('<p>Your bid has not been accepted, most likely you are out of credit.</p><form id="credit_account_form" name="credit_account_form" action="/add_credit.php?ref='+window.location.pathname+'" method="post" class="clearfix"><fieldset><label for="amount">Amount:</label><input type="text" class="input_currency" name="amount" id="amount" value="20"/><br/><label for="type">Type:</label><input type="radio" name="type" id="sagepay" value="Sagepay" checked="checked" /><p class="sagepay-note" style="background:none;width:200px;">Credit/Debit Card</p><br/><label></label>	<input type="radio" name="type" id="paypal" value="Paypal" /><p class="paypal-note" style="background:none;width:200px;">Paypal</p><br/><br/><label for="submit"></label><input type="submit" id="submit" name="submit" value="Add Credit"/></fieldset></form>', 'Bid Failed');
				} else {
					updateauctionstatuses();
					updatecredit();
				}
				if( $(btn).attr('class') == 'bid_button large' ) {
					$(btn).src = '/images/button-bid.jpg';
				} else {
					$(btn).src = '/images/button-bid-small.jpg';
				}
			}, function() { 
				ajaxerror();
				if( $(btn).attr('class') == 'bid_button large' ) {
					$(btn).src = '/images/button-bid.jpg';
				} else {
					$(btn).src = '/images/button-bid-small.jpg';
				}
			} );
		});
	});
	// Watch click event
	$("#[id^=watch_]").each(function() { 
		$(this).click( function() {
			var btn = this;
			reqJSON("/ajaxcall.php", { call: "toggle_watch_auction", auction_id: (this.id).substring(6) }, function(json) {
				if( json.status == -1) {
					jAlert('<p>You must be logged in to watch or unwatch an auction</p><form id="login" action="/login.php?ref='+window.location.pathname+'" method="post" class="clearfix"><label for="email" class="lbl_txt">Email/Username: </label><input type="text" name="email" size="10" value="" /><br /><label for="password" class="lbl_txt">Password: </label><input type="password" name="password" size="10" value="password" /><br /><label for="submit"></label><input type="submit" name="submit" value="Login" /></form><p>Not joined us yet? <a href="/register.php">Register now</a> to start watching!</p>', 'Watch Failed');
				} else if( json.status == 0) {
					jAlert('Watch failed, you may already be watching this item', 'Watch Failed');
				} else {
					if( $(btn).attr('class') == 'watch_button' ) {
						$(btn).attr('src','/images/unwatch.jpg');
						$(btn).attr('class','unwatch_button');
					} else {
						$(btn).attr('src','/images/watch.jpg');							
						$(btn).attr('class','watch_button');
					}
				}
			}, ajaxerror);
		});
	});

	// Loop to update timers and current bids every second
	var refreshstatus = setInterval(function() {
		updateauctionstatuses();
	}, 900);

	// Initialise tabs
	$("#stage_tabs").tabs();
	$("#details_tabs").tabs();
	$("#history_tabs").tabs();

	$('#password').keyup( function(event) { 
		updatepasswordstrength();
	} );

	if( $('#home_banner_sequence').length > 0 ) {
		$('#home_banner_sequence a').cycle({
			fx: 'fade',
			speed: 1000, 
			timeout: 2500
		});
	}

	$("a.single_image").fancybox(); 

	$('.low').blink();		

	$('#headeremail, #headerpassword, #loginemail, #loginpassword, #forename, #surname').focus(function() {
		if( $(this).attr('value') == $(this).attr('alt') ) {
			$(this).attr('value','');
		}
	});
	$('#headeremail, #headerpassword, #loginemail, #loginpassword').blur(function() {
		if( $(this).attr('value') == '' ) {
			$(this).attr('value',$(this).attr('alt'));
		}
	});
	$('input,select,textarea').focus(function() {
		$(this).addClass('focused');
	});
	$('input,select,textarea').blur(function() {
		$(this).removeClass('focused');
	});


	$('#email').keyup(checkemailexists);
	$('#email').focus(function() {
		$("#email_tip .jtip_hover").animate({opacity: "show"}, 500);
	});
	$('#email').blur(function() {
		$("#email_tip .jtip_hover").animate({opacity: "hide"}, 0);
	});

	$('#confirm_email').blur(checkemailmatches);

	$('#username').keyup(checkusername);
	$('#username').focus(function() {
		$("#username_tip .jtip_hover").animate({opacity: "show"}, 500);
	});
	$('#username').blur(function() {
		$("#username_tip .jtip_hover").animate({opacity: "hide"}, 0);
	});


	$('#password').focus(function() {
		$("#password_tip .jtip_hover").animate({opacity: "show"}, 500);
	});
	$('#password').blur(function() {
		$("#password_tip .jtip_hover").animate({opacity: "hide"}, 0);
	});

	$('#confirm_password').blur(checkpasswordmatches);


	$('#voucher').keyup(checkvalidvoucher);

	$(document.body).append('<div id="pageflip"><img src="/images/page_flip.png" alt="flip" /><div class="msg_block"></div></div><img src="/images/spreadsheet.jpg" id="spreadsheet" />');

	$('#spreadsheet').click(function() {
		$('#spreadsheet').css('display','none');
	});
	$('#pageflip').click(function() {
		$('#spreadsheet').css('display','block');
	});


	$("a[rel*='external']").each(function() { 
		this.target = '_blank';
	});

	$("a[rel*='popup']").each(function() { 
		this.onclick = function() {
			window.open(this.href, 'Popup', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=500');	
			return false;
		}
	});
	$("a[rel*='popupnarrow']").each(function() { 
		this.onclick = function() {
			window.open(this.href, 'Popup', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=300');	
			return false;
		}
	});

	$('#winners_category').change(function() { 
		$('#winners_category_form').submit();	
	});

	$('#howtoplaylink').click(function () {
		$('#howtoplay').slideToggle('slow');
	 });
	$('#strategieslink').click(function () {
		$('#strategies').slideToggle('slow');
	 });


});


$(document).ready(function(){
	$("#pageflip").hover(function() {
		$("#pageflip img , .msg_block").stop()
			.animate({
				width: '200px', 
				height: '200px'
			}, 500); 
		} , function() {
		$("#pageflip img").stop() 
			.animate({
				width: '50px', 
				height: '52px'
			}, 220);
		$(".msg_block").stop() 
			.animate({
				width: '50px', 
				height: '50px'
			}, 200);
	});
});


$(document).ready(function() {
	if( $('#scrolling_auctions ul li').length > 6 ) {
		var auto_slide = 1;
		var hover_pause = 1;
		var key_slide = 1;
		var auto_slide_seconds = 3000;
		$('#scrolling_auctions ul li:first').before($('#scrolling_auctions ul li:last')); 
		if(auto_slide == 1){
			var timer = setInterval('slide("right")', auto_slide_seconds); 
			$('#hidden_auto_slide_seconds').val(auto_slide_seconds);
		}
		if(hover_pause == 1){
			$('#scrolling_auctions ul').hover(function(){
				clearInterval(timer)
			},function(){
				timer = setInterval('slide("right")', auto_slide_seconds);
			});
		}
		if(key_slide == 1){
			$(document).bind('keypress', function(e) {
				if(e.keyCode==37){
					slide('left');
				}else if(e.keyCode==39){
					slide('right');
				}
			});
		}
	}
});

function slide(where){
	var item_width = $('#scrolling_auctions ul li').outerWidth() + 10;
	if(where == 'left'){
		var left_indent = parseInt($('#scrolling_auctions ul').css('left')) + item_width;
	}else{
		var left_indent = parseInt($('#scrolling_auctions ul').css('left')) - item_width;
	}
	$('#scrolling_auctions ul:not(:animated)').animate({'left' : left_indent},500,function() {
		if(where == 'left') {
			$('#scrolling_auctions ul li:first').before($('#scrolling_auctions ul li:last'));
		} else {
			$('#scrolling_auctions ul li:last').after($('#scrolling_auctions ul li:first'));
		}
		$('#scrolling_auctions ul').css({'left' : '-'+$('#scrolling_auctions ul li:first').width()+'px'});
	});
}


$(document).ready(function() {
	$(".jtip").hover(function() {
        if ($(".jtip_hover", this).css("display") == "block") { 
			return false;
		}
		var jleft = parseInt($("img", this).css('left'));
		var jbottom = parseInt($("img", this).css('bottom'));
        $(".jtip_hover", this).css({bottom: jbottom+"px", right: "0px"});
		$(".jtip_hover", this).animate({bottom: jbottom+20+"px", opacity: "show"}, 500);
    },
    function() {
        $(".jtip_hover", this).animate({opacity: "hide"}, 500);
    });
});


// Function to check for registered username
checkusername = function() {
	if( $('#username').attr('value') != '' ) {
		reqJSON("/ajaxcall.php", { call: "check_username", username: $('#username').attr('value') }, function(json) {
			if(json==true) {
				if ($("#username_unique_tip .jtip_hover").css("display") == "block") { 
					return false;
				}
				$("#username_unique_tip .jtip_hover").animate({opacity: "show"}, 500);
				
			}else{
				$("#username_unique_tip .jtip_hover").animate({opacity: "hide"}, 0);
			}
		}, ajaxerror);
	} else {
		$("#username_unique_tip .jtip_hover").animate({opacity: "hide"}, 500);
	}
}

// Function to check for registered username
checkemailexists = function() {
	if( $('#email').attr('value').length > 0 ) {
		reqJSON("/ajaxcall.php", { call: "check_email", email: $('#email').attr('value') }, function(json) {
			if(json==true) {
				if ($("#email_unique_tip .jtip_hover").css("display") == "block") { 
					return false;
				}
				$("#email_unique_tip .jtip_hover").animate({opacity: "show"}, 500);
				
			}else{
				$("#email_unique_tip .jtip_hover").animate({opacity: "hide"}, 0);
			}
		}, ajaxerror);
	}
}

checkemailmatches = function() {
	if ($("#email").attr('value') != $("#confirm_email").attr('value')) {
		if ($("#email_match_tip .jtip_hover").css("display") == "block") {
			return false;
		}
		$("#email_match_tip .jtip_hover").animate({opacity: "show"}, 500);
	}else{
		$("#email_match_tip .jtip_hover").animate({opacity: "hide"}, 0);
	}
}

checkpasswordmatches = function() {
	if ($("#password").attr('value') != $("#confirm_password").attr('value')) {
		if ($("#password_match_tip .jtip_hover").css("display") == "block") {
			return false;
		}
		$("#password_match_tip .jtip_hover").animate({opacity: "show"}, 500);
	}else{
		$("#password_match_tip .jtip_hover").animate({opacity: "hide"}, 0);
	}
}


checkvalidvoucher = function() {
	reqJSON("/ajaxcall.php", { call: "check_voucher", voucher: $('#voucher').attr('value') }, function(json) {
		if(json==false) {

			$("#voucher_description").html("Enter a valid voucher code if you have one");			
		}else{
			$("#voucher_description").html("Voucher Applied! "+json);
		}
	}, ajaxerror);
}

swapwinner = function(i) {
	$('#[id^=winners]').css('display','none');
	$('#winners'+i).css('display','block');
}
