
function Property(property_id, lat, lon, number_in_map, daily_rate, weekly_rate, monthly_rate, html_content, name, bedroom, current_site_prefix) {
    this.property_id = property_id;
    this.lat = lat;
    this.lon = lon;
    this.number_in_map = number_in_map;
    this.daily_rate = daily_rate;
    this.weekly_rate = weekly_rate;
    this.monthly_rate = monthly_rate;
    this.html_content = html_content;
    this.name = name;
    this.bedroom = bedroom;
    this.marker = null;
    this.current_site_prefix = current_site_prefix;

    this.set_number_in_map = function(number_in_map) {
        if (this.marker != null) this.marker.setIcon(new google.maps.MarkerImage(window.IMAGES_FOLDER + "/pins/" + window.current_site_prefix + "_map_markers.png", new google.maps.Size(22, 34), new google.maps.Point(0, (number_in_map - 1) * 34)));
        //(window.IMAGES_FOLDER + "/pins/" + this.current_site_prefix + "_" + number_in_map  + ".png");
        //if (this.marker != null) this.marker.setIcon(window.IMAGES_FOLDER + "/pins/" + this.current_site_prefix + "_" + number_in_map  + ".png");
        this.number_in_map = number_in_map;
    }
}

function create_property_map(map_center_lat, map_center_lon, map_zoom, marker_lat, marker_lon, current_site_prefix) {
    window.map = new google.maps.Map(document.getElementById("google_map"), {
        center: new google.maps.LatLng(0, 0),
        zoom: map_zoom,
        mapTypeId: 'roadmap',
        scrollwheel:false
    });

    window.map.setCenter(new google.maps.LatLng(map_center_lat, map_center_lon), map_zoom);


    $('#google_map_container').show();

    // Add a marker
    window.marker = new google.maps.Marker({
        map: window.map,
        position: new google.maps.LatLng(marker_lat, marker_lon),
        icon: window.IMAGES_FOLDER + "/pins/" + current_site_prefix + "_dot_ballon.png",
        draggable: false
    });
}

function search_list_create_neighbourhood_map(max_lat, max_lon, min_lat, min_lon, _zoom) {

    var zoom;
    if (_zoom != undefined) zoom = _zoom;
    else zoom = 14;

    window.map = new google.maps.Map(document.getElementById("google_map"), {
        center: new google.maps.LatLng(max_lat, max_lon),
        zoom: zoom,
        mapTypeId: 'roadmap',
        scrollwheel: false
    });

    if (min_lat != 0 && min_lon != 0) window.map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(min_lat, min_lon), new google.maps.LatLng(max_lat, max_lon)));
    
    // Show map div
    $('#google_map_container').show();

    // Add all properties markers
    var visible = true;
    var sprite_origin_y = 0;
    for (var x = 0 ; x < window.properties_array.length ; x++) {
        if (x + 1 > window.pagination_size) {
            visible = false;
            sprite_origin_y = 0;
        } else sprite_origin_y = x  * 34;
        
        window.properties_array[x].marker = new google.maps.Marker({
            map: window.map,
            position: new google.maps.LatLng(window.properties_array[x].lat, window.properties_array[x].lon),
            title: window.properties_array[x].name,
            icon: new google.maps.MarkerImage(window.IMAGES_FOLDER + "/pins/" + window.current_site_prefix + "_map_markers.png", new google.maps.Size(22, 34), new google.maps.Point(0, sprite_origin_y)),
            visible: visible
        });
        add_navigation_event_listener(window.properties_array[x].marker, window.properties_array[x].property_id);
    }

    // This acts after center moves or zoom changes
    google.maps.event.addListener(window.map, 'idle', function() {
        
        if (window.current_search_result_visibility_boundaries == undefined) window.current_search_result_visibility_boundaries = window.map.getBounds();
        if (window.current_search_result_visibility_zoom == undefined) window.current_search_result_visibility_zoom = window.map.getZoom();
    
        if (map_moved_more_than_threshold(window.map.getBounds()) || map_zoom_level_changed(window.map.getZoom()) || window.first_time_search_result_visibility_update == undefined) {

            // Update visible properties (map and list)
            update_search_result_visibility_based_on_map(false);

            // Disable the "first time update"
            window.first_time_search_result_visibility_update = false;

        }
    });

}

function search_map_create_neighbourhood_map(max_lat, max_lon, min_lat, min_lon, _zoom) {

    var zoom;
    if (_zoom != undefined) zoom = _zoom;
    else zoom = 14;

    window.map = new google.maps.Map(document.getElementById("google_map"), {
        center: new google.maps.LatLng(max_lat, max_lon),
        zoom: zoom,
        mapTypeId: 'roadmap',
        scrollwheel: false
    });

    if (min_lat != 0 && min_lon != 0) window.map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(min_lat, min_lon), new google.maps.LatLng(max_lat, max_lon)));

    // Show map div
    $('#google_map_container').show();

    // Add all properties markers and their info windows
    for (var x = 0 ; x < window.properties_array.length ; x++) {
        window.marker = new google.maps.Marker({
            map: window.map,
            title: window.properties_array[x].name,
            position: new google.maps.LatLng(window.properties_array[x].lat, window.properties_array[x].lon),
            visible: true,
            icon: window.IMAGES_FOLDER + "/pins/" + window.properties_array[x].current_site_prefix + "_dot_ballon.png"
        });        
        add_info_window_event_listener(window.marker, window.properties_array[x].html_content);
    }
}

function search_list_create_neighbourhood_map_empty(country, city, neighbourhood) {
    search_list_map_create_neighbourhood_map_empty('list', country, city, neighbourhood);
}

function search_map_create_neighbourhood_map_empty(country, city, neighbourhood) {
    search_list_map_create_neighbourhood_map_empty('map', country, city, neighbourhood);
}

function search_list_map_create_neighbourhood_map_empty(list_map, country, city, neighbourhood) {

    //alert(country + ' --- ' + city + ' --- ' + neighbourhood);

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( {
        'address': country + ',' + city + ',' + neighbourhood
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var lat = results[0].geometry.location.lat();
            var lon = results[0].geometry.location.lng();

            if (list_map == 'list') search_list_create_neighbourhood_map(lat, lon, 0, 0);
            else if (list_map == 'map') search_map_create_neighbourhood_map(lat, lon, 0, 0);
        } else {
            if (status == 'ZERO_RESULTS') {
                geocoder.geocode( {
                    'address': country + ',' + city
                }, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        var lat = results[0].geometry.location.lat();
                        var lon = results[0].geometry.location.lng();

                        if (list_map == 'list') search_list_create_neighbourhood_map(lat, lon, 0, 0);
                        else if (list_map == 'map') search_map_create_neighbourhood_map(lat, lon, 0, 0);
                    }else {
                        if (status == 'ZERO_RESULTS') {
                            geocoder.geocode( {
                                'address': country + ',' + neighbourhood
                            }, function(results, status) {
                                if (status == google.maps.GeocoderStatus.OK) {
                                    var lat = results[0].geometry.location.lat();
                                    var lon = results[0].geometry.location.lng();

                                    if (list_map == 'list') search_list_create_neighbourhood_map(lat, lon, 0, 0);
                                    else if (list_map == 'map') search_map_create_neighbourhood_map(lat, lon, 0, 0);
                                } else {
                                    if (status == 'ZERO_RESULTS') {
                                        geocoder.geocode( {
                                            'address': country
                                        }, function(results, status) {
                                            if (status == google.maps.GeocoderStatus.OK) {
                                                var lat = results[0].geometry.location.lat();
                                                var lon = results[0].geometry.location.lng();

                                                if (list_map == 'list') search_list_create_neighbourhood_map(lat, lon, 0, 0, 8);
                                                else if (list_map == 'map') search_map_create_neighbourhood_map(lat, lon, 0, 0, 8);
                                            } else {
                                                if (status == 'ZERO_RESULTS') {
                                                    if (list_map == 'list') search_list_create_neighbourhood_map(lat, lon, 0, 0, 8);
                                                    else if (list_map == 'map') search_map_create_neighbourhood_map(lat, lon, 0, 0, 8);
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                });
            }
        }
    });    
}

function update_search_result_visibility_based_on_map(reset_pagination) {

    var map_boundaries = window.map.getBounds();
    
    // Update map boundaries control variables
    window.current_search_result_visibility_boundaries = map_boundaries;
    // Update map zoom control variable
    window.current_search_result_visibility_zoom = window.map.getZoom();

    var visible_count = 0;
    var in_map_frame_count = 0;

    // If this was triggered by the pagination system, do not reset it
    if (reset_pagination != false) window.pagination_current = 1;

    for (var x = 0 ; x < window.properties_array.length ; x++) {
        // If is inside map frame
        if (window.properties_array[x].lat > map_boundaries.getSouthWest().lat() &&
            window.properties_array[x].lat < map_boundaries.getNorthEast().lat() &&
            window.properties_array[x].lon > map_boundaries.getSouthWest().lng() &&
            window.properties_array[x].lon < map_boundaries.getNorthEast().lng()) {
            
            
            visible_count++;
           show_property(x, visible_count);
           
        } else {
        	hide_property(x);
        }
    }

    // Update visible count
    $('.visible_count_span').html(visible_count);

    // Update map frame total count
    //$('.map_frame_total_count_span').html(in_map_frame_count);
}

function map_moved_more_than_threshold(new_map_boundaries) {
    var threshold = 0.2;
    var map_height = Math.abs(window.current_search_result_visibility_boundaries.getSouthWest().lat() - window.current_search_result_visibility_boundaries.getNorthEast().lat());
    var map_width = Math.abs(window.current_search_result_visibility_boundaries.getSouthWest().lng() - window.current_search_result_visibility_boundaries.getNorthEast().lng());
    var limit_top = window.current_search_result_visibility_boundaries.getNorthEast().lat() + map_height * threshold;
    var limit_bottom = window.current_search_result_visibility_boundaries.getSouthWest().lat() - map_height * threshold;
    var limit_right = window.current_search_result_visibility_boundaries.getNorthEast().lng() + map_width * threshold;
    var limit_left = window.current_search_result_visibility_boundaries.getSouthWest().lng() - map_width * threshold;
    if (new_map_boundaries.getNorthEast().lat() > limit_top ||
        new_map_boundaries.getSouthWest().lat() < limit_bottom ||
        new_map_boundaries.getNorthEast().lng() > limit_right ||
        new_map_boundaries.getSouthWest().lng() < limit_left) return true;
    else return false;
}

function map_zoom_level_changed(new_zoom_level) {
    if (new_zoom_level != window.current_search_result_visibility_zoom) return true;
    else return false;
}

function update_pagination_navigation(total_items) {

    // Update amount of page links to display
    window.pagination_limit = Math.ceil(total_items / window.pagination_size);
    //alert("Total items in map frame: " + total_items + ". Pagination pages: " + window.pagination_limit);

    // Update view
    $('.number_pagination_span').remove();
    var active = ' active';
    for (var x = 1 ; x <= window.pagination_limit ; x++) {
        if (x > 1) active = '';
        $('.next_pagination_span').before('<span class="number_pagination_span' + active + ' number_pagination_span_' + x + '" onclick="javascript: set_pagination(' + x + ', this);">' + x + '</span>');
    }
}

function show_property(property_number_in_array, new_number_in_map) {
    
    // Update the property object with its new number in map
//    window.properties_array[property_number_in_array].set_number_in_map(new_number_in_map);
//
//    // Update the list to match the new number_in_map
//    $('#property_' + window.properties_array[property_number_in_array].property_id + '_div .floating_number_div').removeClass().addClass('floating_number_div' + ' ' + window.current_site_prefix + ' circle_' + new_number_in_map);
//   
//
//    // Set the src from hidden_src if necessary
//    if ($('#property_' + window.properties_array[property_number_in_array].property_id + '_div .property_photo_img').attr('src') == '') $('#property_' + window.properties_array[property_number_in_array].property_id + '_div .property_photo_img').attr('src', $('#property_' + window.properties_array[property_number_in_array].property_id + '_div .property_photo_img').attr('hidden_src'));

    // Show the property div and marker
    window.properties_array[property_number_in_array].marker.setVisible(true);
    $('#property_' + window.properties_array[property_number_in_array].property_id + '_div').show();
}

function hide_property(property_number_in_array) {
    
    // Hide the property div and marker
    window.properties_array[property_number_in_array].marker.setVisible(false);
    $('#property_' + window.properties_array[property_number_in_array].property_id + '_div').hide();
                
    // Update the property object to non-existant number 0
   // window.properties_array[property_number_in_array].set_number_in_map(0);
    
    // Update the list to to non-existant number 0
    //$('#property_' + window.properties_array[property_number_in_array].property_id + '_div .floating_number_div img').attr('src', window.IMAGES_FOLDER + "/pins/" + window.properties_array[property_number_in_array].current_site_prefix + "_circle_" + 0 + ".png");
}

function rewind_pagination() {
    if (window.pagination_current > 1) window.pagination_current--;
    update_search_result_visibility_based_on_map(false);
    $('.number_pagination_span').removeClass('active');
    $('.number_pagination_span_' + window.pagination_current).addClass('active');
    window.scrollTo(0,0);
}

function forward_pagination() {
    if (window.pagination_current < window.pagination_limit) window.pagination_current++;
    update_search_result_visibility_based_on_map(false);
    $('.number_pagination_span').removeClass('active');
    $('.number_pagination_span_' + window.pagination_current).addClass('active');
    window.scrollTo(0,0);
}

function set_pagination(new_page, _this) {
    window.pagination_current = new_page;
    update_search_result_visibility_based_on_map(false);
    $('.number_pagination_span').removeClass('active');
    $(_this).addClass('active');
    window.scrollTo(0,0);
}

function sort_properties(filter) {

    createCookie(window.current_site_prefix + '_search_property_filter', filter, 365);
 
    search_properties(1);

    // Reassign numbers and reset pagination
    update_search_result_visibility_based_on_map();
}

function sort_custom(array) {
    var not_done = true;
    var x;
    var temp;
    
    while (not_done) {
        not_done = false;
        for (x = 0 ; x < array.length - 1 ; x++) {
            if (property_sort_function(array[x], array[x + 1]) > 0) {
                temp = array[x];
                array[x] = array[x + 1];
                array[x + 1] = temp;
                temp = null;
                not_done = true;
            }
        }
    }
}

function property_sort_function(a, b) {
    //Compare "a" and "b" in some fashion, and return -1, 0, or 1
    switch (window.sort_field) {
        case 'weekly':
            if (a.weekly_rate == b.weekly_rate) return a.name > b.name;
            else {
                if (window.sort_order == 'asc') return a.weekly_rate - b.weekly_rate;
                else return b.weekly_rate - a.weekly_rate;
            }
            break;
        case 'bedroom':
            if (a.bedroom == b.bedroom) return a.name > b.name;
            else {
                if (window.sort_order == 'asc') return a.bedroom - b.bedroom;
                else return b.bedroom - a.bedroom;
            }
            break;
        case 'name':
            if (a.name == b.name) return a.name > b.name;
            else {
                if (window.sort_order == 'asc') return a.name > b.name;
                else return b.name > a.name;
            }
            break;

        default:
            return -1;
            break;
    }
}

function city_selected(city_id) {
    $(document).unbind();
    $('.neighbourhood_city_select_div').hide();
    createCookie(window.current_site_prefix + '_search_neighbourhood', '', 0.0000000000000001);
    createCookie(window.current_site_prefix + '_search_city', city_id, 1);
    window.location.reload();
}

function neighbourhood_selected(neighbourhood_id) {
    $(document).unbind();
    $('.neighbourhood_city_select_div').hide();
    createCookie(window.current_site_prefix + '_search_neighbourhood', neighbourhood_id, 1);
    createCookie(window.current_site_prefix + '_search_city', '', 0.0000000000000001);
    window.location.reload();
}

function city_or_neighbourhood_selected(type_and_id) {
    var type = type_and_id.split('_');
    var id = type[2];
    type = type[0];
    switch(type) {
        case 'city':
            city_selected(id);
            break;
        case 'neighbourhood':
            neighbourhood_selected(id);
            break;
        default:
            break;
    }
}

function are_valid_from_to_dates(from, to) {
    if (from != '' && to != '') {
        /*var date_from = from.split('-');
        date_from = new Date(date_from[0], date_from[1], date_from[2]);*/
        var date_from = get_Date_object_from_calendar_date_format(from);
        /*var date_to = to.split('-');
        date_to = new Date(date_to[0], date_to[1], date_to[2]);*/
        var date_to = get_Date_object_from_calendar_date_format(to);

        if (date_to - date_from > 0) return true;
    }
    return false;
}

function get_Date_object_from_calendar_date_format(date_string) {
    var date_object = date_string.split('-');
    date_object = new Date(date_object[0], date_object[1] - 1, date_object[2]);
    return date_object;
}

function get_calendar_date_format_from_Date_object(date_object) {
    var day = date_object.getDate();
    if (day < 10) day = '0' + day;
    var month = date_object.getMonth() + 1;
    if (month < 10) month = '0' + month;
    return date_object.getFullYear() + '-' + month + '-' + day;
}

function bedrooms_selected() {
    createCookie(window.current_site_prefix + '_search_bedrooms', $('.bedrooms_select').attr('value'), 1);
    search_properties(1);
}

function add_info_window_event_listener(marker, html_content) {
    google.maps.event.addListener(marker, 'click', function(event) {
        window.info_window.setContent(html_content);
        window.info_window.setPosition(marker.getPosition());
        window.info_window.open(window.map);
    });
}

function add_navigation_event_listener(marker, property_id) {
    google.maps.event.addListener(marker, 'click', function(event) {
        window.location.href = window.current_site_short_url + '/property/' + property_id;
    });
}

function switch_property_img_to(new_image, thumb_id, direction) {
    //alert("switch property img to " + direction);
    if ($('#property_main_photo').attr('src') !=new_image) {
        $('#property_main_photo').fadeOut('fast', function (){
            $('#property_main_photo').attr('src', '');            
            $('.image_thumb').removeClass('active');
            $('#thumb_' + thumb_id).addClass('active');
            window.images_counter = parseInt(thumb_id);
            $('#property_main_photo').attr('src', new_image);
            //$('#property_main_photo').load(function () {
                //alert(direction);
                if(direction == "left") {
                    if (window.images_counter < window.thumbnail_frame_start ) {
                        move_property_thumbs_to_the_left();
                    }
                } else if(direction == "right") {
                    if (window.images_counter > window.thumbnail_frame_end ) {
                        move_property_thumbs_to_the_right();
                    }
                } else if (direction == "end") {
                    if (window.images_counter >= 9) {
                        move_property_thumbs_to_the_end();
                    }
                } else if (direction == "front") {
                    move_property_thumbs_to_the_front();

                }
                $('#property_main_photo').fadeIn('fast');

            //});
        });
    }

}

function switch_property_img_left() {
    //alert(window.images_counter);
    if (window.images_counter != '0') {
        //alert("entro aca");
        window.images_counter--;
        switch_property_img_to(window.images_path[window.images_counter], window.images_counter, "left");
    }else {
        //We need to go to the end
        window.images_counter = window.thumbnail_total-1;
        switch_property_img_to(window.images_path[window.images_counter], window.images_counter, "end");
    }
}

function switch_property_img_right() {
    if (window.images_counter != window.images_counter_top-1) {
        window.images_counter++;
        switch_property_img_to(window.images_path[window.images_counter], window.images_counter, "right");
    } else {
        //We need to go to the end
        window.images_counter = 0;
        switch_property_img_to(window.images_path[window.images_counter], window.images_counter, "front");
    }
}



function move_property_thumbs_to_the_right() {
    if (parseInt(document.getElementById('thumbs').style.left.valueOf()) >= -((window.loaded_property_images - 8) * 58)) {
        document.getElementById('thumbs').style.left = (parseInt(document.getElementById('thumbs').style.left.valueOf()) - 58) + "px" ;
        window.thumbnail_frame_start++;
        window.thumbnail_frame_end++;
    //window.moverightvar = setTimeout("move_property_thumbs_to_the_right()", 20)
    }

}

function move_property_thumbs_to_the_left() {
    //alert("move property thumbs to the left");
    if (parseInt(document.getElementById('thumbs').style.left.valueOf()) < 0) {
        document.getElementById('thumbs').style.left = (parseInt(document.getElementById('thumbs').style.left.valueOf()) + 58) + "px";
        window.thumbnail_frame_start--;
        window.thumbnail_frame_end--;        
    //window.moveleftvar = setTimeout("move_property_thumbs_to_the_left()", 20)
    }else {
        document.getElementById('thumbs').style.left = 0 + "px";
    }
}

function move_property_thumbs_to_the_end() {    
    document.getElementById('thumbs').style.left = ((parseInt(document.getElementById('thumbs').style.left.valueOf()) - 58) * (window.thumbnail_total-9)) + "px";
    //alert("move property thumbs to the end");
    window.thumbnail_frame_start = window.thumbnail_total - 9;
    window.thumbnail_frame_end = window.thumbnail_total - 1;
}

function move_property_thumbs_to_the_front() {
    document.getElementById('thumbs').style.left = 0 + "px";
    //alert("move property thumbs to the end");
    window.thumbnail_frame_start = 0;
    window.thumbnail_frame_end = 9;
}

function add_calendar_days_unique_identifier(reservation_type) {

    $('#' + reservation_type + '_div .calendar').add(function(index) {
        alert(index);
        $(this).addClass(reservation_type + '_calendar_nr_' + index);
        var calendar_month_year = $('.' + reservation_type + '_calendar_nr_' + index + ' td[class="title"]').html();
        calendar_month_year = calendar_month_year.split(' ');
        var month = get_numeric_month(calendar_month_year[0]);
        var year = calendar_month_year[1];
        $('.' + reservation_type + '_calendar_nr_' + index + ' td').each(function(index_day) {
            if (!$(this).hasClass('otherDay') && !$(this).hasClass('title')) {
                var day = $(this).html();
                if (day < 10) day = '0' + day;
                var identifier = reservation_type + '_' + month + '_' + day + '_' + year;
                $(this).addClass(identifier).attr('identifier', identifier);
            }
        });
    });
}

function mark_all_reserved_calenday_days_from_db(days_from_db) {
    var days_to_mark_array = new Array();
    days_to_mark_array = days_from_db.split('::::');
    for ( var x = 0 ; x < days_to_mark_array.length ; x++ ) {
        $('.' + days_to_mark_array[x]).addClass('selected');
    }
}

function get_numeric_month(string) {
    switch(string) {
        case 'January':
            return '01';
            break;

        case 'February':
            return '02';
            break;

        case 'March':
            return '03';
            break;

        case 'April':
            return '04';
            break;

        case 'May':
            return '05';
            break;

        case 'June':
            return '06';
            break;

        case 'July':
            return '07';
            break;

        case 'August':
            return '08';
            break;

        case 'September':
            return '09';
            break;

        case 'October':
            return '10';
            break;

        case 'November':
            return '11';
            break;

        case 'December':
            return '12';
            break;
        default:
            return false;
            break;
    }
}

function switch_home_page_main_image_to(new_image) {
    $('#home_page_main_img').hide().attr('src',window.IMAGES_FOLDER + '/home/' + new_image + '.jpg').show();
    $('#slide_nav li a').removeClass('active');
    $('.slider_a_' + new_image).addClass('active');
}

function switch_to_home_page_next_image() {
    if (window.current_image == 5) window.current_image = 1;
    else window.current_image++;
    switch_home_page_main_image_to(window.current_image);
    time_out_home_page_image();
}

function time_out_home_page_image() {
    setTimeout("switch_to_home_page_next_image()", 5000);
}

function home_page_image_clicked(new_image) {
    if (new_image == 1) window.current_image = 5;
    else window.current_image = new_image - 1;
    switch_home_page_main_image_to(new_image);
}

function send_reserve_form_email(tracker_code, destination_site, initials) {
    
    var form = document.getElementById('reserve_modal_form');

    var property_id = form.property_id.value;
    var error_log = "";
    if (form.first_name.value == "") {
        error_log = error_log + window.missing_name_error_message + "\n";
    }
    if (form.phone.value == "") {
        error_log = error_log + window.missing_phone_error_message + "\n";
    }
    
    var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
    if (form.email.value == "") {
        error_log = error_log +  window.missing_email_error_message + "\n";
    }
    else if (!re.test(form.email.value)) {
        error_log = error_log +  window.wrong_email_error_message + "\n";
    }
    if (!is_range_valid(window.checkin_calendar_object.date.getTime(), window.checkout_calendar_object.date.getTime())) {
        error_log = error_log + window.invalid_dates_error_message + "\n";
    }
    
    if(error_log != "") {
        alert(error_log);
        $('#send_reservation_button_a').bind('click', function(){
            $(this).unbind('click');
            add_ga_data(document.getElementById('reserve_modal_form'));send_reserve_form_email(tracker_code , destination_site, initials);
        });
        return;
    }
    
    
    
    $.post(window.REL_PHP_CODE_FOLDER + "/run_function.php", {
        function_to_call: "send_reserve_form_email",
        tracker_code: tracker_code,
        initials: initials,
        property_id: form.property_id.value,
        property_name: form.property_name.value,
        first_name: form.first_name.value,
        last_name: form.last_name.value,
        email: form.email.value,
        phone: form.phone.value,
        amount_of_guests: form.amount_of_guests.value,
        travel_with_children: get_radio_value(form.travel_with_children),
        hear_about_oasis: form.hear_about_oasis.value,
        comments: form.comments.value,
        checkin_date: window.checkin_calendar_object.date.getTime(),
        checkout_date:window.checkout_calendar_object.date.getTime(),
        referred_by: form.referred_by.value

    }, function(retrieved_data){
        if (retrieved_data == 'success') {            
            _gaq.push(['b._trackPageview','/virtual/submit_reservation_' + tracker_code]);
            _gaq.push(['_trackPageview','/virtual/submit_reservation_' + tracker_code]);
            _gaq.push(['_trackPageview','/virtual/submit_reservation_' + destination_site]);
            if(destination_site == 'ba') {
                doGoal(this);                
            }
            alert(window.send_reserve_form_email_success_message);
            window.open(current_site_short_url + "/property/" + property_id, '_self');
        } else alert(window.send_reserve_form_email_fail_message);
    //window.location.href = window.current_site_short_url + "/property/" + form.property_id.value;
    });
}




function is_range_valid(from,to){
 	from = new Date(from);
	to = new Date(to);
	return from < to;
}



function Point_of_interest(point_of_interest_id, lat, lon, number_in_map, map_zoom, name, address, description, link, current_site_prefix, address_cms, description_cms) {
    this.point_of_interest_id = point_of_interest_id;
    this.lat = lat;
    this.lon = lon;
    this.number_in_map = number_in_map;
    this.map_zoom = map_zoom;
    this.name = name;
    this.address = address;
    this.description = description;
    this.link = link;
    this.current_site_prefix = current_site_prefix;
    this.address_cms = address_cms;
    this.description_cms = description_cms;

    this.show = function() {
        alert('show ' + this.point_of_interest_id);
    }

    this.hide = function() {
        alert('hide ' + this.point_of_interest_id);
    }
}

function create_points_of_interest_map(max_lat, max_lon, min_lat, min_lon) {

    window.map = new google.maps.Map(document.getElementById("google_map"), {
        center: new google.maps.LatLng(max_lat, max_lon),
        zoom: 1,
        scrollwheel:false,
        mapTypeId: 'roadmap'
    });

    window.map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(min_lat, min_lon), new google.maps.LatLng(max_lat, max_lon)));

    // Show map div
    $('#google_map_container').show();
    
    // Add all properties markers
    for (var x = 0 ; x < window.points_of_interest_array.length ; x++) {
        window.marker[x] = new google.maps.Marker({
            map: window.map,
            position: new google.maps.LatLng(window.points_of_interest_array[x].lat, window.points_of_interest_array[x].lon),
            title: window.points_of_interest_array[x].name,
            icon: new google.maps.MarkerImage(window.IMAGES_FOLDER + "/pins/" + window.current_site_prefix + "_map_markers.png", new google.maps.Size(22, 34), new google.maps.Point(0, (x) * 34)),
            visible: true
        });

        var html_text = '<div class="google_map_info_window_div">' +
                        '<div class="point_of_interest_ballon_title">' + window.points_of_interest_array[x].name + "</div>" +
                        '<div class="point_of_interest_ballon_content">';

        if (window.points_of_interest_array[x].address != '') {
            html_text = html_text + '<strong>'+ window.points_of_interest_array[x].address_cms +':</strong> ' + window.points_of_interest_array[x].address + '<br>';
        }

        if (window.points_of_interest_array[x].description != '' ) {
            html_text = html_text + '<strong>'+ window.points_of_interest_array[x].description_cms +':</strong> ' + window.points_of_interest_array[x].description + '<br>';
        }

        if (window.points_of_interest_array[x].link != '' ) {
            var link = window.points_of_interest_array[x].link;
            if (link.indexOf("http://") == -1) {
                link = "http://" + link;
            }
            html_text = html_text + '<strong>Link:</strong> ' + '<a href="' + link + '" target="_blank">' + link + '</a>';
        }
                        
        html_text = html_text + "</div></div>";


//
//                    '<a href="<?php echo CURRENT_SITE_SHORT_URL; ?>/property/<?php echo $property['property_id']; ?>"><img class="info_window_main_img" src="<?php echo $default_image_path; ?>" alt="" style="width:205px; height:154px;"/></a>' +
//                    '<div class="property_name_div"><?php echo $property['name']; ?></div>' +
//                    '<table class="info_window_table">' +
//                    '<tbody>' +
//                    '<tr>' +
//                    '<td class="col1"><?php echo $cms_property_attributes['Daily']; ?>:</td>' +
//                    '<td class="col2">' + daily + '</td>' +
//                    bedrooms +
//                    '</tr>' +
//                    '<tr>' +
//                    '<td class="col1"><?php echo $cms_property_attributes['Weekly']; ?>:</td>' +
//                    '<td class="col2">' + weekly + '</td>' +
//                    bathrooms +
//                    '</tr>' +
//                    '<tr>' +
//                    '<td class="col1"><?php echo $cms_property_attributes['Monthly']; ?>:</td>' +
//                    '<td class="col2">' + monthly + '</td>' +
//                    '<td class="col3" colspan="2"><a class="see_more_a" href="<?php echo CURRENT_SITE_SHORT_URL; ?>/property/<?php echo $property['property_id']; ?>"><?php echo $cms_property_attributes['See more']; ?></a></td>' +
//                    '</tr>' +
//                    '</tbody>' +
//                    '</table>' +
//                    ;

        add_info_window_event_listener(window.marker[x], html_text);
    }
}

function click_on_marker(marker_position) {
    google.maps.event.trigger(window.marker[marker_position-1], 'click');
}

function switch_to_language(new_language) {
    var current_language = readCookie('current_language');
    if (new_language != current_language) {
        createCookie('current_language', new_language, 1);
        var location_array = window.location.toString().split('/');        
        var link = '';
        var contains_language_parameter = false;
        var array_position = 0;
        for(var i=0; i<location_array.length;i++) {
            var language = location_array[i];
            if(language == 'en' || language == 'pt' || language == 'es') {
                contains_language_parameter = true;
                array_position = i + 1;
                break;
            }
        }        
        if (contains_language_parameter) {
             for (i=array_position; i<location_array.length; i++) {
                 link = link + '/' + location_array[i];
             }             
             window.location.href = link;
        }else {
            window.location.reload();
        }
        
    }
}

function spin_home_page_slider() {
    if (window.current_home_page_slide == window.home_page_slider_ids.length - 1) window.current_home_page_slide = 0;
    else window.current_home_page_slide++;
    $('.main_flash_container').hide();
    $('#home_page_flash_div_' + window.home_page_slider_ids[window.current_home_page_slide]).show();
    setTimeout('spin_home_page_slider()', 4000);

}

function get_rss_blog_index_entries(read_more) {

    $.post(window.REL_PHP_CODE_FOLDER + "/run_function.php", {
        function_to_call: 'get_rss_blog_index_entries',
        read_more: read_more
    }, function(retrieved_data){
        if (no_error(retrieved_data)) {
            $('.blog_entries_div').html(retrieved_data);
        } else $('.blog_entries_div').html('Error getting blog posts');
    });
}

function load_background_images() {
    $('.property_main_div .property_photo_img[src|=""]').each(function() {
        $(this).attr('src', $(this).attr('hidden_src'));
    })
}

function clear_all_search_filters() {
    createCookie(window.current_site_prefix + '_search_bedrooms', '', 0.000000000000000001);
    createCookie(window.current_site_prefix + '_search_neighbourhood','',0.000000000000000001);
    createCookie(window.current_site_prefix + '_search_city','',0.000000000000000001);
    createCookie(window.current_site_prefix + '_search_checkin_date','',0.000000000000000001);
    createCookie(window.current_site_prefix + '_search_checkout_date','',0.000000000000000001);
}

function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){		   
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){		   
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){		   
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){		   
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){		   
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){		    
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){		    
		    return false
		 }

 		 return true					
	}


function save_payment() {
    var form = document.getElementById('payment_form');
    var errors = '';

    if (form.first_name.value == ''){
        errors = errors + 'Please provide the First Name \n';
    }
    if (form.last_name.value == ''){
        errors = errors +  ('Please provide the Last Name \n');
    }
    if (form.email.value == '' || !echeck(form.email.value)){
        errors = errors +  ('Please provide a valid Email Address \n');
    }    
    if (form.address_1.value == '' && form.address_2.value == ''){
        errors = errors +  ('Please provide an Address \n');
    }
    if (form.country.value == ''){
        errors = errors +  ('Please provide a Country Name \n');
    }
    if (form.city.value == ''){
        errors = errors +  ('Please provide the City Name \n');
    }
    if (form.zip_code.value == ''){
        errors = errors +  ('Please provide the Zip Code \n');
    }
    if (form.credit_card.value == '' || (form.credit_card.value).match('[^0-9]') ){
        errors = errors +  ('Wrong Credit Card Number \n');
    }
    if (form.civ_code.value == '' || (form.civ_code.value).match('[^0-9]') || (form.civ_code.value).length<3){
        errors = errors +  ('Wrong CIV Code \n');
    }
    if (form.expiration_date.value == '' || (form.expiration_date.value).length<4 || (form.expiration_date.value).match('[^0-9]')){
        errors = errors +  ('Wrong expiration date value \n');
    }
    if ((form.creditcardtype[0].checked == '1') && ((form.credit_card.value).length<13)){
        errors = errors + ('Wrong credit card number \n');

    }
    if ((form.creditcardtype[1].checked == '1') && ((form.credit_card.value).length<16)){
        errors = errors + ('Wrong credit card number \n');

    }
    
    if ((form.creditcardtype[2].checked == '1') && ((form.credit_card.value).length!=15)){
        errors = errors + ('Wrong credit card number \n');

    }

    if (errors != '') {
        alert(errors);
        $('#payment_form_submit_span').bind('click', function(){
            $(this).unbind('click');
            save_payment();
        });
    }
    else {
        $('#payment_form_submit_span').hide();
        $('#ajax_loader').show();
        $.post(window.dev + "/code/php/run_function.php", {
            //function_to_call: "create_payment_xml",
            function_to_call: "create_payment_xml_Test",
            first_name: form.first_name.value,
            last_name: form.last_name.value,
            email: form.email.value,
            address: form.address_1.value + ' ' + form.address_2.value,
            country: form.country.value,
            city: form.city.value,
            state: form.us_ca_states.value,
            zip_code: form.zip_code.value,
            credit_card: form.credit_card.value,
            civ_code: form.civ_code.value,
            expiration_date: form.expiration_date.value,
            amount: form.amount.value,
            amount_currency: form.amount_currency.value
        }, function(retrieved_data){            
            if (retrieved_data == "success") {
                $.post(window.dev + "/code/php/run_function.php", {
                    function_to_call: "save_payment",
                    first_name: form.first_name.value,
                    last_name: form.last_name.value,
                    email: form.email.value,
                    address: form.address_1.value + ' ' + form.address_2.value,
                    country: form.country.value,
                    city: form.city.value,
                    state: form.us_ca_states.value,
                    zip_code: form.zip_code.value,
                    amount: form.amount.value,
                    amount_currency: form.amount_currency.value

                }, function(retrieved_data){
                    window.location.href = window.current_site_short_url + '/payment_success/';
                });
            }
            else {
                $('#payment_form_submit_span').bind('click', function(){
                    $(this).unbind('click');
                    save_payment();
                });
                $('#ajax_loader').hide();
                $('#payment_form_submit_span').show();
                alert ("Missmatch Credit Card Data. Please check Credit Card Type, number, CIV Code and Expiration Date.\n\nPlease feel free to give us a call (+1.631.731.1677) or email (info@oasiscollections) so we can help resolve this issue as soon as possible.");
            }
        });
    }
}

function select_tab_owners(tab) {
    $('#tab_content .main_header').removeClass('overview');
    $('#tab_content .main_header').removeClass('how_we_work');
    $('#tab_content .main_header').removeClass('press');
    $('#tab_content .main_header').addClass(tab);
    $('#tab_content .main_header .header_description a').removeClass('selected');
    $('#tab_content .main_header .header_description.' + tab + ' a').addClass('selected');
    $('#tab_content .main_tab_content .tab_content').removeClass('selected');
    $('#tab_content .main_tab_content .tab_content.' + tab + '_text').addClass('selected');
}

function goToSearchListSite(search_list_site) {
    switch (search_list_site) {
        case "href_rio":
            window.location.href ='/rio/search_list' ;
            break;
        case "href_floripa":
            window.location.href = '/floripa/search_list';
            break;
        case "href_saopaulo":
            window.location.href = '/saopaulo/search_list';
            break;           
    }
}

function getDateFormat(){
	var current_language = readCookie('current_language');
	switch(current_language){
		case "en": return '%m/%d/%Y';
		case "es": return '%d/%m/%Y';
		case "pt": return '%d/%m/%Y';
		default : return '%m/%d/%Y';
	}
}

function getDateMask(){
	var current_language = readCookie('current_language');
	switch(current_language){
		case "en": return 'mm/dd/yyyy';
		case "es": return 'dd/mm/aaaa';
		case "pt": return 'dd/mm/aaaa';
		default : return 'mm/dd/yyyy';
	}
}

function getDateFormated(date){
	var current_language = readCookie('current_language');
	switch(current_language){
	case "en": return date.getMonth() + " " + date.getDate() + " "+ date.getFullYear();
	case "es": return date.getDate() + " " + date.getMonth() + " "+ date.getFullYear();
	case "pt": return date.getDate() + " " + date.getMonth() + " "+ date.getFullYear();
	default : return date.getMonth() + " " + date.getDate() + " "+ date.getFullYear();
}
}
