/**
 * AIMCO User Interface
 */ 
var AIMCO = {

    /**
     * Init UI functions
     */         
    init: function () {
        AIMCO.makeUnitColsSameHeight();
        AIMCO.showUnitOnMap();
        AIMCO.navigationOpacity();
        AIMCO.rightNavTooltips();
        AIMCO.toggleHelpRollover($('#nav .right-nav a.help-icon'));
        AIMCO.toggleHelpRollover($('.sort a.help-icon'));
        AIMCO.toggleHelpRollover($('.notify-me a.help-icon2'));
        AIMCO.toggleHelpRollover($('.notify-me a.help-icon'));
        AIMCO.toggleAdvancedSearch();
        AIMCO.toggleFloorplans();
        AIMCO.togglePlacesOfInteres();
        AIMCO.calendarPopup();
                
        if ($.browser.msie) {
            AIMCO.emulateHover($("#nav .left-nav li"));
            AIMCO.emulateHover($("#nav .right-nav li"));
            document.execCommand("BackgroundImageCache",false,true);
        }
        
        if ($("#google-map2").length) {
            AIMCO.multipleAddressesGoogleMap("google-map2", $('.comparison-list .address'));
        }
        
        if ($("#google-map3").length) {
            AIMCO.multipleAddressesGoogleMap("google-map3", $('.unit-top .address span'));
        }
        
        if ($("#google-map4").length) {
            AIMCO.multipleAddressesGoogleMap("google-map4", $('.community-list .unit2-top .address'), true);
        }
        
        if ($("#google-map5").length) {
            AIMCO.getDirections();
        }
    },

    /**
     * Make unit colums same heigth as is the tallest one from them
     */          
    makeUnitColsSameHeight: function() {
        var units = $('.unit');
        units.each(function (i) {
            var cols;
            var h = 0;
            if ($(this).hasClass('floorplan')) {
                cols = $(this).find(".unit-col");
            } else {
                cols = $(this).find(".unit-col, .unit-right");
            }
            cols.each(function (i) {
                if ($(this).height() > h) {
                    h = $(this).height();
                }
            });
            cols.each(function (i) {
                $(this).get(0).style.height = h + 'px';
            });
        });
    },

    /**
     * Clicking on a checkbox toogle view bubble with coordinates on map
     */         
    showUnitOnMap: function () {
        var checkboxes = $('.popup .content :checkbox');
        checkboxes.each(function (i) {
             if ($(this).attr("value") !== 'on') {
                 
                 // Create view bubble
                 var coordinates = $(this).attr("value").split(',');
                 var x = (coordinates[0] * 1) - 29;
                 var y = (coordinates[1] * 1) - 41;
                 
                 if ($(this).parent().next()) {
                     var unit_num = $(this).parent().next().text();
                 } else {
                     var unit_num = 'None';
                 }

                 var bubble = $('<div class="bubble"><p>' + unit_num + '</p></div>');
                 bubble.css('left', x + 'px');
                 bubble.css('top', y + 'px');
                 $('.popup div.plan').append(bubble); 
                 
                 // Display / hide bubble
                 $(this).bind('click', function () {
                     if($(this).attr("checked")) {
                         bubble.css('display', 'block');
                     } else {
                         bubble.css('display', 'none');
                     }
                 });
             }
        });
    },    
    
    /**
     * Toogle advanced search area
     */         
    toggleAdvancedSearch: function () {
        $('.toggle-advanced-options a.toggle').bind('click', function () {
             $('#search .search-advanced').toggleClass('expanded');
             $(this).toggleClass('expanded');
             return false;
        });
    },
    
    /**
     * Toggle check subscriptions box
     */         
    checkSubscriptions: function () {
        $('.check-subscriptions input').bind('click', function () {
             $('.unsubscribe-notifications').toggle();
             $('.unsubscribe-notifications').toggleClass('opened');
             if ($('.unsubscribe-notifications').hasClass('opened')) {
                 $(this).attr('src', $(this).attr('src').replace(/.gif/, '_opened.gif'));
             } else {
                 $(this).attr('src', $(this).attr('src').replace(/_opened.gif/, '.gif'));
             }             
             return false;
        });
    },
    
    /**
     * Preload images
     * @param {Array} images array with names of images   
     */               
    preloadImages: function (images) {
        for (var i = 0; i < images.length; i++) {
            var image = new Image();
            image.src = images[i];
        }
    },
    
    /**
     * Toggle calendar popup
     */
    calendarPopup: function () {
        Date.firstDayOfWeek = 7;
        Date.format = 'mm/dd/yyyy';
        var today = new Date();
        //var minDate = new Date(today.getTime() + (60 * 60 * 1000 * 24 * 1)); 
		var minDate = new Date(today.getTime()); // Earliest allowed date is Today
		var maxDate = new Date(today.getTime() + (60 * 60 * 1000 * 24 * 365));
		
        var moveInDateOptions = {
            renderCallback: function ($td, thisDate) {
            	
            	if (thisDate.zeroTime() < minDate.zeroTime()) {
            		$td.addClass('disabled');
            	}
            	
                if (thisDate.getDayName() === 'Sunday') {
					$td.addClass('first-day');
				}
				if (thisDate.getDayName() === 'Saturday') {
					$td.addClass('last-day');
				}
			},
			displayClose: true,
			startDate: minDate.asString(),
			endDate: maxDate.asString()
		}
		
        //$('.move-in-date .text').datePicker(moveInDateOptions);
        //$('.ls #search .date').datePicker(moveInDateOptions);
        //The above two lines are replaced by below, to get the datePicker popup when on focus on the calendar text box.
        $('.move-in-date .text').datePicker(moveInDateOptions)
        .bind(
			'focus',
			function()
			{
				$(this).dpSetOffset(0, 100);
				$(this).dpDisplay();
				//reset the offset for calendar
				$(this).dpSetOffset(0, 0);
			}
		);
		
        $('.ls #search .date').datePicker(moveInDateOptions)
        .bind(
			'focus',
			function()
			{
				$(this).dpSetOffset(0, 100);
				$(this).dpDisplay();
				//reset the offset for calendar
				$(this).dpSetOffset(0, 0);
			}
		);
        $('.contact-form .date').datePicker(moveInDateOptions);
        
        moveInDateOptions.clickInput = true;
        moveInDateOptions.createButton = false;
        moveInDateOptions.horizontalOffset = 88;
        dpunflash = $('.move-in-date2 .text').datePicker(moveInDateOptions);

		$('#datebutton').click(function(){ dpunflash.dpDisplay() });
    },  
    
    /**
     * Toogle places of interest
     */         
    togglePlacesOfInteres: function () {
        $('.places-interest h5 a').bind('click', function () {
            $(this).parents('li').toggleClass('expanded');
            return false;
        });
    },
    
    /**
     * Toogle floorplans
     */         
    toggleFloorplans: function () {
        var floorplans = $('.floorplans');
        $('.expand-floorplans a').each(function (i) {
            $(this).bind('click', function () {
                $(floorplans[i]).toggleClass('expanded');
                $(this).toggleClass('expanded');
                return false;
            });
        });
    },
    
    /**
     * Set navigation opacity
     */         
    navigationOpacity: function () {
        if (BrowserDetect.browser == 'Firefox' && BrowserDetect.OS == 'Mac') {
            return;
        }
        $('#nav .left-nav ul').css('opacity', 0.95);
        $('#nav .right-nav ul').css('opacity', 0.95);
    },
    
    /**
     * Right navigation tooltips
     */         
    rightNavTooltips: function () {
        $('#nav .right-nav a.ir:not(.help-icon)').each(function (i) {
            var tooltip = $('<p class="right-nav-tooltip">' + jQuery.trim($(this).text()) + '</p>');
            $('body').append(tooltip);
            $(this).hover(
                function () {
                    var offset =  $(this).offset();
                    
                    var top = offset.top + 11;
                    var left = offset.left - 66;

                    tooltip.css('top', top + 'px'); 
                    tooltip.css('left', left + 'px'); 
                    tooltip.css('display', 'block');
                },
                function () {
                    tooltip.css('display', 'none');
                }
            )
        }); 
    },
    
    /**
     * Toggle Help Rollover
     */         
    toggleHelpRollover: function (help) {
        var helptext = $(help).parent().find('.help-text').text();
        if (helptext) {
            var bubble = $('<div class="help-bubble"><div class="top"></div><p>' + helptext + '</p><div class="bottom"></div></div>');
            $('body').append(bubble);    
            help.hover(
                function () {
                    var offset =  $(this).offset();
                    
                    var top = offset.top + 11;
                    var left = offset.left - 73;
    
                    bubble.css('top', top + 'px'); 
                    bubble.css('left', left + 'px'); 
                    bubble.css('display', 'block');
                },
                function () {
                    bubble.css('display', 'none');
                }
            )
        }
    },    
    
    /**
     * Emulate hover in IE6
     */          
    emulateHover: function (items) {
        items.hover(
            function () {
                $(this).addClass('hover');
            },
            function () {
                $(this).removeClass('hover');
            }
        )
    },
    
        
    /**
     * Multiple addresses Google Map
     * 
     * Initialize Google map. Geodecodes addresses 
     * and places markers on the map                
     */         
    multipleAddressesGoogleMap: function (map, addresses, small_map_control) {
        
        var map = new GMap2(document.getElementById(map));
        if (small_map_control) {
            map.addControl(new GSmallMapControl());
        }
        var geocoder = new GClientGeocoder();
        var points = [];
        
        var numberedIcon = new GIcon(G_DEFAULT_ICON);
        numberedIcon.iconSize = new GSize(34, 38);
        numberedIcon.shadow = "";
        
        if (geocoder) {
            for (var i = 0; i < addresses.length; i++) {
                var address = jQuery.trim($(addresses[i]).text());
                geocoder.getLatLng(
                    address,
                    function(point) {
                        if (point) {
                            points.push(point); 
                        }
                    }
                );
            }
        }
        
        
        setTimeout(createMarkers, 2000);
        
        // Create markers
        function createMarkers() {
            for (var i = 0; i < points.length; i++) {
                var number = i + 1;
                numberedIcon.image = "images/icons/map-icon" + number + ".png";
                markerOptions = { icon:numberedIcon };
                if (i == 0) {
                    map.setCenter(points[i], 13);
                }
                var marker = new GMarker(points[i], markerOptions);
                map.addOverlay(marker);
            }
        } 
    },
    
    /**
     * Get Directions Google Map
     */         
    getDirections: function () {
        
        var map;
        var gdir;
        var geocoder = null;
        var addressMarker;
        
        $('.get-directions').bind('submit', function () {
            setDirections($('#get-directions').val());
            return false;
        });
        
        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById("google-map5"));
            map.addControl(new GSmallMapControl());
            gdir = new GDirections(map, document.getElementById("directions"));
            GEvent.addListener(gdir, "error", handleErrors);

            setDirections("Los Angeles");
        }
        
        function handleErrors(){
	        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_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 setDirections(fromAddress) {
            gdir.load("from: " + fromAddress + " to: 3400 Avenue of the Arts, Costa Mesa, CA 92626" , { "locale": "en_US" });
        }
    }
}

var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {   string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {       // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {       // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};

BrowserDetect.init(); 

$(document).ready(function () {
    AIMCO.init();
    
    //open external links in popup
    
    //  Added for INC486058 Fix (2)(START) 
    $('A[rel="chatLandingNav"]').click( function() {    	
        window.open( $(this).attr('href'), 'chatwin','width=475,height=400, toolbar=0, top=150, left=600, menubar=0, status=1, scrollbars=0, resizable=1'  );
        return false;
    });
    //  Added for INC486058 Fix (2)(END)

    $('A[rel="chat"]').click( function() {    	
        window.open( $(this).attr('href'), 'chatwin','width=475,height=400, toolbar=0, top=150, left=600, menubar=0, status=1, scrollbars=0, resizable=1'  );
        return false;
    });
    
    $('A[rel="call"]').click( function() {    	
        window.open( $(this).attr('href'), 'callwin','width=472,height=320, toolbar=0, top=150, left=600, menubar=0, status=1, scrollbars=0, resizable=1'  );
        return false;
    });
    
    //  Added for INC486058 Fix (2)(START)
    $('A[rel="callLandingNav"]').click( function() {    	
        window.open( $(this).attr('href'), 'callwin','width=472,height=320, toolbar=0, top=150, left=600, menubar=0, status=1, scrollbars=0, resizable=1'  );
        return false;
    });
    //  Added for INC486058 Fix (2)(END)
    
});

