var SyncTimer;
var TimerCounters = {};
var ServerData = {}

//This event is called each server update and from client side countdown
//NOTE: This event can be calleds several times for the same element, so just update DOM
var OnLotStarted = function(lotId) {}

//This event is called each server update and from client side countdown
//NOTE: This event can be calleds several times for the same element, so just update DOM
var OnLotEnded = function(lotId) {}

function updateTimeString(itemId, blnShowSeconds) {

	if(blnShowSeconds === undefined)
        blnShowSeconds = 0;
	
	var timeString = '';
	
	if (ServerData[itemId].days) {
        timeString += ServerData[itemId].days+'d ';
    }

    if (ServerData[itemId].hours || ServerData[itemId].days) {
        timeString += ServerData[itemId].hours+'h ';
    } else if (ServerData[itemId].status == 'in-progress') {
        $('a', $('#'+itemId)).css('color', 'red');
    }

    timeString += ServerData[itemId].minutes+'m ';
	
	if(blnShowSeconds === 1 || blnShowSeconds === '1') {
		timeString += ServerData[itemId].seconds+'s ';
	} else {
	    if (!ServerData[itemId].days && !ServerData[itemId].hours) {
	        timeString += ServerData[itemId].seconds+'s ';
	    }
	}
    
    $('a', $('#'+itemId)).text(timeString);
}

function countersSync(strSaleStarted, strSaleEnded, strSaleStart, strTimeLeft, blnShowSeconds, blnTimeBreak) {
    
    //catch undefined params
    if(strSaleStarted === undefined)
        strSaleStarted = 'Sale has started!'; 
    
    if(strSaleEnded === undefined)
        strSaleEnded = 'Sale has ended!';
    
    if(strSaleStart === undefined)
        strSaleStart = 'Sale start:';
    
    if(strTimeLeft === undefined)
        strTimeLeft = 'Time left';
    
    if(blnShowSeconds === undefined)
        blnShowSeconds = 0;
    
    if(blnTimeBreak === undefined)
        blnTimeBreak = 1;
        
    var brString = '<br />';
    if(blnTimeBreak == '1' || blnTimeBreak == 1)
         brString = '<br />';
    else
         brString = ' ';
    
    clearTimeout(SyncTimer);

    //Destroying old timers
    for (var i in TimerCounters) {
        clearTimeout(TimerCounters[i]);
    }
    
    TimerCounters = {};

    var objlist = {};
    $('.time-left').each(function(i) {
        var lotid = $(this).attr('id').replace(/lot\-time/gi, '');
        objlist['id'+i] = lotid; 
    });
    
    $.post('/timesync.php', objlist, function(res) {
        var OldServerData = ServerData;
        //Destroying server data
        ServerData = {}
        for (var i=0, c=res.length; i<c; i++) {
            if (res[i].status != 'ended') {
                ServerData['lot-time'+res[i].id] = res[i];
                updateTimeString('lot-time'+res[i].id,blnShowSeconds );
                TimerCounters['lot-time'+res[i].id] = setTimeout('countdown("lot-time'+res[i].id+'","' + blnShowSeconds + '")', 1000);
                
                if (OldServerData['lot-time'+res[i].id] && OldServerData['lot-time'+res[i].id].status != res[i].status) {
                	$('#main').append('<hr />');
                    OnLotStarted(res[i].id);
                }
            } else {
                $('span', $('#lot-time'+res[i].id)).text('');
                
                if(res[i].status == '') {
                    //$('a', $('#lot-time'+res[i].id)).text('Sale has ' + ((res[i].status=='') ? 'started' : 'ended') + '!');
                    $('a', $('#lot-time'+res[i].id)).text(strSaleStarted);
                } else {
                    $('a', $('#lot-time'+res[i].id)).text(strSaleEnded);
                }
                
                $('a', $('#lot-time'+res[i].id)).attr('class', ((res[i].status=='') ? 'in-progress' : 'ended'));
                
                if (OldServerData['lot-time'+res[i].id] && OldServerData['lot-time'+res[i].id].status != res[i].status) {
                    OnLotEnded(res[i].id);
                }
            }
            $('a', $('#lot-time'+res[i].id)).attr('class', res[i].status);
            if (res[i].status == '') {
                $('span', $('#lot-time'+res[i].id)).html(strSaleStart + brString);
                $('span', $('#lot-time'+res[i].id)).attr('class', '');
            }

            if (res[i].status == 'in-progress') {
                $('span', $('#lot-time'+res[i].id)).html(strTimeLeft + ':' + brString);
                $('span', $('#lot-time'+res[i].id)).attr('class', 'in-progress');
            }
        }
    }, 'json');
    
    if (sync_timeout > 0) {
        SyncTimer = setTimeout('countersSync("'+ strSaleStarted+'","' + strSaleEnded + '","' + strSaleStart + '","' + strTimeLeft + '","' + blnShowSeconds + '","' + blnTimeBreak + '")', sync_timeout);
    }
}

function countdown(itemId, blnShowSeconds) {
    
    if(blnShowSeconds === undefined)
        blnShowSeconds = 0;
        
    clearTimeout(TimerCounters[itemId]);
    res = ServerData[itemId];
    res.seconds --;
    
    if (res.seconds < 0) {
        var totalSecondsLeft = (res.hours * 60 * 60) + (res.minutes * 60);
        if (totalSecondsLeft > 0 ) {
            res.seconds = 59;
            res.minutes--;
        } else {
            $('span', $('#'+itemId)).text('');
            $('a', $('#'+itemId)).text('Sale has '+((res.status=='') ? 'started' : 'ended')+'!');
            $('a', $('#'+itemId)).attr('class', ((res.status=='') ? 'in-progress' : 'ended'));
            if (res.status=='') {
                OnLotStarted(itemId.replace(/lot-time/, ''));
            } else {
                OnLotEnded(itemId.replace(/lot-time/, ''));
            }
            return;
        }
    }
    if (res.minutes < 0) {
        if (res.hours) {
            res.minutes = 59;
            res.hours--;
        } else {
            res.minutes = 0;
        }
    }
    if (res.hours < 0) {
        if (res.days) {
            res.hours = 23;
            res.days--;
        } else {
            res.hours = 0;
        }
    }
    if (res.days < 0) {
        res.days = 0;
    }
    
    if (res.days == 0 && res.hours == 0 && res.minutes == 0 && res.seconds == 0 && res.status == 'in-progress') {
    	OnLotEnded();
    }

    ServerData[itemId] = res;

    updateTimeString(itemId, blnShowSeconds);
    TimerCounters[itemId] = setTimeout('countdown("'+itemId+'","'+blnShowSeconds+'")', 1000);
}
