

(function () {

    var $ = jQuery,
        $j = jQuery,
        site = window.site = {};


    /*
    Page Specific Functionality 
    */

    // The base Page class. Common functions for pages should go in its prototype.
    site.Page = function (customMembers) {
        this.$I = $(this);

        $.extend(this, customMembers);
    };

    site.Page.prototype = site.Page.fn = {
        $I: null,
        delayTime: 2000,
        pageForm: null,

        init: null,
        load: null,
        delay: null,

        submit: function () {
            return this.pageForm.submit();
        },

        bind: function () {
            this.$I.bind.apply(this.$I, arguments);
            return this;
        },

        trigger: function () {
            this.$I.trigger.apply(this.$I, arguments);
            return this;
        }
    };

    //Declare the unique and prominent pages of the site and their members
    site.pages = {

        common: new site.Page({
            init: function () {
                var P = this,
                    pageForm = this.pageForm = $("#aspnetForm"),
                    sitePage = $("#sitePage"),
                    imgSprites;

                P.prepNav().inputStyles().prepQuickSearch();

                //Setup the property browse tables (developments, dispositions, acquisitions, etc)
                this.prepBrowseTables($("table").filter(".table-dispositions,.table-developments,.table-acquisitions"));


                //Special font stuff
                this.toggleFirefoxFonts($("#siteNav li a,#siteUtilNav li a,#siteHeader .quick-search button,#sitePage .section-title"));

                if (!$.browser.webkit) {
                    //Images with rounded corners and drop shadows
                    //imgSprites = sitePage.find("img.box-rounded, img.box-rounded-shadow, .sbar-item > figure img").imgToSprite({ manipulator: "before" }).addClass("img-sprite");
                }

                if ($.browser.msie) {
                    /*var css3Containers = $("css3-container").remove();
                    console.log(css3Containers.length);
                    $(window).bind("beforeprint", function (evt) {
                    $("css3-container").hide();
                    });*/
                }
								
				// swap out some elements on pad and land property pages
				if( location.href.toLowerCase().indexOf("/pads/property/") > -1 )
				{
					// change the header graphic
					$("#ctl00_ctl00_GraphicHeader_GraphicHeader_imgBanner").attr("src","/pads/images/header_photo.jpg");
				}
				else if( location.href.toLowerCase().indexOf("/land/property/") > -1 )
				{
					// change the header graphic
					$("#ctl00_ctl00_GraphicHeader_GraphicHeader_imgBanner").attr("src","/land/images/header_photo.jpg");
					
					// display the land sidebar
					if( $('#landMarketingImage').length > 0 )
					{					
						$("#primaryMarketingImage").hide();
						$("#landMarketingImage").show();
					}
					
					// display the land marketing image
					$("#propSidebar").hide();
					$("#propSidebarLand").show();
				}
				
				// change the 'Back to Search' href
				if( location.href.toLowerCase().indexOf("/property/") > -1 )
				{					
					var BackToSearchCookie = "BackToSearchLink";
					$(".btn-back a")
						.each(function()
						{
							if( document.referrer.toLowerCase().indexOf("/results.aspx") > -1 || 
								document.referrer.toLowerCase().indexOf("/pads/default.aspx") > -1 || 
								document.referrer.toLowerCase().indexOf("/land/default.aspx") > -1 || 
								document.referrer.toLowerCase().indexOf("/index") > -1)
							{
								this.href = document.referrer;
								SetCookie(BackToSearchCookie, this.href);
							}								
							else if(location.href.toLowerCase().indexOf("/industrial/property/") > -1)
							{
								this.href = (ReadCookie(BackToSearchCookie) != null ? ReadCookie(BackToSearchCookie) : "/industrial/results.aspx");
							}
							else if(location.href.toLowerCase().indexOf("/retail/property/") > -1)
							{
								this.href = (ReadCookie(BackToSearchCookie) != null ? ReadCookie(BackToSearchCookie) : "/retail/results.aspx");
							}
							else if(location.href.toLowerCase().indexOf("/pads/property/") > -1)
							{
								this.href = (ReadCookie(BackToSearchCookie) != null ? ReadCookie(BackToSearchCookie) : "/pads/results.aspx");
							}
							else if(location.href.toLowerCase().indexOf("/land/property/") > -1)
							{
								this.href = (ReadCookie(BackToSearchCookie) != null ? ReadCookie(BackToSearchCookie) : "/land/results.aspx");
							}
							else if(location.href.toLowerCase().indexOf("/index/") > -1)
							{
								this.href = (ReadCookie(BackToSearchCookie) != null ? ReadCookie(BackToSearchCookie) : "/index/");
							}
						
							console.log("Setting btn-back href to: " + this.href);
						});
				}

            },
            load: function () {
                //Equalize the page column heights
                this.equalizeColumns();
            },
            delay: function () {

            },
            prepNav: function () {
                var siteNav = $("#siteNav,#siteUtilNav"),
                    navLinks = siteNav.find("a"),
                    subNav = $("#siteSubNav"),
                    subNavLinks = subNav.find("a"),
                    currentUrl = window.location.href;


                var highlight = function (links, minLvl, useFirstMatch) {
                    var matchLvl = 0,
                        matchLink = null;
                    //Get the matching link
                    links.each(function (i, link) {
                        var $link = $(link),
                        url = link.href.toString(),
                        diff = tbelt.url.compare(currentUrl, url);
                        if (diff >= matchLvl && diff >= minLvl) {
                            matchLink = $link;
                            matchLvl = diff;
                            if (useFirstMatch === true) return false;
                        }
                    });
                    if (matchLink === null) return false;
                    //Add active and active-parent classes where appropriate
                    matchLink.add(matchLink.closest("li")).addClass("active");
                    while (matchLink.parent("li").length) {
                        matchLink = matchLink.parent("li").addClass("active-parent");
                        matchLink.children("a:first").addClass("active-parent");
                    }

                    return true;
                };
                //Highlight primary nav
                highlight(navLinks, 2);

                //Highlight secondary nav
                if (!highlight(subNavLinks, 3, false)) {
                    highlight(subNavLinks, 2, true);
                }

                return this;
            },

            prepQuickSearch: function () {
                var quickSearch = $("#siteHeader .quick-search"),
                    txtSearch = quickSearch.find("input[type='text']"),
                    btnGo = quickSearch.find("button");

                var search = function () {
                    var query = $.trim(txtSearch.val());

                    if (query.length) {
                        window.location.href = "/search/?q=" + escape(query);
                        return true;
                    }
                    return false;
                };

                btnGo.click(function (evt) {
                    evt.stopPropagation();
                    return search();
                });
                txtSearch.keyup(function (evt) {
                    console.log(evt); evt.stopPropagation();
                    evt.stopImmediatePropagation();
                    if (evt.keyCode === 13) {
                        evt.stopPropagation();
                        return search();
                    }

                });

                this.pageForm.submit(function (evt) {
                    if (txtSearch.is(":focus")) {
                        search();
                        evt.stopImmediatePropagation();
                        evt.stopPropagation();
                        return false;
                    }
                });


                return this;
            },

            prepBrowseTables:function(tables){
                tables.children("tbody").children("tr:not(.header)")
                .each(function (r, tr) {

                    var brokerLink = $(tr).children("td:last").children("a").click(function (evt) {
                        window.popup(evt.target.href, site.brokerInfoWindowSettings);
                        evt.preventDefault();
                        //return false;
                    });

                })
                .hover(function (evt) { $(this).addClass("row-hover"); }, function (evt) { $(this).removeClass("row-hover"); })
                .click(function (evt) {
                    var $tr = $(this);
                    window.location = "/" + $.trim($tr.children("td.type").text()).toLowerCase() + "/property/" + $.trim($tr.children("td.id").text()).toLowerCase();
                });

                
                return this;
            },

            inputStyles: function () {
                $("*:input").each(function (i, input) {
                    var $input = $(input);
                    if ($input.is("textarea")) { $input.addClass("input-textarea"); }
                    else if ($input.is("select")) { $input.addClass("input-select"); }
                    else { $input.addClass("input-" + $input.attr("type")); }
                    //create placeholder text
                    if ($input.is(":text[placeholder]")) {
                        $input.placeholderText();
                    }
                });

                return this;
            },

            equalizeColumns: function () {
                var sitePage = $("#sitePage"),
                    inners = sitePage.find("aside.page-left,article.page-main,aside.page-right").find(">div:first"),
                    styles = $("<style type='text/css' media='screen'>#siteWrap #sitePage .col-height {min-height:" + sitePage.height() + "px;}</style>");
                //inners.addClass("col-height");
                sitePage.find("article.page-main > div.page-main-inner").addClass("col-height");
                $("body").append(styles);
                //inners.css({ minHeight: sitePage.height() });
            },

            toggleFirefoxFonts: function (items) {
                if (!$.browser.mozilla) {
                    //Don't need to delay display for fonts outside of Firefox
                    items.css({ visibility: "visible" });
                } else {
                    items.css({ visibility: "hidden" });
                    $(window).load(function () {
                        setTimeout(function () {
                            //We can display the fonts in Firefox now
                            items.css({ visibility: "visible" });
                        }, 2000);
                    });
                }
                return this;
            }
        }),

        "home-default": new site.Page({
            init: function () {
                var P = this;
                P.createBanner();
                P.createMap();

                site.pages.common.toggleFirefoxFonts($("#sitePage h3"));
            },
            load: function () {

            },
            delay: function () {

            },
            createBanner: function () {

                var banner = this._banner = new wri.widget.BannerSequence({
                    container: $("#siteBanner")
                }).init().load();

            },
            createMap: function () {

                var map = new wri.widget.FlashMap({
                    container: $("#FlashMap")
                })
                .settings("flashVars", {
                    display: "home"
                })
                .init()
                .bind("ready", function () {
                    //console.log("map is ready");
                });

                return this;
            }
        }),
		
		"about-management-default": new site.Page({
			init:function(){
				if (!$.browser.webkit) {
                    //Images with rounded corners and drop shadows
                    //imgSprites = $("div.management-team td.image > a > img").addClass("box-shadow");
                }
			}
		}),


        "industrial-results": new site.Page({
            init: function () {

                var table = $("table.table-prop-results");
                table.children("tbody").children("tr:not(.header)")
                .each(function (r, tr) {

                    var $tr = $(tr),
                        mapLink = $tr.children("td:last").children("a").click(function (evt) {
                            window.location = "/" + $tr.attr("data-ptype") + "/property/" + $tr.attr("data-pid") + "/map.aspx";
                            evt.preventDefault();
                            return false;
                        });

                })
                .hover(function (evt) { $(this).addClass("row-hover"); }, function (evt) { $(this).removeClass("row-hover"); })
                .click(function (evt) {
                    var $tr = $(this);
                    window.location = "/" + $tr.attr("data-ptype") + "/property/" + $tr.attr("data-pid");
                });
            }
        })


    };

    // @ prefix e.g. "common" or "popup"
    site.pages.__init = function (prefix) {

        // Initialize any pages with the same name as any of the class names on the <body/> tag.
        $(document).ready(function () {
            $.each($.trim(prefix + " " + document.body.className).split(/\s+/), function (i, className) {
                if (className.length && typeof site.pages[className] === "object" && $.isFunction(site.pages[className].init)) {
                    site.pages[className].init();
                }
            });
        });
        $(window).load(function () {
            $.each($.trim(prefix + " " + document.body.className).split(/\s+/), function (i, className) {
                if (className.length && typeof site.pages[className] === "object") {
                    if ($.isFunction(site.pages[className].load)) {
                        site.pages[className].load();
                    }
                    if ($.isFunction(site.pages[className].delay)) {
                        setTimeout(function () { site.pages[className].delay(); }, site.pages[className].delayTime);
                    }
                }

            });
        });

    };





    site.displayBrokerInfo = function (pid) {
        return window.popup('/common/property/brokerPopup.aspx?projectid=' + ProjectID, "BrokerInfo", site.brokerInfoWindowSettings);
    };


    site.brokerInfoWindowSettings = {
        width: 400,
        height: 300,
        scrollbars: true,
        resizable: true,
        status: false,
        menubar: false
    };







    window.popup = function (url, id, options) {
        var opts = $.extend({
            height: null,
            width: null,
            location: null,
            fullscreen: 0
        }, (typeof id === "object") ? id : options),
            win = window.open(url, id || window.location.host, (function () { var str = ""; for (var optName in opts) { str += optName + "=" + opts[optName] + ","; } return str; })());
        return win;
    };

    window.printHtml = function (htmlStr, opts) {
        var win = window.popup(null, "print", $.extend({ height: 500, width: 800 }, opts));
        win.document.writeln(htmlStr);
        win.print();
        return win;
    };






    /*
    CUSTOM JQUERY PLUGINS
    */




    /**
    @method jQuery.fn.placeholderText
    @description Uses the "placeholder" attribute on a text input to overlay a label or message while the field is not in focus. This is supposed to mimic the HTML5 input's placeholder attribute.
    @author Stephen Rushing, eSiteful
    */
    $.fn.placeholderText = function (opts) {
        if (("placeholder" in $('<input>')[0])) return;

        var I = this,
            options = I.options = $.extend({
                spanHtml: "<span class='input-placeholder'></span>",
                position: "left"
            }, opts);

        I.each(function (i, input) {
            var $input = $(input),
                phText = $input.attr("placeholder");

            if (phText !== null && phText.length) {
                var placeholder = $(options.spanHtml).insertAfter(input).html(phText).css("display", "none");

                $input.data("placeholderText", placeholder);

                $input.blur(function (evt) {

                    if ($.trim($input.val()).length) return true;

                    var pos = $input.position();
                    if (options.position === "right") {
                        pos.left += $input.width() - placeholder.width();
                    } else if (options.position === "center") {
                        pos.left += ($input.width() - placeholder.width()) / 2;
                    }

                    placeholder.css({ display: "", position: "absolute", left: pos.left, top: pos.top });

                }).blur();

                $input.focus(function (evt) {
                    placeholder.css({ display: "none" });
                });

                placeholder.click(function (evt) {
                    $input.focus();
                });

            }
        });


        return I;
    };


    /**
    *   @method jQuery.fn.buildFaqAnchors
    *   @description 
    *   @author Stephen Rushing, eSiteful
    */
    $.fn.buildFaqAnchors = function (ol) {
        if (!(ol instanceof $)) ol = $(ol);

        this.each(function (i, dl) {
            var $q = $(this).children("dt").clone(),
                $a = $(this).children("dd");

            $q.children("a").remove();
            var item = $("<li><a href='#" + $(this).attr("id") + "'>" + $q.html() + "</a></li>").appendTo(ol);

            item.find("a>a").remove();

        });

    };


    /**
    *   @method jQuery.fn.blinkCss
    *   @description 
    *   @author Stephen Rushing, eSiteful
    */
    $.fn.blinkCss = function (css, showTime, hideTime, count) {

        var B = this;
        showTime = showTime != null ? showTime : 500;
        hideTime = hideTime != null ? hideTime : showTime / 2;
        count = count != null ? count : 3;

        this.each(function (n, node) {
            var $node = $(node),
				orig = isClass ? $node.attr("class") : $node.attr("style");
            $node.data("blinkCssOrig", orig || "");
        });

        var isClass = typeof (css) === "string",
			counted = 0,
			showTimer = null,
			hideTimer = null;

        function show() {
            B.each(function (n, node) {
                if (isClass) {
                    $(node).addClass(css);
                } else {
                    $(node).css(css);
                }
                counted++;
            });
            hideTimer = setTimeout(hide, showTime);
        }

        function hide() {
            B.each(function (n, node) {
                var counted = 0,
					$node = isClass ? $(node).addClass(css) : $(node).css(css),
					orig = $node.data("blinkCssOrig") || "";
                $node.attr(isClass ? "class" : "style", orig);
            });
            if (counted < count) {
                setTimeout(show, hideTime);
            }
        }

        show();


    };


    /**
    *   @method jQuery.fn.getLabels
    *   @description 
    *   @author Stephen Rushing, eSiteful
    */
    $.fn.getLabels = function () {
        var labels = $([]),
			all = $("label");

        this.each(function (n, node) {
            var $node = $(node),
				lbl = all.filter("[for='" + node.id + "']");
            if (!lbl.length) lbl = $node.closest("label");
            if (lbl.length) labels = labels.add(lbl);
        });
        return labels;
    };


    /**
    *   @method imgToSprite
    *   @description converts <img/> tags to a specified element with the img src as the background. The original use case is for creating rounded corners on images with the border-radius property, which Firefox and IE+css3pie do not render correctly.
    *   @author Stephen Rushing, eSiteful
    */

    $.fn.imgToSprite = function (opts) {
        var I = this,
            defaults = {
                container: $("<div class='img-sprite'/>"),
                height: -1, //-1 dimension indicates that we should use the current dimension of the image
                width: -1,
                manipulator: "before"
            },
            o = $.extend({}, defaults, opts),
            images = this.filter("img");

        //search for child images if there are no images in this set
        if (!images.length) {
            images = this.find("img");
        }

        function replace(img) {
            var c = o.container.clone(true),
                $img = $(img),
                height = o.height !== -1 ? o.height : $img.height(),
                width = o.width !== -1 ? o.width : $img.width(),
                bgSize = ((height !== null && width !== null) ? height + "px " + width + "px" : null),
                bgUrl = "url('" + img.src + "')",
                cssAttrs = {
                    backgroundImage: bgUrl,
                    height: height,
                    width: width,
                    backgroundRepeat: "no-repeat",
                    backgroundSize: height + "px " + width + "px",
                    visibility: "",
                    display: ""
                };

            //We must remove any scaling from the image until browsers support background scaling better
            if (!$.browser.safari) {
                $img.removeAttr("height").removeAttr("width").css({ height: "auto", width: "auto" });
                cssAttrs.height = img.height;
                cssAttrs.width = img.width;
            }

            c.addClass($img.attr("class"));
            c.attr("style", $img.attr("style"));
            c.css(cssAttrs);

            $img[o.manipulator](c);
        }
		
        images.each(function (i, img) {
            var $img = $(img),
				replaced = false;
			//console.log(img.src + " : "+img.complete);
			
			$img.load(function (evt) {
				if(!replaced) 
				{
					replace(img);
					replaced=true;
				}
				//console.log(img.src + " : "+img.complete);
			});
			
            if($.browser.msie) {
				if(img.complete){
					$img.trigger("load");
				}else{
					var interval = setInterval(function(){
						if(img.complete){
							$img.trigger("load");
							clearInterval(interval);
						}
					}, 250);
				}
            }
        });

        return this;
    };


})();



/* GLOBAL POLLUTION */

// sets a cookie
function SetCookie( cookieName, cookieValue ) 
{
	document.cookie = cookieName + "=" + escape( cookieValue ) + ";path=/;";
}

// deletes a cookie
function DeleteCookie ( cookieName )
{
	document.cookie = cookieName + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// reads a cookie
function ReadCookie( cookieName ) 
{
	var theCookie = "" + document.cookie;
	var ind = theCookie.indexOf( cookieName );

	if (ind === -1 || !cookieName.length) {
	    return "";
	}
			
	var ind1 = theCookie.indexOf( ';' ,ind );

	if (ind1 == -1) {
	    ind1 = theCookie.length;
	}
			
	return unescape( theCookie.substring( ind+cookieName.length+1, ind1 ) );
}
