function AUC_processResponse( text ) {
	var lines = text.split("\n");

	// CHAT
    var chat_id = parseInt(lines[0]);
    if (AUC_CHAT_enabled && chat_id > CHAT_last_line) {
        CHAT_needUpdate = true;
        CHAT_reload();
    }
	// /CHAT

	for (i=1; i<lines.length; i++) {
		var line = lines[i].split("<>");
		if (line.length >= 5) {
			var auc_id    = parseInt(line[0]);
			var status    = line[1];
			var price     = line[2];
			var login     = line[3];
			var lastbid   = line[4];
			var timestamp = line[5];
			var timeleft  = line[6];
			var type      = line[7];
            var timeStep  = line[8];
            var priceComp  = line[9];
			var prevData  = AUC_data[auc_id];
			if ( !prevData || ( lastbid != prevData[4] ) || ( status != prevData[1] ) ) {
			    var updated = true;
			    if ( prevData && lastbid != prevData[4] ) {
			        updated = 2;
			    }
    			AUC_data[auc_id] = [auc_id, status, price, login, lastbid, timestamp, timeleft, type, timeStep, priceComp, updated];
			}
		}
	}
	AUC_redraw();
}

function AUC_redraw() {
    if (AUC_redrawInProgress) return false;
    AUC_redrawInProgress = true;
	for (i in AUC_data) {
	    var data = AUC_data[i];
	    var auc_id    = data[0];
	    var status    = data[1];
	    var price     = data[2];
	    var login     = data[3];
	    var lastbid   = data[4];
		var timestamp = data[5];
	    var timeleft  = data[6];
	    var type      = data[7];
	    //var timeStep  = data[8];
	    //var priceComp  = data[9];
	    var updated   = data[10];
		if (typeof AUC_cache[auc_id] == 'undefined') {
		    AUC_cache[auc_id] = {};
		    AUC_cache[auc_id]['container'] = $('.lot-container-'+auc_id);
		    AUC_cache[auc_id]['timeleft'] = AUC_cache[auc_id]['container'].find('.lot-timeleft');
		    AUC_cache[auc_id]['price'] = AUC_cache[auc_id]['container'].find('.lot-price-number');
		    AUC_cache[auc_id]['lastuser'] = AUC_cache[auc_id]['container'].find('.lot-lastbid');
		}
		var o = AUC_cache[auc_id];
		if ( status == 1 || status == 2) {
		    var timeLeft;
    		if ( status == 1 ) {
    			timeLeft = Math.floor( parseInt(timestamp) / 1000 + parseInt( timeleft ) / 1000  ) - AUC_getTime();
    		} else {
    			timeLeft = Math.floor( parseInt( timeleft ) / 1000  );
    		}
    		o.timeleft.html( AUC_printTime( timeLeft ) );
    		if ( timeLeft < 15 ) {
    		    if ( !o.timeleft.hasClass('short-timeleft') ) {
        		    o.timeleft.addClass('short-timeleft');
    		    }
    		} else if ( o.timeleft.hasClass('short-timeleft')) {
    		    o.timeleft.removeClass('short-timeleft');
    		}
		} else {
			if ( status != 0 ) { 
				o.timeleft.html( '' );
			}
			o.timeleft.removeClass('short-timeleft');
		}
		if ( updated ) {
    		o.price.html(price);
    		o.lastuser.html(login.length ? '<a href="/users/'+login+'">'+login+'</a>' : '');
    		AUC_data[i][10] = false;
    		if ( status == 1 ) {
    		    if ( AUC_username.length ) {
                    o.container.find('.lot-button').html('<div class="lot-button-makebid" onclick="AUC_makeBid('+auc_id+')"></div>');
    		    } else {
                    o.container.find('.lot-button').html('<div class="lot-button-guest"></div>');
    		    }
    		} else if ( status == 2 ) {
    		    o.container.find('.lot-button').html('<div class="lot-button-paused"></div>');
    		} else if ( status == 3 ) {
    		    o.container.find('.lot-button').html('<div class="lot-button-finished"></div>');
    		}
    		if ( login == AUC_username ) {
                AUC_highlight(auc_id, '#00ff00');
    		} else {
                AUC_highlight(auc_id, '#ff6600');
    		}
    		if ( AUC_lotId && AUC_lotId == auc_id && updated === 2 ) {
                AUC_redrawViewLot();
    		}
		}
	}
	AUC_redrawInProgress = false;
    return true;
}

function AUC_redrawViewLot() {
    if ( !AUC_lotId ) return;
    var o = AUC_cache[AUC_lotId];
    var data = AUC_data[AUC_lotId];
    if ( !o || !data ) return;
    var my = data[3] == AUC_username;
    if ( my ) {
        AUC_reloadAutobidsBox();
        doMyInfoRefresh();
    }
    AUC_logAutobid( AUC_lotId, data[2], data[3], data[7] );
    var mp = AUC_lotMarketPrice;
    var p = AUC_parseFloat(data[2]);
    var pc = AUC_parseFloat(data[9]);
    var s = mp - p - pc;
    var mys = 0; 
    if ( AUC_username != '' ) {
    	mys = AUC_parseFloat( $('#currentLotMyBidsS').html() );
    	s -= mys;
    }
    if ( my ) {
        var myBids = parseInt( $('#currentLotMyBids').html() );
        var bidsNumber = AUC_lotTurbo ? AUC_lotTurbo : 1;
        myBids += 1;
        $('#currentLotMyBids').html( myBids );
        mys += AUC_bidPrice*bidsNumber;
        $('#currentLotMyBidsS').html( AUC_printPrice( mys ) );
        s -= AUC_bidPrice*bidsNumber;
    }
    s = s > 0 ? s : 0;
    $('#currentLotP').html( AUC_printPrice( p ) );
    $('#currentLotC').html( AUC_printPrice( pc ) );
    $('#currentLotS').html( AUC_printPrice( s ) );
    $('#currentLotTimeStep').html( data[8] );
}

function AUC_logAutobid( aid, price, login, type ) {
    if ( !aid ) return;
    var o = AUC_cache[aid];
    if ( !o ) return;
    var pattern = $('#autobids-log-pattern').html();
    if ( !pattern ) return;
    var typeStr = $('#autobids-log-pattern-type-'+type).html();
    var html = pattern.replace('%price%', price).replace('%login%', login).replace('%login%', login).replace('%type%', typeStr);
    $('.auction-bids-list').prepend(html);
    $('.auction-bids-list table:gt(19)').remove();
}

function AUC_parseFloat( a ) {
	a = a.replace(',','');
	return parseFloat( a );
}

function AUC_printPrice( price ) {
    var result = '';
    var x = 1;
    if ( price < 0 ) {
    	x = -1;
    	price = -price;
    }
    var p1 = Math.floor( price / 1000 );
    var p3 = Math.floor( price - p1 * 1000 );
    if ( p1 > 0 ) {
        if ( p1 >= 1000 ) {
            var p2 = Math.floor( p1 / 1000 );
            result += p2 + ',';
            p1 = p1 - p2 * 1000;
            if ( p1 < 10 ) {
                p1 = '00' + p1;
            } else if ( p1 < 100 ) {
                p1 = '0' + p1;
            }
        }
        result += p1 + ',';
        if ( p3 < 10 ) {
            p3 = '00' + p3;
        } else if ( p3 < 100 ) {
            p3 = '0' + p3;
        }
    }
    result += p3 + '.';

    var p4 = Math.floor( price * 100 - Math.floor( price ) * 100 );
    if ( p4 < 10 ) {
        p4 = '0' + p4;
    }
    result += p4;
    if ( x == -1 ) {
    	result = '-' + result;
    }
    return result;
}

function AUC_printTime( seconds ) {
    if ( seconds <= 0) return '00:00:00';
    seconds = Math.abs( seconds );
    var h = Math.floor( seconds / 3600 );
    var m = Math.floor( ( seconds % 3600 ) / 60 );
    var s = seconds % 60;
    if (h < 10) h = '0' + h;
    if (m < 10) m = '0' + m;
    if (s < 10) s = '0' + s;
    return h + ':' + m + ':' + s;
}

function AUC_getTime() {
	return AUC_getTimestamp() + AUC_timeDelta;
}

function AUC_getTimestamp() {
	var date = new Date();
	return Math.floor(date.getTime()/1000);
}

function AUC_timer() {
    if (!AUC_refreshEnabled) return false;
    CHAT_enabled = false;
    AUC_reload();
    AUC_redraw();
    setTimeout(AUC_timer, AUC_updateInterval);
    return true;
}

function AUC_timeSync() {
    if (!AUC_refreshEnabled) return false;
    if (AUC_successSyncs>=AUC_successSyncsMax) return false;
    $.get('/sync-time.php?t='+(AUC_getTime()), function(res){
        res = parseInt(res);
        if ( isNaN(res) ) return false;
        if ( res == 0 ) {
        	AUC_successSyncs++;
        } else {
        	AUC_successSyncs = 0;        	
        }
        AUC_timeDelta += res;
    });
    setTimeout(AUC_timeSync, AUC_timeSyncInterval);
    return true;
}

function AUC_reload() {
    $.get('/auction.html?r='+Math.random(), function(res){
        AUC_processResponse(res);
    });
}

function AUC_highlight(aid, color) {
    var o = AUC_cache[aid];
    if (typeof o == 'undefined') return;
    if (o.container.length == 0) return;
    var price = o.price.parent();
    var t_bgcolor = '#FFFFFF';
    var p_bgcolor = '#CC0000';
	o.timeleft
	  .animate({backgroundColor:color}, 200)
	  .animate({backgroundColor:t_bgcolor}, 200);
	price
      .css({backgroundImage:'none'})
	  .animate({backgroundColor:color}, 200)
	  .animate({backgroundColor:p_bgcolor}, 200, null, function(){
          if ( !$.browser.msie || ( $.browser.version.substr(0,1) >= '7' ) ) {
              $(this).css('background-image', null);
          }
      });
}

function AUC_makeBid( aid ) {
    if ( !aid ) return false;
    AUC_cache[aid].container.find('.lot-button div').addClass('lot-button-makebid-na');
    $.post('/lot/bid/', {id: aid}, function(res){
        AUC_cache[aid].container.find('.lot-button div').removeClass('lot-button-makebid-na');
        var message = '';
        if (res == '1') {
            // success
            return true;
        } else if (res == 'need_auth') {
            message = 'Вы не авторизированы.\n\nЗарегистрируйтесь или войдите в свою учётную запись.';
        } else if (res == 'forbidden') {
        	message = 'Вы не допущены к участию в аукционах.\n\nДля выяснения причины обратитесь к Админстрации.';
        } else if (res == 'user_not_found') {
            return false;
        } else if (res == 'user_no_bids') {
            message = 'У вас нет ставок.\n\nВы можете их купить в "Моем кабинете".';
        } else if (res == 'lot_not_found') {
            return false;
        } else if (res == 'lot_not_active') {
            message = 'Этот аукцион уже не принимает новые ставки.';
        } else if (res == 'max_lots_reached') {
            message = 'Вы не можете принимать участие в новых аукционах, так как достигли ограничения одновременных аукционов.';
        } else if (res == 'max_wins_reached') {
            message = 'Вы достигли максимально допустимого числа побед в этом месяце\nи не можете принимать участие в новых аукционах.';
        } else if (res == 'not_newbie') {
            message = 'Это аукцион для новичков.';
        } else if (res == 'real_price_spent') {
            message = 'Вы потратили рыночную стоимость товара на ставки.\nВы получите этот товар в подарок.\n\nСпасибо, что участвовали в аукционе!';
        } else if (res == 'entry_limit_reached') {
        	message = 'Этот лот уже не принимает новых участников.\nОбратите внимание на то, что первую ставку в таких лотах можно сделать только до достижения указанной цены.';
        } else if (res == 'no_need') {
            AUC_highlight(aid, '#ffff00');
        }
        if ( message ) {
            alert( message );
        }
        return true;
    });
    return true;
}

function AUC_reloadAutobidsBox( html, params ) {
    var b = $('#autobids-box');
    if ( !AUC_lotId || !b.size() ) return;
    if ( !html ) {
        b.html( 'Идет обновление...<br /><br />' + b.html() );
        $.post('/lot/index/auto-bid-settings/' + (params ? '?' + params : ''), {lot: AUC_lotId}, function( res ){
            b.html( res );
            AUC_autobidsBindForm();
        });
    } else {
        b.html( html );
        AUC_autobidsBindForm();
    }
}

function AUC_autobidsBindForm()  {
    $('#my-autobid form').ajaxForm({
        success:   AUC_autobidsFormResponse,
        url:       '/lot/index/auto-bid-settings/',
        type:      'post'
    });
}

// post-submit callback
function AUC_autobidsFormResponse(responseText, statusText)  {
	AUC_reloadAutobidsBox( responseText );
}

var AUC_refreshEnabled = false;
var AUC_CHAT_enabled = false;
var AUC_updateInterval = 1000;
var AUC_timeSyncInterval = 10000;
var AUC_redrawInProgress = false;
var AUC_lotId = '';
var AUC_data = {};
var AUC_cache = {};
var AUC_serverTime = 0;
var AUC_successSyncs = 0;
var AUC_successSyncsMax = 3;
var AUC_localTime = AUC_getTimestamp();
var AUC_timeDelta = 0;
//setInterval( function(){AUC_currentTime++;}, 1000);

$(document).ready(function(){
    if ( typeof CHAT_enabled == 'undefined' ) CHAT_enabled = false;
    if (AUC_refreshEnabled) {
    	AUC_timeDelta = AUC_serverTime - AUC_localTime;
        AUC_CHAT_enabled = CHAT_enabled;
        AUC_timer();
        AUC_timeSync();
    }
    AUC_reloadAutobidsBox();
});
