﻿var mapsicle;
var map;
var geocoder;
var zoomLevel = 13;
var _showStreetView = true;
var _pageType = "p";
var _mapId = "map1";
var _streetViewLoadingMsg = "<center><img src='/images/icons/spinner_g.gif' border='0' /><br> Actualizando images...</center>";
var myPano;

if (typeof (console) == 'undefined') {
    window.console = { log: function () { } }
}

function initStreetView() {
   showStreet(startLat, startLong);
}

function showStreet(lat, lng) {
    var strView = new GLatLng(lat, lng);
    panoramaOptions = { latlng: strView };
    $('#street-map').html("");
    myPano = new GStreetviewPanorama(document.getElementById("street-map"), panoramaOptions);
    GEvent.addListener(myPano, "error", handleNoFlash);

}
function handleNoFlash(errorCode) {
    
    if (errorCode == 600) {
        handleNoStreetView();
        return;
    }
    if (errorCode == 603) {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
    }
} 

function loadMap() {

    if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        createMarker(startLat, startLong);
    }

} 
function addressFromPoint(rsp) {

    if (rsp && rsp.Status.code == 200) {
        var pl = rsp.Placemark[0];
        pl = pl.AddressDetails.Country;
        if (pl.AdministrativeArea != null) pl = pl.AdministrativeArea;
        if (pl.SubAdministrativeArea != null) pl = pl.SubAdministrativeArea;
        if (pl.Locality == null) return;

        pl = pl.Locality;
        if (pl.DependentLocality != null) {
            pl = pl.DependentLocality; // Drill down to street
        }
        if (pl.Thoroughfare != null) {
            $('#txtStreetName').val(pl.Thoroughfare.ThoroughfareName);
        }
    }
}

function createMarker(lat, lng) {
    
    var map = new GMap2(document.getElementById(_mapId));

    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());

    var center = new GLatLng(lat, lng);

    map.setCenter(center, zoomLevel);

    var marker = new GMarker(center, { draggable: true });
    map.addOverlay(marker);

    if ($('#hdnLatitude')) {
        $('#hdnLatitude').val(lat);
    }
    if ($('#hdnLongitude')) {
        $('#hdnLongitude').val(lng);
    }

    if (_pageType != "d") {
        GEvent.addListener(marker, "dragend", function () {
            var point = marker.getPoint();
            map.panTo(point);
            $('#hdnLatitude').val(point.lat());
            $('#hdnLongitude').val(point.lng());
            geocoder.getLocations(point, addressFromPoint);
            if (_showStreetView) {
                showStreet(point.lat(), point.lng());
            }
        });
        GEvent.addListener(map, 'click', function (overlay, point) {

            if (point) {

                geocoder.getLocations(point, addressFromPoint);
                zoomLevel = map.getZoom();

                createMarker(point.lat(), point.lng());

                if (_showStreetView) {
                    showStreet(point.lat(), point.lng());
                }
            }
        });
    }

    // Register events
    //    GEvent.addListener(map, "moveend", function () {
    //      //  map.clearOverlays();
    //        //var center = map.getCenter();
    //        //var marker = new GMarker(center, { draggable: true });
    //        //map.addOverlay(marker);    
    //        //GEvent.addListener(marker, "dragend", function () {
    //          //  var point = marker.getPoint();
    //           // map.panTo(point);    
    //       // });
    //    });

}
function showAddress(address) {
    if (geocoder) {
        geocoder.getLatLng(address, function (point) {

            if (!point) {
                //alert(address + " not found");
            } else {
                $('#hdnLatitude').val(point.lat());
                $('#hdnLongitude').val(point.lng());
                zoomLevel = 15;

                createMarker(point.lat(), point.lng());

                try {
                    if (_showStreetView) {
                        showStreet(point.lat(), point.lng());
                    }
                } catch (err) {

                }
            }
        });
    }
}



function translate(text, from, to, callback) {
    text = text.replace(/(<([^>]+)>)/ig, ""); 
    google.language.translate(text, from, to, function (result) {
        if (!result.error) {
            callback(result.translation);
        } else {
        }
    });
}
/*
var Localization =
{
"This field is required.": "Este campo es obligatorio.",
"Please fix this field.": "Por favor, corrija este campo.",
"Please enter a valid email address.": "Por favor, introduzca una dirección de correo electrónico válida.",
"Please enter a valid URL.": "Por favor, introduzca una URL válida.",
"Please enter a valid date.": "Por favor, introduzca una fecha válida.",
"Please enter a valid number.": "Por favor, introduzca un number válido.",
"Please enter only digits.": "Por favor, introduzca sólo números.",
"Please enter the same value again.":"Por favor, introduzca el mismo valor de nuevo",
"Please enter a value with a valid extension.": "Por favor, introduzca un valor con una extensión válida.",
"Please enter no more than {0} characters.":"Por favor, introduzca un máximo de {0} caracteres.",
"Please enter at least {0} characters.":"Por favor, introduzca al menos {0} caracteres.",
"Please enter a value between {0} and {1} characters long.":"Por favor, introduzca un valor entre {0} y {1} caracteres.",
"Please enter a value between {0} and {1}.":"Por favor, introduzca un valor entre {0} y {1}.",
"Please enter a value less than or equal to {0}.":"Por favor, introduzca un valor menor o igual a {0}.",
"Please enter a value greater than or equal to {0}.":"Por favor, introduzca un valor mayor o igual a {0}"
}
function localizeString(string) {
var s = "";
if (Localization && (s = Localization[string])) return s;
return string;
}

*/


function validateEmail(sender, args) {
    if (args.Value.length > 0) {
        var ex = /^([a-zA-Z0-9_.+-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
        var re = new RegExp(ex);

        if (re.exec(args.Value)) {
            args.IsValid = true;
        }
        else {
            sender.innerHTML = sender.errormessage;
            args.IsValid = false;
        }
    }
    else {
        sender.innerHTML = sender.errormessage;
        args.IsValid = false;
    }
}
function transTitle() {

    if ($('#txtTitle').val().length <= 0) { return; }
    var from = _lang;
    var to = "en";
    if (from == "en") { to = "es"; }

    translate($('#txtTitle').val(), from, to, function (txt) {
        $('#titleTranslation').html(txt);
        $('#hdnTitleEnglish').val(txt);
    });
}

function transDescription() {
    if ($('#txtDescription').val().length <= 0) { return; }
    var from = _lang;
    var to = "en";
    if (from == "en") { to = "es"; }
    translate($('#txtDescription').val(), from, to, function (txt) {
        $('#descTranslation').html(txt);
        $('#hdnDescriptionEnglish').val(txt);
    });
}

function flashError(html) {
    $('#flash').html(html);
    $('#flash').addClass('error');
    $('#flash').slideDown('slow');
}

function flashSuccess(html) {
    $('#flash').html(html);
    $('#flash').addClass('success');
    $('#flash').slideDown('slow');
}
/* Wiresup search results listings for click event*/
function initListings() {
    $('#featured .row').addClass("featured");
    $('#listings .row').each(function (i, e) {
        if (!$(e).hasClass('ad')) {
            $(e).mouseover(function () {
                $(this).addClass('rowOn');
            });
            $(e).mouseout(function () {
                $(this).removeClass('rowOn');
            });
            $(e).click(function () {
                window.location = $(this).find('.morebtn').attr('href');
            });
        }

    });
}

$(document).ready(function () {
    initDefaultTxt();
});

function initDefaultTxt() {
    $(".defaultText").focus(function (srcc) {
        if ($(this).val() == $(this)[0].title) {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });

    $(".defaultText").blur(function () {
        if ($(this).val() == "") {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        }
    });

    $(".defaultText").blur();
}
function markerClickHandler(marker, property) {
    return function () {
        window.location = unescape(property.Url);
    }
}

function createMouseOverHandler(marker, property) {
    return function () {
        html = [];
        html.push("<div class=\"mapTooltip\">");
        html.push("<div class=\"propTitle\">" + property.Title + " </div>");
        html.push("<div class=\"mapInfoPrice\">" + property.Price + " </div>");
        html.push("<div class=\"mapInfoBed\">");
        html.push(localStrings.Bedrooms + property.Bed + " ");
        html.push(localStrings.Bath + property.Bath + "</div>");

        html.push("<div class=\"clear\">" + property.Description + " </div>");
        html.push("</div>");
      
        window.toolTipOpen = true;
        marker.openInfoWindowHtml(html.join(''));


    }

}

function createMarkers() {

    for (var i = 0; i < markers.length; i++) {

        if (markers[i].Lat == null || markers[i].Lng == null) {
            continue;
        }
        var iconOptions = {};
        iconOptions.primaryColor = "#3398CB";
        iconOptions.strokeColor = "#FFFFFF";
        iconOptions.label = (i + 1).toString(); //markers[i].ID;
        iconOptions.labelColor = "#FFFFFF";
        iconOptions.addStar = markers[i].IsFeatured;
        iconOptions.starPrimaryColor = "#FFFF00";
        iconOptions.starStrokeColor = "#0000FF";
        var icon = MapIconMaker.createLabeledMarkerIcon(iconOptions);

        $('#m_' + markers[i].ID).html(iconOptions.label);
        $('#m_' + markers[i].ID).addClass("pin");
        var zindex = i + 1;
        if (markers[i].IsFeatured) {
            zindex = zindex + markers.length + 1000;
        }

        var opts = {
            "icon": icon,
            "clickable": true,
            "labelText": markers[i].Title,
            "title": markers[i].Title,
            "labelOffset": new GSize(-6, -5),
            "zIndex": zindex
        };

        // create marker            
        var point = new GLatLng(markers[i].Lat, markers[i].Lng);
        var marker = new GMarker(point, opts);

        var mouseHandler = createMouseOverHandler(marker, markers[i]);
        var clickHandler = markerClickHandler(marker, markers[i]);
        GEvent.addListener(marker, "mouseover", mouseHandler);
        GEvent.addListener(marker, "click", clickHandler);
//        GEvent.addListener(marker, "mouseout", function () {
//            window.toolTipOpen = false;
//            setTimeout(function () {
//                if (!window.toolTipOpen) {
//                    map.closeInfoWindow();
//                } 
//            }, 1500);
//        });

        map.addOverlay(marker);
     

    }
}


// Call this function when the page has been loaded
function initSearch() {
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(startLat, startLong), 12);
    //map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(15,15)));
    map.setUIToDefault();
    createMarkers();
    /*
    var publisher_id = "pub-0572372350232667";
    var adsManagerOptions = {
    maxAdsOnMap: 2,
    style: G_ADSMANAGER_STYLE_ADUNIT,
    channel: '4558394608'
    };

    adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
    adsManager.enable();*/
    

    initListings();
    paginate();
}
function fillPricing() {
    var pOptions = null;
    switch (parseInt($('select#ddlCategory').val())) {
        case 1:
        case 3:
        case 6:
            if ($('#radMXN').is(':checked')) {
                pOptions = _priceOptionsRentMXN;
                
            }
            else {
                pOptions = _priceOptionsRentUSD;
            }
            break;
        default:
            if ($('#radMXN').is(':checked')) {
                pOptions = _priceOptionsSaleMXN;
                
            }
            else {
                pOptions = _priceOptionsSaleUSD;
            }
            break;
    }
    
    var options = '';
    for (var i = 0; i < pOptions.length; i++) {
        options += '<option value="' + pOptions[i].Value + '">' + pOptions[i].Text + '</option>';
    }

    $('select#ddlPriceMax').html(options + '<option value="0">' + localStrings.NoLimits + '</option>');
     $('select#ddlPriceMin').html('<option value="0">0</option>' + options);
}

function initSearchControl() {

    $('#radMXN').change(function () {
        fillPricing();
        _gaq.push(['_trackEvent', 'SearchBar', 'Currency', 'MXN']);
    });
    $('#radUSD').change(function () {
        fillPricing();
        _gaq.push(['_trackEvent', 'SearchBar', 'Currency', 'USD']);
    });

    $('select#ddlCategory').change(function () {
        fillPricing();
        _gaq.push(['_trackEvent', 'SearchBar', 'Category', $(this).val()]);
        // Hide controls
        if ($(this).val() == "7") {
            $('#srrooms').hide();
            $('#srbath').hide();
        } else {
            $('#srrooms').show();
            $('#srbath').show();
        }
    });
    $('select#ddlLocation').change(function () {
        _gaq.push(['_trackEvent', 'SearchBar', 'Location', $(this).val()]);
    });


    $('#ddlPriceMin').change(function () {
        var minPrice = $('#ddlPriceMin option:selected').val();

        $("#ddlPriceMax option").each(function () {
            $(this).show();
            var maxp = parseInt($(this).val());
            if (maxp <= minPrice && maxp != 0) {
//                alert('hide ' + $(this));
                $(this).hide();
            }
        });
        $("select#ddlPriceMax").val($($("#ddlPriceMax option:visible")[0]).val());
    });

    // Lot for sale is selected
    if ($('#ddlCategory option:selected').val() == "7") {
        $('#srrooms').hide();
        $('#srbath').hide();
    }
}
$(document).ready(function () {

    $('#slide .next').click(function () {
        var cindex = parseInt($('#slide .thumb-on').attr('id').replace('imgT', ''));
        if (cindex < photoCount) {
            $('#imgT' + (cindex + 1)).click();
        }
    });
    $('#slide .prev').click(function () {
        var cindex = parseInt($('#slide .thumb-on').attr('id').replace('imgT', ''));
        if (cindex > 0) {
            $('#imgT' + (cindex - 1)).click();
        }
    });

    $('#slide .thumb img').each(function (i, e) {

        if (i == 0) {
            $(this).addClass('thumb-on');
        }
        else {
            $(this).animate({ opacity: 0.5 }, 300)
        }
        $(e).click(function () {
            var regexp = /(w=[0-9]+)(&h=[0-9]+)/gi;
            var src = $(this).attr('dsrc');
            $('#imgMain').attr('src', src);
            $('#imgMain').attr('alt', this.alt);
            $('#photoLink').attr('href', src.replace(regexp, ""));
            $('#imgCaption').html(this.alt);

            $(this).stop().animate({ opacity: 1.0 }, 300);
            $('#slide .thumb img').removeClass('thumb-on');
            $(this).addClass('thumb-on');
            $('#slide .thumb img').each(function (i, e) {
                if (!$(this).hasClass('thumb-on')) {
                    $(this).stop().animate({ opacity: 0.5 }, 300);
                }
            });
        });

        $(this).hover(function () {
            $(this).stop().animate({ opacity: 1.0 }, 300);
        },
               function () {
                   if (!$(this).hasClass('thumb-on')) {
                       $(this).stop().animate({ opacity: 0.5 }, 300);
                   }
               });
    });
});

function valNotDefault(sender, args) {
    var input = $('#' + sender.controltovalidate);
    if (input.val() == input.attr('title') || input.val().length == 0) {
        args.IsValid = false;
    }
    else {
        args.IsValid = true;
    }
}
$.urlParam = function (name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) { return 0; }
    return results[1] || 0;
}

//$.setCursorPos = function (inputEl, selStart, selEnd) {
//    if (inputEl.setSelectionRange) {
//        inputEl.focus();
//        inputEl.setSelectionRange(selStart, selEnd);
//    } else if (inputEl.createTextRange) {
//        var range = inputEl.createTextRange();
//        range.collapse(true);
//        range.moveEnd('character', selEnd);
//        range.moveStart('character', selStart);
//        range.select();
//    }
//}



function paginate() {
    var active = $('#pagination-flickr li.active')[0];
    if ($('#pagination-flickr li.active').length == 0) {
        return;
    }
    var page = parseInt($($('#pagination-flickr li.active')[0]).attr('id').replace('p_', ''));
    var pages = $('#pagination-flickr li.pg');
    for (var i = 0; i < pages.length; i++) {
        $(pages[i]).hide();
    }
    if (page >= 18) {
        var less = 9;
        if ((page + 9) > pages.length / 2) {
            less = 18;
        }
        for (var i = page; i > page - less; i--) {
            $('li#p_' + i).each(function () {
                $(this).show();
            });
        }
        for (var i = page; i < page + 9; i++) {
            $('li#p_' + i).each(function () {
                $(this).show();
            });
        }
    } else {
        for (var i = 1; i <= 19; i++) {
            $('li#p_' + i).each(function () {
                $(this).show();
            });
        }
    }
}

function initHome() {
    $(".slide .thumbs").jCarouselLite({

        btnNext: ".next",
        btnPrev: ".prev",
        visible: 5,
        circular: true

    });
    $('#slide .next').show(); $('#slide .prev').show();
}
function initDetails(){

  if(typeof(startLat) != 'undefined' && typeof(startLong) != 'undefined') {
                _pageType = "d";
                loadMap();
                initStreetView();
            }
            if(photoCount >=7) {
                $("#slide .thumbs").jCarouselLite({
                    
                    btnNext: ".next",
                    btnPrev: ".prev",
                    visible: 7,
                    circular: false

                });
                $('#slide .next').show();$('#slide .prev').show();
            }
    
            $('#slide .thumb img').each(function(i,e) {
                var mainImg = $('#imgMain');
                
                $(e).click(function() {                    
                    //var regexp = /(w=[0-9]+)(&h=[0-9]+)/gi;
                    var src = $(this).attr('dsrc');
                    $('#imgMain').attr('src', src);                    
                    $('#imgMain').attr('alt', this.alt);
                    
                    $('#imgCaption').html(this.alt);
                    
                    $(this).effect("bounce", { times:3 }, 300);
                    $('#slide .thumb img').removeClass('thumb-on');
                    $(this).addClass('thumb-on');

                });
                
            } );       

}
