﻿//Global Variables
var fromPrice;
var toPrice;
var sortedArray = new Array();
var commNameArray = new Array();
var commPriceArray = new Array();
var priceArrayUnique = new Array();
var noBossCommsArray = new Array();
var sort = "";
var bossSort = "A";
var currentBrowserScrollHeight = 351;
var myPreviousFromPrice = 0;
var myPreviousToPrice = 0;


// Initialize metro area page
var map;
var communityData = new Array();
var divDisclaimerLightBox;
var isOLoaded = false;
var innerCommTableHeight = "359px";
var userBrowser;
var divVideoLightBox;
var videoPlayer;

function InitPage() {
    //Eloqua added scripts
    if (this.GetElqCustomerGUID)
        $("#elqCustomerGUID").val(GetElqCustomerGUID());
        
    var ValidatorOnChangeNew = ValidatorOnChange;

    ValidatorOnChange = function(event) {
        var targetedControl;
        if ((typeof (event.srcElement) != "undefined") && (event.srcElement != null)) {
            targetedControl = event.srcElement;
        }
        else {
            targetedControl = event.target;
        }

        if (targetedControl.id == tbPhoneID) {
            ValidatorOnChangeNew(event);
        }
    };

    $(window).unload(function() {
        GUnload();
    });
    window.scrollTo = function(x, y) {

        document.getElementById(validateSummaryID).scrollIntoView();
        $("#" + validateSummaryID).hide().show();
    };

    divDisclaimerLightBox = new YAHOO.widget.Overlay("divDisclaimerLightBox", { visible: false, width: "600px", height: "310px" });
    divDisclaimerLightBox.render();

    divVideoLightBox = new YAHOO.widget.Overlay("divVideoLightBox", { visible: false, width: "356px", height: "326px" });
    divVideoLightBox.render();
    //Bind Input Events


    $("#" + tbFirstNameID).blur(
        function() {
            if ($(this).val() == "") {
                $(this).val(tbFirstName);
            }
        }
    );
    $("#" + tbLastNameID).blur(
        function() {
            if ($(this).val() == "") {
                $(this).val(tbLastName);
            }
        }
    );
    $("#" + tbPhoneID).blur(
        function() {
            if ($(this).val() == "") {
                $(this).val(tbPhone);
            }
        }
    );
    $("#" + tbEmailID).blur(
        function() {
            if ($(this).val() == "") {
                $(this).val(tbEmail);
            }
        }
    );
    $("#" + tbEmailConID).blur(
        function() {
            if ($(this).val() == "") {
                $(this).val(tbEmailCon);
            }
        }
    );
    $("#" + tbCommentID).blur(
        function() {
            if ($(this).val() == "") {
                $(this).val(tbComment);

            }
        }
    );

    //Retrieve Browser Type
    userBrowser = BrowserType();
    //Browser Fixes
    //Calculate community list title
    if (fakeMetro == "false") {

        var data = YAHOO.lang.JSON.parse(jSon);

        communityData = data.Communities;

        MapInit(false);
    }

    //SSFIX: init other fake single-select dropdowns for state, price range and move-in time frame
    $("#" + stateListID).dropdownchecklist({ width: 235, maxDropHeight: 100 });
    $("#" + priceListID).dropdownchecklist({ width: 235, maxDropHeight: 100 });
    $("#" + moveListID).dropdownchecklist({ width: 235, maxDropHeight: 100 });
    //END SSFIX   

    // COI
    LoadCommunityList();
    // End COI

    $(".mInput").bind("click", function() {
        switch ($(this).attr("id")) {
            case tbFirstNameID:
                if ($(this).val() == tbFirstName) {
                    $(this).val("");
                }
                break;
            case tbLastNameID:
                if ($(this).val() == tbLastName) {
                    $(this).val("");
                }
                break;
            case tbPhoneID:
                if ($(this).val() == tbPhone) {
                    $(this).val("");
                }
                break;
            case tbEmailID:
                if ($(this).val() == tbEmail) {
                    $(this).val("");
                }
                break;
            case tbEmailConID:
                if ($(this).val() == tbEmailCon) {
                    $(this).val("");
                }
                break;
            case tbCommentID:
                if ($(this).val() == tbComment) {
                    $(this).val("");
                }
                break;
        }
    });
    $("#selectedComm").text(0);
    $("#maxComm").text(maxCommunity);

    //COI
    /*subscribe to the scroll event of the div*/
    $(".infobox_form").scroll(function() {
        $("html, body").trigger("click");
    });
    //End COI
    //CreateVideoFrame();
    /*initiate event tracking */
    TrackGoogleEvent("Promo", "Submit", "Lead Form");
}

//COI
function ValidateCommunities(source, args) {
    AssignCommunities();
    if ($("#" + selectedCommunities).val().length == 0)
        args.IsValid = false;
    else
        args.IsValid = true;
}

function AssignCommunities() {
    var communities = "";
    if ($(".ui-dropdownchecklist-dropcontainer input.defaultOption:checked").length == 1)
        communities = $(".ui-dropdownchecklist-dropcontainer input.defaultOption").attr("id")
                                                                                  .replace("lstCommunities", "");
    else
        $.each($(".ui-dropdownchecklist-dropcontainer input.metroOption:checked"), function(index) {
            var community = $(this).attr("id")
                                   .replace("lstCommunities", "");
            communities += community + "|";
        });

        $("#" + selectedCommunities).val(communities);

        AddCookie();
}

function AddCookie() {
    var email = $("#" + tbEmailID).val();
    var guid = $("#elqCustomerGUID").val();
    var cookievalues = guid + "|" + email;
    $.cookie("BZ_eloqua", cookievalues);
}

function LoadCommunityList() {
    var communityItems = "";
    communityData.sort(sorterWSByName);
    $.each(communityData, function(index) {
        var community = this;
        communityItems += "<option class=\"metroOption\" value=\"opt" + community.WebsiteCommunityKey + "\" >" + community.Name;

        if (community.WsmetroBosscommunities.length > 0) {
            var minPrice = getMinPrice(community.WsmetroBosscommunities);
            if (minPrice > 0)
                communityItems += "<span class=\"tagline\"> - from $" + addCommas(minPrice) + "</span>";
        }
        communityItems += "</option>";
    });
    communityItems += "<option class=\"defaultOption\" id=\"@\" value=\"@\">I'm not sure</option>";
    var maxHeight = (communityData.length * 21) + 22;
    if (maxHeight > 150) maxHeight = 150;
    if (communityData.length > 0)

        $("#lstCommunities").append(communityItems)
                        .dropdownchecklist({
                            width: 235,
                            maxDropHeight: maxHeight,
                            textFormatFunction: function(options) {
                                var selectedOptions = options.filter(":selected");

                                //if (selectedOptions.length < maxCommunity)
                                $(".ui-dropdownchecklist-dropcontainer .ui-dropdownchecklist-item").removeAttr("disabled")
                                                                                                   .children()
                                                                                                   .removeAttr("disabled")
                                                                                                   .removeClass("disabledText");

                                if (selectedOptions.length > 0 && selectedOptions.filter(":last").val() == "@") {
                                    $(".ui-dropdownchecklist-dropcontainer .ui-dropdownchecklist-item input.metroOption:checked").removeAttr("checked");
                                    $(".ui-dropdownchecklist-dropcontainer .ui-dropdownchecklist-item input.metroOption:not(:checked)").parent()
                                                                                                                           .attr("disabled", "disabled")
                                                                                                                           .children()
                                                                                                                           .attr("disabled", "disabled")
                                                                                                                           .addClass("disabledText");
                                    return ("No communities selected");
                                }
                                else {
                                    var countOfSelected = selectedOptions.size();

                                    var size = options.size();
                                    switch (countOfSelected) {
                                        case 0: return "What communities interest you?";
                                        case 1: return "1 community selected";
                                       /* case maxCommunity:
                                            $(".ui-dropdownchecklist-dropcontainer .ui-dropdownchecklist-item input.metroOption:not(:checked)").parent()
                                                                                                                                                   .attr("disabled", "disabled")
                                                                                                                                                   .children()
                                                                                                                                                   .attr("disabled", "disabled")
                                                                                                                                                  .addClass("disabledText");
                                            return countOfSelected + " communities selected";*/

                                        default: return countOfSelected + " communities selected";
                                    }
                                }
                            }
                        });


    /* Add border to first item*/
    $(".defaultOption").parent().addClass("firstItem");


    $(".ui-dropdownchecklist-text").disableSelection();

    $(".ui-dropdownchecklist-dropcontainer").click(function() {
        return false;
    });

    switch (userBrowser) {
        case "mozilla": case "safari": case "opera":
            $(".defaultOption, .metroOption").css({ margin: "2px" });
            break;
        case "msie6":
            $("html, body").click(function() {
                $("select:not(:first)").css({ 'visibility': 'inherit' });
            });
            $(".ui-dropdownchecklist-item").css({ width: "100%" });
            break;
        default:
            break;
    }
}
//End COI

function getMinPrice(bossCommunities) {
    var minPrice = bossCommunities[0].MinPrice;
    $.each(bossCommunities, function(index) {
        var bossCommunity = this;
        if (bossCommunity.MinPrice < minPrice)
            minPrice = bossCommunity.MinPrice;
    });
    return minPrice;
}


function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}


function searchArray(a, search) {
    for (var i in a) {
        if (a[i] == search)
            return 1;
    }
    return 0;
}

function OpenDisclaimerOverlay() {
    Reposition_Curtain();

    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "block");

    divDisclaimerLightBox.cfg.setProperty("height", "310px");
    if (userBrowser == "msie6") {
        $.each($("select"), function(index) {
            $(this).attr("disabled", "disabled");
            $(this).css("backgroundColor", "#DADADA");
        });
    }

    divDisclaimerLightBox.show();

    Reposition_DisclaimerOverlay();
}

var Reposition_DisclaimerOverlay = function() {
    divDisclaimerLightBox.center();
}

function CloseDisclaimerOverlay() {
    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "none");

    divDisclaimerLightBox.cfg.setProperty("height", "0px");

    divDisclaimerLightBox.hide();
    if (userBrowser == "msie6") {
        $.each($("select"), function(index) {
            $(this).attr("disabled", "");
            $(this).css("backgroundColor", "#FFFFFF");
        });
    }
}

function CreateVideoFrame() {


    var s1 = new SWFObject(flashPlayer, 'player', '316', '276', '9');
    s1.addParam('allowfullscreen', 'true');
    s1.addParam('allowscriptaccess', 'always');
    s1.addParam('wmode', 'opaque');
    s1.addVariable('icons', false);
    s1.addVariable('stretching', 'fill');
    s1.addVariable('file', flashFile);
    s1.addVariable('image', flashImage);
    s1.addVariable("plugins", "gapro-1");
    s1.addVariable("gapro.accountid", gaAccountId);
    s1.addVariable("gapro.trackstarts", "true");
    s1.addVariable('skin', flashStyle);
    s1.addVariable('autostart', "true");
    s1.addVariable('id', 'player');
    s1.addVariable('name', 'player');
    s1.write('promoVidPlayer');
    
  
}

function playerReady(obj) {
    videoPlayer = document.getElementById(obj['id']);

    switch (userBrowser) {
        case "opera":
            videoPlayer.sendEvent("STOP");
            break;
        case "safari":
            if (/chrome/.test(navigator.userAgent.toLowerCase()))
                videoPlayer.sendEvent("STOP");
    }
}

function OpenVideoOverlay() {

    Reposition_Curtain();
    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "block");

    divVideoLightBox.cfg.setProperty("height", "326px");
    if (userBrowser == "msie6") {
        $.each($("select"), function(index) {
            $(this).attr("disabled", "disabled");
            $(this).css("backgroundColor", "#DADADA");
        });
    }

    divVideoLightBox.show();

    Reposition_VideoOverlay();

    setTimeout('playVideo()',1);
}

function playVideo() {
    videoPlayer.sendEvent("PLAY", "true");
}

var Reposition_VideoOverlay = function() {
    divVideoLightBox.center();
}

function CloseVideoOverlay() {
    videoPlayer.sendEvent('STOP');
    
    var divCurtain = YAHOO.util.Dom.get("divCurtain");
    YAHOO.util.Dom.setStyle(divCurtain, "display", "none");

    divVideoLightBox.cfg.setProperty("height", "0px");

    divVideoLightBox.hide();

    if (userBrowser == "msie6") {
        $.each($("select"), function(index) {
            $(this).attr("disabled", "");
            $(this).css("backgroundColor", "#FFFFFF");
        });
    }
    
}

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 ValidatePhoneNumber(source, args) {
    var matchpattern = /\(?([0-9]{3})\)?-?([0-9]{3})-?([0-9]{4})/;
    var matcher = new RegExp(matchpattern);
    var objectValidated = $("#" + $("#" + source.id).attr("controltovalidate"));
    if (objectValidated.val() == "Phone (optional)") {
        args.IsValid = true;
        return;
    }
    var matched = matcher.exec(objectValidated.val());
    if (matched != null) {
        var new_num = "(" + matched[1] + ") " + matched[2] + "-" + matched[3];
        objectValidated.val(new_num);
    }
    var matchpattern2 = /\(([0-9]{3})\) ([0-9]{3})-([0-9]{4})$/;
    matcher = new RegExp(matchpattern2);
    matched = matcher.exec(objectValidated.val());
    if (matched != null)
        args.IsValid = true;
    else
        args.IsValid = false;

}

//End Lightbox code
function MapInit(isLoaded) {

    InitMap("map", 0, 9999999, true, true, true, false, isLoaded);
}

function OpenBubble(data) {
    map.closeInfoWindow();
    resetMarkers();
    var imgUrlPrefix = "";


    if (document.location.href.toLowerCase().indexOf("/build/") != -1) {
        imgUrlPrefix = "../";
    }

    var eventMarker = lookupMarker(data);

    if (eventMarker != null) {
        var latLng = new GLatLng(eventMarker.Lat, eventMarker.Long);

        if (!map.getBounds().containsLatLng(latLng)) {
            map.panTo(latLng);
        }
        var isGreen = false;
        for (var i = 0; i < eventMarker.commArray.length; i++) {
            if (eventMarker.commArray[i].IsGreen)
                isGreen = true;
        }

        eventMarker.gMarker.setImage(imgUrlPrefix + singleHomeClicked);
        if (isGreen)
            eventMarker.gMarker.setImage(imgUrlPrefix + singleHomeClickedGreen);

        GEvent.trigger(eventMarker.gMarker, 'click');

    }


}

function resetMarkers() {

    var imgUrlPrefix = "";


    if (document.location.href.toLowerCase().indexOf("/build/") != -1) {
        imgUrlPrefix = "../";
    }
    for (var i = 0; i < markerArray.length; i++) {
        var communities = markerArray[i].commArray;
        var isGreen = false;
        for (var j = 0; j < communities.length; j++) {
            if (communities[j].IsGreen)
                isGreen = true;
        }
        markerArray[i].gMarker.setImage(imgUrlPrefix + singleHomeImage);
        if (isGreen)
            markerArray[i].gMarker.setImage(imgUrlPrefix + singleHomeImageGreen);
    }
}
function lookupMarker(data) {
    for (var i = 0; i < markerArray.length; i++) {
        for (var j = 0; j < markerArray[i].commArray.length; j++) {
            if (markerArray[i].commArray[j].GeoLatitude == data.GeoLatitude && markerArray[i].commArray[j].GeoLongitude == data.GeoLongitude) {
                return markerArray[i];
            }
        }
    }
    return null;
}

function convetToPricedFromText(price) {

    var priceString = price.toString();
    if (price > 0) {
        if (priceString.length > 6) {
            var rounded = priceString.substr(0, 1);
            var rightOfDec = priceString.substr(1, 2);
            priceString = rounded + "." + rightOfDec;
            priceString = "$" + priceString + "Ms";
        }
        else {
            if (priceString.length > 1) {
                /*var rounded = priceString.substr(0, 2);
                var zeros = "";
                for (var i = 0; i < priceString.length; i++) {
                if (i > 1) {
                zeros = zeros + "0";
                }
                }
                rounded = rounded + zeros;*/
                var rounded = Math.round(price * .001);
                priceString = rounded;
                priceString = "$" + priceString + "s";
            }
        }
    }
    else {
        return notReleasedText;
    }
    return priceString;
}


// 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 }";
}


//custom sorter for BOSS communities passed as objects with min prices
//being properties
function sorterBOSSByPrice(comm1, comm2) {
    var price1 = comm1[0];
    var price2 = comm2[0];
    return ((price1 < price2) ? -1 : ((price1 > price2) ? 1 : 0));
}

//COI
function sorterWSByName(comm1, comm2) {
    var name1 = comm1.Name;
    var name2 = comm2.Name;
    return ((name1 < name2) ? -1 : ((name1 > name2) ? 1 : 0));
}
//End COI


//custom sorter for WS communities with args passed as scalar prices
function sorterWSByPrice(price1, price2) {
    return ((price1 < price2) ? -1 : ((price1 > price2) ? 1 : 0));
}
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;
            case "opera":
                if (val) _browser = i;
            default:
                break;
        }
    });
    return _browser;
}

