var id, selectedIndate, selectedSector, costs = 0, jSElem, jIElem;

jQuery(document).ready(function() {
    id = parseInt(jQuery('#id').val());

//    loadDates();
//
//    rememberInits();
//
//    checkReserv();
});

function checkReady() {
    if (!jQuery('#mfm').is(':visible')) return true;

    jQuery('#mfm').show();

    return false;
}

function showDescription() {
    jQuery.get('/event/description/' + id, undefined, function(html) {
        jQuery('#ed').html(html);
    }, 'txt');
}

function checkReserv() {
    jQuery.get('/event/reserv/check', undefined, function(xml) {
        if (jQuery(xml).find('reserv').length > 0) {
            jQuery('#sidequantityvalue').html(jQuery(xml).find('reserv').attr('quantity') + ' билетов');
            jQuery('#sidecostvalue').html(jQuery(xml).find('reserv').attr('sum') + ' руб.');
        }
    }, 'xml');
}

function loadDates() {
    jQuery.get('/event/reserv/dates/' + id, undefined, function(xml) {
        var html = '';

        if (jQuery(xml).find('indate').length == 0) {
            html += wrapTr(wrapTd('Дамы и Господа, Вы можете заказать билеты по телефону (495)660-94-00', undefined, undefined, 'title'));
        } else {
            var pos = 0;
            jQuery(xml).find('indate').each(function() {
                var iid = jQuery(this).attr('id');

                html += wrapTr(
                        wrapTd(jQuery(this).attr('date'), 'idate' + iid) +
                        wrapTd(jQuery(this).attr('time'), 'itime' + iid) +
                        wrapTd(jQuery(this).attr('quantity')) +
                        wrapTd('<a href="#" class="fall" onclick="toggleIRow(' + iid + ', jQuery(this)); return false;">Развернуть</a>', 'icell' + iid, undefined, 'lst'),
                        'irow' + iid, (pos++ % 2 == 0 ? 'line' : 'line-d'));
            });
        }

        showDates(html);
    }, 'xml');
}

function toggleIRow(iid, elem) {
    if (typeof(jSElem) != 'undefined') {
        jSElem.toggleClass('fall-a');
        jSElem = undefined;
        selectedSector = undefined;
    }
    
    elem.toggleClass('fall-a');

    if (iid == selectedIndate) {
        selectedIndate = undefined;
        jIElem = undefined;

        unloadSeats();
        unloadSectors();
    } else {
        if (typeof(jIElem) != 'undefined')
            jIElem.toggleClass('fall-a');

        jIElem = elem;
        selectedIndate = iid;

        var date = jQuery('#idate' + iid).html();
        var time = jQuery('#itime' + iid).html();

        sectorsLoading(date + ' ' + time);

        jQuery.get('/event/reserv/sectors/' + id + '?indate=' + selectedIndate, undefined, function(xml) {
            var html = '';

            var pos = 0;

            var nodez = new Array();

            jQuery(xml).find('sector').each(function() {
                nodez.push(this);
            });

            nodez.sort(function(a,b){ //using the native sort here
                var at = parseFloat(jQuery(a).find('price').text()), bt = parseFloat(jQuery(b).find('price').text());
                return (at < bt) ? -1 : 1;
            });

            jQuery(nodez).each(function() {
                var sid = jQuery(this).attr('id');

                html += wrapTr(
                        wrapTd(jQuery(this).find('title').text(), 'stitle' + sid) +
                        wrapTd(jQuery(this).find('row').text(), 'srow' + sid) +
                        wrapTd(jQuery(this).find('spots').text(), 'sspots' + sid) +
                        wrapTd(jQuery(this).find('price').text(), 'sprice' + sid) +
                        wrapTd('<a href="#" id="clks' + sid + '" onclick="toggleSRow(\'' + sid + '\', jQuery(this)); return false;" class="fall">Развернуть</a>', 'scell' + sid, undefined, 'lst')
                        , 'srow' + sid, (pos++ % 2 == 0 ? 'line' : 'line-d'));
            });

            showSectors(html);
        }, 'xml');
    }
}

function toggleSRow(sid, elem) {
    elem.toggleClass('fall-a');

    if (sid == selectedSector) {
        selectedSector = undefined;
        jSElem = undefined;

        unloadSeats();
    } else {
        if (typeof(jSElem) != 'undefined')
            jSElem.toggleClass('fall-a');

        jSElem = elem;
        selectedSector = sid;

        seatsLoading();

        jQuery.get('/event/reserv/spots/' + id + '?sectorid=' + sid + '&indate=' + selectedIndate, undefined, function(xml) {
            var html = '';

            jQuery(xml).find('spotrow').each(function() {
                var mid = jQuery(this).attr('id');
                if (jQuery(this).attr('spotless') == 'true') {
                    jQuery('#spothead').html('кол-во мест');
                    html += wrapTr(
                            wrapTd('без мест', 'mrows', 2) +
                            wrapTd(jQuery(this).find('price').text(), 'mprice') +
                            wrapTd(jQuery(this).find('reserv').text(), 'mreserv') +
                            wrapTd(makeSelection(parseInt(jQuery(this).attr('limit')), parseInt(jQuery(this).attr('selected'))))
                            , undefined, 'line');
                } else {
                    html += wrapTr(
                            wrapTd(jQuery(this).find('row').text(), 'mrow' + mid) +
                            wrapTd(jQuery(this).find('spot').text(), 'mspot' + mid) +
                            wrapTd(jQuery(this).find('price').text(), 'mprice' + mid) +
                            wrapTd(jQuery(this).find('reserv').text(), 'mreserv' + mid) +
                            wrapTd('<input ' + (jQuery(this).attr('selected') == 'true' ? ' checked="true" ' : '') + 'type="checkbox" class="mticketbox" id="mid' + mid + '" onclick="toggleTicket(' + mid + ')" />')
                            , undefined, 'line');
                }
            });

            showSeats(html);
        }, 'xml');
    }
}

function processReservXml(xml) {
    var error = '';
    if ((error = jQuery(xml).find('error').text()) != '') {
        alert('Ошибка резервирования: ' + error);
    } /*else {
        var sum = parseFloat(jQuery(xml).find('reserv').attr('sum'));
        var quantity = parseInt(jQuery(xml).find('reserv').attr('quantity'));

        if (sum > 0) {
            jQuery('#submitrow').show();
            jQuery('#sidecostvalue').html(sum + ' руб.');
            jQuery('#sidequantityvalue').html(quantity + ' билетов');
        } else {
            jQuery('#submitrow').hide();
            jQuery('#sidecostvalue').html('0 руб.');
            jQuery('#sidequantityvalue').html('0 билетов');
        }
    }*/
}

function toggleTicket(mid) {
    if (jQuery('#mid' + mid).is(':checked')) {
        jQuery.get('/event/reserv/' + mid, undefined, function(xml) {
            processReservXml(xml);
        }, 'xml');
    } else {
        jQuery.get('/event/reserv/' + mid + '?flag=1', undefined, function(xml) {
            processReservXml(xml);
        }, 'xml');
    }
}

function toggleTickets(eventid, sectorId, indate, price) {
    var q = parseInt(jQuery('#mids').val());

    jQuery.get('/event/reserv/' + eventid + '?flag=2&indate=' + indate + '&sectorid=' + sectorId + '&quantity=' + q + '&price=' + price, undefined, function(xml) {
        var error = '';
        if ((error = jQuery(xml).find('error').text()) != '')
            alert('Ошибка резервирования: ' + error);
        else
            alert('Билеты зарезервированы');
    }, 'xml');
}

function makeSelection(limit, selected) {
    var opts = '';

    for (var i=0;i<=limit;i++)
        opts += '<option value="' + i + '"' + (selected == i ? ' selected="true"' : '') + '>' + i + '</option>';

    return '<select id="mids" onchange="toggleTickets()">' + opts + '</select>';
}

function wrapTdSimple(value, params) {
    return '<td ' + params + '>' + value + '</td>';
}

function wrapTd(value, id, colspan, cls) {
    id = (id || undefined);
    colspan = (colspan || undefined);
    cls = (cls || undefined);

    return '<td' + (typeof(id) != 'undefined' ? ' id="' + id + '"' : '') + (typeof(cls) != 'undefined' ? ' class="' + cls + '"' : '') + (typeof(colspan) != 'undefined' ? ' colspan="' + colspan + '"' : '') + '>' + value + '</td>';
}

function wrapTr(value, id, cls) {
    id = (id || undefined);
    cls = (cls || undefined);

    return '<tr' + (typeof(id) == 'undefined' ? '' : ' id="' + id + '"') + ' class="' + cls + '">' + value + '</tr>';
}

function wrapTable(value, params) {
    params = (params || undefined);

    return '<table' + (typeof(params) != 'undefined' ? ' ' + params : '') + '>' + value + '</table>';
}

var sectorsInit = '';
var seatsInit = '';

function rememberInits() {
    sectorsInit = '<tr id="rowsectorsheader">' + jQuery('#rowsectorsheader').html() + '</tr><tr id="rowsectorsloader">' + jQuery('#rowsectorsloader').html() + '</tr>';
    seatsInit = '<tr id="rowseatsheader">' + jQuery('#rowseatsheader').html() + '</tr><tr id="rowseatsloader">' + jQuery('#rowseatsloader').html() + '</tr>';
}

function showDates(html) {
    jQuery('#rowdatesloader').hide();
    jQuery('#rowdatesheader').after(html);
}

function unloadSectors() {
    jQuery('#seatscontainer').hide();
    jQuery('#sectorscontainer').hide();
}

function sectorsLoading(label) {
    if (jQuery('#seatscontainer').is(':visible'))
        jQuery('#seatscontainer').hide();

    jQuery('#sectorslabel').html(label);

    jQuery('#sectorstable').html(sectorsInit);

    jQuery('#sectorscontainer').show();
}

function showSectors(html) {
    jQuery('#rowsectorsloader').hide();
    jQuery('#rowsectorsheader').after(html);
}

function unloadSeats() {
    jQuery('#seatscontainer').hide();
    jQuery('#sidedatevalue').html('-');
}

function seatsLoading() {
    jQuery('#seatslabel').html(jQuery('#sectorslabel').html());
    jQuery('#sidedatevalue').html(jQuery('#sectorslabel').html());
    jQuery('#seatstable').html(seatsInit);

    jQuery('#seatscontainer').show();
}

function showSeats(html) {
    jQuery('#rowseatsloader').hide();
    jQuery('#rowseatsheader').after(html);
}
