var RequestUrl = "api/json.aspx";
var traderaBidderLink = "http://www.tradera.com/MyTradera/Feedback/ViewFeedback.aspx?ftgnr=";
var ReqGetBidList = null;
var callBidListId = 0;
var intBidDelay = 400;

window.addEvent('domready', function() {

    $('theFromInput').addEvent('change', fromChanged);
    $('theToInput').addEvent('change', toChanged);
    $$('#theDateHolder .on').addEvent('click', dateChanged);

    $('statavg0').getParent().fx = new Fx.Morph($('statavg0').getParent().getElement('.statinfobox'), { duration: (500), link: 'cancel', transition: Fx.Transitions.Quad.easeOut });
    $('statavg0').getParent().addEvent('mouseenter', showStatInfobox);
    $('statavg0').getParent().addEvent('mouseleave', hideStatInfobox);

    var tmpCounter = 0;
    $('theFromHolder').getElements('.char').each(function(tmpItem) {
        tmpItem.fx = new Fx.Morph(tmpItem, { duration: (tmpCounter * 100 + 300), link: 'cancel', transition: Fx.Transitions.Quad.easeOut });
        tmpItem.charid = tmpCounter++;
    });
    tmpCounter = 0;
    $('theToHolder').getElements('.char').each(function(tmpItem) {
        tmpItem.fx = new Fx.Morph(tmpItem, { duration: (tmpCounter * 100 + 300), link: 'cancel', transition: Fx.Transitions.Quad.easeOut });
        tmpItem.charid = tmpCounter++;
    });

    for (var i = 0; i <= 6; i++) {
        var tmpStatAvg = $('statavg' + i);
        tmpStatAvg.fx = new Fx.Morph(tmpStatAvg, { duration: (500), link: 'cancel', transition: Fx.Transitions.Quad.easeOut });
    }

    //ReqGetBidList
    ReqGetBidList = new Request({ method: "post", data: "func=GetBidList&fr={fr}&to={to}&date={date}", link: 'cancel', url: RequestUrl, onSuccess: reqGetBidListSuccess, onFailure: reqGetBidListFailure, onCancel: killCall, onComplete: killCall });
    callReqGetBidList.delay(intBidDelay, null, [++callBidListId]);

    //ReqSignForLetter
    ReqSignForLetter = new Request({ method: "post", data: "func=SignForLetter&from={from}", link: 'cancel', url: RequestUrl, onSuccess: reqSignForLetterSuccess, onFailure: reqSignForLetterFailure, onCancel: killCall, onComplete: killCall });
});

function fromChanged() {
    if ($('theFromInput').get('value') == "-")
        $('theFromInput').selectedIndex = $('theFromInput').selectedIndex + 1;
    $('theFromHolder').getElements('.char').each(function(tmpItem) {
        tmpItem.fx.start({ 'top': 90 }).chain(function() {
            tmpItem.set('src', 'img/chars/' + $('theFromInput').get('value')[tmpItem.charid] + '.png');
            tmpItem.fx.start({ 'top': -2 });
        });
    });
    var tmpCounter = 0;
    while ($('theFromInput').get('value') == $('theToInput').get('value')) {
        $('theToInput').selectedIndex = tmpCounter++;
    }
    if(tmpCounter > 0)
        $('theToHolder').getElements('.char').each(function(tmpItem) {
            tmpItem.fx.start({ 'top': -90 }).chain(function() {
                tmpItem.set('src', 'img/chars/' + $('theToInput').get('value')[tmpItem.charid] + '.png');
                tmpItem.fx.start({ 'top': -2 });
            });
        });
    $('theCountOne').set('html', '');
    $('theLoader').setStyle('display', 'block');
    $('theFootInfo').setStyle('display', 'none');
    $('theContent').empty();
    callReqGetBidList.delay(intBidDelay, null, [++callBidListId]);
}
function toChanged() {
    if ($('theToInput').get('value') == "-")
        $('theToInput').selectedIndex = $('theToInput').selectedIndex +1;
    $('theToHolder').getElements('.char').each(function(tmpItem) {
        tmpItem.fx.start({ 'top': -90 }).chain(function() {
            tmpItem.set('src', 'img/chars/' + $('theToInput').get('value')[tmpItem.charid] + '.png');
            tmpItem.fx.start({ 'top': -2 });
        });
    });
    var tmpCounter = 0;
    while ($('theFromInput').get('value') == $('theToInput').get('value')) {
        $('theFromInput').selectedIndex = tmpCounter++;
    }
    if (tmpCounter > 0)
        $('theFromHolder').getElements('.char').each(function(tmpItem) {
            tmpItem.fx.start({ 'top': 90 }).chain(function() {
                tmpItem.set('src', 'img/chars/' + $('theFromInput').get('value')[tmpItem.charid] + '.png');
                tmpItem.fx.start({ 'top': -2 });
            });
        });
    $('theCountOne').set('html', '');
    $('theLoader').setStyle('display', 'block');
    $('theFootInfo').setStyle('display', 'none');
    $('theContent').empty();
    callReqGetBidList.delay(intBidDelay, null, [++callBidListId]);
}
function dateChanged() {
    $('theCountOne').set('html', '');
    $('theLoader').setStyle('display', 'block');
    $('theFootInfo').setStyle('display', 'none');
    $('theContent').empty();
    $$('#theDateHolder .sel').removeClass('sel');
    this.addClass('sel');
    callReqGetBidList.delay(intBidDelay, null, [++callBidListId]);
}
function callReqGetBidList(inCallId) {
    if (inCallId == callBidListId) {
        ReqGetBidList.send(ReqGetBidList.options.data.replace("{fr}", $('theFromInput').get('value')).replace('{to}', $('theToInput').get('value')).replace('{date}', $$('#theDateHolder .sel')[0].id.split('_')[1]));
        pageTracker._trackEvent('Auctions', $('theFromInput').get('value') + " - " + $('theToInput').get('value'));
    }
}
function showDeparture() {
    if (this.id == "Alla")
        $$(".BidItem").setStyle('display', 'block');
    else {
        $$(".BidItem").setStyle('display', 'none');
        $$("." + this.id).setStyle('display', 'block');
    }
    $$('.deptimeOn').removeClass('deptimeOn');
    this.addClass('deptimeOn');
}

function showStatInfobox() {
    this.toopen = true;
    showStatInfoboxExec.delay(500, null, this);
}
function showStatInfoboxExec(caller) {
    if(caller.toopen)
        caller.fx.start({ 'top': 5 });
}
function hideStatInfobox() {
    this.toopen = false;
    this.fx.start({ 'top': -32 });
}
function closeOm(){
    $('theAbout').setStyle('display', 'none');
}
function openOm() {
    $('theAbout').setStyle('display', 'block');
    pageTracker._trackEvent('View', 'About');
}
function prenumerera() {
    ReqSignForLetter.send(ReqSignForLetter.options.data.replace("{from}", $('theMailToSign').get('value')));
    pageTracker._trackEvent('Subscription', 'KeepMeUpdated', $('theMailToSign').get('value'));
}

//***************************************************************************************************
function killCall(){}

//reqGetBidList -------------------------------------------------------------------------------------
function reqGetBidListSuccess(text, xml) {
    try{
        var tmpResponse = JSON.decode(text);
        if(!tmpResponse.success){
            reqGetBidListFailure(ReqGetBidList);
            return;
        }

        $('theCountOne').set('html', tmpResponse.auctions.length);

        if (tmpResponse.auctions.length > 0) {
            $('theContent').empty();
            var tmpTitle = new Element('div', { 'class': 'BigTitle' });
            tmpResponse.deptimes.each(function(tmpTime) {
                var tmpEl = new Element('div', { 'id': tmpTime.time.replace(':', ''), 'class': (tmpTime.off == "True" ? 'deptime off' : 'deptime') });
                tmpEl.set('html', "<div class='left'></div><div class='middle'>" + tmpTime.time + "</div><div class='right'></div>");
                tmpEl.addEvent('click', showDeparture);
                tmpTitle.adopt(tmpEl);
            });
            $('theContent').adopt(tmpTitle);
            tmpTitle.getChildren()[tmpTitle.getChildren().length - 1].addClass('deptimeOn');

            tmpEl = new Element('div', { 'class': 'BidItemTop' });
            $('theContent').adopt(tmpEl);

            tmpResponse.auctions.each(function(tmpType) {
                tmpEl = new Element('div', { 'id': 'theBid_' + tmpType.id, 'class': tmpType.timedep.replace(':', '') + (tmpType.traintype == 'InterCity' ? ' BidItem' : ' BidItem X2000') });
                tmpEl.set('html', "<a href='" + tmpType.itemlink + "' target='_blank' class='Desc'>" + tmpType.fr + " - " + tmpType.to
                    + "</a><div class='MaxBid'>" + tmpType.maxbid + " kr</div>"
                    + (tmpType.avslutad == true ? "<img src='img/tag_avslutad.png' class='avslutad' />" : "<div class='timeleft'>Tid kvar: <b>" + tmpType.tleft + "</b></div>")
                    + (tmpType.maxbidderid == null ? "" : "<a class='bidder' target='_blank' href='" + traderaBidderLink + tmpType.maxbidderid + "'>H&ouml;gsta budgivare: <span class='bidderalias'>" + tmpType.maxbidderalias + "</span></a>")
                    + "<div class='BidCount'>" + (tmpType.totalbids < 1 ? "Inga" : tmpType.totalbids) + " bud</div>"
                    + "<div class='textdep'>" + tmpType.textdep + "</div>"
                    + "<a class='more' target='_blank' href='" + tmpType.itemlink + "'>Se mer p&aring; Tradera/l&auml;gg ditt bud</a>"
                    );
                $('theContent').adopt(tmpEl);
            });
        }
        else {
            $('theContent').set('html', "<img src='img/tag_notyet.png' />");
        }
        if (tmpResponse.statsavg.length > 0) {
            for (var i = 0; i <= 6; i++) {
                var tmpStatAvg = $('statavg' + i);
                if (tmpResponse.statsavg[i].statavg != "") {
                    tmpStatAvg.getFirst().set('text', tmpResponse.statsavg[i].statavg + " kr");
                    tmpStatAvg.fx.start({ 'height': parseInt(tmpResponse.statsavg[i].statavg / tmpResponse.maxstatavg * 70) });
                }
                else {
                    tmpStatAvg.getFirst().set('text', '-');
                    tmpStatAvg.fx.start({ 'height': 0 });
                }
            }
        }
        //NROFTICKETS
        $$('.dateNrTickets').setStyle('display', 'none');
        tmpResponse.nroftickets.each(function(tmpNrTicket) {
            var tmpEl = $("theDate_" + tmpNrTicket.date);
            if (tmpEl != null) {
                tmpEl = tmpEl.getElement('.dateNrTickets');
                if (tmpNrTicket.nr.toInt() > 99)
                    tmpEl.set('text', '9+');
                else
                    tmpEl.set('text', tmpNrTicket.nr);
                tmpEl.setStyle('display', 'block');
            }
        });
        $('theLoader').setStyle('display', 'none');
        theFootInfo.setStyle('display', 'block');

    } catch (error) { $('theLoader').setStyle('display', 'none'); $('theFootInfo').setStyle('display', 'block'); }
}
function reqGetBidListFailure(instance) {
    $('theLoader').setStyle('display', 'none');
    $('theFootInfo').setStyle('display', 'block');
}
// --------------------------------------------------------------------------------------------------
//reqSignForLetter -------------------------------------------------------------------------------------
function reqSignForLetterSuccess(text, xml) {
    try {
        var tmpResponse = JSON.decode(text);
        if (!tmpResponse.success) {
            reqSignForLetterFailure(ReqSignForLetter);
            return;
        }
        $('theAbout').getElements('input').destroy();
        $('theTack').setStyle('display', 'block');

    } catch (error) {}
}
function reqSignForLetterFailure(instance) {
    alert("Ett fel har uppstat, forsok igen senare.");
}
