$(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-price, #' + 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]['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 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();
            $.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);
                            }
                        }
                    }

                    $.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();
                        }

                        price = convertToNumber(price);

                        if(auctionObjects[item.A.e]['bid-bidder'].html() != item.A.usr){
                            auctionObjects[item.A.e]['bid-bidder'].html(item.A.usr);
                        }

                        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);
                        }
						
						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 row = '<tr><td align="left">' + tRow.B.pr + '</td><td align="left">' + tRow.B.u + '</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'))
										{
											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('Pause');

                            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){
                            auctionObjects[item.A.e]['countdown'].html('Ended');
                            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;
	
		});
    // 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";
    }
  }
}

