﻿
    var map = null;
    var gdir = null;
    var veMap = null;
    var isBirdViewAvailable = false;
    var veLoc = null;
    var isMapDisabled = false;
    var trafficInfo;
    var trafficToggleState = 1;    
    var infoWindowOn = false;
    var vpakGeoRSS = null; 
    var tmpLoc = null;
    var couponsOn = false;
    var pImg = null;
    var dlgBirdsEyePanel = null;
    
    function load() {
        if (!isPrint){
        
            if (isBirdsEyeEnabled) veLoc = new VELatLong(flLocationLat, flLocationLon);
            
            $('#container').tabs( 0, {
                onShow: function(tabToShow, tabToHide) {
                    
                    loadMapDelayed(100);
                    setMSIFrameCode();
                    
                }
                });             
                
            
            if (enableSlideshow ){
                $('#slideshow').cycle({ 
					        fx:    'fade', 
					        speed:  3000 
				        }); 
            }
                         
            try{
                loadMapDelayed(100);       
            }catch(e){}
            

            if (up){
                setTimeout("loadUpgradePanelDelayed()", 3000); 
                return ;
            }        
        
            // if chat is enabled
            if (isChatEnabled && isChatFloating){
            
                //$('#chatPanel').jqDrag('#chatPanelHeader')                 
                $('#chatPanel').css('visibility', 'visible');    
                $('#chatPanel').easydrag();
                    
                
            }
            else if (isChatEnabled && !isChatFloating){
            
                $('#chatPanel').css('position', 'relative');
                $('#chatPanel').css('top', '0px');
                $('#chatPanel').css('left', '0px');
                $('#chatPanel').css('border', '0px');
                $('#chatDock').append($('#chatPanel'));
                $('#chatPanelHeader').css('display','none');
                $('#chatPanel').css('visibility', 'visible');
            }
            
            dlgBookmarkPanel = new YAHOO.widget.Panel("bookmarkPanel", {
            width:"500px", 
            height:"220px",
            fixedcenter: true, 
            constraintoviewport: true, 
            underlay:"shadow", 
            effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5},
            close:false, 
            visible:false, 
            modal:true,
            draggable:false} );        
            
            dlgBookmarkPanel.render();  
            
            dlgContactUsPanel = new YAHOO.widget.Panel("contactUsPanel", {
            width:"470px", 
            height:"350px",
            fixedcenter: true, 
            constraintoviewport: true, 
            underlay:"shadow", 
            effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5},
            close:false, 
            visible:false, 
            modal:true,
            draggable:false} );        
            
            dlgContactUsPanel.render();          

            dlgSharePanel = new YAHOO.widget.Panel("sharePanel", {
            width:"470px", 
            height:"350px",
            fixedcenter: true, 
            constraintoviewport: true, 
            underlay:"shadow", 
            effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5},
            close:false, 
            visible:false, 
            modal:true,
            draggable:false} );        
            
            dlgSharePanel.render();      
            
            // attach thumbnail images
            if (photoArr != 'undefined' && photoArr.length>0){
                photoArPlaceholder = $('.photogalleryitem');
                for (i=0;i<photoArr.length; i++){
                    photoArPlaceholder[i].src = "http://www.realbird.com/Files/HotspotPhotos/" + photoArr[i];
                    
                } 
            } 

        }
        else {
            // print view
            

        }
   

    }
    
    
    
    function setDirections(fromAddress, toAddress, locale) {
        if (gdir != 'undefined' && gdir != null) gdir.clear();
        
        if (GBrowserIsCompatible()) {      
            map = new GMap2(document.getElementById("map_canvas"));
            gdir = new GDirections(map, document.getElementById("directions"));            
            GEvent.addListener(gdir, "load", onGDirectionsLoad);
            GEvent.addListener(gdir, "error", onGDirectionsHandleError);
            fromAddress = $('#fromAddress').val();
            toAddress = $('#toAddress').val();
            locale = $('#locale').val();
            gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
            
        }                
    }

    function onGDirectionsHandleError(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}

	function onGDirectionsLoad(){ 

	}    

    
    function setMSIFrameCode(){
    
        if (msIFrame == "") return;
        
        $('#mlsSearchFrame').attr('src', msIFrame);
        
    }
    
    function resizePrimaryImage(){
        pImg = new Image();
        pImg.src = primaryImage;
        pImg.onLoad=primaryImageLoaded();
    }
    
    function primaryImageLoaded(){
        var w = pImg.width;
        var h = pImg.height;
        if (w >= h){
            nw = 220;
            nh = Math.round(nw*h/w);
        }
        else{        
            nh = 165;
            nw = Math.round(w*nh/h);
        }
        
        $("#primaryImage").width(nw);            
        $("#primaryImage").height(nh);
                   
        $("#primaryImage").css({display:"inline"});
    }
    
    function loadUpgradePanelDelayed(){
        $('#upgradePanel').css({ display: "block"});
        dlgUpgradePanel = new YAHOO.widget.Panel("upgradePanel", {
        width:"650px", 
        height:"400px",
        fixedcenter: true, 
        constraintoviewport: true, 
        underlay:"shadow", 
        effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5},
        close:false, 
        visible:true, 
        modal:true,
        draggable:false} );        
        
        dlgUpgradePanel.render();     
    }
    
    function loadMapDelayed(timespan){
        
        if (isPrint) return;
        
        showGoogleMaps(timespan); 
        
        $("#BirdsEyeOuter").show();
        
    }
    
    function showGoogleMaps(timespan){
        $('#veMapContainer').hide();
        $('#mapcontainer').show();
        if (timespan != 'undefined' && timespan != null ) setTimeout("resetMap()", timespan);  
        else setTimeout("resetMap()", 1);    
    }


    function unloadMap(){
        if (isShowMap) GUnload();
    }
    
    function showCustomGMapButtons(){
        $('#MLSBtnOuter').show();        
        $('#TrafficButtonOuter').show();
        $('#POIBtnOuter').show(); 
        $('#GMapBtnOuter2').show();
    }
    
    function hideCustomGMapButtons(){
        $('#MLSBtnOuter').hide();        
        $('#TrafficButtonOuter').hide();
        $('#POIBtnOuter').hide(); 
    }
    
    
    function resetMap() {           
    
        if (!isShowMap) return;
        
        
        // clean up 
        map = null;
        $('#map').remove();
        
        // now set up again
        $('<div id="map"></div>').appendTo('#mapcontainer');
        
    
	    if (GBrowserIsCompatible() ) {
         		 
		    //  ======== Create map ==========
    		var gBarOptions = {
                resultList : G_GOOGLEBAR_RESULT_LIST_SUPPRESS,
                linkTarget : G_GOOGLEBAR_LINK_TARGET_BLANK,
                searchFormHint : "schools, etc.",
                showOnLoad : true
            };
            
		    map = new GMap2(document.getElementById("map"), {googleBarOptions: gBarOptions});
    		
            if (!isPrint) trafficInfo = new GTrafficOverlay();

		    map.addMapType(G_PHYSICAL_MAP);

		    //  ======== Default location (US center)  ==========
		    map.setCenter(new GLatLng(flLocationLat, flLocationLon ), 15);
		    map.setMapType(0);
    		
		   if (!isPrint)  map.enableDoubleClickZoom();


		    //  ======== Add a map controls  ==========
		    //map.addControl(new GOverviewMapControl(new GSize(150,150)));
		    if (!isPrint) map.addControl(new GScaleControl());		
            if (!isPrint) map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 45)));
            if (!isPrint) map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 19)));	 
            
            if (isGLocalSearch && $('#section-1').css('display') == "block"){
                map.enableGoogleBar();
            }
            
            var flMarker = new GxMarker( new GPoint( flLocationLon, flLocationLat ), getIcon(), flTooltip, this.map );
            map.addOverlay(flMarker);
            
            vpakGeoRSS = new VPakGeoRSS();             
            map.addVPakGeoRSS(vpakGeoRSS);
                        
		    showTraffic();
            
		    //  ======= Set up events ===

		    GEvent.addListener(map, "infowindowopen", function() {
              
		        infoWindowOn = true;
		        tmpLoc = map.getCenter();
                
            });		
            
		    GEvent.addListener(map, "clearoverlays", function() {
    		
                infoWindowOn = false;

            });		        
                    
		    GEvent.addListener(map, "infowindowclose", function() {

		            infoWindowOn = false;
		            if (tmpLoc != null){
		                map.panTo(tmpLoc);
		                tmpLoc = null;
		            }

                
            });	        
    		
		    GEvent.addListener(map, "moveend", function() {

		            onMoveEnd();
                
            });

            GEvent.addListener(map, "zoomend", function(o,n) {

                    onZoomEnd(0,n);
            });    
            
            showCustomGMapButtons();        
        }
    }
    
    function toggleTraffic() {
    
         $('#TrafficButtonInner').toggleClass("TrafficButtonSelected"); 
         
         if (trafficToggleState == 1) {
         
            $('#TrafficButtonInner').text('Show Traffic');
            map.removeOverlay(trafficInfo);
            trafficToggleState = 0;
         } else {

            $('#TrafficButtonInner').text('Hide Traffic');         
            map.addOverlay(trafficInfo);
            trafficToggleState = 1;
         }    
    }
    
    function getIcon(){
        icon  = new GIcon();
	    icon.image = flIcon;
        icon.shadow = flIconShadow;
	    icon.iconSize = new GSize(26, 34);
	    icon.shadowSize = new GSize(50, 34);
	    icon.iconAnchor = new GPoint(9, 34);
	    icon.infoWindowAnchor = new GPoint(17,34);
	    return icon;
    }    
    

    function toggleCoupons(){

        $('#POIBtnInner').toggleClass("POIBtnSelected");        
        
        if (couponsOn){
            // hide
            couponsOn = false;
            $('#POIBtnInner').text('Show Local Coupons');
            vpakGeoRSS.flushMarkers();
            
        }
        else{
            //show
            couponsOn = true;
            $('#POIBtnInner').text('Hide Local Coupons');
            reloadVPakMarkers();
        }
    }
    
    function toggleBtnHover(e){
        $(e).toggleClass("panelActionBtnHover");
    }
 
    
    function showMap(){
        $('#container').triggerTab(1);
        loadMapDelayed();
    }
    
    function showPhotos(){
        $('#container').triggerTab(2);
        
        
    }
    
     function showMLSSearch(){
        var lis = $('#container>ul>li');

        $('#container').triggerTab(lis.length);
        //$('#container').triggerTab(2);
    }
    
    
    // Gets the individual boundary values
    function getBoundaryValues()
    {
        this.b = this.map.getBounds().getSouthWest().lat();
        this.l = this.map.getBounds().getSouthWest().lng();
        this.t = this.map.getBounds().getNorthEast().lat();
        this.r = this.map.getBounds().getNorthEast().lng();    
        this.cLat = this.map.getCenter().lat();
        this.cLon = this.map.getCenter().lng();
        
    }
    
    function onMoveEnd(){
        getBoundaryValues();
        reloadVPakMarkers();
    }

    function onZoomEnd(o,n){
        getBoundaryValues();
        
    }    
    
    function showTraffic(){
        
        if (!isPrint) map.addOverlay(trafficInfo);
    }
    
    function showBookmarkPanel(){
        $("#bookmarkPanel").css({ display: "block"})
        dlgBookmarkPanel.show();
    }
    
    function closeBookmarkPanel(){
        dlgBookmarkPanel.hide();
    }
    
    function showSharePanel(){
        $("#sharePanel").css({ display: "block"})        
        YAHOO.util.Dom.get('shareFormResp').innerHTML = '';
        dlgSharePanel.show();
    }
    
    function closeSharePanel(){
        dlgSharePanel.hide();
    }  
    
    function showContactUsPanel(){
        $("#contactUsPanel").css({ display: "block"});
        YAHOO.util.Dom.get('contactUsFormResp').innerHTML = '';
        dlgContactUsPanel.show();
    }
    
    function closeContactUsPanel(){
        dlgContactUsPanel.hide();
    }        
    
    function showBirdsEyeViewPanel(){
       if(dlgBirdsEyePanel == 'undefined' || dlgBirdsEyePanel == null){
       
            var vWidth = Math.round($(window).width() * 0.8 ) - 20;
            var vHeight = Math.round($(window).height() * 0.8 ) - 20;
            dlgBirdsEyePanel = new YAHOO.widget.Panel("birdseyePanel", {
            width: vWidth + "px", 
            height: vHeight + "px",
            fixedcenter: true, 
            constraintoviewport: true, 
            underlay:"shadow", 
            effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5},
            close:false, 
            visible:false, 
            modal:true,
            draggable:false} );        
            
            dlgBirdsEyePanel.render();    
            $("#birdseyeview").css("height", vHeight - 50 + "px");
            frames['birdseyeview'].location.href = birdsEyeUrl;
                  
            
            
        }
        $("#birdseyePanel").css({ display: "block"}) 
        dlgBirdsEyePanel.show();
        
    }
    
    function closeBirdsEyeViewPanel(){
        dlgBirdsEyePanel.hide();
    }      
    
    
    
    /* ========================================== 
    VPak
     ========================================== */
    var callbackRoot = '';
    var vpakCallbackRoot = root + 'vpak.aspx';
    
    function reloadVPakMarkers()
    {
        
        if (!infoWindowOn && couponsOn){
            vpakGeoRSS.initialize(map);
            vpakGeoRSS.load( getVPakpCallBackUrl() );
        }
    }

    // VPak POI callback
    function getVPakpCallBackUrl()
    {
        //var i = YAHOO.util.Dom.get('CouponType').selectedIndex;
        //paramCouponType = YAHOO.util.Dom.get('CouponType').options[i].value;
        paramCouponType = "General Services";
        cb = vpakCallbackRoot;
        cb += "?z=" + map.getZoom();
        cb += "&b=" + this.b;
        cb += "&l=" + this.l;
        cb += "&t=" + this.t;
        cb += "&r=" + this.r;
        //cb += "&p=" + this.currentPage;  
        cb += "&p=" + 1;    
        cb += "&xy=" + encodeURI(map.getSize());  
        cb += "&cat=" + escape(paramCouponType);     
        
        return cb;
        
    }

    function share(){
        var handleSuccess = function(o){
	        if(o.responseText !== undefined){
	        
		        sendEmailResponse = o.responseText.parseJSON();
		        if (sendEmailResponse){
                    
                    if (sendEmailResponse.EmailResponse[0].IsError == 'True'){
                        YAHOO.util.Dom.get('shareFormResp').innerHTML = sendEmailResponse.EmailResponse[0].Message;
                    }
                    else{
                        YAHOO.util.Dom.get('shareFormResp').innerHTML = '<span style="color:Navy">The message has been successfuly sent.</span>';
                    }
		        }
		        YAHOO.util.Dom.get('shareSendBtn').value = 'Send';
	        }
        }

        var handleFailure = function(o){
            YAHOO.util.Dom.get('shareFormResp').value = 'An error occured while trying to send the email. Please try again.';
            YAHOO.util.Dom.get('shareSendBtn').value = 'Send';
        }

        var callback =
        {
          success:handleSuccess,
          failure: handleFailure,
          argument: ['foo', 'bar'],
          timeout: 3000
        };        
        
        var sUrl = root + 'em.aspx';
        var postData = 
        'fn=' + escape(YAHOO.util.Dom.get('shareFromName').value)
        + '&f=' + escape(YAHOO.util.Dom.get('shareFromEmail').value)     
        + '&ph=' + ''    
        + '&tn=' + '' 
        + '&t=' + escape(YAHOO.util.Dom.get('shareToEmail').value) 
        + '&p=' + escape(pLink) 
        + '&s=' + escape("Take a look at this property: " + postTitle) 
        + '&m=' + escape(YAHOO.util.Dom.get('shareMsg').value) 
        + '&htmpl=' + 'shareHtml.html' 
        + '&ttmpl=' + 'shareTxt.txt';
        
        YAHOO.util.Dom.get('shareFormResp').innerHTML = '';
        YAHOO.util.Dom.get('shareSendBtn').value = 'Wait ...';
        var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
    
    }
    
    function contactUs(){
        var handleSuccess = function(o){
	        if(o.responseText !== undefined){
	        
		        sendEmailResponse = o.responseText.parseJSON();
		        if (sendEmailResponse){
                    
                    if (sendEmailResponse.EmailResponse[0].IsError == 'True'){
                        YAHOO.util.Dom.get('contactUsFormResp').innerHTML = sendEmailResponse.EmailResponse[0].Message;
                    }
                    else{
                        YAHOO.util.Dom.get('contactUsFormResp').innerHTML = '<span style="color:Navy">The message has been successfuly sent.</span>';
                    }
		        }
		        YAHOO.util.Dom.get('contactUsSendBtn').value = 'Send';
	        }
        }

        var handleFailure = function(o){
            YAHOO.util.Dom.get('contactUsFormResp').value = 'An error occured while trying to send the email. Please try again.';
            YAHOO.util.Dom.get('contactUsSendBtn').value = 'Send';
        }

        var callback =
        {
          success:handleSuccess,
          failure: handleFailure,
          argument: ['foo', 'bar'],
          timeout: 3000
        };        
        
        var sUrl = root + 'em.aspx';
        var postData = 
        'fn=' + escape(YAHOO.util.Dom.get('contactUsFromName').value)
        + '&f=' + escape(YAHOO.util.Dom.get('contactUsFromEmail').value)  
        + '&ph=' + escape(YAHOO.util.Dom.get('contactUsFromPhone').value)         
        + '&tn=' + '' 
        + '&t=' + escape(to) 
        + '&p=' + escape(pLink) 
        + '&s=' + escape("Request for more information: " + postTitle) 
        + '&m=' + escape(YAHOO.util.Dom.get('contactUsMsg').value) 
        + '&htmpl=' + 'contactUsHtml.html' 
        + '&ttmpl=' + 'contactUsTxt.txt';
        
        YAHOO.util.Dom.get('contactUsFormResp').innerHTML = '';
        YAHOO.util.Dom.get('contactUsSendBtn').value = 'Wait ...';
        var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
    
    }
    
    function requestMarketStat(){
        var handleSuccess = function(o){
	        if(o.responseText !== undefined){
	        
		        sendEmailResponse = o.responseText.parseJSON();
		        if (sendEmailResponse){
                    
                    if (sendEmailResponse.EmailResponse[0].IsError == 'True'){
                        YAHOO.util.Dom.get('marketStatFormResp').innerHTML = sendEmailResponse.EmailResponse[0].Message;
                    }
                    else{
                        YAHOO.util.Dom.get('marketStatFormResp').innerHTML = '<span style="color:Navy">The request has been successfuly sent.</span>';
                    }
		        }
		        YAHOO.util.Dom.get('marketStatSendBtn').value = 'Send';
	        }
        }

        var handleFailure = function(o){
            YAHOO.util.Dom.get('marketStatFormResp').value = 'An error occured while trying to send the email. Please try again.';
            YAHOO.util.Dom.get('marketStatSendBtn').value = 'Send';
        }

        var callback =
        {
          success:handleSuccess,
          failure: handleFailure,
          argument: ['foo', 'bar'],
          timeout: 3000
        };        
        
        var sUrl = root + 'em.aspx';
        var postData = 
        'fn=' + escape(YAHOO.util.Dom.get('marketStatFromName').value)
        + '&f=' + escape(YAHOO.util.Dom.get('marketStatFromEmail').value)  
        + '&ph=' + escape(YAHOO.util.Dom.get('marketStatFromPhone').value)         
        + '&tn=' + '' 
        + '&t=' + escape(to) 
        + '&p=' + escape(pLink)         
        + '&sp=' + escape(pStatsLink) 
        + '&s=' + escape("Market report request for: " + postTitle) 
        + '&m=' + escape(YAHOO.util.Dom.get('marketStatMsg').value) 
        + '&htmpl=' + 'MarketStatHtml.html' 
        + '&ttmpl=' + 'MarketStatTxt.txt';
        
        YAHOO.util.Dom.get('marketStatFormResp').innerHTML = '';
        YAHOO.util.Dom.get('marketStatSendBtn').value = 'Wait ...';
        var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
    
    }

    
    
