$(function() {
    //Gestione Ui in lingua
    var lang = $("meta[http-equiv=Content-Language]").attr("content");
    
    var lang_yourbooking;
    var lang_accommodation;
    var lang_numrooms;
    var lang_price;
    var lang_numpeople;
    var lang_totals;
    var lang_remove;
    
    switch (lang)
    {
        case 'it':
            lang_yourbooking = 'La tua prenotazione';
            lang_accommodation = 'Tipologia camera';
            lang_numrooms = 'Num. camere';
            lang_price = 'Prezzo';
            lang_numpeople = 'Num. persone';
            lang_totals = 'TOTALE';
            lang_remove = 'rimuovi';
            break;
        case 'en':
            lang_yourbooking = 'Your booking';
            lang_accommodation = 'Accommodation';
            lang_numrooms = 'Num. of rooms';
            lang_price = 'Price';
            lang_numpeople = 'Num. of people';        
            lang_totals = 'TOTAL';
            lang_remove = 'remove';
            break;
    }
    
    var dpLang = lang
    if(dpLang=='en'){dpLang=''};
    
    $.datepicker.setDefaults($.datepicker.regional[dpLang]);
    $.datepicker.setDefaults({
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        minDate: 0,
        yearRange: '-02:+02',
        showOn: 'both',
        buttonImage: 'images/calendar.png',
        changeMonth: true,
        changeYear: true,
        buttonImageOnly: true
    });
    
    $("#sv_checkin").datepicker({
        onClose: function(dateText, inst) {
            if (dateText==''){
                $("#sv_checkout").datepicker('option', 'minDate','0');
            }
            else {
                var arrInDate = dateText.split('/');
                $("#sv_checkout").datepicker('option', 'minDate', new Date(arrInDate[2],arrInDate[1]-1,arrInDate[0]-0+1));
            
            }
            checkDates();
        }


    });
    $("#sv_checkout").datepicker({
        onClose: function(dateText, inst) {
            //alert (dateText);
            if (dateText==''){

                checkDates();
                return;
                
            }

            var checkInText = $("#sv_checkin").val();
            var checkinDate = getDateFromString(checkInText);
            var checkoutDate = getDateFromString(dateText);
            
            if ((!checkInText) || (checkinDate>checkoutDate)){
                var arrDate = dateText.split('/');

                $("#sv_checkin").datepicker('option', 'setDate', new Date(arrDate[2],arrDate[1]-1,arrDate[0]-0-1));
            }
            checkDates();
        }
    });

    $("#sv_datacheck").change(function(){

        if ($("#sv_datacheck").attr('checked')){
            $("#sv_checkin").val('');
            $("#sv_checkout").val('');
        }

    });

    var TotRowPrice = 0;
    var TotNumCam = 0;
    var TotPax = 0;


    $("#tabs").tabs({
        show: function(event, ui){
            /*alert(ui.index);
            if (ui.index==2){
                GmapInit();
            }
            */
        }
    });
    $('#review-link').click(function() { // bind click event to link
        $("#tabs").tabs('select', 3); // switch to third tab
        return false;
    });

    //Form Cambio date
    $('#link-setform').click(function(){
        $('#setdates-bar').show('slow');
        return false;
    });

    //Carrello: cambio pax
    $('.disp-target').change(function() { // bind click event to link

        var opselected = $(this).val();
        var arrSelected = opselected.split(',');
        var idTipo = arrSelected[0];
        var numCam = arrSelected[1];
        var notti = $('#notti').html();
        var NomeTipo = $('#'+idTipo+'-nome').html();

        var selPax = $('#pax-'+idTipo).val();
        var arrPax = selPax.split(',');

        var pax = arrPax[1];
        var price = arrPax[2];
       
        //alert('Tipologia: (' + idTipo + ') '+ NomeTipo + ' | Num. Camere: ' + numCam + '\n| Notti: ' + notti+' | Pax: '+ pax + ' | price: '+ price );

        var totPrice = notti * price * numCam;



        $('#tot-'+idTipo).html(totPrice.formatMoney(2, ',', '.'));
        $('#'+idTipo+'-rowdata').html(NomeTipo + ',' + idTipo + ',' + pax + ',' + numCam + ',' + totPrice);

        if (validRow(totPrice)) {
            $('#'+idTipo+'-add-button').show('fast');
        } else {
            $('#'+idTipo+'-add-button').hide('slow');
        }

    });

    //cambio num. camera
    $('.pax-target').change(function() { // bind click event to link

        var opselected = $(this).val();

        var arrPax = opselected.split(',');
        var idTipo = arrPax[0];
        var pax = arrPax[1];
        var price = arrPax[2];

        var notti = $('#notti').html();
        var NomeTipo = $('#'+idTipo+'-nome').html();

        var selCam = $('#disp-'+idTipo).val();

        var arrCam = selCam.split(',');
        var numCam = arrCam[1];

        //alert('Tipologia: (' + idTipo + ') '+ NomeTipo + ' | Num. Camere: ' + numCam + '\n| Notti: ' + notti+' | Pax: '+ pax + ' | price: '+ price );

        var totPrice = notti * price * numCam;
        $('#tot-'+idTipo).html(totPrice.formatMoney(2, ',', '.'));
        $('#'+idTipo+'-rowdata').html(NomeTipo + ',' + idTipo + ',' + pax + ',' + numCam + ',' + totPrice);

        if (validRow(totPrice)) {
            $('#'+idTipo+'-add-button').show('slow');
        } else {
            $('#'+idTipo+'-add-button').hide('slow');
        }
    });

    /**
     *      bottone aggiungi
     **/
    $('.book-addbutton').click(function() {
        var idTipo = $(this).attr('href');
        idTipo = idTipo.substring(1);
        var bookData = $('#'+idTipo+'-rowdata').html();
        var arrData = bookData.split(',');

        var NomeTipo = arrData[0];
        var pax = arrData[2];
        var selNumCam = arrData[3];
        var totPrice = parseFloat(arrData[4]);
        //alert('nuova camera: ' + selNumCam);
        var oldNumCam = $('#'+idTipo+'-'+arrData[2]+'-row-cam').html();
        //alert('vecchio numero: '+oldNumCam);
        if (oldNumCam==undefined){
            oldNumCam=0;
        }else{
            parseInt(oldNumCam);
        }
        //alert(oldNumCam);
        var newNumCam = parseInt(oldNumCam) + parseInt(selNumCam);
        //alert('nuovo numero: '+newNumCam);

        var oldTotPrice = $('#'+idTipo+'-'+pax+'-row-tot').html();
        if (oldTotPrice==undefined){
            oldTotPrice=0;
        }else{
            parseFloat(oldTotPrice);
        }
        var newTotPrice = totPrice+parseFloat(oldTotPrice);

        //alert(newTotPrice);


        
        //Costruisci la nuova riga!
        var rowData = '<td>'+NomeTipo+'</td>';
        rowData += '<td id="'+idTipo+'-'+pax+'-row-cam">'+newNumCam+'</td>';
        rowData += '<td>'+pax+'</td>';
        
        rowData += '<td class="numero">&euro;. '+newTotPrice.formatMoney(2, ',', '.')+'<span id="'+idTipo+'-'+pax+'-row-tot" style="display:none;">'+newTotPrice+'</span></td>';
        rowData += '<td><input type="hidden" value="'+idTipo+'" name="idtipo[]" /><input type="hidden" value="'+newNumCam+'" name="numcam[]" /><input type="hidden" value="'+pax+'" name="pax[]" />';
        rowData += '<a href="#" id="'+idTipo+'-'+pax+'-remove" class="book-rembutton"><img src="images/cart_button2.gif" />'+lang_remove+'</a></td>';

        if (validRow(newTotPrice)){

            //Costruisce i totali generali
            var totalsRow = '';
            var headRow = '';
            TotRowPrice += totPrice;
            //alert('TotRowPrice:'+TotRowPrice);
            totalsRow = '<td class="numero">'+lang_totals+'</td><td></td><td></td><td class="numero"><strong>&euro;. '+TotRowPrice.formatMoney(2, ',', '.')+'</strong></td><td><input type="hidden" name="totprice" value="'+TotRowPrice.formatMoney(2, '.', '')+'" /></td>';
            headRow = '<th>'+lang_accommodation+'</th><th>'+lang_numrooms+'</th><th>'+lang_numpeople+'</th><th class="numero">'+lang_price+'</th>';

            //aggiorna riga totali
            $('#totalsRow').html(totalsRow);
            //Aggiorna head tabella
            $('#carrello thead tr').html(headRow);
            //aggiorna intestazione
            $('#bookdata h4').html(lang_yourbooking);


            //Aggiungi / aggiorna la riga e pulsante
            $('#'+idTipo+'-'+arrData[2]+'-row').html(rowData);
            $('#book-submit').show('slow');

            //Nascondi Aggiungi
            $('#'+idTipo+'-add-button').hide('slow');

            //Aggiorna num. camere ordinabili
            var oldCam = $('#'+idTipo+'-numCam').html();
            var numCam = oldCam - arrData[3];
 
            //alert(newOptions(numCam, idTipo));
            $('#disp-'+idTipo).html(newOptions(numCam, idTipo));
            $('#'+idTipo+'-numCam').html(numCam);
            $('#tot-'+idTipo).html('0,00');
            $('#'+idTipo+'-rowdata').html(NomeTipo + ',' + idTipo + ',' + pax + ',' + numCam + ',0');




            //Aggiungi bottone rimozione riga
            $('#'+arrData[1]+'-'+pax+'-remove').click(function(){
                $('#disp-'+idTipo).html(newOptions(newNumCam, idTipo));
                $('#'+idTipo+'-numCam').html(newNumCam);
                $('#'+idTipo+'-'+pax+'-row').empty();
                TotRowPrice -= newTotPrice;
                
                if(TotRowPrice==0){
                    $('#totalsRow').empty();
                    $('#carrello thead tr').empty();
                    $('#bookdata h4').empty();
                    //Nascondi Aggiungi
                    $('#book-submit').hide('fast');
                } else {
                    totalsRow = '<td class="numero">'+lang_totals+'</td><td></td><td></td><td class="numero"><strong>&euro;. '+TotRowPrice.formatMoney(2, ',', '.')+'</strong></td><td><input type="hidden" name="totprice" value="'+TotRowPrice.formatMoney(2, '.', '')+'" /></td>';
                    $('#totalsRow').html(totalsRow);
                }
                return false;
            });
        }

        return false;
    });

    $("#svs_checkin").datepicker({
        onClose: function(dateText, inst) {
            if (dateText==''){
                $("#svs_checkout").datepicker('option', 'minDate','0');
            }
            else {
                var arrInDate = dateText.split('/');
                $("#svs_checkout").datepicker('option', 'minDate', new Date(arrInDate[2],arrInDate[1]-1,arrInDate[0]-0+1));

            }
            checkDates();
        }


    });
    $("#svs_checkout").datepicker({
        onClose: function(dateText, inst) {
            //alert (dateText);
            if (dateText==''){

                checkDates();
                return;

            }

            var checkInText = $("#svs_checkin").val();
            var checkinDate = getDateFromString(checkInText);
            var checkoutDate = getDateFromString(dateText);

            if ((!checkInText) || (checkinDate>checkoutDate)){
                var arrDate = dateText.split('/');

                $("#svs_checkin").datepicker('option', 'setDate', new Date(arrDate[2],arrDate[1]-1,arrDate[0]-0-1));
            }
            checkDates();
        }
    });
    /*
    $(function(){
        $(".gallery a[rel^='prettyPhoto']").prettyPhoto({
            theme:'facebook'
        });
    });
    */
    $('#fototab-link').click(function() { // bind click event to link
        $('#tabs').tabs('select', 1); // switch to third tab
        return false;
    });

    
});


// formatta currrency
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/number/fmt-money [v1.1]

Number.prototype.formatMoney = function(c, d, t){
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

//Valida l'aggiunta camere
function validRow(tot) {
    if((tot==undefined)||(tot==0)){
        return false;
    } else {
        return true;
    }
}
function newOptions(numCam, idTipo) {
    var strOptions='';
    for (var c=0;c<=numCam;c++) {
        strOptions += '<option value="'+idTipo+','+c+'">'+c+'</option>';
    }
    return strOptions;
}
/**
 * @param strDate as string 'dd/mm/aaaa'
 * return a javascript date object
*/
function getDateFromString(strDate){
    var arrDate = strDate.split('/');
    return new Date(arrDate[2],arrDate[1]-1,arrDate[0]);
}
function checkDates() {
    var checkOutText = $("#sv_checkout").val();
    var checkInText = $("#sv_checkin").val();

    if ((!checkInText) || (!checkOutText)) {
        $("#sv_datacheck").attr('checked', true);
    } else {
        $("#sv_datacheck").attr('checked', false);
    }
}
 
