var flipflop=1;
var storedata;

// Default frequency for auction updating and time sync
var auctionUpdateTime = 0.5;
var counterUpdateTime = 1000;

// Convert it to milisecond
auctionUpdateTime = auctionUpdateTime * 1000;

// Variable to hold auction data
var auctions = '';
var prices = '';
var auctions1 = '';

var firstimage_bold;
	
var GlobalVar = 0;
$(document).ready(function(){
	if($.browser.msie){
        //Configuring ajax
        $.ajaxSetup({
            cache: false
        });
    }
	$('#bidsniper').click(function(){
		var state=$(this).attr('checked');
		var suid=$('#sniper_uid').attr('value');
		var saucid=$('#sniper_aucid').attr('value');
		var bids=$('#bidsniper_bids').attr('value');
		var password=$('#password').attr('value');
		
		if(bids==''){
			alert("You have to put bids!");
			return false;
		}
		if(state==true){
			var postdata='bids='+bids+'&uid='+suid+'&aucid='+saucid+'&method=add'+'&password='+password;
			
			$.ajax({
                url: 'managesniper.php',
                type: 'POST',
				cache:false,
                data: postdata,
                success: function(data){
					var state1=$.evalJSON(data).state;					
					if(state1=="passnotmatch")
					{
						var reason=$.evalJSON(data).reason;
						$('#bidsniper').attr('checked',false);
						alert(reason);
						$('#password').focus();
					}
					if(state1=="unsuccess")
					{
						var reason=$.evalJSON(data).reason;
						if(confirm(reason))
						{
							window.location.href='buybids.html';
						}
					}else if(state1=="unsuccess1")
					{
						var reason=$.evalJSON(data).reason;
						if(confirm(reason))
						{
						}
					}else if(state1=="success"){
						var bids=$.evalJSON(data).bids;
						var sid=$.evalJSON(data).sid;
						var freeauction=$('#freeauction').attr('value');
						
						if(freeauction!=1)
						{
							obj = document.getElementById('bids_count');
							objvalue = document.getElementById('bids_count').innerHTML;
							if(obj.innerHTML!='0')
							{
								obj.innerHTML = Number(objvalue) - Number(bids);
							}
						}
						var putbids=$('#bidsniper_bids').attr('value')
						$('#snipers tr:last').after('<tr id="sn'+sid+'"><td>'+putbids+'</td><td><img src="/images/btn_closezoom.png" onclick="deletesniper('+sid+')"></td></tr>');
						$('#bidsniper').attr('checked',false);
						$('#bidsniper_bids').attr('value','');
					}
				},
			});
		}
	});
	// Collecting auction data, the layer id and auction id
	$('.auction-item').each(function(){
		var auctionId    = $(this).attr('id');
        var auctionTitle = $(this).attr('title');
		auctions = auctions + auctionId + '=' + auctionTitle + '&';
		var time=$('#counter_index_time_'+eval(auctionTitle)).attr('value');
		$('#counter_index_page_'+eval(auctionTitle)).countdown({until: eval(time),layout:'<b>{d<}{dn} {dl} {d>}'+ 
		'{hnn}:{mnn}:{snn}</b>'}); 
	});
	
	if($('.firstimagebold').length)
	{
		firstimage_bold = document.getElementById('firstimage_bold').innerHTML;
	}
	
	 // Main countdown for updating auction and flashing
    setInterval(function(){
        if(auctions){
            getStatusUrl = 'update_information.php?flp=' + flipflop;
            $.ajax({
                url: getStatusUrl,
                dataType: 'json',
                type: 'POST',
                data: auctions,
				global: false,
                success: function(data){
					storedata = data;
					$.each(data, function(i, item){
						auction_id = item.auction.id;
						auction_price = item.auction.price;
						auction_bidder_name = item.auction.username;
						//alert(auction_bidder_name);
						if(auction_bidder_name=="")
						{
						   auction_bidder_name="---" 
						}
						if(document.getElementById('price_index_page_' + auction_id).innerHTML != auction_price)
						{
							
							if(GlobalVar == 1)	
							{
								var forhoverid = new Spry.Effect.Highlight('price_index_page_' + auction_id , {duration: 500, from:'#f79909', to:'#FFFFFF', restoreColor: '#FFFFFF'});
								var forhoverid2 = new Spry.Effect.Highlight('currencysymbol_' + auction_id , {duration: 500, from:'#f79909', to:'#FFFFFF', restoreColor: '#FFFFFF'});
								forhoverid.start();
								forhoverid2.start();
							}
							document.getElementById('price_index_page_' + auction_id).innerHTML = auction_price;
							document.getElementById('currencysymbol_' + auction_id).innerHTML = "$";
							document.getElementById('product_bidder_' + auction_id).innerHTML = auction_bidder_name;
						}
						else
						{
							document.getElementById('price_index_page_' + auction_id).style.backgroundColor = "white";	
						}						
					});
					GlobalVar = 1;
				},
				error: function(XMLHttpRequest,textStatus, errorThrown){
				}
			});
		}
		if(flipflop==1) { flipflop = 2; }
		else if(flipflop==2) { flipflop = 1;}
		ChangeCountdownData(storedata);
	}, auctionUpdateTime);
	
	
	
	// Function for bidding
    $('.bid-button-link').click(function(){
//        var auctionElement = $(this).parent().parent().parent().attr('id');
//        var bidButton      = $(this).parent().parent().children('.bid-button');
//        var bidLoading     = $(this).parent().parent().children('.bid-loading');

//        bidButton.hide(1);
//        bidLoading.show(1);
		var password=$('#password').attr('value');
        $.ajax({
            url: $(this).attr('name')+'&password='+password,
	  //  alert(url);
            dataType: 'json',

            success: function(data){
				$.each(data, function(i, item){
				result = item.result;
				if(result=="notlogged")
				{
					if(confirm("you must log in to bid..!"))
					{
						window.location.href='login.html';
					}
				}
				if(result=="passwordnotmatch")
				{
					if(confirm("Password didn't match!Please go to detail page of this auction and type password there!"))
					{
						
					}
				}
				if(result=="unsuccess")
				{

					if(confirm(plsrechargebid))
					{
						window.location.href='buybids.html';
					}
				}
                                 if(result=="beginner")
				{
					if(confirm("Only beginner can bid on this auction..!"))
					{
						
					}
				}
                                     if(result=="reachingwin")
				{
					if(confirm("you have reach the win Limit Please try later..."))
					{
						window.location.href='logout.html';
					}
				}
				
				if(result=="topbidder")
				{
					alert("You are the top bidder now");
				}

				if(result=="success")
				{
					var freeauction=$('#freeauction').attr('value');
					if(freeauction!=1){
						obj = document.getElementById('bids_count');
						objvalue = document.getElementById('bids_count').innerHTML;
						if(obj.innerHTML!='0')
						{
							obj.innerHTML = Number(objvalue) - 1;
						}
					}
				}
/*			    if($('.index_setting').length){
					oldused = Number(document.getElementById("totalusedbids_index").innerHTML);
					document.getElementById("totalusedbids_index").innerHTML = oldused + 1;
				}
*/			});
            },
			error: function(XMLHttpRequest,textStatus, errorThrown){
//				alert(textStatus);
			}
        });

        return false;
    });
	if($('#productdetailpage').attr('value')=="detailpage"){
		setInterval(function(){
			var buid=$('#buid').attr('value');
			var baucid=$('#baucid').attr('value');
			var postdata='uid='+buid+'&aucid='+baucid;
			
			$.ajax({
                url: 'getbidscount.php',
                type: 'GET',
				cache:false,
                data: postdata,
				success:function(data){
					//alert(data);
					var placebidscount=$.evalJSON(data).placebidscount;
					var placebidsamount=$.evalJSON(data).placebidsamount;	
					var placebidssavingdisp=$.evalJSON(data).placebidssavingdisp;
					$('#placebidscount').html(placebidscount);
					$('#placebidsamount').html(placebidsamount);
					$('#placebidssavingdisp').html(placebidssavingdisp);
					
				},
			});
		},counterUpdateTime);
		setInterval(function(){
			
			var baucid=$('#baucid').attr('value');
			var postdata='aucid='+baucid;
			
			$.ajax({
                url: 'getlastbidder.php',
                type: 'GET',
				cache:false,
                data: postdata,
				success:function(data){
					//alert(data);
					var biddernum=$.evalJSON(data).bidders;
					$('#lastbiddernum').html(biddernum);
					
				},
			});
		},counterUpdateTime);
	}
	if($('.productImageThumb').length){
    setInterval(function(){
		auctionhisid = document.getElementById('history_auctionid').innerHTML;

		oldprice = document.getElementById('curproductprice').innerHTML;
//		alert(oldprice);
		newprice = document.getElementById('price_index_page_' + auctionhisid).innerHTML;
	if(oldprice!=newprice)
	{
		getStatusUrl3 = 'updatehistory.php?aucid_new='+auctionhisid;
//		alert(getStatusUrl3);
		//alert(auctions); 
	$.ajax({
		url: getStatusUrl3,
		dataType: 'json',
		success: function(data){

			data1 = eval('(' + data.responseText + ')');
			for(i=0;i<data.histories.length;i++)
			{
				biddingprice = data.histories[i].history.bprice;
				biddingusername = data.histories[i].history.username;
				biddingtype = data.histories[i].history.bidtype;

				document.getElementById('bid_price_' + i).innerHTML = "$" + biddingprice;
				document.getElementById('bid_user_name_' + i).innerHTML = biddingusername;

				if(biddingtype=='s')
				{
					document.getElementById('bid_type_' + i).innerHTML = placesinglebid;
				}
				else if(biddingtype=='sn')
				{
					document.getElementById('bid_type_' + i).innerHTML = placesniperbid;
				}
				else if(biddingtype=='b')
				{
					document.getElementById('bid_type_' + i).innerHTML = placebidbuddy;
				}
				else if(bidding_type=='m')
				{
					document.getElementById('bid_type_' + i).innerHTML = placesmsbid;
				}
			}
			
			if(data.myhistories.length)
			{
				for(j=0;j<data.myhistories.length;j++)
				{
					biddingprice1 = data.myhistories[j].myhistory.bprice;
					biddingusername1 = data.myhistories[j].myhistory.time;
					biddingtype1 = data.myhistories[j].myhistory.bidtype;

					document.getElementById('my_bid_price_' + j).innerHTML = "$" + biddingprice1;
					document.getElementById('my_bid_time_' + j).innerHTML = biddingusername1;
	
					if(biddingtype1=='s')
					{
						document.getElementById('my_bid_type_' + j).innerHTML = placesinglebid;
					}
					else if(biddingtype1=='sn')
					{
						document.getElementById('my_bid_type_' + j).innerHTML = placesniperbid;
					}
					else if(biddingtype1=='b')
					{
						document.getElementById('my_bid_type_' + j).innerHTML = placebidbuddy;
					}
					else if(biddingtype1=='m')
					{
						document.getElementById('my_bid_type_' + j).innerHTML = placesmsbid;
					}
				}
			}
			document.getElementById('curproductprice').innerHTML = "$" + data.histories[0].history.bprice;
		},
		error: function(XMLHttpRequest,textStatus, errorThrown){
//			alert(textStatus);	
		}
		   });
	}
	 },counterUpdateTime);
    }

	$('.bookbidbutlerbutton').click(function(){
	if(document.getElementById('bookbidbutlerbutton').name!="")
	{
		var bidbutstartprice;
		var bidbutendprice;
		var totalbids;
		var password=$('#password').attr('value');
		bidbutstartprice = Number(document.bidbutler.bidbutstartprice.value);
		bidbutendprice = Number(document.bidbutler.bidbutendprice.value);
		totalbids = document.bidbutler.totalbids.value;
		if(bidbutstartprice=="")
		{
			alert(entbutsprice);
			return false;
		}
		if(bidbutendprice=="")
		{
			alert(entbuteprice);
			return false;
		}
		if(totalbids=="")
		{
			alert(entbutbids);
			return false;
		}
		if(totalbids<=1)
		{
			alert(entmoreone);
			return false;
		}
		if(bidbutstartprice>bidbutendprice)
		{
			alert(spricegreat);
			return false;
		}
		if(bidbutstartprice==bidbutendprice)
		{
			alert(endpricegreat);
			return false;
		}

		$.ajax({
            url: "addbidbutler.php?aid="+$(this).attr('name')+"&bidsp="+bidbutstartprice+"&bidep="+bidbutendprice+"&totb="+totalbids+"&password="+password,
            dataType: 'json',
            success: function(data){
				$.each(data, function(i, item){
				result = item.result;
                if(result=="passwordnotmatch")
				{
					alert("Please enter password in password box!");
					$('#password').focus();
				}
				if(result=="failbooking")
				{
					alert("beginner can not  Book a BidBuddy");
				}
				if(result=="unsuccessprice")
				{
					alert(bidfromvalueismust);
				}
				else if(result=="unsuccess")
				{
					alert(plsrechargebid);
				}
				else
				{
					document.bidbutler.bidbutstartprice.value="";
					document.bidbutler.bidbutendprice.value="";
					document.bidbutler.totalbids.value="";
					document.getElementById('butlermessage').style.display='block';
					changeMessageTimer = setInterval("ChangeButlerImageSecond()",3000);
					changedatabutler(data,"abut",totalbids);
				}
                            
			  });
			},
			error: function(XMLHttpRequest,textStatus, errorThrown){
//				alert(textStatus);
			}
        });

        return false;
	 }
    });
});
function deletesniper(id)
{
	var suid=$('#sniper_uid').attr('value');
	var postdata='sid='+id+'&uid='+suid+'&method=delete';
	$.ajax({
        url: 'managesniper.php',
        type: 'POST',
        data: postdata,
        success: function(data){	
			var state1=$.evalJSON(data).state;
			if(state1=="success"){
				$('#snipers tr#sn'+Number(id)).remove();
				var bids=$.evalJSON(data).bids;			
				obj = document.getElementById('bids_count');
				objvalue = document.getElementById('bids_count').innerHTML;
				if(obj.innerHTML!='0')
				{
					obj.innerHTML = Number(objvalue) + Number(bids);
				}
			}
		},
	});
}
function DeleteBidButler(id,div_id)
{
	$.ajax({
		url: url = "deletebutler.php?delid=" + id,
		dataType: 'json',
		success: function(data){
		$.each(data, function(i, item){
			result = item.result;
			if(result=="unsuccess")
			{
				alert(youbidisrunning);
			}
			else
			{
				placebids = document.getElementById('butlerbids_' + div_id).innerHTML;
				objbids = document.getElementById('bids_count');
				objbidsvalue = document.getElementById('bids_count').innerHTML;
				if(objbids.innerHTML!='0')
				{
					objbids.innerHTML = Number(objbidsvalue) + Number(placebids);
				}
				changedatabutler(data,"dbut","");
			}
		});
	},
		error: function(XMLHttpRequest,textStatus, errorThrown){
//				alert(textStatus);
		}
	});
	return false;
}

function ChangeCountdownData(resdata)
{
	if(resdata && resdata!="")
	{
		data = resdata;
		var f=0;
	$.each(data, function(i, item){
			auction_id = item.auction.id;
			auction_time = item.auction.time;
			pausestatus = item.auction.pause;
		if(auction_time)
		{
			if(auction_time=='0')
			{
				document.getElementById('counter_index_page_' + auction_id).style.color = '#000000';
				document.getElementById('counter_index_page_' + auction_id).innerHTML = printended;					
				document.getElementById('image_main_' + auction_id).onclick="";
				document.getElementById('image_main_' + auction_id).name="";
				document.getElementById('image_main_' + auction_id).onmouseover="";
				document.getElementById('image_main_' + auction_id).onmouseout="";
				if($('.history_auctionid').length)
				{	
					if(document.getElementById('history_auctionid').innerHTML==auction_id)
					{
						document.getElementById('bookbidbutlerbutton').name = "";
						document.getElementById('image_main_' + auction_id).src = allimagepath + "BIG_SOLD_btn.png";
					}
					else
					{
						document.getElementById('image_main_' + auction_id).src = allimagepath + "SOLD_btn.png";
					}
				}
				else
				{
					if(f<firstimage_bold)
					{
						document.getElementById('image_main_' + auction_id).src = allimagepath + "SOLD_btn.png";
					}
					else
					{
						document.getElementById('image_main_' + auction_id).src = allimagepath + "SOLD_btn2.png";
					}
				}
			}
			else if(pausestatus==1)
			{
				document.getElementById('counter_index_page_' + auction_id).innerHTML = 'Pause';
				if($('.history_auctionid').length){
					if(document.getElementById('history_auctionid').innerHTML == auction_id)
					{
						document.getElementById('image_main_' + auction_id).src = allimagepath + "BIG_BID_btn.png";									
					}
					else
					{
						document.getElementById('image_main_' + auction_id).src = allimagepath + "BID_btn.png";									
					}
				}
				else
				{
					if(f<firstimage_bold)
					{
						document.getElementById('image_main_' + auction_id).src = allimagepath + "BID_btn.png";
					}
					else
					{
						document.getElementById('image_main_' + auction_id).src = allimagepath + "BID_btn2.png";
					}
				}
				document.getElementById('image_main_' + auction_id).onclick="";
				document.getElementById('image_main_' + auction_id).onmouseover="";
				document.getElementById('image_main_' + auction_id).name="";							
				document.getElementById('image_main_' + auction_id).onmouseout="";
			}
			else
			{
				//{{ commented by maxwell, on 2010-11-17
				/*
				if(auction_time<10)
				{
					document.getElementById('counter_index_page_' + auction_id).style.color = '#E80000';	
					document.getElementById('counter_index_page_' + auction_id).innerHTML = calc_counter_from_time(auction_time);
				}
				else
				{
					document.getElementById('counter_index_page_' + auction_id).style.color = '#000000';	
					document.getElementById('counter_index_page_' + auction_id).innerHTML = calc_counter_from_time(auction_time);
				}
				*/
				//}} commented by maxwell, on 2010-11-17
						
				
				// added by maxwell, on 2010-11-17
				/*var server_time = auction_time;
				var client_time = auction_times[i];
				var interval = server_time - client_time;
				
				if (interval > 0) {
					timer_interval = 1000 + interval * 200;
				} else if (interval < 0) {
					timer_interval = 1000 + interval * 200;
				} else { // interval == 0
					timer_interval = 1000;
				}
				
				
				auction_ids[i] = auction_id;
				
				if (auction_times[i] == null)
					auction_times[i] = auction_time;*/
				var client_time_str=$('#counter_index_page_'+eval(auction_id)+' b').html();
				var time;
				if(client_time_str.indexOf('Days')>0) time=client_time_str.split(" Days ");
				else time=client_time_str.split(" Day ");
				var time2='';
				var day='';
				if(time[1]==undefined){
					day=0;
					time2=time[0];
				}else{
					day=time[0];
					time2=time[1];
				}
				var time1=time2.split(":");
				var client_time=0;
				client_time=client_time+eval(time1[2]);
				client_time=client_time+eval(time1[1])*60;
				client_time=client_time+eval(time1[0])*60*60;
				client_time=client_time+eval(day)*60*60*24;
				if(eval(auction_time)-client_time>0){
					//$('#counter_index_page1_'+eval(auction_id)).countdown({until: eval(auction_time),layout:'<b>{d<}{dn} {dl} {d>}'+ 
					//'{hnn}:{mnn}:{snn}</b>'}); 
					//alert("ok");
					$('#counter_index_page_'+eval(auction_id)).countdown('destroy');
					$('#counter_index_page_'+eval(auction_id)).countdown({until: eval(auction_time),layout:'<b>{d<}{dn} {dl} {d>}'+ 
					'{hnn}:{mnn}:{snn}</b>'}); 
					
				}
			}
		}
		f++;
	  }
  );
		
}
}

