$(document).ready(function(){
//**************************************//


// header items hover effects
$(".logo, .menu li").mouseover(function() {
    $(this).css("border-bottom", "#0a71b3 4px solid");
});

$(".logo, .menu li").mouseleave(function() {
    if ( !$(this).hasClass("menu_active") )
        $(this).css("border-bottom", "#fff 4px solid");
});
// // header items hover effects


/*
 * SLIDESHOW PAGINA BOX DETTAGLIO
 */
// check se pagina corrente e' scheda dettaglio
// in base alla classe foto-cont-home-dett

if ($("#img_big_villa_container").length > 0) {
	
// THUMBS SLIDER
var descrschedapos = 0;
var itemstot = $("#tot-img-scheda-dett").val();
var indiceitems = 1;
itemstot -= 3;
$("#thumbs-gall-dettaglio-n").click(function(){
	if (indiceitems < itemstot) {
		indiceitems++;
		descrschedapos -= 129;
		$("#thumbs-gall-dettaglio").animate({"left": descrschedapos-7}, 700);
		$("#thumbs-gall-dettaglio").animate({"left": descrschedapos+7}, 300);
		descrschedapos += 7;
	}
	else {
		$("#thumbs-gall-dettaglio").animate({"left": "0px"}, 500);
		indiceitems = 1;
		descrschedapos = 0;
	}
});
$("#thumbs-gall-dettaglio-p").click(function(){
	if (indiceitems > 1) {
		indiceitems--;
		descrschedapos += 129;
		$("#thumbs-gall-dettaglio").animate({"left": descrschedapos+7}, 700);
		$("#thumbs-gall-dettaglio").animate({"left": descrschedapos-7}, 300);
		descrschedapos -= 7;
	}
});
// FINE THUMBS SLIDER
// THUMB HOVER OPACITY
$("#thumbs-gall-dettaglio img").mouseenter(function(){
	$(this).animate({"opacity": "0.7"}, "fast");
});
$("#thumbs-gall-dettaglio img").mouseleave(function(){
	$(this).animate({"opacity": "1.0"}, "fast");
});
// FINE THUMB HOVER OPACITY
// THUMB ONCLICK MAIN IMAGE CHANGER
$("#thumbs-gall-dettaglio img").click(function(){
	url_clicked_thumb = $(this).attr("src");
	url_clicked_thumb = url_clicked_thumb.replace(/c_/, "a_");
	// preloading immagine
    var _images = [url_clicked_thumb];
    $("#img_big_villa_container img").hide();
    $.each(_images,function(e) {
    	$(new Image()).load(function() {
    		$("#img_big_villa_container img").attr("src", url_clicked_thumb);
    		$("#img_big_villa_container img").fadeIn("slow");
    	}).attr('src',this);
    });
	$("#img_big_villa_container img").attr("src", url_clicked_thumb);
});
// FINE THUMB ONCLICK MAIN IMAGE CHANGER
// THUMBS BUTTONS EVENTS CHANGER
$("#thumbs-gall-dettaglio-p").mouseenter(function(){
	$("#thumbs-gall-dettaglio-p img").attr("src", ROOT_FOLDER+"immagini/left_over.gif");
});
$("#thumbs-gall-dettaglio-p").mouseleave(function(){
	$("#thumbs-gall-dettaglio-p img").attr("src", ROOT_FOLDER+"immagini/left.gif");
});
$("#thumbs-gall-dettaglio-p").mousedown(function(){
	$("#thumbs-gall-dettaglio-p img").attr("src", ROOT_FOLDER+"immagini/left_down.gif");
});
$("#thumbs-gall-dettaglio-p").mouseup(function(){
	$("#thumbs-gall-dettaglio-p img").attr("src", ROOT_FOLDER+"immagini/left_over.gif");
});
$("#thumbs-gall-dettaglio-n").mouseenter(function(){
	$("#thumbs-gall-dettaglio-n img").attr("src", ROOT_FOLDER+"immagini/right_over.gif");
});
$("#thumbs-gall-dettaglio-n").mousedown(function(){
	$("#thumbs-gall-dettaglio-n img").attr("src", ROOT_FOLDER+"immagini/right_down.gif");
});
$("#thumbs-gall-dettaglio-n").mouseup(function(){
	$("#thumbs-gall-dettaglio-n img").attr("src", ROOT_FOLDER+"immagini/right_over.gif");
});
$("#thumbs-gall-dettaglio-n").mouseleave(function(){
	$("#thumbs-gall-dettaglio-n img").attr("src", ROOT_FOLDER+"immagini/right.gif");
});
// FINE THUMBS BUTTONS EVENTS CHANGER

}
// FINE SLIDESHOW BOX DETTAGLIO


$('#calendario .mese_cont .opzionato').click(function () { 
   showCalError(2);
});


if ($("#req_npersone").length > 0) {
    if (typeof(submittedWeeks) != "undefined") {
    if (submittedWeeks.length > 0 && submittedWeeks.length < 5) {
        for (b = 0; b < submittedWeeks.length; b++) {
            selectWeek(submittedWeeks[b], "6");
        }
    }
    }
}


if ($("#home_search_periodi_from").length > 0) {
    //filtraPeriodiHome();
    $("#home_search_periodi_from").change(function() {
        if ($("#home_search_periodi_from").val() != "%") {
            filtraPeriodiHome();
            $("#home_search_periodi_to").removeAttr("disabled");
        } else {
            $("#home_search_periodi_to").html("");
            $("#home_search_periodi_to").attr("disabled", "disabled");
        }
    });
}





var browser=(function x(){})[-5]=='x'?'FF3':(function x(){})[-6]=='x'?'FF2':/a/[-1]=='a'?'FF':'\v'=='v'?'IE':/a/.__proto__=='//'?'Saf':/s/.test(/a/.toString)?'Chr':/^function \(/.test([].sort)?'Op':'Unknown';
if (browser == "IE") {
    if (IE6 = (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) && (navigator.userAgent.toLowerCase().indexOf('msie 7') == -1))
        browser = "IE6";
}

// IE6 && FF2
if (browser == "IE6" || browser == "FF2") {
    $("#overlay2").show();
}


/** TOTALE MESI CALENDARIO **/

cal_itemstot = $("#totale_mesi_calendar").val();
cal_itemstot -= 3;
/****/

//**************************************//
});




function filtraPeriodiHome() {
    
    var pos_period_from = getPosition($("#home_search_periodi_from").val(), settimaneRicercaFrom);
    var settimane_max = 4;
    if ((settimaneRicercaFrom.length - 1) - pos_period_from < 4)
        settimane_max = (settimaneRicercaFrom.length) - pos_period_from;
        
    $("#home_search_periodi_to").html("");
    for (c = 0; c < settimane_max; c++) {
        $("#home_search_periodi_to").append("<option value='"+ settimaneRicercaTo[(pos_period_from + c)] +"'>"+ settimaneRicercaToRead[(pos_period_from + c)] +"</option>");
    }
    
}







// THUMBS SLIDER
var cal_descrschedapos = 0;
var cal_itemstot;
var cal_indiceitems = 1;

function scrollCalNext() {
	if (cal_indiceitems < cal_itemstot) {
		cal_indiceitems++;
		cal_descrschedapos -= 209;
		$("#calendario").animate({"left": cal_descrschedapos-7}, 900);
		$("#calendario").animate({"left": cal_descrschedapos+7}, 500);
		cal_descrschedapos += 7;
		
		primoMese = mesiVisibili[0];
		for (a = 0; a < 3; a++)
		    mesiVisibili[a] = primoMese + (a + 1);
	}
}

function scrollCalPrev() {
	if (cal_indiceitems > 1) {
		cal_indiceitems--;
		cal_descrschedapos += 209;
		$("#calendario").animate({"left": cal_descrschedapos+7}, 900);
		$("#calendario").animate({"left": cal_descrschedapos-7}, 500);
		cal_descrschedapos -= 7;
		
    	primoMese = mesiVisibili[0];
    	for (a = 0; a < 3; a++)
    	    mesiVisibili[a] = mesiVisibili[a] - 1;
	}
}
// // thumbs slider


// scrollCalNext();

// CALENDARIO
var selectedWeeks = new Array();

function selectWeek(weekNum, mese) {
    
    var week_classname = $('#weekn' + weekNum + ' li');
    
    if (weekNum != "" && week_classname.hasClass("disponibile") == true) {
        resetMsgCalendar();
            
        if (week_classname.hasClass("selected") == false) {
            if ((selectedWeeks.length >= 1 && selectedWeeks.length <= 3) && ((array_search((parseInt(weekNum)-1), selectedWeeks) != -1) || (array_search((parseInt(weekNum)+1), selectedWeeks) != -1))) 
            {                
                $("#calendar_message_1").hide();
                
                week_classname.addClass("selected");
                selectedWeeks.push(weekNum);
                
                addItemPreventivo();
                
                if ($(week_classname).hasClass("scroll_n_"+mese) == true && mese == mesiVisibili[2])
                    scrollCalNext();
                else if ($(week_classname).hasClass("scroll_p_"+mese) == true && mese == mesiVisibili[0])
                    scrollCalPrev();
                
                
                week_classname.each(function() {
                    if ($(this).hasClass("empty_disponibile") == true)
                        $(this).addClass("empty_selected");
                });
                
            } else if (selectedWeeks.length == 0) {
                $("#calendar_message_1").hide();
                
                week_classname.addClass("selected");

                selectedWeeks.push(weekNum);
                
                addItemPreventivo();
                
                
                if (week_classname.hasClass("scroll_n_"+mese) == true && mese == mesiVisibili[2])
                    scrollCalNext();
                else if (week_classname.hasClass("scroll_p_"+mese) == true && mese == mesiVisibili[0])
                    scrollCalPrev();                
                
                
                week_classname.each(function() {
                    if ($(this).hasClass("empty_disponibile") == true)
                        $(this).addClass("empty_selected");

                });
            } else
                $("#calendar_message_1").fadeIn();

        } else {
            if (array_search((parseInt(weekNum)+1), selectedWeeks) == -1 || array_search((parseInt(weekNum)-1), selectedWeeks) == -1) {
                
                $("#calendar_message_1").hide();
                
                week_classname.removeClass("selected");
                
                if (week_classname.hasClass("empty_selected") == true)
                    week_classname.removeClass("empty_selected");
                    
                selectedWeeks.splice(getPosition(weekNum, selectedWeeks), 1);
                addItemPreventivo();
            } else 
                $("#calendar_message_1").fadeIn();
        }
    }
}


function addItemPreventivo() {

    selectedWeeks.sort();
    $("#cont_periodi_sel_villa").hide();
    $("#periodi_sel_villa li").remove();
    
    
    try {
        var dal_primo = $("#data_inizio_" + selectedWeeks[0]).val().split("-");
        dal_primo = dal_primo[2] + "/" + dal_primo[1];
        var al_ultimo = $("#data_fine_" + selectedWeeks[(selectedWeeks.length)-1]).val().split("-");
        al_ultimo = al_ultimo[2] + "/" + al_ultimo[1];
    } catch (err) {}
    
    
    if (selectedWeeks.length > 0) {
        $("#totale_sel_villa, #nome_villa").show();
    }
    else {
        $("#totale_sel_villa, #nome_villa").hide();
    }
    
    var totale_costo = 0;
    $.each( selectedWeeks, function(i, n) {
        
        
        var costo_singola_sett = 0;
        var dal = 0;
        var al = 0;
        
        dal = $("#data_inizio_" + n).val().split("-");
        dal = dal[2] + "/" + dal[1];
        al = $("#data_fine_" + n).val().split("-");
        al = al[2] + "/" + al[1];
        
        costo_singola_sett = $("#costo_" + n).val();
        
        var lingua_hidden = $("#hidden_lingua").val();
        if (lingua_hidden == "it") {
            var i18n_dal = "Dal ";
            var i18n_al = " al ";
        }
        else {
            var i18n_dal = "From ";
            var i18n_al = " to ";
        }
        
        $("#periodi_sel_villa").append("<li class='periodo_sel_villa' id='sel"+ n +"' style='display:none;'><span>"+ i18n_dal  +" "+ dal +" "+ i18n_al  +" "+ al +"</span>"+ costo_singola_sett +" EUR <div onclick='selectWeek("+n+", 7);' style='cursor:pointer;position:absolute;right:5px;top:4px;'>X</div></li>");
        $("#cont_periodi_sel_villa").show();
        $("#periodi_sel_villa li").show();
        
        if (totale_costo == 0)
            totale_costo = costo_singola_sett;
        else
            totale_costo = ( parseFloat(totale_costo) + parseFloat(costo_singola_sett) ).toFixed(2);
        
    });
    
    
   $("#hidden_totale_costo").val(totale_costo);
   $("#hidden_totale_dal").val(dal_primo);
   $("#hidden_totale_al").val(al_ultimo);
    
    $("#totale_dal").html(dal_primo);
    $("#totale_al").html(al_ultimo);
    $("#totale_costo").html(totale_costo);
 
}


function showCalError(errorNum) {
    $("#calendar_message_2").fadeIn("slow");
}    

function resetMsgCalendar() {
    $("#calendar_messages li").each(function (){
        if ($(this).attr("id") != "calendar_message_1") {
            $(this).fadeOut("slow");
        }
    }); 
}

function highlightWeek(week_num, mese_num) { 
    if (week_num != "") {
        var hover_class_cella = $('#weekn' + week_num + ' li');
        if (hover_class_cella.hasClass("disabled") == false) {
            hover_class_cella.addClass("hover"); 
        }
    }
}

function rmHighlightWeek(week_num, mese_num) { 
    if (week_num != "") {
        var hover_class_cella = $('#weekn' + week_num + ' li');
        if (hover_class_cella.hasClass("disabled") == false){
            hover_class_cella.removeClass("hover"); 
        }
    }
}


function richiediInfo(req_url) {
    var weeksURL;
    
    if (selectedWeeks.length > 0) {
        for (i = 0; i < selectedWeeks.length; i++ ) {
            
            if (i == 0)
                weeksURL = "&weeks[]=" + selectedWeeks[i];
            else
                weeksURL = weeksURL + "&weeks[]=" + selectedWeeks[i];
            
        }
        //alert(weeksURL);
        window.location = req_url + weeksURL;
    } else
        window.location = req_url;
}


function submitInfoRequest() {

    var var_nome        = $("#req_nome").val();
    var var_cognome     = $("#req_cognome").val();
    var var_agenzia     = $("#req_agenzia").val();
    var var_email       = $("#req_email").val();
    var var_telefono    = $("#req_telefono").val();
    var var_cellulare   = $("#req_cellulare").val();
    var var_fax         = $("#req_fax").val();
    var var_contact_pref    = $("#req_contact_pref").val();
    var var_note        = $("#req_note").val();
    
    var var_tipo_feedback = $("#tipo_feedback").val();
    
    var var_totale      = "";
    var var_totale_dal  = "";
    var var_totale_al   = "";
    var var_nome_villa  = "";
    var var_id_villa    = "";
    var var_npersone    = "";
    var var_localita    = "";
    
    
    
    if (var_tipo_feedback == "rent") {
        
        var_totale      = $("#hidden_totale_costo").val();
        var_totale_dal  = $("#hidden_totale_dal").val();
        var_totale_al   = $("#hidden_totale_al").val();
        var_nome_villa  = $("#req_nome_villa").val();
        var_npersone    = $("#req_npersone").val();
        var_localita    = $("#req_localita").val();
        var_id_villa    = $("#id_villa").val();
    }
    else if (var_tipo_feedback == "sale") {
        var_nome_villa  = $("#req_nome_villa").val();
        var_localita    = $("#req_localita").val();
        var_id_villa    = $("#id_villa").val();
    }
    
    if (var_nome == "")     $("#req_nome").css({"border-color": "#ff0000", "background": "url(/immagini/exclamation.png) right 2px no-repeat"});
    else                    $("#req_nome").css({"border-color": "#ccc", "background": "none"}); scroll(0,0);
    
    if (var_cognome == "")  $("#req_cognome").css({"border-color": "#ff0000", "background": "url(/immagini/exclamation.png) right 2px no-repeat"});
    else                    $("#req_cognome").css({"border-color": "#ccc", "background": "none"}); scroll(0,0);
    
    if (var_telefono == "") $("#req_telefono").css({"border-color": "#ff0000", "background": "url(/immagini/exclamation.png) right 2px no-repeat"});
    else                    $("#req_telefono").css({"border-color": "#ccc", "background": "none"}); scroll(0,0);
    
    if (email_validate(var_email) == false)
        $("#req_email").css({"border-color": "#ff0000", "background": "url(/immagini/exclamation.png) right 2px no-repeat"});
    else
        $("#req_email").css({"border-color": "#ccc", "background": "none"}); scroll(0,0);
    
    if (var_nome != "" && var_cognome != "" && var_telefono != "" && email_validate(var_email) != false) {
        if ((var_tipo_feedback == "rent" && var_totale_dal != "" && var_totale_al != "" && var_nome_villa != "") || (var_tipo_feedback == "sale" && var_nome_villa != "") || var_tipo_feedback == 0) {
        $.post(ROOT_FOLDER+"submit_request.php", { 
            nome: var_nome, 
            cognome: var_cognome, 
            agenzia: var_agenzia, 
            email: var_email, 
            telefono: var_telefono, 
            cellulare: var_cellulare, 
            fax: var_fax, 
            npersone: var_npersone, 
            contact_pref: var_contact_pref, 
            note: var_note,
            totale: var_totale,
            totale_dal: var_totale_dal,
            totale_al: var_totale_al,
            nome_villa: var_nome_villa,
            localita: var_localita,
            tipo_feedback: var_tipo_feedback,
            id_villa: var_id_villa
        }, function(data){
            if (data == 1) {
                window.scroll(0, 0);
                $("#request_confirm").animate({"height": "toggle", "opacity": "toggle"});
                $(".req_form").fadeOut();
            }
            
        });
        } else 
            $("#calendar_message_1").fadeIn();
    }
    
}

var tipo_villa_home = 'rent';
function nascondiFormPeriodo() {
    $("#search_form_periodo").hide();
    tipo_villa_home = 'sale';
}
function mostraFormPeriodo() {
    $("#search_form_periodo").show();
    tipo_villa_home = 'rent';
}


function SubmitHomeSearch(lang) {
    var tipo_villa = tipo_villa_home;
    var period_home_from = $("#home_search_periodi_from").val();
    var period_home_to = $("#home_search_periodi_to").val();
    var localita = $("#home_search_localita").val();
    
    if (period_home_from == "%" || period_home_from == null || period_home_from == "") { period_home_from = 0; }
    if (period_home_to == "%" || period_home_to == null || period_home_to == "") { period_home_to = 0; }
    if (localita == "%") { localita = 0; }
    
    if (tipo_villa == "rent")
        window.location = ROOT_FOLDER + lang + "/rent/villas/&filter=" + period_home_from + "|" + period_home_to + "|" + localita;
    else
        window.location = ROOT_FOLDER + lang + "/sale/villas/&filter=" + localita;
}


/***** GENERIC FUNCTIONS ********/

function email_validate(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email) == false)
      return false;
}


function array_search(needle, haystack) {
    var myPosition=-1
    for (i=0;i<haystack.length;i++) {
        if (haystack[i] == needle) {
            myPosition = i;
            break;
        }
    }
    return myPosition;
}

function getPosition(needle, haystack) {
    for (var i=0; i < haystack.length; i++){ 
        if (haystack[i] == needle)
            return i;
    }
}


function explode( delimiter, string, limit ) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/explode
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

