var flashvars = {};
var params = {};
params.wmode = "transparent";
var attributes = {};
attributes.id = "flash_content";
swfobject.embedSWF("/swf/legacy.swf", "flash_content", "960", "490", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);

//this is for the image map
//will expand the region onclick in the image map 
function imageMap(region){
    $(".portfolio_list_treeview li.region_li > span:contains(" + region + ")").trigger('click');
}

if (window.location.toString().indexOf('empirestaging') < 0) {
    try {
        var pageTracker = _gat._getTracker("UA-0000000-0");
        pageTracker._trackPageview();
    } 
    catch (err) {
    }
}

jQuery.fn.addPrintButton = function(){
    return this.each(function(){
        $('<a class="print_button" href=""><span class="skip">Print this Page</span></a>').click(function(){
            window.print();
            return false;
        }).appendTo(this);
    });
}

this.screenshotPreview = function(){
    /* CONFIG */
    
    xOffset = 150;
    yOffset = -5;
    
    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result
    
    /* END CONFIG */
    $("a.screenshot").hover(function(e){
        this.t = this.title;
        this.title = "";
        var c = (this.t != "") ? "<br/>" + this.t : "";
        $("body").append("<p id='screenshot'><img src='" + $(this).attr('rel') + "' alt='" + $.trim($(this).text()) + "' />" + c + "</p>");
        $("#screenshot").css("top", (e.pageY - xOffset) + "px");
        $("#screenshot").show();
    }, function(){
        this.title = this.t;
        $("#screenshot").hide();
        $("#screenshot").remove();
    });
    $("a.screenshot").mousemove(function(e){
        $("#screenshot").css("top", (e.pageY - xOffset) + "px").css("left", (e.pageX + yOffset) + "px");
    });
};

// Variables used for Auto Coda Slilder
var theInt = null;
var $crosslink, $navthumb;
var curclicked = 0;

theInterval = function(cur){
    clearInterval(theInt);
    
    if (typeof cur != 'undefined') 
        curclicked = cur;
    
    $crosslink.removeClass("active-thumb");
    $navthumb.eq(curclicked).parent().addClass("active-thumb");
    $(".home_mid_col .stripNav ul li a").eq(curclicked).trigger('click');
    $(".home_left_col .stripNav ul li a").eq(curclicked).trigger('click');
    
    theInt = setInterval(function(){
        $crosslink.removeClass("active-thumb");
        $navthumb.eq(curclicked).parent().addClass("active-thumb");
        $(".home_mid_col .stripNav ul li a").eq(curclicked).trigger('click');
        $(".home_left_col .stripNav ul li a").eq(curclicked).trigger('click');
        curclicked++;
        if (4 == curclicked) 
            curclicked = 0;
        
    }, 10000);
};

$(document).ready(function(){

    $('#sub_nav').addPrintButton();
    
    // Main Menu SuperFish
    $("ul.sf-menu").supersubs({
        minWidth: 12,
        maxWidth: 27,
        extraWidth: 1
    }).superfish({
        animation: {
            height: 'show'
        },
        speed: 'fast',
        delay: 500,
        autoArrows: false
    });
    
    // Sub Menu SuperFish
    $("ul.sf-menu2").supersubs({
        minWidth: 12,
        maxWidth: 27,
        extraWidth: 1
    }).superfish({
        animation: {
            height: 'show'
        },
        speed: 'fast',
        delay: 500,
        autoArrows: false
    });
    
    // Thumbnail Preview on Hover
    screenshotPreview();
    
    // Coda Slider
    $("#slider").codaSlider();
    $("#slider2").codaSlider();
    $("#slider3").codaSlider();
    
    $navthumb = $(".nav-thumb");
    $crosslink = $(".cross-link");
    
    $navthumb.click(function(){
        var $this = $(this);
        theInterval($this.parent().attr('href').slice(1) - 1);
        return false;
    });
    theInterval();
    
    var myIcon = new GIcon();
    myIcon.image = '/images/markers/image.png';
    myIcon.printImage = '/images/markers/printImage.gif';
    myIcon.mozPrintImage = '/images/markers/mozPrintImage.gif';
    myIcon.iconSize = new GSize(20, 34);
    myIcon.shadow = '/images/markers/shadow.png';
    myIcon.transparent = '/images/markers/transparent.png';
    myIcon.shadowSize = new GSize(37, 34);
    myIcon.printShadow = '/images/markers/printShadow.gif';
    myIcon.iconAnchor = new GPoint(10, 34);
    myIcon.infoWindowAnchor = new GPoint(10, 0);
    myIcon.imageMap = [13,0,15,1,16,2,17,3,18,4,18,5,19,6,19,7,19,8,19,9,19,10,19,11,19,12,19,13,18,14,18,15,17,16,16,17,15,18,14,19,14,20,13,21,13,22,12,23,12,24,12,25,12,26,11,27,11,28,11,29,11,30,11,31,11,32,11,33,8,33,8,32,8,31,8,30,8,29,8,28,8,27,8,26,7,25,7,24,7,23,6,22,6,21,5,20,5,19,4,18,3,17,2,16,1,15,1,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,1,5,1,4,2,3,3,2,4,1,6,0];

    // Click handlers for thumbnails 
    $('#thumb_nav li a').click(function(){
    
        $('#thumb_nav li a').removeClass('selected');
        $(this).addClass('selected');
        var url = $(this).attr('href');
        
        var img = new Image();
        //apply the fading effect once the image has loaded
        img.onload = function(){
            $('#image_holder').fadeOut('fast', function(){
                $('#image_holder').attr('src', '' + url + '');
                $('#image_holder').fadeIn();
            });
        }
        
        // set the source of the image to monitor the load  
        img.src = url;
        return false;
    });
    
    // Sorted Table
    $("#fund_table").tablesorter({
        widgets: ['zebra'],
        // define a custom text extraction function 
        textExtraction: function(node){
            // extract data from markup and return it  
            var textNode = $(node).text();
            return $.trim(textNode);
        }
    })
    
    // Before / After Widget
    
    $('a.caller').click(function(){
        //try{
        $(this).siblings("div").children('a').lightBox();
        $(this).siblings("div").children('a:first').trigger('click');
        return false;
        //}catch(err){
        // console.log("failed");		
        //}
    });
    
    //hide everything by default
    $('.portfolio_list_treeview li.region_li ul').hide();
    
		//reset all of the region elements and show the initial region map
		$('#portfolio_reset').click(function(){
			  $regions = $('.portfolio_list_treeview').siblings('ul').children('li');
        $regions.children('ul').hide();
        $regions.removeClass('open');
				
				$regions = $('.portfolio_list_treeview').children('li');
        $regions.children('ul').hide();
        $regions.removeClass('open');
				
				//check to see if there are any regions left open, if not replace the map with the west coast static map
        if(!$(this).parent().is('.open')){
          $('#map1').html($('#map1_hidden').html());
        }
				
				return false;
		})
		
    //onclick the spans
    $('.portfolio_list_treeview li.region_li span').click(function(){
    
        var regionData = $(this).siblings(':input');
        if (regionData.length == 0 || $(this).parent().is('.open')) {
            submarketData = $(this).parent().parent().siblings(':input');
            if (submarketData.length > 0) {
                regionData = submarketData;
            }
        }
        
        // Retrieve regions lat/long and zoom level
        var longt = $(regionData[0]).val();
        var lat = $(regionData[1]).val();
        var zoom = parseInt($(regionData[2]).val());
        
        //reset the google map with custom zoom controls on the bottom left
        $('#map1').jmap('init', {
            'mapType': 'map',
            'mapCenter': [lat, longt],
            'mapZoom': zoom,
            'mapShowjMapsIcon': false,
            'mapControl': 'zoomTopLeft'
        });
        
        //hide the other elements region elements on the level
        $kids = $(this).parent().siblings('li').children('ul');
        $kids.hide();
        $kids.parent().removeClass('open');
        
        //toggle the children ul elements
        $(this).siblings('ul').toggle();
        
        //change the class on the parent
        if ($(this).parent().is('.open')) {
            $(this).parent().removeClass('open');
        }
        else {
            $(this).parent().addClass('open');
        }
        
        //set the parent selector node
        $parentNode = $(this).parent().parent();
        
        //determine the region then close other regions
        if ($(this).parent().hasClass('region_li')) {
            $regions = $(this).parent().parent().siblings('ul').children('li');
            $regions.children('ul').hide();
            $regions.removeClass('open');
            
            //close children below the region
            $children = $(this).parent().children('ul').children('li');
            $children.children('ul').hide();
            $children.removeClass('open');
						
						//check to see if there are any regions left open, if not replace the map with the west coast static map
						if(!$(this).parent().is('.open')){
							$('#map1').html($('#map1_hidden').html());
						}
        }
        
        //determine the submarket click closed all views in that market, if so show all properties
        if ($(this).parent().hasClass('submarket_li')) {
            if (!$(this).parent().hasClass('open')) {
                $parentNode = $('.tree_wrapper');
            }
        }
				
				
        
        $("li.open table tr", $parentNode).each(function(){
        
            // Retrieve property attributes - title, type, image, link for infoWindow
            var propertyTitle = $(this).find(':input[name=property]')[0].value;
            var propertyAddress = $(this).find(':input[name=property_address]')[0].value;
						var propertyAddressGoogle = $(this).find(':input[name=property_address_google]')[0].value;
            var propertyType = $(this).find(':input[name=property_type]')[0].value;
						//flag for comm / resid
						var propertyTypeId = $(this).find(':input[name=property_type_id]')[0].value;
            var propertyImage = $(this).find(':input[name=property_image]')[0].value;
            var propertyLink = $(this).find(':input[name=property_link]')[0].value;
						var hasNewWindow = $(this).find(':input[name=has_newwindow]')[0].value;
            
            var propertyId = $(this).find(':input[name=property_id]')[0].value;
            var propertyLocationKey = $(this).find(':input[name=property_location_key]')[0].value;
            var propertyLocationLatitude = $(this).find(':input[name=property_location_latitude]')[0].value;
            var propertyLocationLongitude = $(this).find(':input[name=property_location_longitude]')[0].value;
            
						//check to see if the link should open in a new window, ONLY OPEN IN NEW WINDOW ON RESID!
						newWindowHTML = '';
						if(hasNewWindow && propertyTypeId == 2){
							newWindowHTML = ' target="blank"';
						}
						
            //format the marker for placement on the map 
            var currPointHTML = '<div style="width: 240px;">';
            if (propertyImage != '') {
                currPointHTML += '<div style="width:105px; height: 102px; float: left;"><img src="/images/public/' + propertyImage + '&h=102&w=100" alt="' + propertyTitle + '" /></div>';
                currPointHTML += '<div style="width: 135px; float: left;"><h4><a href="' + propertyLink + '"' + newWindowHTML + '>' + propertyTitle + '</a></h4>' + propertyAddress + '</div></div>'
            }
            else {
							  if( propertyLink !=''){ 
                  currPointHTML += '<div style="width: 240px; "><h4><a href="' + propertyLink + '"' + newWindowHTML + '>' + propertyTitle + '</a></h4>' + propertyAddress + '</div></div>'
                }else{
									currPointHTML += '<span style="width: 240px; "><h4>' + propertyTitle + '</h4>' + propertyAddress + '</span></div>'
								}
						}
            
            
            //cache 'this' scope to search on it later      
            var currThis = this;
            
            /*
             * Check to see if the marker is already available in the cache and that the address has not been updated.
             * Note, it creates an MD5 hash of the address and stores this in the database. If the street address is updated
             * at all this will change the hash and cause it to re-ping Google for the address
             */
            if (propertyLocationKey != hex_md5(propertyAddressGoogle) || propertyLocationLatitude == '' || propertyLocationLongitude == '') {
                // marker was not found in the db, so we'll need to add it
                $('#map1').jmap('SearchAddress', {
                    'query': propertyAddressGoogle,
                    'returnType': 'getLocations'
                }, function(result, options){
                    var valid = Mapifies.SearchCode(result.Status.code);
                    if (valid.success) {
                        $.each(result.Placemark, function(i, point){
                            //store the new lat/long into the database for caching
                            $.post("/remote/RemotePropertyService.cfc?method=updatePropertyLocation", {
                                property_id: propertyId,
                                latitude: point.Point.coordinates[1],
                                longitude: point.Point.coordinates[0],
                                property_location_key: hex_md5(propertyAddressGoogle)
                            });
                            
                            //might be able to just set this originally and have it update the form
                            propertyLocationKey = hex_md5(propertyAddressGoogle);
                            propertyLocationLatitude = point.Point.coordinates[1];
                            propertyLocationLongitude = point.Point.coordinates[0];
                            
                            $(currThis).find(':input[name=property_location_key]')[0].value = propertyLocationKey;
                            $(currThis).find(':input[name=property_location_latitude]')[0].value = propertyLocationLatitude;
                            $(currThis).find(':input[name=property_location_longitude]')[0].value = propertyLocationLongitude;
                            
                            //place the element on the map
                            $('#map1').jmap('AddMarker', {
                                'pointLatLng': [propertyLocationLatitude, propertyLocationLongitude],
                                'pointHTML': currPointHTML,
                                'pointIcon': myIcon
                            }, function(marker, options){
                            
                            });
                            
                        });
                    }
                    else {
                        $('h4').val(valid.message);
                    }
                });
            }
            else {
                //place the element on the map
                $('#map1').jmap('AddMarker', {
                    'pointLatLng': [propertyLocationLatitude, propertyLocationLongitude],
                    'pointHTML': currPointHTML,
                    'pointIcon': myIcon
                }, function(marker, options){
                
                });
            }
            
        })
    })
    
    // Fund Map
    var fundLong = $("input[name='fund_map_longitude']").val();
    var fundLat = $("input[name='fund_map_latitude']").val();
    var fundZoom = parseInt($("input[name='fund_zoom_level']").val());
    
    $('#map2').jmap('init', {
        'mapType': 'map',
        'mapCenter': [fundLat, fundLong],
        'mapZoom': fundZoom,
        'mapShowjMapsIcon': false
    });
    $("#fundMap .fundProperty").each(function(){
    
    
        var propertyTitle = $(this).next().val();
        var propertyImage = $(this).next().next().val();
        var propertyLink = $(this).next().next().next().val();
        
        // Retrieve property attributes - title, type, image, link for infoWindow
        var propertyTitle = $(this).find(':input[name=property]')[0].value;
        var propertyImage = $(this).find(':input[name=property_image]')[0].value;
        var propertyLink = $(this).find(':input[name=property_link]')[0].value;
        var propertyAddress = $(this).find(':input[name=property_address]')[0].value;
				/*get the non-pretty google address */
				var propertyAddressGoogle = $(this).find(':input[name=property_address_google]')[0].value;
        
				var propertyId = $(this).find(':input[name=property_id]')[0].value;
        var propertyLocationKey = $(this).find(':input[name=property_location_key]')[0].value;
        var propertyLocationLatitude = $(this).find(':input[name=property_location_latitude]')[0].value;
        var propertyLocationLongitude = $(this).find(':input[name=property_location_longitude]')[0].value;
        
        //format the marker for placement on the map 
        var currPointHTML = '<div style="width: 240px;">';
        if (propertyImage != '') {
            currPointHTML += '<div style="width:105px; height: 102px; float: left;"><img src="/images/public/' + propertyImage + '&h=102&w=100" alt="' + propertyTitle + '" /></div>';
            currPointHTML += '<div style="width: 135px; float: left;"><h4><a href="' + propertyLink + '">' + propertyTitle + '</a></h4>' + propertyAddress + '</div></div>'
        }
        else {
            currPointHTML += '<div style="width: 240px; "><h4><a href="' + propertyLink + '">' + propertyTitle + '</a></h4>' + propertyAddress + '</div></div>'
        }
				
				            //cache 'this' scope to search on it later      
        var currThis = this;
        
        if (propertyLocationKey != hex_md5(propertyAddressGoogle) || propertyLocationLatitude == '' || propertyLocationLongitude == '') {
            // marker was not found in the db, so we'll need to add it
            $('#map2').jmap('SearchAddress', {
                'query': propertyAddressGoogle,
                'returnType': 'getLocations'
            }, function(result, options){
                var valid = Mapifies.SearchCode(result.Status.code);
                if (valid.success) {
                    $.each(result.Placemark, function(i, point){
                        //store the new lat/long into the database for caching
                        $.post("/remote/RemotePropertyService.cfc?method=updatePropertyLocation", {
                            property_id: propertyId,
                            latitude: point.Point.coordinates[1],
                            longitude: point.Point.coordinates[0],
                            property_location_key: hex_md5(propertyAddressGoogle)
                        });
                        
                        //might be able to just set this originally and have it update the form
                        propertyLocationKey = hex_md5(propertyAddressGoogle);
                        propertyLocationLatitude = point.Point.coordinates[1];
                        propertyLocationLongitude = point.Point.coordinates[0];
                        
                        $(currThis).find(':input[name=property_location_key]')[0].value = propertyLocationKey;
                        $(currThis).find(':input[name=property_location_latitude]')[0].value = propertyLocationLatitude;
                        $(currThis).find(':input[name=property_location_longitude]')[0].value = propertyLocationLongitude;
                        
                        //place the element on the map
                        $('#map2').jmap('AddMarker', {
                            'pointLatLng': [propertyLocationLatitude, propertyLocationLongitude],
                            'pointHTML': currPointHTML,
                            'pointIcon': myIcon
                        }, function(marker, options){
                        
                        });
                        
                    });
                }
                else {
                    $('h4').val(valid.message);
                }
            });
        }
        else {
            //place the element on the map
            $('#map2').jmap('AddMarker', {
                'pointLatLng': [propertyLocationLatitude, propertyLocationLongitude],
                'pointHTML': currPointHTML,
                'pointIcon': myIcon
            }, function(marker, options){
            
            });
        }
        
    });
    
    // Property Map
    //need to get the zoom level from db
    var default_zoom = parseInt($("input[name='zoom_level']").val());
    var default_lat = $("input[name='lat']").val();
    var default_long = $("input[name='long']").val();
    
    $('#map3').jmap('init', {
        'mapType': 'map',
        'mapCenter': [default_lat, default_long],
        'mapZoom': default_zoom,
        'mapShowjMapsIcon': false
    });
    $("input[name='property_address']", this).each(function(){
        $('#map3').jmap('SearchAddress', {
            'query': $(this).val(),
            'returnType': 'getLocations'
        }, function(result, options){
            var valid = Mapifies.SearchCode(result.Status.code);
            if (valid.success) {
                $.each(result.Placemark, function(i, point){
                    $('#map3').jmap('AddMarker', {
                        'pointLatLng': [point.Point.coordinates[1], point.Point.coordinates[0]],
                        'pointHTML': point.address,
                        'pointIcon': myIcon
                    }, function(marker, options){
                        GEvent.addListener(marker, "click", function(){
                            $('#map3').jmap('MoveTo', {
                                'centerMethod': 'pan',
                                'mapCenter': [point.Point.coordinates[1], point.Point.coordinates[0]]
                            });
                        });
                    });
                });
            }
            else {
                $('h4').val(valid.message);
            }
        });
    });
    
    //this is needed for the property detail page, so it centers on property lat/long and not region lat/long 
    $("input[name='property_address_detail_google']", this).each(function(){
        $('#map3').jmap('SearchAddress', {
            'query': $(this).val(),
            'returnType': 'getLocations'
        }, function(result, options){
            var valid = Mapifies.SearchCode(result.Status.code);
            if (valid.success) {
                $.each(result.Placemark, function(i, point){
                    $('#map3').jmap('init', {
                        'mapType': 'map',
                        'mapCenter': [point.Point.coordinates[1], point.Point.coordinates[0]],
                        'mapZoom': 13,
                        'mapShowjMapsIcon': false
                    });
                    $('#map3').jmap('AddMarker', {
                        'pointLatLng': [point.Point.coordinates[1], point.Point.coordinates[0]],
                        'pointHTML': point.address,
                        'pointIcon': myIcon
                    }, function(marker, options){
                        GEvent.addListener(marker, "click", function(){
                            $('#map3').jmap('MoveTo', {
                                'centerMethod': 'pan',
                                'mapCenter': [point.Point.coordinates[1], point.Point.coordinates[0]]
                            });
                        });
                    });
                });
            }
            else {
                $('h4').val(valid.message);
            }
        });
    });
    
    /* Update the submarket drop down based on change to region */
    var updateSubmarkets = function(){
        var seletedRegionID = this.value;
        $.getJSON('/remote/RemoteRegionService.cfc?method=getSubmarkets&returnFormat=json&queryFormat=column&region_id=' + this.value, function(data){
            /* Parse JSON and create html */
            
            //empty the default submarkets, defaults to all
            $('#region_submarket_id').empty();
            var response = data.DATA;
            var options = '';
            $('#submarket_container').show();
            
            if ((response['TITLE'].length == 0) || (seletedRegionID == 0)) {
                $('#submarket_container').hide();
            }
            //build the submarket dd with the appropriate submarkets
            $('#region_submarket_id').addOption('', 'Select a Submarket');
            for (var i = 0, len = response['TITLE'].length; i < len; i++) {
                $('#region_submarket_id').addOption(response['REGION_SUBMARKET_ID'][i], response['TITLE'][i]);
            }
            
            $("option:first", "#region_submarket_id").attr("selected", "selected");
        });
    };
    
    /* On Region change */
    $("#quick_search_form #region_id").change(updateSubmarkets);
});

