trustdev.provide('lots');
trustdev.provide('lots.config');

lots.isHomePage = false;

lots.updaterTimer = null;
lots.updaterSimpleTimer = null;
lots.updaterSimpleCount = 0;
lots.updaterLock = false;
lots.betLock = false;
lots.price = new Array();
lots.betLastUserId = new Array();
lots.betLastId = new Array();

var requestLastId = new Array();

lots.requestLastUserId = new Array();
lots.requestLock = false;
lots.participantsAmount = new Array();
lots.serverTime = null;

lots.latestData = null;

lots.config.animationFadeTime = 150;

lots.updaterSimple = function() {
	
	if (!lots.latestData)
		return;
	
	for (var lotId in lots.latestData) {
		
        var lot = lots.latestData[lotId];
        var lotTimeElement = $('#lot_' + lotId + '_time').html() ? $('#lot_' + lotId + '_time') : $('#lot_full_' + lotId + '_time');
        
		if (lotTimeElement) {
			
            var timeNewFormatted = lots.getLotTimeFormatted(lot.dt_end, lots.updaterSimpleCount);
            var timeNew = lots.getLotTime(lot.dt_end, lots.updaterSimpleCount);
            
            if (timeNew < 15)
            	lotTimeElement.css('color', '#F70027');
            else
            	lotTimeElement.css('color', '');

            if (timeNewFormatted) {

            	lotTimeElement.html(timeNewFormatted);
                
            }
			
		}
		
	}
	
	lots.updaterSimpleCount++;
	
    lots.updaterSimpleTimer = setTimeout("lots.updaterSimple()", 1000);
	
}

lots.toggle = function(id)
{
    $('#claim_' + id).toggle();
    $('#bid_' + id).toggle();
    $('#autobet_' + id).toggle();
}

lots.updater = function() {

	if (!lots.updaterLock) {
		
		lots.updaterLock = true;
		
		var request = $.get('/static/status.html?random=' + Math.random(), function (jsonData) {

            // (!!!) Время сервера, используется для отсчета
            lots.serverTime = request.getResponseHeader('Date');
            
			if (jsonData) {
			    
				data = $.evalJSON(jsonData);
				
				// Запускаем простой таймер
				lots.latestData = data;
			    clearTimeout(lots.updaterSimpleTimer);
			    lots.updaterSimpleCount = 0;
			    lots.updaterSimple();
				
				for (var lotId in data) {

                    var lot = data[lotId];
                    
                    lots.betLastUserId[lotId] = lot.betLastUserId;
                    lots.requestLastUserId[lotId] = lot.requestLastUserId;

                    // ***** КРАТКИЙ ВИД АУКЦИОНА *****
                    if ($('#lot_' + lotId + '_time').html()) {
                    	
                        var timeNewFormatted = lots.getLotTimeFormatted(lot.dt_end);
                        var timeNew = lots.getLotTime(lot.dt_end);

                        if (timeNew < 15)
                            $('#lot_' + lotId + '_time').css('color', '#F70027');
                        else
                            $('#lot_' + lotId + '_time').css('color', '');

                        if (timeNewFormatted) {

                            $('#lot_' + lotId + '_time').html(timeNewFormatted);
                            
                        } else if ('Завершен' != $('#lot_' + lotId + '_time').text() && lot.isClosed) {
                        	
                        	$('#lot_' + lotId + '_button').fadeOut(lots.config.animationFadeTime);

                            $('#lot_' + lotId + '_time').fadeOut(lots.config.animationFadeTime, function() {

                                $(this)
                                    .html('Завершен')
                                    .fadeIn(lots.config.animationFadeTime);

                            });

                        }
                        
                        if (lots.price[lotId] != lot.price) { // Обновляем информацию только при необходимости
  
                            // Обновляем цену
                            lots.price[lotId] = lot.price;

                            if ($('#lot_' + lotId + '_author').html().toLowerCase() == '<br>') {                          
                            	$('#lot_' + lotId + '_author').empty();
                            	var authorHtml = lot.user;                            	
                            	authorHtml += ' <a id="lot_' + lotId + '_author_url" title="Профиль участника"'; 
                            	authorHtml += 'href="/profile/' + lot.betLastUserId + '"'; 
                            	authorHtml += 'onmouseout="$(this).find(\'img\').attr(\'src\', \'/images/info_sm.png\');"';
                            	authorHtml += 'onmouseover="$(this).find(\'img\').attr(\'src\', \'/images/info_sm_over.png\');">';
                            	authorHtml += '<img height="13" width="13" alt="Профиль участника" style="margin-bottom: -1px;" src="/images/info_sm.png"/></a>';
                            	$('#lot_' + lotId + '_author').html(authorHtml);
                            } else {
	                            $('#lot_' + lotId + '_author_url').attr('href', '/profile/' + lot.betLastUserId);
	                            $('#lot_' + lotId + '_author').contents().filter(function(){ return this.nodeType != 1; }).replaceWith(lot.user ? lot.user + ' ' : '<br />');
                            }
                            
                            $('#lot_' + lotId + '_price').html(lot.price + ' руб.');
                            $('#lot_' + lotId + '_price').shake(3, 5, 1000);

                            if (userId == lot.betLastUserId) {
                                $('#lot_' + lotId + '_price').parent().css('backgroundColor', '#F70027');
                            } else {
                                $('#lot_' + lotId + '_price').parent().css('backgroundColor', '#74A600');
                            }
                            
                        	// Обновляем историю + вычисляем кол-во потраченных текущим участником ставок
                        	var history = lot.betsList;
                        	
                        	var betsUsed = 0;
                        	
                        	for (var i = 0; i < history.length; i++) {
                        		if (history[i][4] > lots.betLastId[lotId] && history[i][3] == userId)
                        			betsUsed++;
                        	}
                        	
                        	lots.betLastId[lotId] = lot.betLastId;
                            
                            // Обновляем инфу в хедере если пришла ставка текущего юзера
                            if (betsUsed && (!lots.isHomePage || !lot.isDummy)) {

                                betsRemaining -= betsUsed;

                                lots.updateBetsRemaining(lot.isDummy);

                            }

                        }
                    }
                    
            		if ($('#lot_' + lotId + '_price').html()) {
                        
                        // если страницу перезагрузили
                        if (requestLastId[lotId] == null)
                        {
                            requestLastId[lotId] = lot.requestLastId;
                        }
                        
                        // обновляем инфу в хедере, если пришла заявка текущего юзера
                        else if (requestLastId[lotId] != lot.requestLastId) {
                            
                            requestLastId[lotId] = lot.requestLastId;
                            // обновляем количество участников
                            // lots.participantsAmount[lotId] = lot.participantsAmount;
                            
                            // уменьшаем количество ставок
                            if (userId == lot.requestLastUserId) {
                                    betsRemaining -= lot.requestPrice;
                                    
                                    lots.updateBetsRemaining(lot.isDummy);
                            }
                        }
                    
                    }

                    // ***** ПОЛНЫЙ ВИД АУКЦИОНА *****
                    if ($('#lot_full_' + lotId + '_time').html()) {
                    	
                    	var timeNewFormatted = lots.getLotTimeFormatted(lot.dt_end);
                        var timeNew = lots.getLotTime(lot.dt_end);

                        if (timeNew < 15)
                            $('#lot_full_' + lotId + '_time').css('color', '#F70027');
                        else
                            $('#lot_full_' + lotId + '_time').css('color', '');

                        if (timeNewFormatted) {

                            $('#lot_full_' + lotId + '_time').html(timeNewFormatted);

                        } else if ('Завершен' != $('#lot_full_' + lotId + '_time').text() && lot.isClosed) {
                        	
                        	$('#autobets_off').fadeOut(lots.config.animationFadeTime);
                        	$('#autobets_on').fadeOut(lots.config.animationFadeTime);

                            $('#lot_full_' + lotId + '_time').fadeOut(lots.config.animationFadeTime, function() {

                                $('#lot_full_' + lotId + '_time')
                                    .html('Завершен')
                                    .fadeIn(lots.config.animationFadeTime/2);

                            });

                        }
                        
                        if (lot.betLastUserId != 0) {                          
                        	$('#lot_full_' + lotId + '_author').empty();
                        	var authorHtml = lot.user;                            	
                        	authorHtml += ' <a id="lot_' + lotId + '_author_url" title="Профиль участника"'; 
                        	authorHtml += 'href="/profile/' + lot.betLastUserId + '"'; 
                        	authorHtml += 'onmouseout="$(this).find(\'img\').attr(\'src\', \'/images/info_sm.png\');"';
                        	authorHtml += 'onmouseover="$(this).find(\'img\').attr(\'src\', \'/images/info_sm_over.png\');">';
                        	authorHtml += '<img height="13" width="13" alt="Профиль участника" style="margin-bottom: -1px;" src="/images/info_sm.png"/></a>';
                        	$('#lot_full_' + lotId + '_author').html(authorHtml);
                        } else {
                            $('#lot_full_' + lotId + '_author_url').attr('href', '/profile/' + lot.betLastUserId);
                            $('#lot_full_' + lotId + '_author').contents().filter(function(){ return this.nodeType != 1; }).replaceWith(lot.user ? lot.user + ' ' : '<br />');
                        }
                       
                        $('#lot_full_' + lotId + '_price').html('&nbsp;' + lot.price + ' руб.');
                        $('#lot_full_' + lotId + '_profit').html(lot.profitPercentage + '%');

                        if (userId == lot.betLastUserId)
                            $('#lot_full_' + lotId + '_price').parent().css('backgroundColor', '#F70027');
                        else
                            $('#lot_full_' + lotId + '_price').parent().css('backgroundColor', '#74A600');

                        if (betLastId != lot.betLastId) { // Пришла новая ставка
                        	
                        	$('#lot_full_' + lotId + '_price').shake(3, 5, 1000);
                        	
                        	// Обновляем историю + вычисляем кол-во потраченных текущим участником ставок
                        	var history = lot.betsList;
                        	var historyHtml = '';
                        	
                        	var betsUsed = 0;
                        	var autobetsUsed = 0;
                        	
                        	for (var i = 0; i < history.length; i++) {
                        		historyHtml += '<tr><td class="first">' + history[i][0] + ' руб.</td><td><a onmouseover="$(this).find(\'img\').attr(\'src\', \'/images/info_sm_over.png\');" onmouseout="$(this).find(\'img\').attr(\'src\', \'/images/info_sm.png\');" href="/profile/' + history[i][3] + '" title="Профиль участника"><img src="/images/info_sm.png" width="13" height="13" style="margin-bottom: -1px;" alt="Профиль участника" /></a></td><td width="90" height="16"> &nbsp; <strong>' + history[i][1] + '</strong></td><td>' + (1 == history[i][2] ? 'авто' : 'ручная') +'</td></tr>';
                        		
                        		if (history[i][4] > betLastId && history[i][3] == userId) {
                        			betsUsed++;
                        			
                        			if (1 == history[i][2])
                        				autobetsUsed++;
                        		}
                        	}
                        	
                        	$('#bets_log').html(historyHtml);
                        	
                        	betLastId = lot.betLastId;

                            // Пришла ставка от текущего юзера => уменьшаем общее кол-во ставок
                        	if (betsUsed) {
                            	
                                betsRemaining -= betsUsed;

                                lots.updateBetsRemaining(lot.isDummy);
                                
                                if (typeof betsPayed != 'undefined') { // Аукцион с компенсацией
                                	
                                	betsPayed += betsUsed*500;
                                	
                                	$('#lot_full_' + lotId + '_payed').html(betsPayed);
                                	$('#lot_full_' + lotId + '_payed').format({format:'#,###', locale:'fr'});
                                
                                }
                                
                                if (typeof lotBetsRemaining != 'undefined') { // Аукцион с ограничением
                                	
                                	lotBetsRemaining--;
                                	
                                	$('#lot_full_' + lotId + '_remaining').html(lotBetsRemaining);
                                	
                                }
                            	
                            }

                            // Пришла автоставка текущего юзера => обновляем инфу об авоставках
                    		if (autobetsUsed) { // Пришла автоставка текущего юзера

                                $('#autobet_bets_remaining').html($('#autobet_bets_remaining').html()-autobetsUsed);

                            } 
                        }

                    }

                    if ($('#lot_full_' + lotId + '_profit').html()) {
                                
                        // если страницу перезагрузили
                        if (requestLastId[lotId] == null)
                        {
                            requestLastId[lotId] = lot.requestLastId;
                        }
                        
                        // обновляем инфу в хедере, если пришла заявка текущего юзера
                        else if (requestLastId[lotId] != lot.requestLastId) {
                            
                            requestLastId[lotId] = lot.requestLastId;
                            // обновляем количество участников
                            // lots.participantsAmount[lotId] = lot.participantsAmount;
                            
                            // уменьшаем количество ставок
                            if (userId == lot.requestLastUserId) {
                                betsRemaining -= lot.requestPrice;
                                
                                lots.updateBetsRemaining(lot.isDummy);
                            }
                        }
                            
                    }
				}
			
			}
			
			lots.updaterLock = false;
			
		});
		
	}
	
    lots.updaterTimer = setTimeout("lots.updater()", 700);
	
}

lots.betAdd = function (lotId) {

    if (userId == lots.betLastUserId[lotId]) {
        messages.show('ERR_BET_LAST');
        return;
    }

    if (lots.betLock) {
        messages.show('ERR_BET_WAIT');
        return;
    }
    
    lots.betLock = true;

	$.get('/api/bet_add.php?random=' + Math.random(), {'lotId': lotId}, function(data) {
        lots.betLock = false;
        
        if (1 != data) {

            messages.show(data);
                
        } else {

            messages.show('BET_SUCCESS');
        }
    });
	
}

lots.requestToParticipate = function (lotId) {

    if (lots.requestLock) {
        messages.show('ERR_REQUEST_WAIT');
        return 'ERR_REQUEST_WAIT';
    }

    lots.requestLock = true;
    
    $.get('/api/request_add.php?random=' + Math.random(), {'lotId': lotId}, function(data) {
    	
        lots.requestLock = false;
        
        if (data == '') {
        	return false;
        }
        
        if (1 != data) {
            
            messages.show(data);
            
        } else {
            
            messages.show('REQUEST_SUCCESS');
            lots.toggle(lotId);
            
        }
    });
}

lots.autobetAdd = function (lotId) {

    $('#popup_autobets').fadeOut('fast');

    $.get('/api/autobet_add.php?random=' + Math.random(), {
        'lotId':     lotId,
        'priceFrom': $('#autobet_input_price_from').val(),
        'priceTo':   $('#autobet_input_price_to').val(),
        'betsLimit': $('#autobet_input_bets_limit').val()
    }, function (data) {
        
        if (1 == data) {
        		
        	autobetsRemaining = $('#autobet_input_bets_limit').val();
            
            $('#autobet_price_from').html($('#autobet_input_price_from').val());
            $('#autobet_price_to').html($('#autobet_input_price_to').val());
            $('#autobet_bets_remaining').html($('#autobet_input_bets_limit').val());
            $('#autobet_bets_limit').html($('#autobet_input_bets_limit').val());
            
            $('#autobets_off').fadeOut('fast', function() {
            	$('#autobets_on').fadeIn('fast');
            });

//            $('#autobets_on').fadeIn('fast');
            
        } else {

            messages.show(data);

        }

    });

}

lots.autobetRemove = function (lotId) {

    $.get('/api/autobet_remove.php?random=' + Math.random(), {
        'lotId':     lotId
    }, function (data) {

        $('#autobets_on').fadeOut('fast', function() {
            $('#autobets_off').fadeIn('fast');
        });
    	
    });

}

lots.updateBetsRemaining = function(isDummy) {
	
    var output = '';
    
    if ( (10 <= betsRemaining && 20 >= betsRemaining) || (-1 != jQuery.inArray(betsRemaining%10, [ 0, 5, 6, 7, 8, 9 ])) )
        output = '' + betsRemaining + (isDummy ? ' учебных' : '') + ' ставок';

    else if (1 == betsRemaining%10)
        output = '' + betsRemaining + (isDummy ? ' учебная' : '') + ' ставка';
    
    else
        output = '' + betsRemaining + (isDummy ? ' учебные' : '') + ' ставки';

    $('#balance_header').html(output);
    
}

lots.getLotTime = function (dtEnd, staticTime) {
	
	if (!staticTime)
		staticTime = 0;

	var dtNow = parseInt(getCurrentTimestamp());

	return dtEnd - dtNow - staticTime;
}

lots.getLotTimeFormatted = function (dtEnd, staticTime) {
	
	var timeToEnd = lots.getLotTime(dtEnd, staticTime);

    if (timeToEnd < 0)
        return false;
	
	var h = Math.floor(timeToEnd/3600);
	var m = Math.floor((timeToEnd%3600)/60);
	var s = timeToEnd%60;
	
	if (m<10) m = '0' + m; 
	if (s<10) s = '0' + s;
	
	return '' + h + ':' + m + ':' + s;
}

lots.toggleExcept = function () {
	
    if (1 == $.cookie('except_index_enabled'))
        $.cookie('except_index_enabled', 0, { expires: 31, path: '/' });
    else
        $.cookie('except_index_enabled', 1, { expires: 31, path: '/' });
	
	$('#except_list').slideToggle();
	$('#except_arrow').html('↓' == $('#except_arrow').html() ? '↑' : '↓');

}

function getCurrentTimestamp()
{
	var dt = new Date();
//	return dt.getTime()/1000.0;
	return Date.parse(lots.serverTime)/1000.0;
}