function dateToArray(string){
    var s = string.split('-');
    return new Array(parseInt(s[0], 10), (parseInt(s[1], 10)), parseInt(s[2]));
}

function leadZero(n){
    return (parseInt(n, 10) < 10) ? "0" + n : n;
}

function futureDate(value){
    var d = new Date();
    d.setMilliseconds(d.getMilliseconds() + parseInt(value * 86400000, 10));
    return d.getFullYear() + '-' + leadZero(d.getMonth() + 1) + '-' + leadZero(d.getDate());
}

function selectAirportBack(code, field){
    $('#' + field).val(code);
}

function selectCityBack(code, city){
    $('#city').val(city);
    $('input[name="autoSelect"]').val("true");
    $('input[name="cityCode"]').val(code);
    closeCitySelct();
}

function closeCitySelct(){
    window.close();
}

function noenter(){
    return !(window.event && window.event.keyCode == 13);
}

function processCityNames(){
    $('#qsfFlightsForm').submit();
}

function calculateNights(ret_nights){
    var cin = dateToArray($('#cindate').val());
    var cinDate = new Date(cin[2], (cin[1] - 1), cin[0]);
    var cot = dateToArray($('#cotdate').val());
    var cotDate = new Date(cot[2], (cot[1] - 1), cot[0]);
    var dif = new Date();
    dif.setTime(cotDate.getTime() - cinDate.getTime());
    var nights = dif.getTime() / (86400 * 1000);
    if (ret_nights) {
        return nights;
    }
    else {
        return (nights >= 1 && nights <= 90) ? true : false;
    }
}

function processHotelsForm(){
    var re = new RegExp("^[0-9]{2}-[0-9]{2}-[0-9]{4}$", "i");
    var cindate = $('#cindate').val();
    var cotdate = $('#cotdate').val();
    if ($('#city').val() == '') {
        alert(txt_select_city);
        return false;
    }
    else 
        if (re.test(cindate) == false || cindate == '') {
            alert(txt_select_cindate);
            return false;
        }
        else 
            if (re.test(cotdate) == false || cotdate == '') {
                alert(txt_select_cotdate);
                return false;
            }
            else 
                if (!calculateNights()) {
                    alert(txt_calculate_nights);
                }
                else {
                    var cin = dateToArray(cindate);
                    $('input[name="cinday"]').val(cin[0]);
                    $('input[name="cinmonth"]').val(cin[1]);
                    $('input[name="cinyear"]').val(cin[2]);
                    var cot = dateToArray(cotdate);
                    $('input[name="cotday"]').val(cot[0]);
                    $('input[name="cotmonth"]').val(cot[1]);
                    $('input[name="cotyear"]').val(cot[2]);
                    $('#qsfHotelsForm').submit();
                }
}

function processCarsForm(){
    var re = new RegExp("^[0-9]{2}-[0-9]{2}-[0-9]{4}$", "i");
    var pupdate = $('#tmp_pupdate').val();
    var doffdate = $('#tmp_doffdate').val();
    if ($('#pupcity').val() == '' || $('#doffcity').val() == '') {
        alert(txt_select_city);
        return false;
    }
    else 
        if (re.test(pupdate) == false || pupdate == '') {
            alert(txt_select_cindate);
            return false;
        }
        else 
            if (re.test(doffdate) == false || doffdate == '') {
                alert(txt_select_cotdate);
                return false;
            }
            else {
                var pup = dateToArray(pupdate);
                $('input[name="pupday"]').val(pup[0]);
                $('input[name="pupmonth"]').val(pup[1] - 1);
                var doff = dateToArray(doffdate);
                $('input[name="doffday"]').val(doff[0]);
                $('input[name="doffmonth"]').val(doff[1] - 1);
                $('#qsfCarsForm').submit();
            }
}

function evalTrip(AgentId, Sprzedawca, language){
    if (document.afpForm.triptype.selectedIndex == 2) {
        processCityNames();
        var redir = (language == false || language == 'pl') ? "podroz-wieloodcinkowa.html?agentid=" + AgentId + "&triptype=MULTIPLE&do_multiprefs=yes&sysentrypoint=porch&command=flights&path=add/Progress&outhour=8&rethour=8&meta_do=do_power&externalprefs=Y&leg1fromcity=" + document.qsfFlightsForm.fromcity.value + "&leg1tocity=" + document.qsfFlightsForm.tocity.value + "&loclanguage=pl&udf_I_mb_partner_id=" + Sprzedawca : "multileg-trip.html?agentid=" + AgentId + "&triptype=MULTIPLE&do_multiprefs=yes&sysentrypoint=porch&command=flights&path=add/Progress&outhour=8&rethour=8&meta_do=do_power&externalprefs=Y&loclanguage=en&leg1fromcity=" + document.qsfFlightsForm.fromcity.value + "&leg1tocity=" + document.qsfFlightsForm.tocity.value + "&loccurrency=EUR&udf_I_mb_partner_id=" + Sprzedawca;
        window.top.location.href = redir;
    }
}

function childrenControl(obj){
    var age = '';
    for (i = 2; i <= 12; i++) {
        age += '<option value="' + i + '">' + i + '</option>';
    }
    var n = obj.val();
    $('#h-select-age').remove();
    if (n > 0) {
        $('#h-select-children').after($('<div></div>').attr('id', 'h-select-age').append($('<label></label>').text(txt_children)));
        for (i = 0; i < n; i++) {
            $('#h-select-age').append($('<select></select>').attr('name', 'children_age[0][]').html(age));
        }
    }
}

$(document).ready(function(){
    $('#outdate,#cindate').val(futureDate(10));
    $('#retdate,#cotdate').val(futureDate(37));
    var hash_raw = window.location.hash;
    var hash = (hash_raw) ? hash_raw.substr(1, parseInt(hash_raw.length)) : $('.qsfBox:first').attr('id');
    $('.qsfBox,.set-hiden').hide();
    $('a[rel=' + hash + ']').parent().addClass('selected');
    $('#' + hash).show();
    $('#qsf-tabs li a').each(function(){
        $(this).click(function(){
            $('#qsf-tabs li').removeClass('selected');
            $(this).parent().addClass('selected');
            $('.qsfBox').hide();
            var rel = $(this).attr('rel');
            $('#' + rel).show();
            return false;
        });
    });
    $('#id_children_num').change(function(){
        childrenControl($(this));
    });
    $('#id_children').click(function(){
        $('#h-select-children').parent().toggle();
        childrenControl($('#id_children_num'));
    });
    $('#id_hotnumpersons').change(function(){
        var v = $(this).val();
        if (v == 'DB' || v == 'TB') {
            $('#id_children').removeAttr('disabled')
        }
        else {
            $('#id_children').removeAttr('checked').attr('disabled', 'true')
            $('#h-select-children').parent().hide();
            childrenControl($('#id_children_num'));
        }
    });
    $('a.pop-calendar').unbind().click(function(){
        var o = $(this);
        var l = $('#' + o.attr('rev')).val();
        o.esky_calendar({
            thisInput: o.attr('rel'),
            linkedInput: o.attr('rev'),
            loop: 2,
            blockedDays: 1,
            allowSameDay: true
        });
        return false;
    });
    $('a.pop-cities').click(function(){
        esky_cities($(this));
        return false;
    });
    $('#city').change(function(){
        $('input[name="autoSelect"]').val('false');
        $('input[name="cityCode"]').val('');
    });
});

