﻿var isMapInitialized = false;
var isTab2Filtered = false;
var isTab3Filtered = false;
var communityName;
var userBrowser;
var divOfferLightBox;
var divDirectionsWindow;
var divMapit;
//Tracking Code
var pageTrackingCode = "UT_Community";

//Preload images
function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; }
    }
}

var iTab1 = imagePath + "communities_tab1.jpg";
var iTab1Active = imagePath + "communities_tab1_active.jpg";
var iTab2 = imagePath + "communities_tab2.jpg";
var iTab2Active = imagePath + "communities_tab2_active.jpg";
var iTab3 = imagePath + "communities_tab2.jpg";
var iTab3Active = imagePath + "communities_tab3_active.jpg";
var iTab4 = imagePath + "communities_tab2.jpg";
var iTab4Active = imagePath + "communities_tab4_active.jpg";
var headerTop = imagePath + "communities_top.jpg";
var headerBorder = imagePath + "communities_border.jpg";
var headerBottom = imagePath + "communities_bottom.jpg";
var mainTop = imagePath + "communities_main_bordertop.gif";
var mainBottom = imagePath + "communities_main_borderbottom.jpg";
var rightDarkTop = imagePath + "comm_header_bg.gif";
var rightDarkBorder = imagePath + "communities_border_dark.gif";
var rightDarkBottom = imagePath + "communities_bottom_dark.gif";
var rightLightTop = imagePath + "communities_top_light.jpg";
var rightLightBottom = imagePath + "communities_side_borderbottom.jpg";
var deleteImage = imagePath + "delete.gif";
var sdLogo = imagePath + "sdTitle.gif";
var offerGraphic = imagePath + "communities_offer.gif";

MM_preloadImages(iTab1, iTab1Active, iTab2, iTab2Active, iTab3, iTab3Active, iTab4, iTab4Active, mainTop, offerGraphic, mainBottom, headerTop, headerBorder, headerBottom, rightDarkTop, rightDarkBorder, rightDarkBottom, rightLightTop, rightLightBottom, deleteImage, sdLogo);

//Initialize Page
function InitPage() {
    communityName = $("div.mainHeaderTitle").text();
    //Retrieve Browser Type
    userBrowser = BrowserType();

    divOfferLightBox = new YAHOO.widget.Overlay("divOfferLightBox", { visible: false, width: "655px", height: "580px" });
    divOfferLightBox.render();

    divMapit = new YAHOO.widget.Overlay("divMapIt", { visible: false, width: "800px", height: "580px" });
    divMapit.render();

    //check if there is an offer
    //show banner if there is one
    if ($("div.mainTopBorderOffer div").children().length != 0) {
        $("div.mainTopBorder").hide();
        $("div.mainTopBorderOffer").show();

    }

    $("a#lnkOffer,a#lnkMetroOffer").click(function() {
        var offerKey = $(this).attr("rel");
        OpenOfferOverlay(offerKey);
    });
    //Initialize Main Tabs
    InitCommMainTabs();
    //Only display Plans Tabs if there are existing plans
    if (hasPlans == "True") {
        InitCommSideTabs();
        $("#sidePanels").fadeIn(10);

        if ($(".side").length == 1) {
            $("#commTabsRow").css({ display: "none" });
            //$("div.tabSideContent").css({ borderTop: "solid 1px #8B8B8B" });
        }

        if (hasModel > 0) $("div.modelMessage").show();

        //add links to images
        $("div.elevationPhotodiv").click(function() {
            var url = $(this).parents().find("tr").find("a").attr("href");
            if (url.trim() != "") {
                window.location = url;
            }
        });
    }
    //Initialize Local Interest Content
    InitLocalInterestTab();
    //Initialize Slide Show Content
    InitSlideShow();
    //Initialize tooltips for smart design blocks
    InitToolTips();
    //Initialize Driving Directions links
    InitDrivingDirectionLinks();

    //unload
    $(window).unload(function() {
        GUnload();
    });

    //Add click for community site map
    $("div.mainHeaderSiteMap").find("a").live("click", function() {
        var url = $(this).attr("href");
        window.open(url, "sitemap", "toolbar=0,menubar=0,location=0,status=0");
        return false;
    });

    //Add click event for mapDirections LightBox
    $("a.lnkMapAddress").click(function() {
        var link = $(this);
        $("#windowRoute").empty();
        var fromAddr = $("#salesofficeaddress").html().replace("<BR />", " ");
        if (useCoords) fromAddr = geolat + "," + geolng;
        var toAddr = link.parent().text();
        toAddr = toAddr.replace(link.text(), "").trim().replace(/\u00a0/g, "");
        var routeInfo = "from: " + fromAddr + " to: " + toAddr;
        var localTitle = link.parents("table").find("tr:first td.value").text();

        OpenMapItOverlay(localTitle, toAddr, routeInfo);
    });
}

//functions for lightbox
function OpenOfferOverlay(offerKey) {
    Reposition_Curtain();

    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "block");

    divOfferLightBox.cfg.setProperty("height", "580px");

    divOfferLightBox.show();

    $("#ifrOffer").attr("src", lfSource + offerKey);

    Reposition_OfferOverlay();
}

function OpenMapItOverlay(title, toaddress, routeinfo) {
    Reposition_Curtain();

    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "block");

    divMapit.cfg.setProperty("height", "600px");

    divMapit.show();

    $("#ifrMapIt").attr("src", mapitSource + "?title=" + escape(replaceChars(title)) + "&toadd=" + escape(replaceChars(toaddress)) + "&rinfo=" + escape(replaceChars(routeinfo)) + "");

    Reposition_MapItOverlay();
}

var Reposition_MapOverlay = function() {
    divDirectionsWindow.center();
}


var Reposition_OfferOverlay = function() {
    divOfferLightBox.center();
}

var Reposition_MapItOverlay = function() {
    divMapit.center();
}

function CloseOfferOverlay() {
    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "none");

    divOfferLightBox.cfg.setProperty("height", "0px");

    divOfferLightBox.hide();
}

function CloseMapItOverlay() {
    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "none");

    divMapit.cfg.setProperty("height", "0px");

    divMapit.hide();
}

var Reposition_Curtain = function() {
    var divCurtain = YAHOO.util.Dom.get("divCurtain");

    var docHeight = YAHOO.util.Dom.getDocumentHeight();
    var docWidth = YAHOO.util.Dom.getDocumentWidth();

    divCurtain.style.width = docWidth + "px";
    divCurtain.style.height = docHeight + "px";
}

//Function to retrieve Browser Type
function BrowserType() {
    var _browser;
    jQuery.each(jQuery.browser, function(i, val) {
        switch (i) {
            case "msie":
                if (val) _browser = "msie" + jQuery.browser.version.substr(0, 1);
                break;
            case "mozilla":
                if (val) _browser = i;
                break;
            case "safari":
                if (val) _browser = i;
            default:
                break;
        }
    });
    return _browser;
}

//function for get directions link
function DisplayRoute() {
    //Clear previous result
    clearerr("directionsErrorArea");
    if (!ValidateAddress()) { return; }
    $("#directionsPanel").empty();
    var fromAddr = $("#txtddAddress").val().trim() + ", " + $("#txtddCity").val().trim() + ", " + $("#txtddState").val().trim() + " " + $("#txtddZipCode").val().trim();
    var toAddr = $("#salesofficeaddress").html().replace("<BR />", " ");
    if (useCoords) toAddr = geolat + "," + geolng;
    var routeInfo = "from: " + fromAddr + " to: " + toAddr;
    BZInitDirectionsMap(routeInfo, locale, "directionsMap", "directionsPanel");

    $("html,body").animate({ scrollTop: $("#directionsPanel").position().top }, "fast")
}

//Validate if either city, state or zip is present
function ValidateAddress() {
    var errSummary = { "messages": [] };
    if ($("#txtddState").val().trim() == "" && $("#txtddCity").val().trim() == "" && $("#txtddZipCode").val().trim() == "") {
        errSummary.messages.push({ text: errMessage });
    }

    return processval("directionsErrorArea", errSummary);
}

//functions for displaying error messages
function adderr(errorAreadId, message) {
    $("#" + errorAreadId).append("<div class=\"errorMessage\">" + message + "</div>");
    $("#" + errorAreadId).css({ display: "block" });
}

function clearerr(errorAreadId) {
    $("#" + errorAreadId).empty();
    $("#" + errorAreadId).css({ display: "none" });
    $("#" + errorAreadId).append("<div class=\"errorAreaIntro\">" + errHeader + "</div>");
}

function processval(errorAreaId, errSummary) {
    if (errSummary.messages.length > 0) {
        clearerr(errorAreaId);
        $.each(errSummary.messages, function(index) {
            adderr(errorAreaId, "- " + this.text);
        });

        return false;
    }

    return true;
}

//Initialize links for driving directions to switch tab 
function InitDrivingDirectionLinks() {
    $("a.ddlinks").click(function() {
        $("#communities_tab4").trigger("click");
    });
}

//function to retrieve the smartblock content of the clicked link
function getSDBlock(sdBlockId) {
    var result;
    result = $("div#smartBlock").find("#" + sdBlockId).html();
    return (result == "" ? "No details available" : result);
}

//Initialize tooltips for each link that has smart design block content
//Only links with rel attributes will be initialized
function InitToolTips() {
    $("div.communityDescription a").each(
                function() {
                    if ($(this).attr("rel") == "") return;
                    var self = this;
                    var sdId = $(this).attr("rel").replace("balloon", "");
                    var sdContent = getSDBlock(sdId);
                    var strTitle = SDTitle;

                    if (userBrowser == "msie6") sdContent = "<div style=\"display:inline-block;\">" + sdContent + "</div>";

                    var areaX = "R";
                    var areaY = "U";
                    var area = areaY + areaX;

                    var positions = new Array(
                        {
                            "UpperLeft": { corner: "bottomRight", target: "topRight", tooltip: "rightBottom" },
                            "UpperRight": { corner: "bottomLeft", target: "topRight", tooltip: "leftBottom" },
                            "LowerLeft": { corner: "topRight", target: "topRight", tooltip: "rightTop" },
                            "LowerRight": { corner: "topLeft", target: "topRight", tooltip: "leftTop" }
                        }
                    );
                    var position = eval(positions);

                    switch (area) {
                        case "UL":
                            position = position[0].UpperLeft;
                            break;
                        case "UR":
                            position = position[0].UpperRight;
                            break;
                        case "LL":
                            position = position[0].LowerLeft;
                            break;
                        case "LR":
                            position = position[0].LowerRight;
                            break;
                    }

                    $(self).qtip(
                      {
                          content: {
                              text: sdContent,
                              title: {
                                  text: strTitle,
                                  button: "<img onclick=\"return false;\" style=\"border:solid 1px #E0E0E0;\" src=\"" + imagePath + "delete.gif\" alt=\"Close\" />"
                              }

                          },
                          hide: false,
                          show: {
                              solo: true,
                              when: { event: 'click' }
                          },
                          style: {
                              width: 250,
                              padding: 12,
                              background: '#FFFFFF',
                              color: '#3E3E3E',
                              border: {
                                  width: 1,
                                  radius: 12,
                                  color: '#F2F3ED'
                              },
                              tip: {
                                  corner: position.corner,
                                  color: '#F2F3ED',
                                  size: { x: 12, y: 40 }
                              },
                              name: 'dark'
                          },
                          position: {
                              corner: {
                                  target: position.target,
                                  tooltip: position.tooltip
                              },
                              adjust: {
                                  x: -6, y: 12
                              }
                          }
                      });
                });



}

//Initialize Slide Show
function InitSlideShow() {
    //Show first slide show
    var slideshows = $("div#slideShow div");
    var count = slideshows.length;

    //Hide slide show block if there are no images
    if (count == 0) {
        $("div.mainBody").hide();
        $("div.slideshowCaption").hide();
        return;
    }

    var page = $("#page");
    slideshows.removeClass("selected");
    $("div#slideShow div:first").addClass("selected").fadeIn(10);
    $("div.slideshowText").html($("div#slideShow div:first").find("INPUT").val());
    if (count > 0) {
        page.html(1);
        $("#totalPages").html(" of " + count);
    }

    //function to move the image 
    $("a.linkSS").click(function() {
        var isFirst = false;
        var isLast = false;
        var curPage;
        if ($("div#slideShow div.selected").html() == $("div#slideShow div:first").html()) isFirst = true;
        if ($("div#slideShow div.selected").html() == $("div#slideShow div:last").html()) isLast = true;

        var slideshow;
        if ($(this).attr("ID") == "lnkssLeft") {
            if (isFirst) {
                slideshow = $("div#slideShow div:last")
                curPage = count;
            }
            else {
                slideshow = $("div#slideShow div.selected").prev();
                curPage = parseInt(page.html()) - 1;
            }
        }
        if ($(this).attr("ID") == "lnkssRight") {
            if (isLast) {
                slideshow = $("div#slideShow div:first")
                curPage = 1;
            }
            else {
                slideshow = $("div#slideShow div.selected").next();
                curPage = parseInt(page.html()) + 1;
            }
        }
        $("div#slideShow div").removeClass("selected").css({ display: "none" });
        slideshow.addClass("selected");
        slideshow.fadeIn(500);
        $("div.slideshowText").html(slideshow.find("INPUT").val());
        page.html(curPage);
    });

}
//Initialize Local Interest Tab
function InitLocalInterestTab() {
    //Initialize only if there is at least one local interest defined
    if ($("a.linkCategory").length == 0) { return; }
    $("a.linkCategory").click(function() {
        var catID = $(this).attr("ID").replace("lnkCat", "");

        //remove selected
        $("a.linkCategory").removeClass("selected");
        $("#divLocalInterests div").removeClass("selected");
        $("#divLocalInterests div").css({ display: "none" })

        $(this).addClass("selected");
        $.each($("#divLocalInterests div.divCategory"), function(index) {
            if ($(this).find("INPUT").val() == catID) {
                $(this).fadeIn(10);
                $(this).find("div").fadeIn(10);
                $(this).addClass("selected");
            }
        });

    });

    //Display data for first category
    var firstCat = $("a.linkCategory:first");
    var firstCatId = firstCat.attr("ID").replace("lnkCat", "");

    firstCat.addClass("selected");
    $.each($("#divLocalInterests div.divCategory"), function(index) {
        if ($(this).find("INPUT").val() == firstCatId) {
            $(this).fadeIn(10);
            $(this).find("div").fadeIn(10);
            $(this).addClass("selected");
        }
    });

    //Adjust padding for local interest tab if browser is safari
    if (userBrowser == "safari") $("#communities_tab2Content").find("div.tabHeaderSideImage").css({ paddingBottom: "0px" });

}


//Initialize Main Tabs
function InitCommMainTabs() {

    if ($.browser.msie) {
        $("#commDetTabs tr td").css({ display: "block" });
    }
    else {
        $("#commDetTabs tr td").css({ display: "table-cell" });
    }


    //init hovers on all metro tabs
    $("#commDetTabs tr td").hover(function() {
        if (!$(this).hasClass("selected")) {
            $(this).addClass("hover");
        }
    }, function() {
        if (!$(this).hasClass("selected")) {
            $(this).removeClass("hover");
        }
    });

    //bind switching events
    $("#commDetTabs tr td").click(function() {
        var tdItem = $(this);
        var tabId = $(this).attr("id");
        //clicked on a selected tab should be ignore
        if (!tdItem.hasClass("selected")) {
            //unmark all

            $("#commDetTabs tr td").removeClass("selected");


            $("div#mainContent div.tabContent").filter("div[id!='" + tabId + "Content']").css({ display: "none" });

            $("div#mainContent").find("div[id='" + tabId + "Content']").fadeIn(500);

            if (tabId == "communities_tab4") {
                if (!isMapInitialized) {
                    //Adjust contianer top position for IE6
                    //if (userBrowser == "msie6") $("div.DirectionsContainer").css({ marginTop: "-13px" });
                    //Initialize google map
                    InitMap("directionsMap", geolat, geolng, "Current location");
                    isMapInitialized = true;
                }
                $("html,body").animate({ scrollTop: "100px" }, "fast")
            }


            if (tabId == "communities_tab2") {
                if (!isTab2Filtered) {
                    //Adjust contianer top position for IE6
                    //if (userBrowser == "msie6") $("div.LocalInterestContainer").css({ marginTop: "-13px" });
                    //Hide fields that have no values
                    $.each($("div.LocalInterestContainer td.value"), function() {
                        var obj = $(this);
                        if (obj.text().trim() == "") {
                            obj.parent("tr").css({ display: "none" });
                        }
                    });
                    isTab2Filtered = true;
                }
            }

            if (tabId == "communities_tab3") {
                if (!isTab3Filtered) {
                    //Adjust contianer top position for IE6
                    //if (userBrowser == "msie6") $("div.SchoolContainer").css({ marginTop: "-13px" });
                    //Hide fields that have no values
                    $.each($("div.SchoolContainer td.value"), function() {
                        var obj = $(this);
                        if (obj.text().trim() == "") {
                            obj.parent("tr").css({ display: "none" });
                        }
                    });
                    isTab3Filtered = true;
                }
            }

            //mark newly clicked one
            tdItem.addClass("selected");
            tdItem.removeClass("hover");
            tdItem.css({ backgroundImage: "url(\"" + imagePath + tabId + "_active" + ".jpg\")" });

            $.each($("#commDetTabs tr td"), function() {
                if (!$(this).hasClass("selected")) {
                    $(this).css({ backgroundImage: "url(\"" + imagePath + $(this).attr("id") + ".jpg\")" });
                }
            });

            //make sure no tooltip is displayed when changing tabs
            $("div.qtip-active").hide();

        }
    });
    //Mozilla fix for top border
    if (userBrowser == "mozilla") {
        $("div.mainTopBorder").css({ backgroundPosition: "0px -1px" });
    }

    //check for sales hours and hide if not existing
    var objHours = $("#saleshours");
    if (objHours.find("div:last").text().trim() == "") {
        objHours.hide();
    }

    //Switch to directions tab upon load if parameter "DD" is detected
    if (initTab == "DD") {
        $("#communities_tab4").trigger("click");
    }
    else {
        //make first comm tab selected
        $("#commDetTabsRow td:first").addClass("selected")
            .css({ backgroundImage: "url(\"" + imagePath + $("#commDetTabsRow td:first").attr("id") + "_active" + ".jpg\")" });

        //make first comm tab content visible
        $("div#mainContent div[class='tabContent']:first").fadeIn(10);
    }
}

//Function to initialize side tabs (product listing)
function InitCommSideTabs() {
    if ($.browser.msie) {
        $("#commTabs tr td").css({ display: "block" });
    }
    else {
        $("#commTabs tr td").css({ display: "table-cell" });
    }


    //init hovers on all metro tabs
    $("#commTabs tr td").hover(function() {
        if (!$(this).hasClass("selected")) {
            $(this).addClass("hover");
        }
    }, function() {
        if (!$(this).hasClass("selected")) {
            $(this).removeClass("hover");
        }
    });

    //bind switching events
    $("#commTabs tr td.side").click(function() {
        var tdItem = $(this);
        var tabId = tdItem.attr("id");
        //clicked on a selected tab should be ignore
        if (!tdItem.hasClass("selected")) {

            //unmark all
            $("#commTabs tr td").removeClass("selected");

            var product = tdItem.html().trim();
            //remove selected
            $("div.divProductListing").css({ display: "none" })
            $.each($("div.divProductListing"), function(index) {
                if ($(this).find("INPUT").val() == product) {
                    $(this).fadeIn(10);
                    $(this).addClass("selected");
                }
            });

            //mark newly clicked one
            tdItem.addClass("selected");
            tdItem.removeClass("hover");
        }
    });

    //make first comm tab selected
    var firstTab = $("#commTabsRow td.side:first");
    firstTab.addClass("selected");
    var selected = firstTab.text().trim();
    //make first comm tab content visible
    $.each($("div.divProductListing"), function(index) {
        if ($(this).find("INPUT").val() == selected) {
            $(this).fadeIn(10);
        }
    });
}


//For google map routing
var map = null;
var directionsPanel;
var directions;
var currentMap;

//Initialize map and display marker for geo address
function InitMap(mapElementId, initialLat, initialLong, locationName) {

    if (GBrowserIsCompatible()) {
        //initialize coordinate encoder
        InitBZGC();
        var mapElement = document.getElementById(mapElementId);
        //get map ref
        map = new GMap2(mapElement);
        //        map.disableDoubleClickZoom();

        //add map control
        map.addControl(new GSmallMapControl());

        //navigate to initial location
        NavMapToLocation(initialLong, initialLat, locationName);
    }
}


function NavMapToLocation(lon, lat, bubbleCaption) {
    var currentlocation = new GLatLng(lat, lon);
    map.setCenter(currentlocation, 10);
    map.panTo(currentlocation);
    map.addOverlay(new GMarker(currentlocation));
    bubbleCaption = "<div style=\"font-weight:bold\">" + communityName + "</div>";
    bubbleCaption += "<div>" + $("#salesofficeaddress").html() + "</div>";
    map.openInfoWindow(currentlocation, bubbleCaption);
}

function InitBZGC() {
    bzGC = new GClientGeocoder();
}


//Display routing info
function BZInitDirectionsMap(routeInfo, locale, mapId, directionsId) {
    currentMap = mapId;
    if (directions != null)
        GEvent.clearListeners(directions, "error");

    var mapobj = document.getElementById(mapId);
    var panelobj = document.getElementById(directionsId);
    GUnload();
    map = new GMap2(mapobj);

    directionsPanel = panelobj;
    directions = new GDirections(map, directionsPanel);
    GEvent.addListener(directions, "error", handleRoutingErrors);
    directions.load(routeInfo, { "locale": locale });
}

//Capture routing errors
function handleRoutingErrors() {
    var mapError = "";
    if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        mapError = "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.";
    else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
        mapError = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.";

    else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
        mapError = "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.";

    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

    else if (directions.getStatus().code == G_GEO_BAD_KEY)
        mapError = "The given key is either invalid or does not match the domain for which it was given.";

    else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
        mapError = "A directions request could not be successfully parsed.";

    else mapError = "An unknown error occurred.";

    if (currentMap == "directionsMap") {
        $("div#directionsErrorArea").text(mapError);
        $("div#directionsErrorArea").show();
        InitMap("directionsMap", geolat, geolng, "Current location");
        isMapInitialized = true;
    }
    else {
        $("div.windowBody").hide();
        $("div#windowError").text(mapError);
        $("div#windowError").show();
    }

}


// Create XML namespace and vml styles if IE
if (document.namespaces && document.namespaces["v"] == null) {
    document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
    var stylesheet = document.createStyleSheet().owningElement;
    stylesheet.styleSheet.cssText = "v\\:*{behavior:url(#default#VML); display: inline-block }";
}

String.prototype.trim = function() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "").replace(/(\r\n|\r|\n)/g, "");
}

function replaceChars(text) {
    return text.replace("\"", "\\\"").trim();
}