﻿var FavoriteGrid="";

function applyFilter() {
    var href = "";
    
    if (document.getElementById('frm_property_type_drop')){
        document.getElementById('frm_property_type').value = document.getElementById('frm_property_type_drop').value;
    };
    
    if (document.getElementById('frm_home_type_drop')){
        document.getElementById('frm_home_type').value = document.getElementById('frm_home_type_drop').value;
    };
    
    href = '/default.aspx?cl=' + document.getElementById('frm_combined_location').value;
    
    href += '&lit=' + document.getElementById('frm_listing_type').value;
    href += '&pt=' + document.getElementById('frm_property_type').value;
    href += '&ht=' + document.getElementById('frm_home_type').value;
    
    href += '&pr=' + document.getElementById('frm_price').value;
    href += '&s=' + document.getElementById('frm_surface').value;
    if (document.getElementById('frm_rooms') != null)
        href += '&r=' + document.getElementById('frm_rooms').value;
    else
        href += '&r=';
        
    href += '&t=' + document.getElementById('textboxSearchText').value;
    href += '&ft=' + "true";
    /*que guarde el poligono*/
    //href += '&pol=' + document.getElementById('divPolygon').value; 
   // href += '&mz=' + document.getElementById('frm_gmap_Zoom').value; 
    //href += '&mc=' + document.getElementById('frm_gmap_Center').value;
    /**/
    
    //document.forms[0].action = href;
    //document.forms[0].submit();
    document.location = href;
};

//Google me devuelve un objeto
function google_afs_request_done(google_ads) {
        printResult(google_ads);
};

function printResult(google_ads) {
    var s = '';
    var i;
    if (google_ads.length > 0) {
        //Para Parrilla abajo
        for (i = 0; i < google_ads.length; ++i) {
            if (navigator.appName.indexOf("Explorer") != -1) {
                //ie   
                s += '<ul class="AdSenseRow" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'Ir a http://' + google_ads[i].visible_url + '\'; return true;">';
            }
            else {
                s += '<ul class="AdSenseRow"><li>';
            }
            //s += '<span class="li0"><a href="http://services.google.com/feedback/online_hws_feedback">' + adsByGoogle + '</a></span>';
            s += '<span class="li1">';
            s += '<a target="_blank" id="a_googleGrid" href="' + google_ads[i].url;
            s += '"><b>' + google_ads[i].line1 + '</b></a><br>' + google_ads[i].line2 + ' ' + google_ads[i].line3;
            s += '</span>';
            s += '<span class="li2">';
            s += '<a target="_blank" id="a_googleGrid" href="' + google_ads[i].url + '">' + google_ads[i].visible_url + '</a>';
            s += '</span>';
            s += '</li></ul>';

            if (i == 2) {
                //pinto el div 1 y vacio la s
                //Adsense en primeras posiciones de parrilla
                //document.getElementById("AdsenseHeader").innerHTML = s;
                s = '';
            };

        };
        //pinto el div2
        document.getElementById("AdsenseFooter").innerHTML = "<span class='titleAdsense'><a href='http://services.google.com/feedback/online_hws_feedback'>" + adsByGoogle + "</a></span>" +s;
    }
    return;
};

// Muestra una ventana modal al clicar sobre el globo de notificación    
var ModalForm = {
    open: function (dialog) {
	    dialog.overlay.fadeIn(100, function () {
		    dialog.container.fadeIn(100, function () {
               dialog.data.fadeIn(100);
		    });
	    });
    }
};
    
function showModal(url){
    $('<iframe src="' + url + '" scrolling="auto" height="340" border="0" frameborder="0"></iframe>').modal({
        onOpen: ModalForm.open
    });
};

function setZoomToMarker(x,y) {

    var point = new GLatLng(y, x);
    if (y == 0 || x == 0) {
        document.getElementById("lbNoDirection").className = "show";
        document.getElementById("map-container").className = "hide";
    }
    else {
        document.getElementById("lbNoDirection").className = "hide";
        document.getElementById("map-container").className = "show";
        if (map != null) {
            if (x == '') {
                if (initalZoom != null && initalCenter != null) {
                    map.setZoom(initalZoom);
                    map.setCenter(initalCenter);
                };
            }
            else {
                map.setZoom(15);
                map.setCenter(point);
            };
        };
    }
    
};

function previewDetail(id){
    var ad = $(".grid-table-row[adid='" + id + "']");
    
    $('#property-photo').html('<img src="' + ad.attr('thumb') + '" border="0" />');
    $('#property-title').html($(".grid-table-row[adid='" + id + "'] li").children('.grid-col-zone').html());
};

var myPano = null;

function showStreetView(y, x) {
    //si !showpoi elimino pano
    if ($(this).attr('sp') == null || $(this).attr('sp') == "undefined" || $(this).attr('sp') == "") {
        if (y == 0 || x == 0) {
            if (myPano != null) {
                myPano.remove();
                document.getElementById("pano").className = "hide";
            }
        }
        else {
            if (x != '') {
                var point = new GLatLng(x, y);
                if (myPano == null) {
                    panoramaOptions = { latlng: point };
                    myPano = new GStreetviewPanorama(document.getElementById("pano"), panoramaOptions);
                    document.getElementById("pano").className = "show";
                }
                else {
                    panoramaOptions = { latlng: point };
                    document.getElementById("pano").innerHTML = "";
                    myPano.setLocationAndPOV(point);
                    document.getElementById("pano").className = "show";
                };
            }
            else if (myPano != null) {
                myPano.remove();
                document.getElementById("pano").className = "hide";
            };
        }
    }
    else {
        if (myPano != null) myPano.remove();
        document.getElementById("pano").className = "hide";
    }
};

// Creates a marker whose info window displays the letter corresponding
// to the given index.
function createMarker(point, index) {
    // Create a lettered icon for this point using our icon class
    
    var letter = String.fromCharCode("A".charCodeAt(0) + index);
    var imagepath = "/images/common/GlobeIcon_";
    var letteredIcon = new GIcon(baseIcon, imagepath + letter + ".png");
    markerOptions = { icon:letteredIcon };
    
    var marker = new GMarker(point, markerOptions);
    
    bounds.extend(point);
    return marker;
};

// Obtiene el valor de una cookie
function GetCookie(name) {
    var dc = document.cookie;
    var cname = name + "=";
    
    if (dc.length > 0) {
        begin = dc.indexOf(cname);

        if (begin != -1) {
            begin += cname.length;
            end = dc.indexOf(";", begin);
            if (end == -1) end = dc.length;
            return unescape(dc.substring(begin, end));
        };
    };

    return null;
};

function checkCookie(){
    if (guestId == '0'){
        if (GetCookie('GuestCookie') != null && GetCookie('GuestCookie') != '') {
            guestId = GetCookie('GuestCookie');
        };
    };
};

function manageFavorite(fav) {
    
    checkCookie();
    
    var pars = 'guestId=' + guestId
                + '&adId=' + fav
                + '&portalId=' + $('#frm_portalid').val() 
                + '&transactionTypeId=' + $('#frm_transactionTypeId').val();

    $.ajax({
        async: true,
        type: "GET",
        url: '/ws/Favorites.asmx/SaveFavorite',
        data: pars,
        dataType: "xml",
        contentType: "application/x-www-form-urlencoded"
    });
};

function DeleteFavorite(fav) {

    checkCookie();
    
    var pars = 'guestId=' + guestId
                    + '&adId=' + fav
                    + '&portalId=' + $('#frm_portalid').val()
                    + '&transactionTypeId=' + $('#frm_transactionTypeId').val();
    $.ajax({
        async: true,
        type: "GET",
        url: '/ws/Favorites.asmx/DeleteFavorite',
        data: pars,
        dataType: "xml",
        contentType: "application/x-www-form-urlencoded"
    });
};

//método que accede al WS y recupera los favoritos del cliente.
function LoadFavorites() {

    checkCookie();
    FavoriteGrid = "";
    var pars = 'guestId=' + guestId + '&portalId=' + $('#frm_portalid').val() + '&TransactionTypeId=' + $('#frm_transactionTypeId').val()
    $.ajax({
        async: true,
        type: "GET",
        url: '/ws/Favorites.asmx/LoadFavorites',
        data: pars,
        dataType: "xml",
        contentType: "application/x-www-form-urlencoded",
        beforeSend: function(objeto) {
            $("#favorites").html("Realizando búsqueda...");
        },
        complete: fillGrid

    });
};



 //Graba el favorito en BBDD
function addFavorite(id, url, portal, surface, price,zone) {
    manageFavorite(id);
    LoadFavoritesTemplate(id, url, portal, surface, price,zone);
    $("#dragAdsHere").hide();
};

//Elimina el favorito de BBDD
function delFavorite(id) {
    DeleteFavorite(id);
    $("#divFav_" + id).remove();

    if ($("#favorites").html() == "")
        $("#dragAdsHere").show();
};

//método que monta la parrilla de Favoritos
function fillGrid(ofiginalRequest) {
    if (ofiginalRequest.responseXML.getElementsByTagName("string")[0] != null) {

        // si firefox, textContent
        if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1)
            content = ofiginalRequest.responseXML.getElementsByTagName("string")[0].textContent;
        else
            content = ofiginalRequest.responseXML.getElementsByTagName("string")[0].firstChild.data;

        if (content == "") {
            $("#favorites").html("No se han encontrado resultados");
            $("#dragAdsHere").show();
        }
        else {
            $("#favorites").html(content);
        }
        
    }
    else {
        $("#favorites").html("No se han encontrado resultados");
        $("#dragAdsHere").show();
    }
}




/*Antes en el aspx del default.aspx*/
var guestId = '0';

checkCookie();

$(".draggable").draggable({
    helper: 'clone',
    cancel: 'a', // clicking an anchor won't initiate dragging
    opacity: 0.7,
    revert: 'invalid',
    cursor: 'move'
});

$("#box-favorites").droppable({
tolerance: 'pointer',
    hoverClass: 'ui-state-active',
    drop: function(ev, ui) {
        var id = $(ui.draggable).attr('adid');
        var url = $(ui.draggable).attr('url');
        var portal = $(ui.draggable).attr('portal');
        if ($('#divFav_' + id).length == 0) {
            addFavorite(id, url, portal, $('#ul_' + id + ' .lbSurface').html(), $('#ul_' + id + ' .lbPrice').html(), $('#ul_' + id + ' .lnkZoneGrid').html() + '<br/><span class=\"lbZoneGrid\">' + $('#ul_' + id + ' .lbZoneGrid').html() + "</span>");
        };
    }
});

var map = null;
var baseIcon = null;
var bounds = null;
var initalCenter = null;
var initialZoom = null;

function getHeight(ele) {
    if (ele.innerHeight != undefined) {
        return ele.innerHeight;
    };

    return $(ele).height();
};

function getWidth(ele) {
    if (ele.innerWidth != undefined) {
        return ele.innerWidth;
    };

    return $(ele).width();
};


function LoadFavoritesTemplate(adid, url, portal, surface, price,zone) 
{
    var newFavorite = "";
    newFavorite = $('#templateFavorites').html();
    newFavorite = newFavorite.replace(/_adid_/gi, adid);
    newFavorite = newFavorite.replace(/_url_/gi, url);
    newFavorite = newFavorite.replace(/%7Burl%7D/gi, url);
    newFavorite = newFavorite.replace(/_portal_/gi, portal);
    newFavorite = newFavorite.replace(/_surface_/gi, surface);
    newFavorite = newFavorite.replace(/_price_/gi, price);
    newFavorite = newFavorite.replace(/_zone_/gi, zone);
    
    var actual = $('#favorites').html();
    var result = (actual + newFavorite);
    $('#favorites').html(result);

    $(".divFavorite").unbind('click');
    
    $(".divFavorite").click(function() {
        openDetail($(this).attr('url'), $(this).attr('adid'), $(this).attr('portal'));
    });
}




//por si presionan la tecla enter, que coja la acción del botón buscar de 
//debajo de la caja de texto.
function keyPressed(event) {
    tecla = (document.all) ? event.keyCode : event.which;
    if (tecla == 13) {
        event.returnValue = false;
    }
}

function muestraFlecha(obj, psAdId) {
    if (document.getElementById("ul_" + psAdId) != null) {
        document.getElementById("divFlecha").style.display = 'block';
        if (document.getElementById('BrowserId').value == "1") {
            //IE6 //557
            document.getElementById('divFlecha').style.top = parseInt(document.getElementById('ul_' + psAdId).offsetTop) + parseInt(227) + parseInt(0) + "px";
        }
        else if (document.getElementById('BrowserId').value == "2") {
        //safari557
        document.getElementById('divFlecha').style.top = parseInt(document.getElementById('ul_' + psAdId).offsetTop) + parseInt(228) + parseInt(0) + "px";
        }
        else if (document.getElementById('BrowserId').value == "3") {
        //firefox558
        document.getElementById('divFlecha').style.top = parseInt(document.getElementById('ul_' + psAdId).offsetTop) + parseInt(227) + parseInt(0) + "px";
        }
        else if (document.getElementById('BrowserId').value == "4") {
        //ie7557
        document.getElementById('divFlecha').style.top = parseInt(document.getElementById('ul_' + psAdId).offsetTop) + parseInt(227) + parseInt(0) + "px";
        }
        else {
            document.getElementById('divFlecha').style.top = parseInt(document.getElementById('ul_' + psAdId).offsetTop) + parseInt(227) + parseInt(0) + "px";
        }


        document.getElementById('divFlecha').style.left = parseInt(document.getElementById("GridResults").offsetLeft) + parseInt(470) + "px";
    }
}


function ShowHideMap(ShowHide) {
    if (ShowHide == 1) {
        document.getElementById("box_mapsearch").style.display = 'none';
     }
    else {
        document.getElementById("box_mapsearch").style.display = 'block';
    }

}