﻿// -------------------------------------------------------------------------------------------
// Seach Generator
// -------------------------------------------------------------------------------------------

var searchRows = 1;
var cleanHtml = null;
var NRooms;
var ad = null;
var ch = null;

$(document).ready(function () {
    if (cleanHtml == null)
        cleanHtml = $("#SearchContent").html();

    NRooms = parseInt($.getUrlVar('NRooms'));
    if ($.getUrlVar('ad') && $.getUrlVar('ch')) {
        ad = $.getUrlVar('ad').split(",");
        ch = $.getUrlVar('ch').split(",");
    }

    if (!isNaN(NRooms))
        $("#select_search_rooms").val(NRooms);
    else
        $("#select_search_rooms").val(1);

    generateSearchUI(true);

});

function generateSearchUI(startUp) {
    //select_Childs
    // $("a").live("click", function () { return false; })

    var searchRooms = parseInt($("#select_search_rooms").val());
    if (ad != null && ch != null) {
        if (!isNaN(ad[0]))
            $("#searchAdults1").val(ad[0])
        if (!isNaN(ch[0]))
            $("#searchChilds1").val(ch[0])

    }

    if (searchRooms > searchRows) {
        var newRows = searchRooms - searchRows;
        if (newRows > 0) {
            for (var i = 0; i < newRows; i++) {
                searchRows++;
                var newHTML = $(cleanHtml);
                newHTML.children('.col1').text(newHTML.children('.col1').text().replace("1", searchRows));
                newHTML.attr('id', "searchRow" + searchRows);
                newHTML.find('.select_Childs').attr('id', "searchChilds" + searchRows);
                newHTML.find('.select_Adults').attr('id', "searchAdults" + searchRows);
                if (ad != null && ch != null && startUp == true) {
                    if (!isNaN(ad[i + 1]))
                        newHTML.find('.select_Adults').val(ad[i + 1]);
                    if (!isNaN(ch[i + 1]))
                        newHTML.find('.select_Childs').val(ch[i + 1]);
                }

                $("#SearchContent").append(newHTML);
            }

        }
    } else {
        var newRows = searchRooms - searchRows;

        if (newRows < 0) {
            newRows *= -1;
            for (var i = 0; i < newRows; i++) {
                searchRows--;
                $('#SearchContent .searchRow:last-child').remove();
            }
        }
    }
}

function checkSearch() {

    var search_where = $("#search_where").val();
    if (search_where == autoDefault)
        search_where = "";

    var query;
    if ($("#search_type").val() == "") {
        query = "/sugestion.aspx?Where=" + search_where + "&type=" + $("#search_type").val() + "&value=" + $("#search_value").val() + "&CheckIn=" + $("#when_check_in").val() + "&CheckOut=" + $("#when_check_out").val();
    }
    else {
        if ($("#search_type").val() == "hotel")
            query = "/details.aspx?Where=" + search_where + "&type=" + $("#search_type").val() + "&value=" + $("#search_value").val() + "&CheckIn=" + $("#when_check_in").val() + "&CheckOut=" + $("#when_check_out").val() + "&propertyID=" + $("#search_value").val();
        else
            query = "/search.aspx?Where=" + search_where + "&type=" + $("#search_type").val() + "&value=" + $("#search_value").val() + "&CheckIn=" + $("#when_check_in").val() + "&CheckOut=" + $("#when_check_out").val();

    }
    var nights = parseInt($("#search_nights").val());
    if (nights > 30) {
        showSpecialModal('#mod_Error');
        //return false;
    }
    else {
        var checkAges = true;
        jQuery.cookie('searchFilter', null);
        var NRooms = parseInt($("#select_search_rooms").val());
        var Adults = new Array();
        var Childs = new Array();
        var Ages = new Array();
        var strAge = "";
        if (NRooms >= 1) {
            for (var i = 1; i <= NRooms; i++) {
                var nAdults = parseInt($("#searchAdults" + i).val());
                var nChilds = parseInt($("#searchChilds" + i).val());
                Adults.push(nAdults);
                Childs.push(nChilds);

                var $place = $("#searchChilds" + i).parent().parent().find(".col4");
                var tempAge = new Array();
                $place.children().each(function (index) {
                    var age = parseInt($(this).val())
                    if (age == NaN)
                        checkAges = false;
                    tempAge.push(age);
                });
                Ages.push(tempAge.join(";"));
            }
            query += "&NRooms=" + NRooms + "&ad=" + Adults.toString() + "&ch=" + Childs.toString(); //  + "&ag=" + Ages.toString();

            //alert(Childs)
        }
        if (checkAges == false)
            alert("faltam idades");
        else
            window.location = query;


        //return true;
    }
}
/************************************************************************************   NEW AUTO COMPLETE ************************************************/
var StationID = "";
var tempText = "";
var searchType = "";
var searchValue = "";
function onChange() {
    if (tempText != $("#search_where").val()) {
        var d = new Date();
        tempText = $("#search_where").val();
        $("#search_value").val("");
        $("#search_type").val("");
        if ($("#search_where").val() != "") {
            $.ajax({
                url: "/util/autoComplete.ashx?maxRows=10&name_startsWith=" + tempText,
                dataType: "jsonp",
                success: function (data) {
                    var items = [];
                    //{"name":"Albufeira","uid":0,"hotelCount":39}]
                    $.each(data, function (key, val) {

                        var name = val.name
                        var regex = new RegExp(tempText, "gi");
                        if (name.length > 45)
                            name = name.substring(0, 45) + "...";
                        name = name.replace(regex, function (matched) { return "<span class='bold'>" + matched + "</span>"; });

                        items.push('<ul class="' + val.type + '" id="' + val.UID + '"><li class="col1">' + val.type + '</li><li class="col2">' + name + '</li><li class="col3">' + val.hotelCount + ' Hotéis</li></ul>');
                    });

                    // if (data.length >= 10)
                    //items.push('<ul class="more"><li><a>More Options</a></li></ul>');
                    var outHtml = items.join('');
                    $("#autoComplete").html(outHtml);
                    /*Evente*/
                    $("#autoComplete ul").hover(
                        function () {
                            $(this).addClass("over");
                        },
                        function () {
                            $(this).removeClass("over");
                        }
                    );
                    $("#autoComplete ul").click(
                        function () {
                            var text = $(this).children(".col2").text();
                            var uid = $(this).attr("id");
                            var type = $(this).children(".col1").text();
                            if (type == "city")
                                uid = text;

                            $("#search_where").val(text);
                            $("#search_type").val(type);
                            $("#search_value").val(uid);
                            $("#autoComplete").hide();

                            tempText = "";
                        }
                    );
                    var mouse_is_inside = false;

                    $('#autoComplete').hover(function () {
                        mouse_is_inside = true;
                    }, function () {
                        mouse_is_inside = false;
                    });

                    $("body").mouseup(function () {
                        if (!mouse_is_inside) $('#autoComplete').hide();
                    });


                    /* END EVENTS */
                    if (data.length <= 0) {
                        $("#autoComplete").hide();
                    }
                    else {
                        $("#autoComplete").show();
                        alignAutoComplete()
                    }

                }
            });
        }
        else {
            $("#autoComplete").hide();
        }
    }
}
function alignAutoComplete() {
    $("#autoComplete").position({
        my: "left top",
        at: "left bottom",
        of: $("#search_where"),
        collision: "none"
    });
}
$(window).resize(function () {
    alignAutoComplete()
    // $("#search_where").val(autoDefault);
});
/**/
// -------------------------------------------------------------------------------------------
// Slideshow
// -------------------------------------------------------------------------------------------

var slideshowSpeed = 8000;

$(document).ready(function () {

    if ($('#homeheader').size() > 0) {

        try {

            var activeContainer = 1;
            var currentImg = 0;
            var animating = false;

            var navigate = function (direction) {

                if (animating) {
                    return;
                }

                if (direction == "next") {
                    currentImg++;
                    if (currentImg == photos.length + 1) {
                        currentImg = 1;
                    }
                } else {
                    currentImg--;
                    if (currentImg == 0) {
                        currentImg = photos.length;
                    }
                }

                var currentContainer = activeContainer;
                if (activeContainer == 1) {
                    activeContainer = 2;
                } else {
                    activeContainer = 1;
                }

                showImage(photos[currentImg - 1], currentContainer, activeContainer);

            };

            var currentZindex = -1;
            var showImage = function (photoObject, currentContainer, activeContainer) {
                animating = true;

                currentZindex--;

                $("#headerimg" + activeContainer).css({
                    "background-image": "url(" + photoObject.image + ")",
                    "display": "block",
                    "z-index": currentZindex
                });

                $("#headerimg" + currentContainer).fadeOut(function () {
                    setTimeout(function () {
                        $("#headertxt").css({ "display": "block" });
                        animating = false;
                    }, 800);
                });

            };

            navigate("next");

            interval = setInterval(function () {
                navigate("next");
            }, slideshowSpeed);
        }
        catch (ex) { }

    }

});


// -------------------------------------------------------------------------------------------
// Cufon Replace
// -------------------------------------------------------------------------------------------   
Cufon.replace('.cufon', { hover: 'false', hoverables: { a: true, li: false} });


// -------------------------------------------------------------------------------------------
// Dom Ready
// -------------------------------------------------------------------------------------------
$(document).ready(function () {
    //imagesFx();
    promoSlider();
    selectSkins();
    getChildrens();
    browserExceptions();
    ajaxTabs();
    domReady();
    expandResults();
    bingMaps();
    //sliderRange();
    checkBoxs();    
    //autoComplete();
    roomDetails();
    searchDetail();
    faq();
    siteMap();
    imagesAlign();
    sendFriend();
    modalDialog();
    jTooltip();
    //datePicker();
    changeDate();
    prettyPhoto();
    blMap();
    blMapContacts();
    sortSearchOrders();
});


// -------------------------------------------------------------------------------------------
// Functions
// -------------------------------------------------------------------------------------------

function sortSearchOrders() {
    $('#nav .bottom ul.main li.main').hover(function () {
        $(this).children('ul.select').toggle();
        return false;
    });
}

function validatePopUpReservation() {   
    var emailError = 0;
    var numberError = 0;

    if (validateEmail() != 1 && validateNumber() != 1) {
        return true;
    } else {
        $('p.novisible').removeClass('novisible').addClass('error');
        // $('#popup_reservation li.input input').addClass('error');
        return false;
    };

    function validateNumber() {
        if ($('input#txtReservNumber').val() == "") {
            // false
            numberError = 1;
        } else {
            // true
            numberError = 0;
        }
        return numberError;
    }

    function validateEmail() {
        if ($('input#txtReservEmail').val() == "") {
            // campo de e-mail vazio 
            emailError = 1;
        } else {
            var a = $('input#txtReservEmail').val();
            var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
            if (filter.test(a)) {
                // true
                emailError = 0;
            }
            else {
                // false;
                emailError = 1;
            }
        }
        return emailError;
    }
}

/* ajaxTabs */
function ajaxTabs() {
    $("div[id^='tabs_result']").tabs({
        ajaxOptions: {
            error: function (xhr, status, index, anchor) {
                $(anchor.hash).html("Loading... Please wait!");
            }
        },
        error: function (xhr, status, index, anchor) {
            $(anchor.hash).html("Couldn't load this tab. We'll try to fix this as soon as possible. " + "If this wouldn't be a demo.");
        },
        show: function (event, ui) {
            var selected = $(this).tabs("option", "selected");
            var content = $(this).find('iframe');
            if (content!=undefined)
                content.attr("src", content.attr("src"));
        },
        cache: false,
        async: false,
        collapsible: false
    });
    $('#results .result').css('display', 'block');
};



function getData(queryArg) {
    $.ajax({
        url: '/util/resultsLoader.ashx' + queryArg,
        dataType: 'html',
        success: function (data) {
            $("#resultsContent").html(data);
            ajaxTabs();
            $('#results .result').css('display', 'block');
        }
    });
}

// domReady  
function domReady() {    
    $('#mainhome .promos').addClass('bkg');
};


// expandResults  	
function expandResults() {
   /* $('.more_options').click(
		function () {
		    $array = new Array();
		    $array = $(this).attr('class');
		    $class = $array.split(" ");
		    $second = $class[1];
		    $third = $class[2];
		    if ($(this).html() != $(this).attr('rel')) { $('.tab_resume .footer .' + $third).html($(this).attr('rel')); }
		    else { $('.tab_resume .footer .' + $third).html($(this).attr('name')); }
		    $('#' + $third + ' #' + $second + ' .hide').toggle();
		    return false;
		}
	);*/
};

function sendAfriend() {
    var url = "";
    $('#mod_send_friend .top input').each(function () {
        if (isEmail($(this).val())) {
            url += ($(this).val() + ",");
        }
    });
    var hashes = "&" + window.location.href.slice(window.location.href.indexOf('?') + 1);
    if (url != "") {
        var link = '/ajax/sendEmailToFriend.aspx?email=' + url + hashes + '&iframe=true&width=508&height=255';
        $.prettyPhoto.open(link, 'Title', 'Description');
    }
}

function isEmail(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (reg.test(email) == false) {
        return false;
    }
    else
        return true;
}

// bingMaps
function bingMaps() {

    var compatScriptURL = "https://dev.virtualearth.net/mapcontrol/v6.3/js/atlascompat.js";
    var mapScriptURL = "https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3&mkt=pt-PT";
    var callback;

    var methods = {
        Load: function () {
            // Check if the script is already loaded
            try {
                if (VEMap) {
                    return this;
                }
            } catch (e) { }

            if (!($.browser.msie)) {
                // Ensure other browsers will be compatible to the map script
                jQuery.ajaxSetup({ cache: true });

                $.getScript(compatScriptURL, function () {
                    methods.LoadMapScript(callback);
                });

                return this;
            } else {
                methods.LoadMapScript(callback);
            }
        },
        LoadMapScript: function () {
            jQuery.ajaxSetup({ cache: true });
            $.getScript(mapScriptURL, callback);

            return this;
        }
    };

    $.fn.BingMap = function (method) {
        callback = method;
        return methods['Load'].call(this);
    };

    $('.btn_map a').click(function () {
        $(this).toggleClass('expanded');
        $("#map").BingMap(function () {
            var map = new VEMap("map");
            map.LoadMap();
            //alert("MAP");
            var geoHotel = new VEShapeLayer();
            var geoHotelLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, "/util/geoHotel.ashx" + location.search, geoHotel);
            map.ImportShapeLayerData(geoHotelLayerSpec, onGeoHotel, true);

            function onGeoHotel(layer) {
                var options = new VEClusteringOptions();
                var customIcon = new VECustomIconSpecification();
                customIcon.Image = "/images/png/bl-map-icon.png";
                options.Icon = customIcon;

                layer.SetClusteringConfiguration(VEClusteringType.Grid, options);
                options.Callback = clusteringCallback;

                var numShapes = layer.GetShapeCount();
                for (var i = 0; i < numShapes; ++i) {
                    var s = layer.GetShapeByIndex(i);
                    s.links = "";
                    s.SetCustomIcon("/images/png/bl-map-icon.png");
                }
                function clusteringCallback(clusters) {
                    for (var i = 0; i < clusters.length; ++i) {
                        var cluster = clusters[i];
                        var clusterShape = cluster.GetClusterShape();
                        clusterShape.SetTitle("Booking Lisboa");
                        clusterShape.SetDescription("Foram encontrados <b>" + cluster.Shapes.length + " hoteis</b> nesta zona. <br/><br/> Por favor faça zoom para ver mais informações");
                    }
                }
            }
            //$("#map").append('<span class="mask"></span>');
        });
        $('.wrap_map').slideToggle('normal', function () {
            $("head").append($("<link rel='stylesheet' href='/includes/css/maps.css?reload='" + new Date().getTime() + " type='text/css' media='screen' />"));
        });
        return false;
    });

    $('.navigation .view_map a').click(function () {
        $('.wrap_map').slideToggle('normal', function () {
            var content = $('#iMap');
            if (content != undefined)
                content.attr("src", content.attr("src"));
        });
        return false;
    });
}


// selectSkins  
function selectSkins() {
    try {        
      /*  $("#mainhome .select_search_rooms").msDropDown({ mainCSS: 'dd2' });*/
        $(".select_rooms_number, .my-cc-validate-month").msDropDown({ mainCSS: 'dd3' });
        $(".change_search_rooms").msDropDown({ mainCSS: 'dd4' });
        $(".select-myinfo-country, .select-my-cc-type").msDropDown({ mainCSS: 'dd5' });
        $(".my-cc-validate-year").msDropDown({ mainCSS: 'dd6' });
        $(".select-area-maps").msDropDown({ mainCSS: 'dd7' });
    } catch (e) { }
}


// checkBoxs
function checkBoxs() {
    $("#check-search-types").change(function () {
        if (this.checked) {
            v = true;
            $('ul.advanced').fadeIn();
        } else {
            v = false;
            $('ul.advanced').hide();
        }
    });
};


// Autocomplete
function autoComplete() {
    $(function () {
        function log(message) {
            $("<div/>").text(message).prependTo("#log");
            $("#log").scrollTop(0);
        }

        $("#search_where").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/util/autoComplete.ashx",
                    dataType: "jsonp",
                    data: {
                        maxRows: 50,
                        name_startsWith: request.term
                    },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.name,
                                value: item.name
                            }
                        }));
                    }
                })
            },
            minLength: 0,
            select: function (event, ui) {
                log(ui.item ?
					"Selected: " + ui.item.label :
					"Nothing selected, input was " + this.value);
            },
            open: function () {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function () {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
            }
        });
    });

    /*$('#search_where').click(function() {
    $(this).toggleClass('preloader');
    $('div.autosugest').slideToggle();
    }); 
    $('.autosugest li').hover(function() {
    $(this).toggleClass('hover');
    });  */
};


// Childs
function getChildrens() {
    function getChild($class, $pos, $add, $clear, $separator) {
        $num_divs = $($class).length;
        $i = 1;
        for ($i; $i <= $num_divs; $i++) {
            if ($i % $pos == 0) {
                $($class).eq($i - 1).addClass($add);
                if ($clear == 1) {
                    $('<div class="clear"></div>').insertAfter($($class).eq($i - 1));
                }
                if ($separator == 1) {
                    $('<div class="separator"></div>').insertAfter($($class).eq($i - 1));
                }
            }

        }
    }
    try { getChild('#search .persons .wrap', 2, 'nomarginright', 1, 0); } catch (e) { }
    try { getChild('#shopping .small_preview img', 5, 'nomarginright', 1, 0); } catch (e) { }
    try { getChild('#room_detail .small_preview img', 5, 'nomarginright', 1, 0); } catch (e) { }
    try { getChild('#hotel_amenities li', 3, 'last', 0, 0); } catch (e) { }
    $('#detail .checkboxs').each(function () { $(this).parent().children().find('li:last').addClass('nomarginbottom'); });
    $('#room_detail .prices .room .result').each(function () { $(this).parent().children().find('ul.row:last').css({ 'background-image': 'none' }); });
    $('#book .my_room_policies .room:last').css({ 'background-image': 'none' });
    $('.terms .item:last').css({ 'background-image': 'none', 'padding-bottom': '10px' });
    $('.faq .item:last').css({ 'background-image': 'none', 'padding-bottom': '0px' });
    $('#book .my_creditcard ul.left li.label').eq(2).css('line-height', '13px');
    $('#book .block:last').addClass('nobkgimg');
};


// Room Details
function roomDetails() {
    $('#room_detail .prices .room .result ul.column li.more a').click(function () {
        $(this).toggleClass('pink');
        $this_id = $(this).attr('id');
        $array = new Array();
        $array = $this_id;
        $string = $array.split('-');
        $id = $string[1];
        $('#roomdetails-' + $id).slideToggle();
        $('#roomdetails-' + $id).parent().find('.cb').toggleClass('bkgbottom')
        return false;
    });
};


// Browser Exceptions 
function browserExceptions() {

    function detectBrowserVersion() {

        var userAgent = navigator.userAgent.toLowerCase();
        $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
        var version = 0;

        // Is this a version of IE?
        if ($.browser.msie) {
            userAgent = $.browser.version;
            userAgent = userAgent.substring(0, userAgent.indexOf('.'));
            version = userAgent;
            name = 'internet explorer';           
        }

        // Is this a version of Chrome?
        if ($.browser.chrome) {
            userAgent = userAgent.substring(userAgent.indexOf('chrome/') + 7);
            userAgent = userAgent.substring(0, userAgent.indexOf('.'));
            version = userAgent;
            // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
            $.browser.safari = false;
            name = 'chrome';
        }

        // Is this a version of Safari?
        if ($.browser.safari) {
            userAgent = userAgent.substring(userAgent.indexOf('safari/') + 7);
            userAgent = userAgent.substring(0, userAgent.indexOf('.'));
            version = userAgent;
            name = 'safari';
        }

        // Is this a version of Mozilla?
        if ($.browser.mozilla) {
            //Is it Firefox?
            if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
                userAgent = userAgent.substring(userAgent.indexOf('firefox/') + 8);
                userAgent = userAgent.substring(0, userAgent.indexOf('.'));
                version = userAgent;
                name = 'mozilla';
            }
            // If not then it must be another Mozilla
            else { }

        }

        // Is this a version of Opera?
        if ($.browser.opera) {
            userAgent = userAgent.substring(userAgent.indexOf('version/') + 8);
            userAgent = userAgent.substring(0, userAgent.indexOf('.'));
            version = userAgent;
            name = 'opera';

        }
        return name;

    }

    $browser_version = detectBrowserVersion();

    if ($browser_version == "chrome" || $browser_version == "safari") {
        try{
        $('#book .my_info input, #book .my_requests input, #book .my_rooms input, #book .my_creditcard input, #mod_send_friend input').addClass('webkit');
        $('#mainhome .search .webkit').css({ 'position': 'relative', 'top': '2px' });
        }catch(e){}
    }

    if ($browser_version == "mozilla" || $browser_version == "opera") {
        $('#popup_reservation .input input, #book .my_info input, #mod_send_friend ul.top input').css('padding', '6px 6px 4px 6px');
        $('#contacts .contactform .text input').css('padding', '0px 6px 0px 6px');
        // addthis bug
        try {
            $(window).resize(function () {
                if ($(window).width() < 1100) {
                    $('body').css('overflow-x', 'visible');
                } else {
                    $('body').css('overflow-x', 'hidden');
                }
            });
            $('body').css('overflow-x', 'hidden');
        } catch (e) { }
    }
};

/* Accordion Policies */
$(document).ready(function () {
    $('.room_policies .item > h3').click(function () {
        $(this).toggleClass('open');
        $(this).next('.editor').slideToggle('normal');
        $(this).parent().siblings('.item').children('.editor:visible').slideUp('normal')
			.parent('.item').find('h3').removeClass('open');
        return false;
    });
});


// Accordion Search Detail	
function searchDetail() {
    $('#detail .pane .title > h3').click(function () {
        $(this).parent().next('.content').slideToggle();
        return false;
    });
};


// Accordion FAQ	
function faq() {
    $('.faq .item h3.title').click(function () {
        $(this).toggleClass('open').toggleClass('close');
        $(this).next('.editor').slideToggle('normal');
        $(this).parent().siblings('.item').children('.editor:visible').slideUp('normal')
			.parent('.item').find('h3.title').removeClass('open');
        return false;
    });
};


// Accordion Sitemap	
function siteMap() {
    $('.sitemap .item h3.title').click(function () {
        $(this).toggleClass('open').toggleClass('close');
        $(this).next('ul').slideToggle('normal');
        return false;
    });
};


// Images Align
function imagesAlign() {
    $('.editor img').each(function () {
        if (
			$(this).css('float') == 'left') {
            $(this).addClass('align_left');
        }
        if ($(this).css('float') == 'right') {
            $(this).addClass('align_right');
        }
    });
};


// Send to a Friend	
function sendFriend() {
    $('#mod_send_friend .remove').live("click", function () {
        $('li#' + $(this).attr('id')).remove();
        return false;
    });
    $('#mod_send_friend ul.bottom li.add a:first').click(function () {
        $array = new Array();
        $array = $('#mod_send_friend ul.top li input:last').attr('id');
        $class = $array.split("-");
        $inputId = parseInt($class[2]) + 1;
        $('#mod_send_friend ul.top').append('<li id="send-friend-' + $inputId + '"><input type="text" name="send-friend-' + $inputId + '" id="send-friend-' + $inputId + '" value="" onfocus="_clear(this);" onblur="_check(this);"/><a href="javascript:void(0);" class="remove" id="send-friend-' + $inputId + '">Remove</a></li>');
        return false;
    });
};


// Modal Dialog
function modalDialog() {
    // contactform
    $('#fullwidth .submit input[type="submit"]').click(function (event) {
        showModal();
    }); 

};

function showModal() {
    // coords
    scrollX = document.documentElement.scrollLeft;

    if ($browser_version == "chrome" || $browser_version == "safari") {
        scrollY = document.body.scrollTop;
    } else {
        scrollY = document.documentElement.scrollTop;
    }

    // overlay
    $('.md_overlay').css('height', $(document).height()).fadeIn('fast');

    $('body').css('overflow-x', 'hidden');

    // align
    alignModal('#mod_dialog', scrollX, scrollY);

    // keycode
    $(window).keypress(function (event) {
        if (event.keyCode == '27') {
            $('#mod_dialog').fadeOut(500);
            $('.md_overlay').fadeOut(500);
            $('body').css('overflow-x', 'visible');
            return false;
        }
    });

    // vertical align
    function alignModal($selector, scrollX, scrollY) {

        $modal = $($selector);
        $x = ($(window).width() / 2) - ($modal.width() / 2);
        $y = scrollY + ($(window).height() / 2) - ($modal.height() / 2);
        $modal.css({ 'top': $y, 'left': $x }).delay(250).fadeIn('fast');

    }

    // close btns
    $('#mod_dialog .close a, #mod_dialog .footer input, #mod_dialog .top ul li.close a, #mod_dialog .btn_ok_pt').click(function () {

        $('#mod_dialog').fadeOut(250);
        $('.md_overlay').fadeOut(250);
        //		$('body').css('overflow-x','visible');

    });

    // align btns
    $a = 0;
    $b = 0;
    $dist = 0;
    $num_btns = $('#mod_dialog .footer input').size();

    for ($i = 0; $i < $num_btns; $i++) {
        $a = $a + $('#mod_dialog .footer input').eq($i).width();
    }

    $b = $('#mod_dialog .footer').width();

    if ($num_btns > 1) {
        $dist = ($b * 0.5) - ($a * 0.5) - 5;
    } else {
        $dist = ($b * 0.5) - ($a * 0.5);
    }

    $('#mod_dialog .footer input').eq(0).css({ 'margin-left': $dist });


}






function showSpecialModal(selector) {

    var selectorID = selector;

    // coords
    scrollX = document.documentElement.scrollLeft;

    if ($browser_version == "chrome" || $browser_version == "safari") {
        scrollY = document.body.scrollTop;
    } else {
        scrollY = document.documentElement.scrollTop;
    }

    // overlay
    $('.md_overlay').css('height', $(document).height()).fadeIn('fast');

    $('body').css('overflow-x', 'hidden');

    // align
    alignModal(selectorID, scrollX, scrollY);

    // keycode
    $(window).keypress(function (event) {
        if (event.keyCode == '27') {
            $(selectorID).fadeOut(500);
            $('.md_overlay').fadeOut(500);
            $('body').css('overflow-x', 'visible');
            return false;
        }
    });

    // vertical align
    function alignModal($selector, scrollX, scrollY) {

        $modal = $($selector);
        $x = ($(window).width() / 2) - ($modal.width() / 2);
        $y = scrollY + ($(window).height() / 2) - ($modal.height() / 2);
        $modal.css({ 'top': $y, 'left': $x }).delay(250).fadeIn('fast');

    }

    // close btns
    $(selector + ' .close a, ' + selectorID + ' .footer input, ' + selectorID + ' .top ul li.close a, ' + selectorID + ' .btn_ok_pt').click(function () {

        $(selector).fadeOut(250);
        $('.md_overlay').fadeOut(250);
        //		$('body').css('overflow-x','visible');

    });

    // align btns
    $a = 0;
    $b = 0;
    $dist = 0;
    $num_btns = $(selectorID + ' .footer input').size();

    for ($i = 0; $i < $num_btns; $i++) {
        $a = $a + $(selectorID + ' .footer input').eq($i).width();
    }

    $b = $(selectorID + ' .footer').width();

    if ($num_btns > 1) {
        $dist = ($b * 0.5) - ($a * 0.5) - 5;
    } else {
        $dist = ($b * 0.5) - ($a * 0.5);
    }

    $(selectorID + ' .footer input').eq(0).css({ 'margin-left': $dist });


}

// Tooltip	
function jTooltip() {
    function simple_tooltip(target_items, name, type) {

        $(target_items).each(function () {
            var my_tooltip = $(name);

            if (type == "text") {

                $(this).mouseover(function () {

                    if ($.browser.msie = "true" && $.browser.version == "7.0") { $('html').addClass('overflow-x'); }

                    $segundos = 0;
                    $timer = 0;
                    contador();

                    function contador() {
                        $segundos = setTimeout(function () { contador(); }, 1000);
                        $timer = $timer + 1;
                        if ($timer == 2) {
                            my_tooltip.fadeIn('normal');
                            clearTimeout($segundos);
                        }
                    }

                }).mousemove(function (kmouse) {
                    var border_top = $(window).scrollTop();
                    var border_right = $(window).width();
                    var left_pos;
                    var top_pos;
                    var offset = 0;

                    if (border_right - (offset * 2) >= my_tooltip.width() + kmouse.pageX) {
                        left_pos = kmouse.pageX + offset;
                    } else {
                        left_pos = border_right - my_tooltip.width() - offset;
                    }

                    if (border_top + (offset * 2) >= kmouse.pageY - my_tooltip.height()) {
                        top_pos = border_top + offset;
                    } else {
                        top_pos = kmouse.pageY - my_tooltip.height() - offset;
                    }
                    my_tooltip.css({ left: left_pos, top: top_pos });
                    $('.tooltip_fav').hover(
						function () {
						    my_tooltip.show();
						},
						function () {
						    my_tooltip.fadeOut('normal');
						    clearTimeout($segundos);
						}
					);
                }).mouseout(function () {
                    clearTimeout($segundos);
                    my_tooltip.hide();
                    if ($.browser.msie = "true" && $.browser.version == "7.0") { $('html').removeClass('overflow-x'); }
                });
            }
        });
    }
    try {
        simple_tooltip(".info_tooltip", ".tooltip_fav", "text");

        $(function () {
            $('.tooltip_fav .middle ul .delete a').click(function () {
                $(this).closest('ul').fadeOut('slow').remove();
                $num_hotels = $('.tooltip_fav .middle ul').size();
                $('.fav_number').html('(' + $num_hotels + ')');
                if ($num_hotels == 0) {
                    $('.tooltip_fav .no_fav').fadeIn('normal');
                }
                return false;
            });
            $num_hotels = $('.tooltip_fav .middle ul').size();
            $('.fav_number').append('(' + $num_hotels + ')');
        });
    } catch (e) { }
};


// Datepicker
$(document).ready(function () {
    try {
        $(function () {

            // sidebar
            /*var dates_sidebar = $( "#when-check-in, #when-check-out").datepicker({
            minDate: 0, maxDate: "+1Y",
            dateFormat: 'dd/mm/yy',
            changeMonth: false,
            numberOfMonths: 2
            });
            */
            $('#search li.check li.left a').click(function () {
                $("#when_check_in").datepicker("show");
            });

            $('#search li.check li.center a').click(function () {
                $("#when_check_out").datepicker("show");
            });

            $('#mainhome .search ul.when a:first').click(function () {
                $("#when_check_in").datepicker("show");
            });
            $('#mainhome .search ul.when a:last').click(function () {
                $("#when_check_out").datepicker("show");
            });

            var tomorrow = new Date();
            var startDate = new Date();

            var tomorrow_change = new Date();
            var oneDay = 24 * 60 * 60 * 1000;
            var diffDays = 1;
            var newDate = new Date();
            var dates_sidebar = $("#when_check_in, #when_check_out").datepicker({
                dateFormat: "dd-mm-yy",
                minDate: 0, maxDate: "+1Y",
                changeMonth: false,
                numberOfMonths: 2,

                onSelect: function (selectedDate) {
                    var option = this.id == "when_check_in" ? "minDate" : "maxDate",
					instance = $(this).data("datepicker"),
					date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);

                    if (option == "minDate") {
                        startDate = new Date(date.getTime());
                        if (Math.ceil((newDate.getTime() - startDate.getTime()) / (oneDay)) < 1) {
                            tomorrow = new Date(date.getTime());
                            tomorrow.setDate(tomorrow.getDate() + 1);
                            var month = tomorrow.getMonth() + 1;
                            var day = tomorrow.getDate();
                            var year = tomorrow.getFullYear();
                            newDate = $.datepicker.parseDate(instance.settings.dateFormat, day + "-" + month + "-" + year);
                        }
                        else {
                            var tempDate = new Date(date.getTime());
                            tempDate.setDate(tempDate.getDate() + 1);
                            var month = tempDate.getMonth() + 1;
                            var day = tempDate.getDate();
                            var year = tempDate.getFullYear();
                            newDate = $.datepicker.parseDate(instance.settings.dateFormat, day + "-" + month + "-" + year);
                        }

                        dates_sidebar.not(this).datepicker("option", option, newDate);
                    }

                    if (option == "maxDate") {
                        tomorrow = date;
                    }
                    // diffDays = Math.ceil((tomorrow.getTime() - startDate.getTime()) / (oneDay));
                    var sDate = $.datepicker.parseDate(instance.settings.dateFormat, $("#when_check_in").val());
                    var eDate = $.datepicker.parseDate(instance.settings.dateFormat, $("#when_check_out").val());
                    diffDays = Math.ceil((eDate.getTime() - sDate.getTime()) / (oneDay));
                    $("#search_nights").val(diffDays);
                    $("#search_nights").val(diffDays);
                }
            })

            var dates_change = $("#change_checkin, #change_checkout").datepicker({
                dateFormat: "dd-mm-yy",
                minDate: 0, maxDate: "+1Y",
                changeMonth: false,
                numberOfMonths: 2,

                onSelect: function (selectedDate) {
                    var option = this.id == "change_checkin" ? "minDate" : "maxDate",
					instance = $(this).data("datepicker"),
					date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);

                    if (option == "minDate") {
                        startDate = new Date(date.getTime());
                        if (Math.ceil((newDate.getTime() - startDate.getTime()) / (oneDay)) < 1) {
                            tomorrow = new Date(date.getTime());
                            tomorrow.setDate(tomorrow.getDate() + 1);
                            var month = tomorrow.getMonth() + 1;
                            var day = tomorrow.getDate();
                            var year = tomorrow.getFullYear();
                            newDate = $.datepicker.parseDate(instance.settings.dateFormat, day + "-" + month + "-" + year);
                        }
                        else {
                            var tempDate = new Date(date.getTime());
                            tempDate.setDate(tempDate.getDate() + 1);
                            var month = tempDate.getMonth() + 1;
                            var day = tempDate.getDate();
                            var year = tempDate.getFullYear();
                            newDate = $.datepicker.parseDate(instance.settings.dateFormat, day + "-" + month + "-" + year);
                        }

                        dates_change.not(this).datepicker("option", option, newDate);
                    }

                    if (option == "maxDate") {
                        tomorrow = date;
                    }
                    diffDays = Math.ceil((tomorrow.getTime() - startDate.getTime()) / (oneDay));
                    // $("#search_nights").val(diffDays);
                }
            })

            /* var dates_sidebar = $("#when_check_in, #when_check_out").datepicker({
            dateFormat: "dd-mm-yy",
            minDate: 0, maxDate: "+1Y",
            changeMonth: false,
            numberOfMonths: 2,

            onSelect: function (selectedDate) {
            var option = this.id == "when_check_in" ? "minDate" : "maxDate",
            instance = $(this).data("datepicker"),
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);

            if (option == "minDate") {
            startDate = new Date(date.getTime());
            if (Math.ceil((newDate.getTime() - startDate.getTime()) / (oneDay)) < 1) {
            tomorrow = new Date(date.getTime());
            tomorrow.setDate(tomorrow.getDate() + 1);
            var month = tomorrow.getMonth() + 1;
            var day = tomorrow.getDate();
            var year = tomorrow.getFullYear();
            newDate = $.datepicker.parseDate(instance.settings.dateFormat, day + "-" + month + "-" + year);
            }
            else {
            var tempDate = new Date(date.getTime());
            tempDate.setDate(tempDate.getDate() + 1);
            var month = tempDate.getMonth() + 1;
            var day = tempDate.getDate();
            var year = tempDate.getFullYear();
            newDate = $.datepicker.parseDate(instance.settings.dateFormat, day + "-" + month + "-" + year);
            }

            dates_sidebar.not(this).datepicker("option", option, newDate);
            }

            if (option == "maxDate") {
            tomorrow = date;
            }
            var sDate = $.datepicker.parseDate(instance.settings.dateFormat, $("#when_check_in").val());
            var eDate = $.datepicker.parseDate(instance.settings.dateFormat, $("#when_check_out").val());
            diffDays = Math.ceil((eDate.getTime() - sDate.getTime()) / (oneDay));
            $("#search_nights").val(diffDays);
            }
            })
            var dates_sidebar = $("#change_checkin, #change_checkout").datepicker({
            dateFormat: "dd-mm-yy",
            minDate: 0, maxDate: "+1Y",
            changeMonth: false,
            numberOfMonths: 2,

            onSelect: function (selectedDate) {
            var option = this.id == "change_checkin" ? "minDate" : "maxDate",
            instance = $(this).data("datepicker"),
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);

            if (option == "minDate") {
            startDate = new Date(date.getTime());
            if (Math.ceil((newDate.getTime() - startDate.getTime()) / (oneDay)) < 1) {
            tomorrow = new Date(date.getTime());
            tomorrow.setDate(tomorrow.getDate() + 1);
            var month = tomorrow.getMonth() + 1;
            var day = tomorrow.getDate();
            var year = tomorrow.getFullYear();
            newDate = $.datepicker.parseDate(instance.settings.dateFormat, day + "-" + month + "-" + year);
            }
            else {
            var tempDate = new Date(date.getTime());
            tempDate.setDate(tempDate.getDate() + 1);
            var month = tempDate.getMonth() + 1;
            var day = tempDate.getDate();
            var year = tempDate.getFullYear();
            newDate = $.datepicker.parseDate(instance.settings.dateFormat, day + "-" + month + "-" + year);
            }

            dates_sidebar.not(this).datepicker("option", option, newDate);
            }

            if (option == "maxDate") {
            tomorrow = date;
            }
            var sDate = $.datepicker.parseDate(instance.settings.dateFormat, $("#when_check_in").val());
            var eDate = $.datepicker.parseDate(instance.settings.dateFormat, $("#when_check_out").val());
            diffDays = Math.ceil((eDate.getTime() - sDate.getTime()) / (oneDay));
            // $("#search_nights").val(diffDays);
            }
            })/*
            var dates_sidebar = $("#when_check_in, #when_check_out").datepicker({
            dateFormat: "dd-mm-yy",
            minDate: 0, maxDate: "+1Y",
            changeMonth: false,
            numberOfMonths: 2,

            onSelect: function (selectedDate) {
            var option = this.id == "when_check_in" ? "minDate" : "maxDate",
            instance = $(this).data("datepicker"),
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);

            if (option == "minDate") {
            startDate = new Date(date.getTime());
            if (Math.ceil((newDate.getTime() - startDate.getTime()) / (oneDay)) < 1) {
            tomorrow = new Date(date.getTime());
            tomorrow.setDate(tomorrow.getDate() + 1);
            var month = tomorrow.getMonth() + 1;
            var day = tomorrow.getDate();
            var year = tomorrow.getFullYear();
            newDate = $.datepicker.parseDate(instance.settings.dateFormat, day + "-" + month + "-" + year);
            }
            else {
            var tempDate = new Date(date.getTime());
            tempDate.setDate(tempDate.getDate() + 1);
            var month = tempDate.getMonth() + 1;
            var day = tempDate.getDate();
            var year = tempDate.getFullYear();
            newDate = $.datepicker.parseDate(instance.settings.dateFormat, day + "-" + month + "-" + year);
            }

            dates_sidebar.not(this).datepicker("option", option, newDate);
            }

            if (option == "maxDate") {
            tomorrow = date;
            }
            diffDays = Math.ceil((tomorrow.getTime() - startDate.getTime()) / (oneDay));
            $("#search_nights").val(diffDays);
            }

            });*/
        });
    } catch (e) { }

    /*	$(".ui-datepicker-today").live("click", function(){
    $(this).siblings().children('a').addClass('test');	
    });		*/
});


// Change Date
function changeDate() {
    $('#room_detail .prices .room .heading .right a').click(function () {
        $(this).toggleClass('active');
        $array = new Array();
        $array = $(this).attr('id');
        $class = $array.split("-");
        $second = $class[1];
        $('#room_detail #changedate-' + $second).slideToggle();
        return false;
    });
    try {
        $('.select_change_nights').each(function () {
            $alpha_array = new Array();
            $alpha_array = $(this).attr('class');
            $alpha_status = $alpha_array.split(" ");
            $alpha_element = $alpha_status[1];
            if ($alpha_element == "alpha") {
                $alpha_id_array = new Array();
                $alpha_id_array = $(this).attr('id');
                $alpha_id_status = $alpha_id_array.split("_");
                $alpha_id_element = $alpha_id_status[2];
                $('#select_nights_' + $alpha_id_element + '_title').addClass('alpha');
            }
        });
    } catch (e) { }
};


// Clear
function _clear(t) {
    if (t._Temp == "" || t._Temp == null || t._Temp == undefined) {
        t._Temp = t.value;
    }
    if (t.value == t._Temp) {
        t.value = "";
    }
}
function _check(t) {
    if (t.value == "" || t.value == null && t.value != t._Temp) {
        t.value = t._Temp;
    }
}

// Gallery
$(function () {

    $number_of_thumbs = $('.gallery .small_preview img').size();

    if ($number_of_thumbs > 0) {

        $(function () {

            $segundos = 0;
            clearTimeout($segundos);
            var timer = 0;
            $i = 0;

            contador();

            function contador() {

                $segundos = setTimeout(function () { contador(); }, 1000);
                timer = timer + 1;


                if (timer == 6) {
                    $i = $i + 1;
                    // change to first photo 
                    if ($i == $number_of_thumbs) { $i = 0; }

                    $url = $('.gallery .small_preview img').eq($i).attr('name');
                    $('.gallery .big_preview img').fadeOut(250, function () {
                        // complete
                        $(this).remove();
                        var item = $('<img src="' + $url + '" title="" width="264" height="194"/>').hide();
                        $('.gallery .big_preview li').append(item);
                        item.show();
                    });

                    timer = 0;

                    clearTimeout($segundos);
                    contador();
                }

                // click on thumbnail
                $('.gallery .small_preview img').click(function (event) {

                    event.preventDefault();

                    $url = $(this).attr('name');
                    $('.gallery .big_preview img').remove();
                    $('.gallery .big_preview li').append('<img src="' + $url + '" title="" width="264" height="194"/>').show();
                    timer = 10;
                    $i = $(this).attr('rel');

                    clearTimeout($segundos);

                    return false;

                });
            }
        });
    }
});


// Prettyphoto
function prettyPhoto() {
    try {
        $("a[rel^='prettyPhoto']").prettyPhoto();
    } catch (e) { }
};


// Promotions Slider
function promoSlider() {
    try {
        $('.promos #slider').nivoSlider({
            effect: 'fade',
            slices: 12,
            animSpeed: 250,
            pauseTime: 8000,
            startSlide: 0,
            directionNav: true,
            directionNavHide: false,
            controlNav: false,
            controlNavThumbs: false,
            controlNavThumbsFromRel: false,
            controlNavThumbsSearch: '.jpg',
            controlNavThumbsReplace: '_thumb.jpg',
            keyboardNav: false,
            pauseOnHover: true,
            manualAdvance: false,
            captionOpacity: 1,
            prevText: 'Prev',
            nextText: 'Next',
            beforeChange: function () { },
            afterChange: function () { },
            slideshowEnd: function () { },
            lastSlide: function () { },
            afterLoad: function () { }
        });
    } catch (e) { }
};


// BL Map
function blMap() {
    $(window).load(function () {
        try {
            //GetBlMap();
          //  $("#bl_map").append('<span class="mask"></span>');
        } catch (e) { }
    });
};


// BL Map Contacts
function blMapContacts() {
    $(window).load(function () {
        try {
            /*GetBlMapContacts();
            $("#bl_map_contacts").append('<span class="mask"></span>');		*/
        } catch (e) { }
    });
};


// Image Effect
function imagesFx() {

    // preloader
    try {
        $(".preloader").preloadify({ imagedelay: 200 });
    } catch (e) { }

    // hover effects
    $('a img, .ad1, .ad2, .small_preview img').hover(
		function () {
		    $(this).stop().fadeTo(300, 0.9);
		}, function () {
		    $(this).stop().fadeTo(300, 1);
		}
	);

    // hover effects
    $('.small_preview img').hover(
		function () {
		    $(this).stop().fadeTo(300, 0.8);
		}, function () {
		    $(this).stop().fadeTo(300, 1);
		}
	);

    // certify preloader is removed 
    $('a img').hover(function () {
        try {
            $(this).parent().removeClass('preloader');
        } catch (e) { }
    });

};


/* cancel room */
$(document).ready(function () {
    $('.canceled').each(function () {
        $altura = $(this).height();
        $(this).append('<div class="mask"></div>');
        $('.my_rooms .mask').height($altura + 26);
    });
});


/* popup cancel room */
$(function () {
    $('#popup_cancel .nav li').click(function () {

        $array = new Array();
        $array = $(this).attr('class');
        $class = $array.split(" ");
        $btn = $class[0];
        $status = $class[1];

        if ($status == "active") { }
        else {
            $('#popup_cancel .nav li').removeClass('active');
            $(this).toggleClass('active');
        }

        $array2 = new Array();
        $array2 = $btn;
        $class2 = $array2.split("_");
        $pane = $class2[1];

        $('.pane_editor').hide();
        $('#room_' + $pane).show();

        return false;
    });
});


/* edit room title */
$(function () {

    // link
    $('#fullwidth a.edit_link').click(function () {
        $(this).parent().toggle();
        $link_id = $(this).attr('id');
        $array = new Array();
        $array = $link_id;
        $class = $array.split("_");
        $room = $class[1];
        $('#input_' + $room).toggle();
        return false;
    });

    // input cancel 
    $('.price .btns input').click(function () {
        try {
            $cancel_id = $(this).attr('class');
            if ($cancel_id != "undefined") {
                $array = new Array();
                $array = $cancel_id;
                $class = $array.split(" ");
                $cancel = $class[1];
                $array2 = new Array();
                $array2 = $cancel;
                $class2 = $array2.split("_");
                $room = $class2[1];
                $('#input_' + $room).hide();
                $('#edit_' + $room).parent().show();
            }
        } catch (e) { }
    });

});


/* votacao */
$(function () {
    $('.trip_score a').live('click', function () {

        // estados
        $(this).parent().children().removeClass('selected');
        $(this).addClass('selected').prevUntil("li").addClass('selected');

        // pergunta		
        $perguntaArray = new Array();
        $perguntaArray = $(this).parent().attr('class');
        $perguntaSplit = $perguntaArray.split(" ");
        $perguntaSplit = $perguntaSplit[1]; // opt-1		
        $perguntaArray2 = new Array();
        $perguntaArray2 = $perguntaSplit;
        $perguntaSplit2 = $perguntaArray2.split("-"); // 1
        $pergunta = $perguntaSplit2[1];

        // resposta		
        $resposta = $(this).attr('rel'); // star-1		

        // regista o score no li parent
        $score = $(this).parent().children().next('.selected').size() + 1;
        $(this).parent().attr('score', $score);

        return false;
    });
});

$(function () { // this line makes sure this code runs on page load
    $('.trip_reason_all').click(function () {
        $(this).parent().nextAll().find(':checkbox').attr('checked', this.checked);
    });
});


// -------------------------------------------------------------------------------------------
// Regioes de Lisboa
// -------------------------------------------------------------------------------------------
$(document).ready(function () {
    $('.geo .prev').click(function () {
        $(this).parent().children('ul').slideToggle('fast').toggleClass('open close');

        return false;
    });

    $('.geo .next').click(function () {
        $(this).parent().children('ul').slideToggle('fast').toggleClass('close open');

        return false;
    });
});


/* void */
$(document).ready(function () {
    $('.room_table .body .type li.right .icon, #room_detail .prices .room .result ul li.max a, #room_detail .prices .room .result ul li.price a,.tab_resume ul.center li.area a.zone, .room_table .body .type li.right .icon, li.stars a, .book_navigation a').attr('href', 'javascript:void(0)');
});


/* Clue Tip */
$(document).ready(function () {
    $('a.price_tooltip').cluetip({ width: '350px' }); // tabela de preços
    $('a.rate_thumbs').cluetip({ width: '245px' });  // miniaturas detalhe da rate
    $('.cvc a').cluetip({ width: '345px' });
    $('.ratename a').cluetip({ width: '345px' });  
});



// -------------------------------------------------------------------------------------------
// Loading Modal
// -------------------------------------------------------------------------------------------

function loadingModal() {

    // keycode
    $(window).keypress(function (event) {
        if (event.keyCode == '27') {
            $('#modal_loading').hide();
            $('.md_overlay').hide();
            $('body').css('overflow-x', 'visible');
        }
        return false;
    });

    $('.md_overlay').css({ 'height': $(document).height(), 'width': $(document).width() });       

    // coords
    document.documentElement.scrollTop = 0;
    scrollX = document.documentElement.scrollLeft;

    if ($browser_version == "chrome" || $browser_version == "safari") {
        scrollY = document.body.scrollTop;
    } else {
        scrollY = document.documentElement.scrollTop;
    }
    scrollY = document.documentElement.scrollTop;

    $('body').css('overflow-x', 'hidden');
    $('.md_overlay').show();

    // vertical align
    function alignModalLoading($selector, scrollX, scrollY) {
        $modal = $($selector);
        $x = ($(window).width() / 2) - ($modal.width() / 2);
        $y = scrollY + ($(window).height() / 2) - ($modal.height() / 2);
        $modal.css({ 'top': $y, 'left': $x }).delay(250).show();
    }

    alignModalLoading('#modal_loading', scrollX, scrollY);

    $('#progresscircle').show();

    // Is this a version of IE?
    if ($.browser.msie) {
   
        $('#progresscircle').html("<img src='http://www.bookinglisboa.com/images/gif/home-loading.gif' height='66' width='66' style='border:none;' />");

    }

}

// ******************************************************* QueryString Extractor

$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    }
});
$.extend({
    getStringVars: function (string) {
        var vars = [], hash;
        var hashes = string.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getStringVar: function (string, name) {
        return $.getStringVars(string)[name];
    }
});

/* new validation */

function validateCustomForm(formId) {

  

    var parent = $(formId);
    var submitButton = parent.children().find('input.submit');

    // form submit
    submitButton.click(function () {        

        $(parent + '[class*="required"]').each(function () {
            if ($(this).val() == "") {
                $(this).addClass('colorError');
                $(this).parent().addClass('bkgerror210');
            } else {
                $(this).removeClass('colorError');
                $(this).parent().removeClass('bkgerror210');
            }
            $(parent + '[class*="custom_email"]').each(function () {
                validateCustomEmail($(this));
            });
            $(parent + '[class*="custom_phone"]').each(function () {
                validateCustomPhone($(this));
            });
        });

        if (parent.children().find('.colorError').size() <= 0) {
            return true;
        } else {
            return false;
        }
    });

    // blur fields
    $(parent + '[class*="required"]').each(function () {
        $(this).blur(function () {
            if ($(this).val() == "") {
                $(this).addClass('colorError');
                $(this).parent().addClass('bkgerror210');
            } else {
                $(this).removeClass('colorError');
                $(this).parent().removeClass('bkgerror210');
            }
        });
    });

    // email fields
    $(parent + '[class*="custom_email"]').each(function () {
        $(this).blur(function () {
            validateCustomEmail($(this));
        });
    });

    // phone fields
    $(parent + '[class*="custom_phone"]').each(function () {
        $(this).blur(function () {
            validateCustomPhone($(this));
        });
    });

    // validate email 
    function validateCustomEmail(field) {
        if (field.val() == "") {
            $(this).addClass('colorError');
            $(this).parent().addClass('bkgerror210');
        } else {
            var a = field.val();
            var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
            if (filter.test(a)) {
                field.removeClass('colorError');
                $(this).parent().removeClass('bkgerror210');
            }
            else {
                field.addClass('colorError');
                $(this).parent().addClass('bkgerror210');
            }
        }
    }

    function validateCustomPhone(field) {
        if (field.val() == "") {
            $(this).addClass('colorError');
        } else {
            var a = field.val();
            var filter = /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/;
            if (filter.test(a)) {
                field.removeClass('colorError');
            }
            else {
                field.addClass('colorError');
            }
        }
    }
}


