var started = false;

var lotInfoAutoUpdate = {
        type: 'POST',
        url: '/catalog/sync/',
        data: {"auc-lots": ""},
        dataType: 'json',
        
        timeout: 2000, // ajax request timeout in ms
        timerMaxSecs: 60000, // period between executions in ms
        timer: null,
        lotTimer: null,
        lotCountDowns: {},
        
        lotNextCountDowns: {},
        lotNextCount: 0, 
        removeClosed: 0, 
        totalItems: 0,
        auclots: [],
        
        lotDetail: false,
        processing: false,
        userid: false,
        strLoading: 'Loading',
        blnShowSec: true,
        
        
        /**
         * hook executed before executing the ajax requests.
         * returns false if request is currently processed
         */
        beforeSend: function(jqXHR, settings){if(this.processing) return false; this.processing=true;},
        
        /**
         * hook executed after completed ajax request
         * will restart the timeout
         */
        complete: function(jqXHR, textStatus) { 
            this.processing = false;
            this.timer = setTimeout('lotInfoAutoUpdate.onTimer()', this.timerMaxSecs);
        },
        
        error: function(jqXHR, textStatus){},
        
        /**
         * set the lots to auto-update
         * @param mixed lots string with comma separated values or array with auction_lot_item.id
         */
        setLots: function(lots){ 
        	strlots = ((typeof lots == 'string')?lots:lots.join(','));
        	//$("#dom").append('set lots:' + strlots + '<hr />');
        	this.data = {'auc-lots': strlots};
            this.auclots = strlots.split(',');
        },
        
        /**
         * set the logged in user's id
         * @param integer intUserId
         */
        setUserId: function(intUserId){ this.userid = intUserId;},

        /**
         * execute the AJAX request
         */
        onTimer: function(){
            clearTimeout(this.timer);
            $.ajax(this);
        },
        
        /**
         * loop through all results to render the data
         * @param object resp AJAX Response object
         */
        success: function(resp, textStatus, jqXHR){
            var obj = this;
            jQuery.each(resp, function(alid, data) {
                obj.renderAucLot(alid, data);
                if(data['sl']!= undefined || data['sb']!= undefined){
                    obj.lotCountDowns[alid] = {"sl": data['sl'],
                                                "sb": data['sb'],
					                            "aid": data['aid'],
					                            "lid": data['lid'],
                                                "ls": data['ls'],
                                                "at": data['at']
                    
                    };
                }
            });
        },
        
        /**
         * hook to render lot info, like current bid, winner, etc
         * @param integer alid auction_lot_item.id
         * @param array data returned from the update script
         */         
        renderLotInfo: function(alid, data){},
        
        /**
         * hook to render buy now for an auction_lot_item.id
         * @param integer alid auction_lot_item.id
         * @param array data returned from the update script
         */
        renderBuyNow: function(alid, data){},
        
        /**
         * hook to render time left for an auction_lot_item.id
         * @param integer alid auction_lot_item.id
         * @param array data returned from the update script
         */
        renderTimeLeft: function(alid, data){
        },
        
        /**
         * hook to render actions for the auction_lot_item.id
         * @param integer alid auction_lot_item.id
         * @param array data returned from the update script
         */
        renderActions: function(alid, data){
        },
        
        /**
         * hook to render the auction_lot_item.id
         * @param integer alid auction_lot_item.id
         * @param array data returned from the update script
         */
        renderAucLot: function(alid, data){
            this.renderLotInfo(alid, data);
            this.renderTimeLeft(alid, data);
            this.renderActions(alid, data);
            this.renderBuyNow(alid, data);
        },
        
        renderWinner: function(alid, data){
            strHtml = '';
            return strHtml;
        },
        
        showQueueLot: function(alid){
        	var obj = this;
        	
        	$(".trlot" + alid).hide();
        	
        	var alidN = '';
        	
        	for (alidN in obj.lotNextCountDowns) {
        		$(".trlot" + alidN).show();
        		delete this.lotNextCountDowns[alidN];
        		break;
        	}
        	
    		for(i in obj.auclots) {
    			if (obj.auclots[i] == alid) {
    				if (alidN == '')
    					obj.auclots.splice(i,1);
    				else
    					obj.auclots.splice(i,1,alidN);	
    				break;
    			}
    		}
    		lots = obj.auclots.join(',');
    		obj.setLots(lots);
        	
			delete this.lotCountDowns[alid];
        	
        	var totalItems = obj.totalItems;
        	if (totalItems > 0) {
            	totalItems = totalItems - 1;
            	$("#totalItems").html(totalItems);
            	this.totalItems = totalItems;
            	
            	if (obj.lotNextCount == 0) {
            		$("#endResult").html(totalItems);
            	}
            	
        	}
        	
			var ctralidN = 0;
        	for (alidN in obj.lotNextCountDowns) {
        		ctralidN++;
			}
			
        	if (obj.lotNextCount > 0 && ctralidN == 0) {
        		document.location = document.location.href;
        	} 
        	
        	return;
        },
        
        onLotTimer: function(){
            var obj = this;
            clearTimeout(this.lotTimer);
            var tmp = '';
            jQuery.each(obj.lotCountDowns, function(alid, data){
            	
            	if (obj.removeClosed > 0 && data['sl'] == 1 && obj.lotDetail == false) {	
                	obj.showQueueLot(alid);
            	}
            	
            	if (typeof obj.lotCountDowns[alid] == 'object') {
            		
                	if (data['at'] == 'L') {
                		if (data['sl'] > 0) {
                			if (obj.lotCountDowns[alid].sl != '') obj.lotCountDowns[alid].sl--;
                		}
                		if (data['sb'] != undefined && data['sb'] > 0) {
                			if (obj.lotCountDowns[alid].sb != '') obj.lotCountDowns[alid].sb--;	
                		}	
                	} else {
                        if (obj.lotCountDowns[alid].sl != '') obj.lotCountDowns[alid].sl--;
                        if (obj.lotCountDowns[alid].sb != '') obj.lotCountDowns[alid].sb--;
                	}
                    obj.renderLotTimer(alid, data);
            	} else {
            	}
            	
            	
            });
            
            this.lotTimer = setTimeout('lotInfoAutoUpdate.onLotTimer()', 1000);
        },
        
        renderLotTimer: function(alid, data){
        	
        	var obj = this;
        	var sthtml = '';
            var sb = data['sb'];
            var sl = data['sl'];
            var ls = data['ls'];
            var at = data['at'];

            if ((sb != undefined && sb != '') && 0 < Number(sb)) {
            } else if ((sl != undefined)) {
                if (sl == 0) {
                    sthtml = sthtml + this.strLoading;
                    if (at == 'T') {
                    	$("#bPbid"+alid).attr("disabled", "disabled");
                    	$("#bNxtBtn"+alid).attr("disabled", "disabled");
                    }
                } else if (sl > 0) {
                    sl = sl - 1;
                    sthtml = sthtml + timeLeft(parseInt(sl), this.blnShowSec);
                    $("#bPbid"+alid).attr("disabled", "");  
                } else if (sl < 0 && ls == 1) {
                	
                	if (obj.removeClosed > 0) {	
                    	obj.showQueueLot(alid);
                	}	
                	
                    sthtml = sthtml + this.strLoading;
                    $("#bPbid"+alid).attr("disabled", "disabled");
                	$("#bNxtBtn"+alid).attr("disabled", "disabled");
                    $("#tl"+alid).removeClass("ended");
                    
                } else if (sl < 0 && ls != 1) {
                	
                	return;
                	
                }
            }        
            
            $("#tl"+alid).html(sthtml);      

        },
        
        /**
         * start execution of the auto update
         */
        start: function(){
        	//if (started == true) {
                clearTimeout(this.timer);
                this.timer = setTimeout('lotInfoAutoUpdate.onTimer()', this.timerMaxSecs);
        	//} else {
        		//lotInfoAutoUpdate.onTimer(); 
        		//started = true;
        	//}	
            
            clearTimeout(this.lotTimer);
            this.lotTimer = setTimeout('lotInfoAutoUpdate.onLotTimer()', 1000);
        }
    };
    
/*
Sample usage

lotInfoAutoUpdate.setLots('1,2,3,4,5'); // set auction_lot_item.id's
lotInfoAutoUpdate.setUserId(15); // set logged in user's id
lotInfoAutoUpdate.start();
*/

