//let's override the jquery show and animate functions so
//that we can force it to fade in elements that have
//visibility set to hidden
jQuery.fn.extend({
    show: function(speed, callback) {
        if (speed || speed === 0) {
            return this.animate(genFx("show", 3), speed, callback);

        } else {
            var tempProperties = ["display", "visibility"];
            var temp;
            for (var n = 0; n < tempProperties.length; n++) {
                for (var i = 0, l = this.length; i < l; i++) {
                    var old = jQuery.data(this[i], "old" + tempProperties[n]);

                    this[i].style[tempProperties[n]] = old || "";
                    temp = jQuery.css(this[i], tempProperties[n]);

                    if (temp === "none" || temp === "hidden") {
                        var nodeName = this[i].nodeName, display;

                        if (!window["elem" + tempProperties[n]]) {
                            window["elem" + tempProperties[n]] = {};
                        }
                        if (window["elem" + tempProperties[n]][nodeName]) {
                            temp = window["elem" + tempProperties[n]][nodeName];
                        } else {
                            var elem = jQuery("<" + nodeName + " />").appendTo("body");

                            temp = elem.css(tempProperties[n]);

                            switch (tempProperties[n]) {
                                case "display":
                                    if (temp === "none")
                                        temp = "block";
                                    break;
                                case "visibility":
                                    if (temp === "hidden")
                                        temp = "visible";
                                    break;
                            }

                            elem.remove();

                            window["elem" + tempProperties[n]] = temp;
                        }

                        jQuery.data(this[i], "old" + tempProperties[n], temp);
                    }
                }

                // Set the display of the elements in a second loop
                // to avoid the constant reflow
                for (var j = 0, k = this.length; j < k; j++) {
                    this[j].style[tempProperties[n]] = jQuery.data(this[j], "old" + tempProperties[n]) || "";
                }
            }
            return this;
        }
    },
    animate: function(prop, speed, easing, callback, intervalCallback) {
        var optall = jQuery.speed(speed, easing, callback);

        return this[optall.queue === false ? "each" : "queue"](function() {

            var opt = jQuery.extend({}, optall), p,
			hidden = this.nodeType == 1 && (jQuery(this).is(":hidden") || this.style.visibility === "hidden"),
			self = this;

            for (p in prop) {
                if (prop[p] == "hide" && hidden || prop[p] == "show" && !hidden)
                    return opt.complete.call(this);

                if ((p == "height" || p == "width") && this.style) {
                    // Store display property
                    opt.display = jQuery.css(this, "display");

                    // Make sure that nothing sneaks out
                    opt.overflow = this.style.overflow;
                }
            }

            if (opt.overflow != null)
                this.style.overflow = "hidden";

            opt.curAnim = jQuery.extend({}, prop);

            jQuery.each(prop, function(name, val) {
                var e = new jQuery.fx(self, opt, name);

                if (/toggle|show|hide/.test(val))
                    e[val == "toggle" ? hidden ? "show" : "hide" : val](prop);
                else {
                    var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
					start = e.cur(true) || 0;

                    if (parts) {
                        var end = parseFloat(parts[2]),
						unit = parts[3] || "px";

                        // We need to compute starting value
                        if (unit != "px") {
                            self.style[name] = (end || 1) + unit;
                            start = ((end || 1) / e.cur(true)) * start;
                            self.style[name] = start + unit;
                        }

                        // If a +=/-= token was provided, we're doing a relative animation
                        if (parts[1])
                            end = ((parts[1] == "-=" ? -1 : 1) * end) + start;

                        e.custom(start, end, unit);
                    } else
                        e.custom(start, val, "");
                }
            });

            // For JS strict compliance
            return true;
        });
    }
});

$(function() {
    //Some convenience functions added to the String prototype
    String.prototype.trim = function() {
        return
        (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))
    }

    String.prototype.startsWith = function(str) {
        if (this.length == 0) return false;
        return (this.match("^" + str) == str)
    }

    String.prototype.endsWith = function(str) {
        if (this.length == 0) return false;
        return (this.match(str + "$") == str)
    }

    Array.prototype.exists = function(value) {
        var exists = false;
        for (var n = 0; n < this.length; n++) {
            if (this[n] == value) {
                exists = true;
                break;
            }
        }
        return exists;
    }

    window.fb_parseQuery = function(query) {
        var Params = {};
        if (!query) { return Params; } // return empty object
        var Pairs = query.replace("?", "").split(/[;&]/);
        for (var i = 0; i < Pairs.length; i++) {
            var KeyVal = Pairs[i].split('=');
            if (!KeyVal || KeyVal.length != 2) { continue; }
            var key = unescape(KeyVal[0]);
            var val = unescape(KeyVal[1]);
            val = val.replace(/\+/g, ' ');
            Params[key] = val;
        }
        return Params;
    };
    window.addOrReplaceQSParam = function(url, paramName, paramValue) {
        var loweredUrl = url.toLowerCase();
        var index = -1;
        if (paramName != null && paramName.length) {
            index = loweredUrl.lastIndexOf("/" + paramName.toLowerCase() + "/");
        }
        else {
            paramName = "";
        }
        if (index > -1) {
            var temp = url.split("/");
            for (var n = 0; n < temp.length; n++) {
                if (temp[n].toLowerCase() == paramName.toLowerCase() && temp.length > n + 3) {
                    temp[n + 1] = paramValue;
                    url = temp.join("/");
                    break;
                }
            }
        }
        else {
            if (loweredUrl.indexOf("?") > -1) {
                url = url + "&" + paramName + "=" + paramValue;
            }
            else {
                index = loweredUrl.lastIndexOf("/");
                if (index >= 0) {
                    url = url.substring(0, index) + paramName + "/" + paramValue + url.substring(index);
                }
            }
        }
        return url;
    };

    window.googleLinkTrack = function(linkNode) {

        if (_gat) {
            linkNode.href = _gat._getTrackerByName()._getLinkerUrl(linkNode.name);
        }

        /* var t = _gat._getTracker("UA-6108869-1");
        if (t && t._link && linkNode) {
        t._setAllowLinker(true);
        t._setDomainName("none");
        t._link(linkNode.href);
        }*/
    };
    //tabbing for blue/green tabs
    var tabBlueContainers = $('div.sfTabBlueButtonBox > div');
    var tabGreenContainers = $('div.sfTabGreenButtonBox > div');

    $('div.sfBlueTabs a').click(function() {
        tabBlueContainers.hide().filter(this.hash).show();

        $('div.sfBlueTabs a').removeClass('sfTabBlueButton_selected');
        $(this).addClass('sfTabBlueButton_selected');

        return false;
    }).filter(':first').click();

    $('div.sfTabGreenButtonClear div.sfGreenTabs a').click(function() {
        tabGreenContainers.hide().filter(this.hash).show();
        $('div.sfTabGreenButtonClear div.sfGreenTabs a').removeClass('sfTabGreenButton_selected');
        $(this).addClass('sfTabGreenButton_selected');

        return false;
    }).filter(':first').click();

    $("table .sfAlternatingRows tr:even").addClass("alt");

    var $sfTabGreenTable = $("table.sfTabGreenTable");
    var $greenTableRows = $sfTabGreenTable.find("tr.sfTabGreenTable-row");

    $greenTableRows.mouseover(function() {
        $(this).addClass('sfTabGreenTable-row-over');
    }).mouseout(function() {
        $(this).removeClass('sfTabGreenTable-row-over');
    }).click(function(evt) {
        evt = evt ? evt : event;
        if ($(evt.target).hasClass("sfButton") || $(evt.target).parent().hasClass("sfButton")) {
            return true;
        }
        var $this = $(this);
        if ($this.find("div.no-green-arrow").length > 0) {
            return true;
        }
        var $sibling = $this.next("tr.sfTabGreenTable-row-alt");
        if ($this.hasClass("sfTabGreenTable-row-active")) {
            $this.removeClass('sfTabGreenTable-row-active');
            $sibling.css("display", "none");
        }
        else {
            $this.addClass('sfTabGreenTable-row-active');
            $sibling.css("display", "");
        }
        return false;
    });

    var $sfTabBlueTable = $("table.sfTabBlueTable");
    var $blueTableRows = $sfTabBlueTable.find("tr.sfTabBlueTable-row");

    $blueTableRows.mouseover(function() {
        $(this).addClass('sfTabBlueTable-row-over');
    }).mouseout(function() {
        $(this).removeClass('sfTabBlueTable-row-over');
    }).click(function() {
        var $this = $(this);
        var $sibling = $this.next("tr.sfTabBlueTable-row-alt");
        if ($this.hasClass("sfTabBlueTable-row-active")) {
            $this.removeClass('sfTabBlueTable-row-active');
            $sibling.css("display", "none");
        }
        else {
            $this.addClass('sfTabBlueTable-row-active');
            $sibling.css("display", "");
        }
        return false;
    });


    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        $('.sfButton').hover(function() {
            $(this).addClass('sfBtnHover');
        }, function() {
            $(this).removeClass('sfBtnHover');
        });

        $('.sfButtonOpp').hover(function() {
            $(this).addClass('sfButtonOpp');
        }, function() {
            $(this).removeClass('sfButtonOpp');
        });

        $('.sfButtonTall').hover(function() {
            $(this).addClass('sfButtonTallHover');
        }, function() {
            $(this).removeClass('sfButtonTallHover');
        });

        $('.sfButtonPaging').hover(function() {
            $(this).addClass('sfBtnPagingHover');
        }, function() {
            $(this).removeClass('sfBtnPagingHover');
        });
    }

    //COMPARISON TABLE
    var $sfComparisonTable = $("table.sfCommunity-table");
    var $sfComparisonTableRows = $sfComparisonTable.find("tr");

    $sfComparisonTableRows.mouseover(function() {
        $(this).addClass('sfComparison-row-over');
    }).hover(function() {
        $('#sfCommunity-Balcony').hover(function() {
            $('#sfCommunityFurnishied-compareToHotel .sfCommunity-image')
                .attr("className", "sfCommunity-image")
                .addClass('sfCommunity-image1');
        });

        $('#sfCommunity-Bathroom').hover(function() {
            //add only specific classes it needs
            $('#sfCommunityFurnishied-compareToHotel .sfCommunity-image')
                .attr("className", "sfCommunity-image")
                .addClass('sfCommunity-image2');
        });

        $('#sfCommunity-Bedroom').hover(function() {
            //add only specific classes it needs
            $('#sfCommunityFurnishied-compareToHotel .sfCommunity-image')
                .attr("className", "sfCommunity-image")
                .addClass('sfCommunity-image3');
        });

        $('#sfCommunity-Closet').hover(function() {
            //add only specific classes it needs
            $('#sfCommunityFurnishied-compareToHotel .sfCommunity-image')
                .attr("className", "sfCommunity-image")
                .addClass('sfCommunity-image4');
        });

        $('#sfCommunity-Dishwasher').hover(function() {
            //add only specific classes it needs
            $('#sfCommunityFurnishied-compareToHotel .sfCommunity-image')
                .attr("className", "sfCommunity-image")
                .addClass('sfCommunity-image5');
        });

        $('#sfCommunity-Entry').hover(function() {
            //add only specific classes it needs
            $('#sfCommunityFurnishied-compareToHotel .sfCommunity-image')
                .attr("className", "sfCommunity-image")
                .addClass('sfCommunity-image6');
        });

        $('#sfCommunity-Kitchen').hover(function() {
            //add only specific classes it needs
            $('#sfCommunityFurnishied-compareToHotel .sfCommunity-image')
                .attr("className", "sfCommunity-image")
                .addClass('sfCommunity-image7');
        });

        $('#sfCommunity-LivingRoom').hover(function() {
            //add only specific classes it needs
            $('#sfCommunityFurnishied-compareToHotel .sfCommunity-image')
                .attr("className", "sfCommunity-image")
                .addClass('sfCommunity-image8');
        });

        $('#sfCommunity-WorkArea').hover(function() {
            //add only specific classes it needs
            $('#sfCommunityFurnishied-compareToHotel .sfCommunity-image')
                .attr("className", "sfCommunity-image")
                .addClass('sfCommunity-image9');
        });

    }).mouseout(function() {
        $(this).removeClass('sfComparison-row-over');

        //add only specific classes it needs
        $('#sfCommunityFurnishied-compareToHotel .sfCommunity-image')
            .attr("className", "sfCommunity-image")
    });

    //special link tracking for external link found on nav
    var linkInvestorHP = $("#sfHeaderWrapper a[href*='investor.homeproperties.com']")
    linkInvestorHP.click(function() {
        _gaq.push(['_trackPageview', '/exit/investor/']);
    });
});



//Date math fun
//Add a string in the form 13d or 5m where the characters are:
// -- s: Seconds
// -- m: minutes
// -- h: hours
// -- d: days
// -- w: weeks
Date.prototype.sfAdd = function(value) {
    value = value.toString()
    var unitPart = value.substring(value.length - 1, value.length);
    var magnitudePart = parseFloat(value.substring(0, value.length - 1));

    var current = this.getTime();

    var multiplier = 1000;

    switch (unitPart) {

        case 'w':
            multiplier *= 60 * 60 * 24 * 7;
            break;
        case 'd':
            multiplier *= 60 * 60 * 24;
            break;
        case 'h':
            multiplier *= 60 * 60;
            break;
        case 'm':
            multiplier *= 60;
            break;
        case 's':
        default:
            break; //default is seconds

    }

    var newVal = current + (magnitudePart * multiplier);

    return new Date(newVal);

}
Date.prototype.sfSubtract = function(value) {

    return this.sfAdd('-' + value.toString());

}
Date.prototype.toUSTimeString = function() {

    var meridian = 'am';
    var hour = this.getHours();
    if (hour >= 12) {
        meridian = 'pm';
    }

    if (hour > 12) {
        hour -= 12;
    }

    return hour + ':' + this.getMinutes().toString().padLeft(2, '0') + ' ' + meridian;

}

String.prototype.padLeft = function(length, padChar) {

    padChar = padChar == null ? '0' : padChar;

    var str = '' + this;
    while (str.length < length) {
        str = padChar + str;
    }

    return str;
}

jQuery(document).ready(function() {

    jQuery(".sfReadMore").click(function() {
        var $longContent = $(this).parent().parent().parent().find(".longContent");
        var $shortContent = $(this).parent().parent().parent().find(".shortContent");
        
        if ($longContent.is(':visible')) {
            $longContent.hide();
            $shortContent.show();
        } else {
            $longContent.show();
            $shortContent.hide();
        }
    });

    //pseudo link
    jQuery(".sfReadMore").mouseover(function() {
        $(this).css("text-decoration", "none");
    });
    jQuery(".sfReadMore").mouseout(function() {
        $(this).css("text-decoration", "underline");
    });
   });

	//used to track GA events
   function googleEventTrack(categoryName, actionName) {
		_gaq.push(['_trackEvent', categoryName, actionName]);
   }
