﻿// JScript File

//Only load frames once
var amenitiesLoaded = false;
var floorplanLoaded = false;
var virtualTourLoaded = false;
var communityLoaded = false;
var brochureLoaded = false;
var photosLoaded = false;
var lastTab = "";
var lastTabIndex = -1;

var frameHeight, frameWidth;
var pwin;

function printImg() 
{
  pwin = window.open(document.getElementById("floorPlanImg").src,"_blank");
  setTimeout("pwin.print()",2000);
}

function selectFrame()
{
    if (amenitiesLoaded == false)
        SelectTab('frame');
    
    amenitiesLoaded = true;
}

function tabChanged(sender, e)
{
   var tab =  sender.get_activeTab();
   if (tab != null)
   {
        var x = tab._header.id;
        var y = x.replace('__tab_TabContainer1_', '');
        if (lastTab == "tabVT")
        {
            if (document.getElementById('video1') != null)
            {
                var obj = document.getElementById('video1').controls;
                if (obj != null)
                    obj.pause();       
            }            
        }
        else if (y = "tabVT")
        {
            if (document.getElementById('video1') != null)
            {
                var obj = document.getElementById('video1').controls;
                if (obj != null)
                    obj.play();        
            }            
        }
        lastTab = x.replace('__tab_TabContainer1_', '');
        lastTabIndex = tab._tabIndex;
   } 
}

function selectVT()
{
    if (document.getElementById('EmbeddedVT').value == "true")
    {
        if (document.getElementById('video1') != null)
        {
            var obj = document.getElementById('video1').controls;
            if (obj != null)
                obj.play();        
        }
    }
    else if (virtualTourLoaded == false) 
        SelectTab('tour');
        
    virtualTourLoaded = true;        
}

function selectBrochure()
{
    if (brochureLoaded == false)
        SelectTab('brochure');
    
    brochureLoaded = true;
}

function selectPhotos()
{
    if (photosLoaded == false)
        SelectTab('photos');
        
    photosLoaded = true;
}

function selectFloorplan()
{
    var floorPlanURL = document.getElementById('FloorPlanURL').value;
    if ((floorPlanURL != "NON-PDF") || (floorplanLoaded == false))
        SelectTab('floorplan');
    
    floorplanLoaded = true;
}

function getHeight()
{
    var myHeight = 0;
    if (typeof(window.innerHeight) == 'number') 
        myHeight = window.innerHeight;
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) 
        myHeight = document.documentElement.clientHeight;
    else if (document.body && (document.body.clientWidth || document.body.clientHeight)) 
        myHeight = document.body.clientHeight;
        
    return myHeight;
}

//Reload the window on a resize event
function redo() 
{   
    var newHeight = getHeight();
    if (orgHeight != newHeight)
    {        
        //Ignore popup warnings bar adjustments. 
        if ((newHeight > (orgHeight -32)) && (newHeight < (orgHeight + 32)))
            return;
        orgHeight = newHeight;
        if (location.href.indexOf('activeTab') > -1)
        {
            var ref = location.href;
            var indx = location.href.indexOf('activeTab');
            location.href = ref.substring(0, indx) + 'activeTab=' + lastTabIndex;
        }
        else
            location.href = location.href + '&activeTab=' + lastTabIndex;
    }
}

//Initial load from embedded.aspx
function preloadFrames()
{  
    //Auto re
    orgHeight = getHeight();
    window.onresize = redo;  
    
    //Load community
    if (document.getElementById('TabContainer1_tabCommunity_wikiDisplay') != null)
    {
        if (document.getElementById('TabContainer1_tabCommunity_wikiDisplay').innerHTML.length == 0)
        {
            var id = document.getElementById('PropertyID').value;    
            var addr = document.getElementById('HomeAddress').value;
            getLocation(id, addr);
        }
    }   
    
    //If a tab was preselected populate it now
    if (document.getElementById('ActiveTab').value.length > 0)
    {
        var activeTab = document.getElementById('ActiveTab').value;
        lastTabIndex = document.getElementById('ActiveTabIndex').value;
        switch (activeTab)
        {
            case 'tabPropertyDetails':
                break;
            case 'tabPhotos':
                selectPhotos();
                break;
            case 'tabBrochure':
                selectBrochure();
                break;
            case 'tabFloorplan':
                selectFloorplan();
                break;
            case 'tabCommunity':
                break;
            case 'tabVT':
                selectVT();
                break;
            case 'tabAmenities':
                selectFrame();
                break;
        }
    }   
    else
    {  
        //Check if the first tabs are missing to preload the first listed tab...
        var pd = document.getElementById('TabContainer1_tabPropertyDetails');        
        if (pd == null)
        {
            var ph = document.getElementById('TabContainer1_tabPhotos');   
            var am = document.getElementById('TabContainer1_tabAmenities');
            var br = document.getElementById('TabContainer1_tabBrochure');
            var fp = document.getElementById('TabContainer1_tabFloorplan');
            var cm = document.getElementById('TabContainer1_tabCommunity');
            var vt = document.getElementById('TabContainer1_tabVT');
            if (ph != null)
                selectPhotos();
            else if (vt != null)
                selectVT();
            else if (fp != null)
                selectFloorplan();
            else if (br != null)
                selectBrochure();
            else if (am != null)
                selectFrame();          
        }
    }    
}

function SelectTab(itemID)
{
	var addr = document.getElementById('HomeAddress').value;     
    var id = document.getElementById('PropertyID').value;     
    var desc = document.getElementById('description');
    var PCID = document.getElementById('PCID').value;
    try { desc.innerHTML = addr; } catch (err) {}
    
    if (window.innerHeight)
        var height = window.innerHeight - 160; 
    else
        var height = document.documentElement.offsetHeight - 160; 
                                       
    var frame = document.getElementById(itemID);
    frame.height = height + 'px';  
		
    if (itemID == 'frame')
    {        
        var agentID = document.getElementById('AgentID').value;
        if (agentID.length > 0)
           frame.src = itemID + ".aspx?address=" + addr + "&propertyID=" + id + '&AgentID=' + agentID + '&PCID=' + PCID;
        else
            frame.src = itemID + ".aspx?address=" + addr + "&propertyID=" + id + '&PCID=' + PCID;
    }
    else if (itemID == 'brochure')
    	frame.src = document.getElementById('BrochureURL').value;
    else if (itemID == 'tour')
        frame.src = document.getElementById('VirtualTourURL').value;        
    else if (itemID == 'floorplan')
    {
        var floorPlanURL = document.getElementById('FloorPlanURL').value;
        if (floorPlanURL == "NON-PDF")
            frame.src = "EmbeddedFloorPlan.aspx?PropertyID=" + id  + '&PCID=' + PCID;
        else
            frame.src = floorPlanURL;      
    }   
    else if (itemID == 'photos')
    {
        frame.src = "PhotoPage.aspx?PropertyID=" + id  + '&PCID=' + PCID;
    }
}

function getLocation(id, addr)
{
    PageMethods.GetLatLon(id, function (results)
        {
            //If we don't already have it try looking it up now...
            if (results.length == 0)
            {
                var geocoder = new GClientGeocoder();
                geocoder.getLatLng(addr, function(point) 
                    {
                        if (point)                
                        {
                            var lat = point.y;
                            var lon = point.x;
                        
                            //Find the neighborhood and select and draw polygon
                            PageMethods.GetCity(lat, lon, selectHood);                     
                        }
                        else
                            document.getElementById('TabContainer1_tabCommunity_wikiDisplay').innerHTML = "Unable to determine the community for the selected property.";
                    }
                );    
            }
            else
                PageMethods.GetCity(results[0], results[1], selectHood);            
        }  
    );  
}

function selectHood(results)
{
    PageMethods.GetHelpText("Neighborhood", results, function (txt)
        {
            if (txt.length > 0)
                document.getElementById('TabContainer1_tabCommunity_wikiDisplay').innerHTML = txt;
            else
                document.getElementById('TabContainer1_tabCommunity_wikiDisplay').innerHTML = "There is no community information available.";
                
            document.getElementById('wikiLoading').style.visibility = 'hidden';
        }
    );
}

function pictureChange(img, makeBig)
{
    var src = img.src;
    if (makeBig)
        img.width = 400;
    else
        img.width = 200;    
}

//Set the clicked image to the current image
function changeImage(imageID)
{
    if (currentCamera != null)
        currentCamera.style.backgroundColor = "";
    currentCamera = null;
    
    var imgCurrent = document.getElementById('currentImage');
    imgCurrent.src = 'http://www.peekacity.com/Handler.ashx?Size=M&PhotoID=' + imageID;  
    imgCurrent.alt = 'Click image to view full size';
}

var currentCamera;
//Change the current image display
function imageUpdate(imgCamera)
{   
    if (currentCamera != null)
        currentCamera.style.backgroundColor = "";
    
    currentCamera = imgCamera;
    imgCamera.style.backgroundColor = "Red";
    var imgFloorPlan = document.getElementById('floorPlanImg');
    var img = document.getElementById('currentImage');
    var imgSrc = imgCamera.id.replace('img_', '');
    img.src = "http://www.peekacity.com/handler.ashx?Size=M&PhotoID=" + imgSrc;   
}

//Add the hotspot on the client side so we don't need to reload
function addHotspot()
{
    //Update the database
    var floorPlan = readCookie('SelectedFloorplan');
    var hotspot = document.getElementById('HotSpotLocation').value;
    var direction = document.getElementById('ddlDirections').value;
    var image = document.getElementById('ddlImages').value;    
         
    //Clear the item from the display if it already exists
    var cameraArea = document.getElementById('cameraArea');
    var img = document.getElementById('img_' + image);
    if (img != null)
        cameraArea.removeChild(img);    
    
    //Update the database with the hotspot
    PageMethods.AddHotSpot(floorPlan, hotspot, direction, image);
    
    //Now add in the hotspot 
    PageMethods.GetPhotoInPlan(image, loadAreas);
    
    //Remove the display
    document.getElementById('floatAdd').style.visibility = 'hidden'; 
    return false;
}

function deleteHotSpot()
{
    //Update the database
    var imageID = document.getElementById('HotSpotLocation').value;
    PageMethods.RemoveHotSpot(imageID);
        
    //Clear the item from the display
    var cameraArea = document.getElementById('cameraArea');
    var img = document.getElementById('img_' + imageID);
    cameraArea.removeChild(img);    
    
    //Remove the display
    document.getElementById('floatRemove').style.visibility='hidden'; 
    return false;
}

//Remove the selected hotspot...
function removeHotSpot(imgCamera)
{
    //We are going to remove this id if they confirm the click...
    var imgSrc = imgCamera.id.replace('img_', '');
    var loc = document.getElementById('HotSpotLocation');
    loc.value = imgSrc;
    
    //Set the shader size and location
    var shader = document.getElementById('floatRemove').style;
    shader.visibility = "visible";
    shader.left = imgCamera.offsetLeft + "px";
    shader.top = imgCamera.offsetTop + "px";   
    
}

function findPos(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	
	return [curleft,curtop];
}

function whereClick(e)
{   
    var imgFloorPlan = document.getElementById('floorPlanImg');    
    if (e.pageX || e.pageY)
    {    
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY)
    {
        posx = e.clientX + document.documentElement.scrollLeft;
        posy = e.clientY + document.documentElement.scrollTop;                       
    }
              
    var objPos = findPos(imgFloorPlan);    
    var x = posx - objPos[0];
    var y = posy - objPos[1];              
    var loc = document.getElementById('HotSpotLocation');
    loc.value = x + "," + y;
    
    //Set the shader size and location
    var shader = document.getElementById('floatAdd').style;
    shader.visibility = "visible";
    shader.left = posx + "px";
    shader.top = posy + "px";    
}

//Change the current floorplan display
function floorPlan(imgSrc, mapID, floorPlanID)
{   
    //If we are tracking this store it.
    setCookie('SelectedFloorplan', floorPlanID);
        
    //Get the map object and clear out existing elements
    var cameraArea = document.getElementById('cameraArea');
    while (cameraArea.childNodes.length) 
        cameraArea.removeChild(cameraArea.firstChild)            
    
    var img = document.getElementById('floorPlanImg');
    img.removeAttribute("width");
    img.removeAttribute("height");
    img.src = imgSrc;
    
    //Set the print image as well
    var imgPrint = document.getElementById('floorPlanPrintImg');
    if (imgPrint != null)
        imgPrint.src = imgSrc;
        
    img.useMap = '#floorMap';
    var floorName = document.getElementById('floorName');
    floorName.innerHTML = mapID;
    var floorPrintName = document.getElementById('floorPrintName');
    if (floorPrintName != null)
        floorPrintName.innerHTML = mapID;
       
    if (document.getElementById('camerasLoading') != null)
        document.getElementById('camerasLoading').style.visibility = 'visible';
    PageMethods.GetFloorPlanArea(floorPlanID, loadAreas);
}

var objPos = null;

//Preload the images and the maps
function getImages()
{
   var imgFloorPlan = document.getElementById('floorPlanImg');
   objPos = findPos(imgFloorPlan); 
   var property_intid = document.getElementById('PropertyID').value;
   if (property_intid != "")
        PageMethods.GetFloorPlans(property_intid, loadPlans);
}

function loadPlans(results)
{
    var list = document.getElementById('floorList');
    for (i=0;i<results.length;i++)
    {
        var imgSrc = results[i].ImageSource;
        var mapID = results[i].Name;
                
        var listItem = document.createElement("li");
        var link = document.createElement('a');
        link.href = "javascript:floorPlan('" + imgSrc + "', '" + mapID + "', '" + results[i].Id + "')";
        link.innerHTML = mapID;
        listItem.appendChild(link);
        list.appendChild(listItem);   
        //if (i == 0)
            //floorPlan(imgSrc, mapID, results[i].Id);
    }  
    
    //There are no plans...
    if (results.length == 0) {
        var imgFloorPlan = document.getElementById('floorPlanImg');
        imgFloorPlan.src = "";
        var instructions = document.getElementById('instructions');
        if (instructions != null) {
            document.getElementById('instructions').innerText = "Please add a floorplan.";
            document.getElementById('butDelete').style.visibility = 'hidden';
        }
    }
    else
        floorPlan(results[0].ImageSource, results[0].Name, results[0].Id);   
}

//Build the map areas for a given floorplan
function loadAreas(results)
{
    //Get the map object and clear out existing elements
    var cameraArea = document.getElementById('cameraArea');
    var imgFloorPlan = document.getElementById('floorPlanImg');
            
    var objPos = findPos(imgFloorPlan); 
    
    for (i=0;i<results.length;i++)
    {
        var img = document.createElement("img");
        switch (results[i].Direction)
        {
            case 'N':
                img.src = 'images/camera/North.gif';
                break;
            case 'NW':
                img.src = 'images/camera/North-West.gif';
                break;
            case 'NE':
                img.src = 'images/camera/North-East.gif';
                break;
            case 'E':
                img.src = 'images/camera/East.gif';
                break;
            case 'S':
                img.src = 'images/camera/South.gif';
                break;
            case 'SE':
                img.src = 'images/camera/South-East.gif';
                break;
            case 'SW':
                img.src = 'images/camera/South-West.gif';
                break;
            case 'W':
                img.src = 'images/camera/West.gif';
                break;
        }
        img.id = "img_" + results[i].Id;
        img.width = '18';
        img.height = '18';
        var coordinates = results[i].Name.split(',');
        var x = parseInt(coordinates[0]) + objPos[0] - 9;
        var y = parseInt(coordinates[1]) + objPos[1] - 9;       
    
        img.style.left = x + 'px';
        img.style.top = y + 'px';        
        img.style.position = 'absolute';
        addEvent(img, 'mouseover', function() { imageUpdate(this); }); 
        if (document.getElementById("Builder") != null)
            addEvent(img, 'click', function() { removeHotSpot(this); });
        cameraArea.appendChild(img);        
        
        //Force preload of images
        var imgPreload = document.createElement("image");
        imgPreload.src = "http://www.peekacity.com/handler.ashx?Size=M&PhotoID=" + results[i].Id;   
        
         if (currentCamera == null)
            imageUpdate(img);
      }      
       
      if (document.getElementById('camerasLoading') != null)
            document.getElementById('camerasLoading').style.visibility = 'hidden';    
}

function addEvent(obj, type, fn) 
{
    if (obj.attachEvent) 
    {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
        obj.attachEvent('on'+type, obj[type+fn]);
    } 
    else
        obj.addEventListener( type, fn, false );
}

function removeEvent(obj, type, fn)
{
    if (obj.detachEvent) 
    {
        obj.detachEvent( 'on'+type, obj[type+fn] );
        obj[type+fn] = null;
    } 
    else
        obj.removeEventListener( type, fn, false );
}

function write_div(text)
{
    var div1 = document.getElementById('di1');
    div1.innerHTML=text;
}
 
function big()
{
    var ctrl = document.getElementById('currentImage');
    if (ctrl == null)
        ctrl = document.getElementById('TabContainer1_Panel1_currentImage');
    var src = ctrl.src;
    ondiv=src;
	write_div("<a href=javascript:void(0) onmouseout='big_hide()' onmouseover='ondiv=1'><img border=0 name=ib src="+src+"></a>");
}

function big_hide()
{
	ondiv=0;
	t3=window.setTimeout('big_hide2()',100);
}

function big_hide2()
{
    if (ondiv==0)
        write_div("");	    
}

//Generic method to read a cookie
function readCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
	    var c = ca[i];
	    while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

//Set temporary cookie expiring in one hour
function setCookie(cookieName, cookieValue) 
{
    var today = new Date();
    var expire = new Date();
   
    expire.setTime(today.getTime() + 3600000);
    document.cookie = cookieName+"="+cookieValue + ";expires="+expire.toGMTString();
}

function deleteCookie(cookieName)
{
    var today = new Date();
    var expire = new Date();
   
    expire.setTime(today.getTime() - 1);
    document.cookie = cookieName+"=0;expires="+expire.toGMTString(); 
}