var url = '/ajaxscript/auction.php';
//Milliseconds between ajax update
var updateInterval = 15000;
//Controls when to go to sleep. We don't want a users browser to request data all night when user dont uses it.
// activeCycles*updateInterval = "live" update time. 500*100 = 5000/60
var activeCycles = 50;
var closingAuction = false;

//Language strings
var languageArray;

//Creates new bid.
function createAuctionBid(auctionId, bidValue, bidMaxValue, bidQuantity, email_notify, sms_notify)
{
    new Ajax.Request(url,
    {
      method: 'post',
      parameters: { auctionId: auctionId,
                    action: 'createAuctionBid',
                    bidValue: bidValue,
                    bidMaxValue: bidMaxValue,
                    bidQuantity: bidQuantity,
                    email_notify: email_notify, 
                    sms_notify: sms_notify},
      onSuccess: function(transport)
      {
        if(transport.responseText == 0)
        {
            $('bidBox').setStyle("display: none;");
            $('bidok').setStyle("display: inline;");
            showMyActiveAuctionsBox();
            getBidList(auctionId);
            updateAuctionsData();
        }
        else
        {
            $('error_msg').innerHTML = transport.responseText;
            $('bidBox').setStyle("display: none;");
            $('biderror').setStyle("display: inline;");
            $('ibox_wrapper').setStyle("height: auto;");
        }
      },
      onFailure: function()
      {
        //alert('Something went wrong...');
      }
    });
}


//Updates existing bid.
function updateAuctionBid(auctionId, bidId, bidValue, bidMaxValue)
{
    new Ajax.Request(url,
    {
      method: 'post',
      parameters: { auctionId: auctionId,
                    bidId: bidId,
                    action: 'updateAuctionBid',
                    bidValue: bidValue,
                    bidMaxValue: bidMaxValue},
      onSuccess: function(transport)
      {
        if(transport.responseText == 0)
        {
            $('bidBox').setStyle("display: none;");
            $('bidok').setStyle("display: inline;");
            
            $$('.myAuctionsCurrentBid'+auctionId+bidId).each(
                                                function(el){
                                                    try{
                                                        el.innerHTML= bidValue;
                                                    }catch(err){
                                                    }
                                                }
                                            )
            
            $$('.myAuctionsCurrentMaxBid'+auctionId+bidId).each(
                                                function(el){
                                                    try{
                                                        el.innerHTML= bidMaxValue;
                                                    }catch(err){
                                                    }
                                                }
                                            )
            
            showMyActiveAuctionsBox();
            getBidList(auctionId);
            updateAuctionsData();
        }
        else
        {
            $('error_msg').innerHTML = transport.responseText;
            $('bidBox').setStyle("display: none;");
            $('biderror').setStyle("display: inline;");
            $('ibox_wrapper').setStyle("height: auto;");
        }
      },
      onFailure: function()
      {
        //alert('Something went wrong...');
      }
    });
}


//Return to bidding interface when bid didn't go through.
function backToBid(){
    $('bidBox').setStyle("display: inline;");
    $('biderror').setStyle("display: none;");
}


//Displays my auctions box.
function showMyActiveAuctionsBox()
{
    new Ajax.Request(url,
    {
      method: 'post',
      parameters: { action: 'showMyActiveAuctionsBox'},
      onSuccess: function(transport)
      {
        $('myActiveAuctionsBox').innerHTML = transport.responseText;
      },
      onFailure: function()
      {
        //alert('Something went wrong...');
      }
    });
}


function getBidList(auctionId)
{
    new Ajax.Request(url,
    {
      method: 'post',
      parameters: { auctionId: auctionId,
                    action: 'getBidList'},
      onSuccess: function(transport)
      {
      // auctionList
        $('bidList'+auctionId).innerHTML = transport.responseText;
      },
      onFailure: function()
      {
        //alert('Something went wrong...');
      }
    });
    setTimeout("getBidList("+auctionId+")",updateInterval)
}

//Responsible for displaying all the countdowns
function displayCountDown(auctionId, timeLeft)
{
    var id = id;
    var secondsInDay = (24*60*60);
    var secondsInHour = (60*60);
    var secondsInMin = (60);
    var seconds = 0;
    var minutes = 0;
    var hours = 0;
    var days = 0;
    if(timeLeft<=0)
    {
        if(closingAuction){
            $$('.auctionsTimer'+auctionId).each(
                                            function(el){
                                                try{                     
                                                    el.innerHTML= languageArray["AJAX_LANGUAGE_AUCTION_FINISHED"];  
                                                }catch(err){
                                                }
                                            }
                                        )
        }else{
            closingAuction = true;
            getAuctionTime(auctionId, id);
            $$('.auctionsTimer'+auctionId).each(
                                            function(el){
                                                try{                 
                                                    el.innerHTML= languageArray["AJAX_LANGUAGE_AUCTION_PROCESSING"];  
                                                }catch(err){
                                                }
                                            }
                                        )
        }
        
    }
    else
    {
        closingAuction = false;
        var tmpTimeLeft = timeLeft;
        days = Math.floor(timeLeft/secondsInDay);
        timeLeft -=  days * secondsInDay;
        hours = Math.floor(timeLeft/secondsInHour);
        timeLeft -=  hours * secondsInHour;
        minutes = Math.floor(timeLeft/secondsInMin);
        timeLeft -=  minutes * secondsInMin;
        seconds = timeLeft;
        $$('.auctionsTimer'+auctionId).each(
                                                function(el){
                                                    try{
                                                        if(days==1){
                                                            daystring = languageArray["AJAX_LANGUAGE_DAY"];
                                                        }else{
                                                            daystring = languageArray["AJAX_LANGUAGE_DAYS"];
                                                        }
                                                        if(hours==1){
                                                            hourstring = languageArray["AJAX_LANGUAGE_HOUR"];
                                                        }else{
                                                            hourstring = languageArray["AJAX_LANGUAGE_HOURS"];
                                                        }                                                       
                                                        el.innerHTML= days +daystring+hours+hourstring+minutes+languageArray["AJAX_LANGUAGE_MINUTE"]+seconds+languageArray["AJAX_LANGUAGE_SECOND"];
                                                    }catch(err){
                                                    }
                                                }
                                            )
        
        tmpTimeLeft--;
        setTimeout(function(){displayCountDown(auctionId, tmpTimeLeft)},1000);
    }
    
}


//Retrives remaing time and starts the countdowns 
function getAuctionTime(auctionId)
{
    new Ajax.Request(url,
    {
      method: 'post',
      parameters: { auctionId: auctionId,
                    action: 'getAuctionTime'},
      onSuccess: function(transport)
      {
        var timeLeft = transport.responseText;
//        if(timeLeft >= 0)
//        {
            displayCountDown(auctionId, timeLeft);
//        }
      },
      onFailure: function()
      {
        //alert('Something went wrong...');
      }
    });
}

//Function that makes ajax call to server and updates visible auction price.
function updateAuctionsData(){
    new Ajax.Request(url,
    {
      method: 'post',
      parameters: { action: 'updateAuctionsData'},
      onSuccess: function(transport)
      {
        data = transport.responseText.evalJSON();
        data.each(
                    function(auction){
                         $$('.auctionsPrice'+auction.auctions_id).each(
                                                function(el){
                                                    try{
                                                        el.innerHTML= auction.highestbid;
                                                    }catch(err){
                                                    }
                                                }
                                            )
                        
                    }
                );
      },
      onFailure: function()
      {
        //alert('Something went wrong...');
      }
    });
    setTimeout("updateAuctionsData()",updateInterval)
}

function updateBidLeader(){
    new Ajax.Request(url,
    {
      method: 'post',
      parameters: { action: 'updateBidLeader'},
      onSuccess: function(transport)
      {
        data = transport.responseText.evalJSON();
        data.each(
                    function(bid){
                         $$('.bidLeader'+bid.auctions_id+bid.bid_id).each(
                                                function(el){
                                                    try{
                                                        try{
                                                            if(bid.bidleader==true){
                                                                el.setStyle({color: "#399B38"});
                                                            }else{
                                                                el.setStyle({color: "#ED493F"});                                                            
                                                            }
                                                        }catch(err){
                                                        }
                                                        el.innerHTML = bid.bidleadertext;
                                                    }catch(err){
                                                    }
                                                    
                                                }
                                            )
                        
                    }
                );
      },
      onFailure: function()
      {
        //alert('Something went wrong...');
      }
    });
    setTimeout("updateBidLeader()",updateInterval)
}    


function getActiveAuctions(){
    new Ajax.Request(url,
    {
      method: 'post',
      parameters: { action: 'getActiveAuctionsId'},
      onSuccess: function(transport)
      {
        data = transport.responseText.evalJSON();
        data.each(
                    function(auction){
                        getAuctionTime(auction.auctions_id);
                    }
                  )
      },
      onFailure: function()
      {
        //alert('Something went wrong...');
      }
    });
}

function getLanguage(){
    new Ajax.Request(url,
    {
      method: 'post',
      parameters: { action: 'getLanguage'},
      onSuccess: function(transport)
      {
        languageArray = transport.responseText.evalJSON();
      },
      onFailure: function()
      {
        //alert('Something went wrong...');
      }
    });
}


Event.observe(window, 'load', function(){
    getLanguage();
    getActiveAuctions();
    showMyActiveAuctionsBox();
    updateAuctionsData();
    updateBidLeader();
});



