$(document).ready(function(){
    // Variable to hold auction data
    var auctions = '';
    var auctionObjects = new Array();

    // Collecting auction data, the layer id and auction id
    $('.auction-item').each(function(){
        var auctionId    = $(this).attr('id');
        var auctionTitle = $(this).attr('title');

        if($('#' + auctionId + ' .countdown').length){
            // collect the id for post data
            auctions = auctions + auctionId + '=' + auctionTitle + '&';

            // collect the object
            auctionObjects[auctionId]                           = $('#' + auctionId);
            auctionObjects[auctionId]['flash-elements']         = $('#' + auctionId + ' .countdown, #' + auctionId + ' .bid-bidder, #' + auctionId+ ' .bid-savings-price, #' + auctionId + ' .bid-savings-percentage, #' + auctionId + ' .closes-on, #sav_' + auctionId + ' .bid-savings-price, #sav_' + auctionId + ' .bid-savings-percentage');
            auctionObjects[auctionId]['countdown']              = $('#' + auctionId + ' .countdown');
            auctionObjects[auctionId]['closes-on']              = $('#' + auctionId + ' .closes-on');
            auctionObjects[auctionId]['bid-bidder']             = $('#' + auctionId + ' .bid-bidder');
            auctionObjects[auctionId]['bid-button']             = $('#' + auctionId + ' .bid-button');
            auctionObjects[auctionId]['bid-button-a']           = $('#' + auctionId + ' .bid-button a');
            auctionObjects[auctionId]['bid-button-p']           = $('#' + auctionId + ' .bid-button p');
            auctionObjects[auctionId]['bid-price']              = $('#' + auctionId + ' .bid-price');
			auctionObjects[auctionId]['bought-item']            = $('#' + auctionId + ' .bought-item');
			auctionObjects[auctionId]['sold-item']              = $('#' + auctionId + ' .sold-item');
            auctionObjects[auctionId]['bid-price']              = $('#' + auctionId + ' .bid-price');
			auctionObjects[auctionId]['CDUMSTcounter']          = $('#' + auctionId + ' .CDUMSTcounter');
			auctionObjects[auctionId]['cd_uhrnew']        		= $('#' + auctionId + ' .cd_uhrnew');				
			auctionObjects[auctionId]['seats']        			= $('#' + auctionId + ' .seats');				
			auctionObjects[auctionId]['credit-history']        	= $('#credit-history');
            auctionObjects[auctionId]['bid-loading']            = $('#' + auctionId + ' .bid-loading');
            auctionObjects[auctionId]['bid-message']            = $('#' + auctionId + ' .bid-message');
            auctionObjects[auctionId]['bid-flash']              = $('#' + auctionId + ' .bid-flash');
            auctionObjects[auctionId]['bid-savings-price']      = $('#sav_' + auctionId + ' .bid-savings-price');
            auctionObjects[auctionId]['bid-savings-percentage'] = $('#sav_' + auctionId + ' .bid-savings-percentage');
			auctionObjects[auctionId]['bid-savings-rebate']     = $('#' + auctionId + ' .bid-savings-rebate');
			auctionObjects[auctionId]['bid-savings-purchase']   = $('#' + auctionId + ' .bid-savings-purchase');
            auctionObjects[auctionId]['bid-bookbidbutler']      = $('#' + auctionId + ' .bid-bookbidbutler');
            auctionObjects[auctionId]['revealprice']            = $('#' + auctionId + ' .revealprice');
			auctionObjects[auctionId]['revealprice-link']       = $('#' + auctionId + ' .revealprice-link');
			auctionObjects[auctionId]['time-increment']         = $('#' + auctionId + ' .time-increment');
			auctionObjects[auctionId]['time-incrementcounter']  = $('#' + auctionId + ' .time-incrementcounter');
			auctionObjects[auctionId]['bid-newprice']           = $('#' + auctionId + ' .bid-newprice');
			auctionObjects[auctionId]['new-newprice']           = $('#' + auctionId + ' .new-newprice');
            auctionObjects[auctionId]['bid-histories']          = $('#bidHistoryTable' + auctionTitle);
            auctionObjects[auctionId]['bid-histories-p']        = $('#bidHistoryTable' + auctionTitle + ' p');
            auctionObjects[auctionId]['bid-histories-tbody']    = $('#bidHistoryTable' + auctionTitle + ' tbody');
        }
    });

    // additional object
    var bidOfficialTime        = $('.bid-official-time');
    var bidBalance             = $('.bid-balance');
    var winning_day_limit      = $('.winning_day_limit');
    var winning_week_limit     = $('.winning_week_limit');
    var price                  = '';
    var getstatus_url_time;
    var getstatus_url;
	var historyupdate = true;

/*

    if($('.bid-histories').length){

		

        getstatus_url = '/getstatus.php?histories=yes&ms=';

    }else{

		

        getstatus_url = '/getstatus.php?ms=';

    }

    */

	getstatus_url = '/getstatus.php?ms=';

    function convertToNumber(sourceString)
    {
        return sourceString.replace(/&#[0-9]{1,};/gi, "")
                            .replace(/&[a-z]{1,};/gi, "")
                            .replace(/[a-zA-Z]+/gi, "")
                            .replace(/[^0-9\,\.]/gi, "");
    }

    // Do the loop when auction available only
    if(auctions){
        setInterval(function(){
            getstatus_url_time = getstatus_url + new Date().getTime();//alert(getstatus_url_time);
            $.ajax({
                url: getstatus_url_time,
                dataType: 'json',
                type: 'POST',
                data: auctions,
                success: function(data){
                    if(data[0]){
                        if(data[0].A.sts){
                            if(bidOfficialTime.html()){
                               // bidOfficialTime.html(data[0].A.sts);
                            }
                        }

                        if(data[0].A.b){
                            if(bidBalance.html()){
                                bidBalance.html(data[0].A.b);
                            }
                        }
						if(data[0].A.w_lim){
                            if(winning_week_limit.html()){
                                winning_week_limit.html(data[0].A.w_lim);
                            }
                        }
						if(data[0].A.d_lim>=0){
                            if(winning_day_limit.html()){
                                //winning_day_limit.html(data[0].A.d_lim);
								document.getElementById("winning_day_limit").innerHTML=data[0].A.d_lim;
                            }
                        }
                    }

                    $.each(data, function(i, item){
						if(auctionObjects[item.A.e]['CDUMSTcounter'])
						{
							auctionObjects[item.A.e]['CDUMSTcounter'].html(item.A.countmsg);
						}
						//alert(auctionObjects[item.Auction.element]['cd_uhrnew'])
						if(auctionObjects[item.A.e]['cd_uhrnew'])
						{//alert(item.Auction.countmsgnonseat)
							auctionObjects[item.A.e]['cd_uhrnew'].html(item.A.countmsgnonseat);
						}
						//alert(auctionObjects[item.Auction.element]['credit-history'])
						if(auctionObjects[item.A.e]['credit-history'])
						{//alert(item.Auction.credithistory)
							auctionObjects[item.A.e]['credit-history'].html(item.A.credithistory);
						}
						//	alert(auctionObjects[item.Auction.element]['seats'].html())
						if(auctionObjects[item.A.e]['seats'].html())
						{
							//	alert(item.Auction.seatsavail)
							auctionObjects[item.A.e]['seats'].html(item.A.seatsavail);
						}
                        if(auctionObjects[item.A.e]['bid-price'].length > 1){
                            auctionObjects[item.A.e]['bid-price'].each(function(){
                                price = $(this).html();
                            });
                        }else{
                            price = auctionObjects[item.A.e]['bid-price'].html();
                        }
						//alert(price);
                        if(price)price = convertToNumber(price);
						else price =convertToNumber(item.A.pr);

                        if(auctionObjects[item.A.e]['bid-bidder'].html() != item.A.usr){
							/*var urltem1=document.location.href;//alert(urltem.search("winners"));

							if(urltem1.search("winners")>=0 || urltem1.search("profile_detail")>=0)
							{
                            	var tmpusr='<a href="/users/profile_detail/'+item.A.usr_id+'/'+item.A.usr+'">'+item.A.usr+'</a>';
								auctionObjects[item.A.e]['bid-bidder'].html(tmpusr);
							}
							else
							{
								  auctionObjects[item.A.e]['bid-bidder'].html(item.A.usr);
							}*/

							if(item.A.usr=="No existen ofertas")
								var tmpusr=item.A.usr;
							else 
								var tmpusr='<img src="/themed/sinlio/images/ico/leader.png" width="16" height="16" alt="Actual lider" /> '+item.A.usr+'';
							auctionObjects[item.A.e]['bid-bidder'].html(tmpusr);
                        }

                        if(auctionObjects[item.A.e]['bid-flash'] && !item.A.c && item.A.tl > 1){
                            if(item.Message){
                                auctionObjects[item.A.e]['bid-flash'].html(item.Message.message).show(1).animate({opacity: 1.0}, 2000).hide(1);
                            }
                        }

                        if(price != convertToNumber(item.A.pr)){
                            auctionObjects[item.A.e]['bid-price'].html(item.A.pr);
							historyupdate = true;
                            auctionObjects[item.A.e]['flash-elements'].effect("highlight", {color: "#ffff00"}, 1500);
							auctionObjects[item.A.e]['bid-price'].css({'background-color': '#CFC7AE'});
							auctionObjects[item.A.e]['bid-price'].fadeOut("slow").fadeIn("slow");
							//auctionObjects[item.A.e]['bid-price'].style.removeAttribute("filter");
							//auctionObjects[item.A.e]['bid-price'].css({'background-color': '#ffffff'});
							auctionObjects[item.A.e]['bid-price'].fadeOut("slow").fadeIn("slow");
                        }

						if(auctionObjects[item.A.e]['bid-histories'].length && historyupdate){
							if (item.H) {
								if (auctionObjects[item.A.e]['bid-histories-p'].html()) {
									auctionObjects[item.A.e]['bid-histories-p'].remove();
								}
								
								auctionObjects[item.A.e]['bid-histories-tbody'].empty();
						
								$.each(item.H, function(n, tRow){
									var tmpusr12=tRow.B.u+'';
									var row = '<tr><td align="left">' + tRow.B.pr + '</td><td align="left">' + tmpusr12 + '</td><td align="left">' + tRow.B.d + '</td></tr>';
									auctionObjects[item.A.e]['bid-histories-tbody'].append(row);
								});
								
								auctionObjects[item.A.e]['closes-on'].html(item.A.co);
								auctionObjects[item.A.e]['bid-savings-percentage'].html(item.A.sp1);
								auctionObjects[item.A.e]['bid-savings-price'].html(item.A.sp2);
								if(auctionObjects[item.A.e]['bid-savings-rebate'])
								{
										if(auctionObjects[item.A.e]['bid-savings-rebate'].attr('title'))
										{
											// document.getElementById("bid-savings-rebate").innerHTML=item.A.reb;
											//  document.getElementById("bid-savings-purchase").innerHTML=item.A.pur;
											auctionObjects[item.A.e]['bid-savings-rebate'].html(item.A.reb);
											auctionObjects[item.A.e]['bid-savings-purchase'].html(item.A.pur);
										}
								}
								//normale Daten empfangen
								getstatus_url = '/getstatus.php?ms=';
								historyupdate = false;
							}else{
								//history muss erst angefragt werden
								getstatus_url = '/getstatus.php?histories=yes&ms=';
							}
                        }

                        if(item.A.p == 1){
                            auctionObjects[item.A.e]['countdown'].html('Pausado');

                            auctionObjects[item.A.e]['bid-button-a'].hide();
                            if(auctionObjects[item.A.e]['bid-button-p'].html() == ''){
                                auctionObjects[item.A.e]['bid-button'].append('<p>Peak Only Auction</p>');
                            }
                        }else{
                            if(item.A.et - item.A.st > 0){
                                auctionObjects[item.A.e]['countdown'].html(item.A.ets);

                                if(item.A.tl <= 10){
                                    auctionObjects[item.A.e]['countdown'].css('color', '#ff0000');
                                }else{
                                   // auctionObjects[item.A.e]['countdown'].removeAttr('style');
                                }
                            }

                            if(auctionObjects[item.A.e]['bid-button-p'].html()){
                                auctionObjects[item.A.e]['bid-button-a'].show();
                                auctionObjects[item.A.e]['bid-button-p'].remove();
                            }
                        }

                        if(item.A.tl < 1 && item.A.c == 1){
							var urltem=document.location.href;//alert(urltem.search("winners"));
							if(urltem.search("winners")>=0)
							{
                            //auctionObjects[item.A.e]['countdown'].html('Won at');
							auctionObjects[item.A.e]['countdown'].html('');
							}
							else
							{
								 auctionObjects[item.A.e]['countdown'].html('Finalizada');
							}
                            auctionObjects[item.A.e]['bid-button'].hide();
                            auctionObjects[item.A.e]['bid-bookbidbutler'].hide();
                        }
                    });
                },

                error: function(XMLHttpRequest, textStatus, errorThrown){
                    // nothing implement here
                    // have an idea?
                }
            });

        }, 1000);

    }else{
        if(bidOfficialTime.length){
            setInterval(function(){
                var gettime = '/gettime.php?' + new Date().getTime();
                $.ajax({
                    url: gettime,
                    success: function(data){
                       // bidOfficialTime.html(data);
                    }
                });
            }, 1000);
        }
    }

//$('a[rel*=facebox]').facebox() ;

		if(document.getElementById("chat_chatroom"))
		{
		setInterval(function(){
			  
		//alert("das")
				   var  getStatusUrlnew = '/getshoutmsg.php';
		
					$.ajax({
						url: getStatusUrlnew,
						dataType: 'text',
						type: 'POST',
						timeout: 2999,
						global: false,
					   
						success: function(data){
						 //alert(data)
						 
						 document.getElementById("chat_chatroom").innerHTML=data;
						   /* $.each(data, function(i, item)
										{  alert(item.Auction.id)
											});*/
						},

						error: function(XMLHttpRequest, textStatus, errorThrown){
							//$('.countdown').text(textStatus);
						}
					});
			   
			}, 1000);
		
		
		 // Function for bidding
	
	   
	
		}

	 $('.shout-button-link').click(function(){

       if (document.getElementById("ChatText").value != "")
	   {
//alert("hi")
			add_msg();
			
			$.ajax({
	
				url: $(this).attr('href') + '&ChatKey=' + document.getElementById("ChatKey").value + '&ChatHandle=' + document.getElementById("ChatHandle").value + '&ChatText=' + document.getElementById("ChatText").value,
	
				dataType: 'text',
	
				success: function(data){
	//alert("hi")
				  //  document.getElementById("chat_chatroom1").innerHTML=data;
					//location.reload(true);
					if(data!="")alert(data);
					document.getElementById("ChatText").value="";
				}
	
			});

	   }

        return false;

    });

    // Function for bidding
    $('.bid-button-link').click(function(){
        var auctionElement = 'auction_' + $(this).attr('title');

        auctionObjects[auctionElement]['bid-button'].hide(1);
        auctionObjects[auctionElement]['bid-loading'].show(1);

        $.ajax({
            url: $(this).attr('href') + '&ms=' + new Date().getTime(),
            dataType: 'json',
            success: function(data){
                auctionObjects[auctionElement]['bid-message'].html(data.Auction.message)
                                                             .show(1)
                                                             .animate({opacity: 1.0}, 2000)
                                                             .hide(1);

                auctionObjects[auctionElement]['bid-button'].show(1);
                auctionObjects[auctionElement]['bid-loading'].hide(1);
            }
        });

        return false;
    });

//fucntion for seat auction
	 $('.seat-button-link').click(function(){
	
		   
	
	
			$.ajax({
	
				url: $(this).attr('href') + '&name=' + new Date().getTime(),
	
				dataType: 'json',
	
				success: function(data){
	
				  // alert(data.message);
					location.reload(true);
				}
	
			});
	
	
	
			return false;
	
		});
	 //fucntion for bid insure auction
	 $('.bidinsure-button-link').click(function(){
	
		   
	
	
			$.ajax({
	
				url: $(this).attr('href') + '&name=' + new Date().getTime(),
	
				dataType: 'json',
	
				success: function(data){
	
				   alert(data.message);
					//location.reload(true);
				}
	
			});
	
	
	
			return false;
	
		});

 

	  // Function for bidding
    $('.uncoverbid-button-link').click(function(){
        var auctionElement = 'auction_' + $(this).attr('title');
		var id=$(this).attr('title');
       // auctionObjects[auctionElement]['bid-button'].hide(1);
       auctionObjects[auctionElement]['bid-loading'].show(1);
	
	
	
		//alert(auctionObjects[auctionElement]['bid-newprice']);
        $.ajax({
            url: $(this).attr('href') + '&ms=' + new Date().getTime(),
            dataType: 'json',
            success: function(data){
                auctionObjects[auctionElement]['bid-message'].html(data.Auction.message)
                                                             .show(1)
                                                             .animate({opacity: 1.0}, 2000)
                                                             .hide(1);
 auctionObjects[auctionElement]['bid-loading'].hide(1);
                //alert(data.Auction.price)
				if(data.Auction.message=="Price has been revealed")
				{
						var tmp='<a href="/closebid.php?id='+id+'" class="buybid-button-link" title="'+id+'">Buy </a>';
						var price = '<span class="new-newprice">' +data.Auction.price+'</span>' + tmp;
						auctionObjects[auctionElement]['bid-newprice'].html(price);
						auctionObjects[auctionElement]['bid-newprice'].show(1);
						auctionObjects[auctionElement]['bid-loading'].hide(1);
						auctionObjects[auctionElement]['bid-button'].hide(1);
						 //auctionObjects[auctionElement]['countdown'].effect("highlight", {color: "#ffff00"}, 1500);
                                                            
															 
						/* $('.buybid-button-link').click(function()
							{
								var auctionElement = 'auction_' + $(this).attr('title');
						//alert($(this).attr('href') + '&ms=' + new Date().getTime());
							   // auctionObjects[auctionElement]['bid-button'].hide(1);
									//alert(price);
								$.ajax({
									url: $(this).attr('href') + '&ms=' + new Date().getTime(),
									dataType: 'json',
									success: function(data){
										//alert(data.message);
										location.href=data.message;
										//startTime(auctionElement,0);
									}
								});
						
								return false;
							});*/
						 var cnt=0;
						 setInterval(function(){
											  cnt=cnt+1;
											  
											  //alert(cnt)
											   var tme=auctionObjects[auctionElement]['time-increment'].html();
											  if(eval(tme)-eval(cnt)>=0)
											  {
												 
												var tmpp=eval(tme)-eval(cnt);
												var tempp=eval(tmpp)+" Seconds";
												 auctionObjects[auctionElement]['time-incrementcounter'].html(tempp);
												  auctionObjects[auctionElement]['time-incrementcounter'].show(1);
												  if(eval(cnt)==eval(tme))
												  {
													  var price =  auctionObjects[auctionElement]['revealprice-link'].html();
													 // auctionObjects[auctionElement]['bid-button'].html(price);
													  auctionObjects[auctionElement]['bid-button'].show(1);
													  auctionObjects[auctionElement]['time-incrementcounter'].html(eval(tme));
													   auctionObjects[auctionElement]['time-incrementcounter'].hide(1);
													  auctionObjects[auctionElement]['bid-newprice'].hide(1);
													  
													 // cnt=0;
													}
											  }
											 }, 1000);
				}
				//startTime(auctionElement,0);
            }
        });

        return false;
    });
	

    // Function to check limit and change the icon whenever it's changed

    // Run only when bid icon available

    if($('.bid-limit-icon').length){

        setInterval(function(){

            var count = $('.bid-limit-icon').length

            if(count > 0){

                $.ajax({

                    url: '/limits/getlimitsstatus/?ms=' + new Date().getTime(),

                    dataType: 'json',

                    success: function(data){

                        if(data){

                            $('.bid-limit-icon').each(function(i){

                                if(data[i].image){

                                    $(this).attr('src', '/img/'+data[i].image);

                                }

                            });

                        }

                    }

                });

            }

        }, 30000);

    }



    if($('.productImageThumb').length){

        $('.productImageThumb').click(function(){

            $('.productImageMax').fadeOut('fast').attr('src', $(this).attr('href')).fadeIn('fast');

            return false;

        });

    }



    if($('#CategoryId').length){

        $('#CategoryId').change(function(){

            document.location = '/categories/view/' + $('#CategoryId option:selected').attr('value');

        });

    }



    if($('#myselectbox').length){

        $('#myselectbox').change(function(){

            document.location = '/categories/view/' + $('#myselectbox option:selected').attr('value');

        });

    }

});





function add_msg() 
{
	if (document.getElementById("ChatText").value != "") 
	{var msgContainer = document.createElement("p");msgContainer.setAttribute("class", "new");var nameContainer = document.createElement("strong");var nameNode = document.createTextNode(document.getElementById("ChatHandle").value + " (now): ");var msgNode = document.createTextNode(document.getElementById("ChatText").value);nameContainer.appendChild(nameNode);msgContainer.appendChild(nameContainer);msgContainer.appendChild(msgNode);document.getElementById("chat_chatroom").insertBefore(msgContainer, document.getElementById("chat_chatroom").firstChild);
	}
}

//wrok for close cron job
function closedauctions() 
{
	 		var  getStatusUrlnew = '/daemons.php?type=close';
//alert("hi")
            $.ajax({
                url: getStatusUrlnew,
                dataType: 'text',
                type: 'POST',
                timeout: 2999,
                global: false,
                success: function(data){
                 //alert(data)
				 
				 //document.getElementById("chat_chatroom").innerHTML=data;
				   /* $.each(data, function(i, item)
								{  alert(item.Auction.id)
									});*/
                },

                error: function(XMLHttpRequest, textStatus, errorThrown){
                    //$('.countdown').text(textStatus);
                }
            });
}

//wrok for close wiiner job
function winnerauctions() 
{
	 		var  getStatusUrlnew = '/daemons/winner';
            $.ajax({
                url: getStatusUrlnew,
                dataType: 'text',
                type: 'POST',
                timeout: 2999,
                global: false,
               
                success: function(data){
                 //alert(data)
				 
				 //document.getElementById("chat_chatroom").innerHTML=data;

				   /* $.each(data, function(i, item)

								{  alert(item.Auction.id)

									});*/

                },



                error: function(XMLHttpRequest, textStatus, errorThrown){

                    //$('.countdown').text(textStatus);

                }

            });



}



//wrok for bid butler cron job

function bidbutlerauctions() 

{



	 		var  getStatusUrlnew = '/daemons.php?type=bidbutler';



            $.ajax({

                url: getStatusUrlnew,

                dataType: 'text',

                type: 'POST',

                timeout: 2999,

                global: false,

               

                success: function(data){

                 //alert(data)

				 

				 //document.getElementById("chat_chatroom").innerHTML=data;

				   /* $.each(data, function(i, item)

								{  alert(item.Auction.id)

									});*/

                },



                error: function(XMLHttpRequest, textStatus, errorThrown){

                    //$('.countdown').text(textStatus);

                }

            });



}





function loginbox(obj,model)

{

		//alert("hi")

 		var paymentype;

		var val="";

 		for (var i = 0; i < document.packages.elements.length; i++) 

		  {

			var e = document.packages.elements[i];

			if ((e.name == 'Mer') && (e.type == 'radio')) 

			{

				if(e.checked)paymentype = e.value;

			}

			

		  }

		//  alert(paymentype); alert(val);

		  if(paymentype=="")

		  {

			alert("Please select any one payment method");  

			return false;

		   }

		   else

		   {

				//if(paymentype=="paypal")var url="/payment_gateways/paypal/buyitem/"+ obj;

				//if(paymentype=="moneybooker")var url="/payment_gateways/moneybooker/buyitem/"+ obj;

				//alert(url)

				var url="/payment_gateways/"+paymentype+"/"+model+"/"+ obj;

				//alert(url)

				document.packages.action=url;

				document.packages.submit();

				return false;

		   }

}

function hidedisplay(div_id) {
  el =document.getElementById(div_id);
  if (el) {
    if (el.style.display == "none") {
      el.style.display = "";
    } else {
      el.style.display = "none";
    }
  }
}




