﻿// global vars
var SlideArray = null;
var SlideArrayCount = 0;
var t = null;

$(document).ready(function() {

    // navigation dropdowns
    var dropIt;
    var closeIt;
    $("#navigation li").hover(function() {
        clearTimeout(closeIt);
        var thisThing = $(this);
        var showDropdown = function() { thisThing.children("div.dropdown:hidden").slideDown(); };
        dropIt = setTimeout(showDropdown, 150);
        $(this).siblings("li").children("div.dropdown").slideUp();
    }, function() {
        clearTimeout(dropIt);
        var thisThing = $(this);
        var hideDropdown = function() { thisThing.children("div.dropdown").slideUp(); };
        closeIt = setTimeout(hideDropdown, 300);
    });

    //email subscription form
    $("form#email.formwrapper input[type='submit']").live("click", function() {
        var entity = $(this).parents("form").find("input[name='formentity']").attr("value");
        submitForm(entity);
        return false;
    });

    //quick search form
    $("form#quick_search.formwrapper input[type='submit']").live("click", function() {
        var state = $(this).parents("form").find("select[name='state']").attr("value");
        window.location.href = "/search.aspx?state=" + state
        return false;
    });

    //"contact an expert" button
    $("div#contactBox").live("click", function() {
        window.location.replace("/about/contact-us.aspx");
    });


    //BUGTracker
    $("#reportBug").live("click", function() {
        serializedForm = "location=" + urlencode(window.location.href);
        var action = "BugReporter.aspx?action=show";
        $.post(action, serializedForm, showBugForm);
    });

    $("form#bugReporter .submit").live("click", function() {
        var serializedForm = $("#bugReporter").serialize();
        var action = "BugReporter.aspx?action=submit";
        $.post(action, serializedForm, showBugForm);
        $("form#bugReporter, #bugMask").remove();
    });

    $("form#bugReporter #levelID option").live("click", function() {
        $("form#bugReporter #levelID").attr("style", $(this).attr("style"));
    });

    $("form#bugReporter .bugClose").live("click", function() {
        $("form#bugReporter, #bugMask").remove();
    });

    /* Focus and Exit Form Fields  */
    $("input").focus(function() {
        var ex = $(this).attr("example");
        if (ex == $(this).val()) {
            $(this).val("");
        }
    });
    $("input").blur(function() {
        if ($(this).val() == "") {
            $(this).val($(this).attr("example"));
        }
    });

    /*setEqualHeight($(".column"));*/

    // HOMEPAGE only:
    if ($("div#pageWrap").hasClass("home")) {
        slideshow();
    }

    // INSIDE PAGES only:
    if ($("div#pageWrap").hasClass("inside")) {

        // select active sidenav link
        $("#leftCol a").each(function() {
            var className = $(this).attr("class");
            if ($("#pageWrap").hasClass(className)) {
                $(this).addClass("active");
            }
        });
        
        // hide "Client List" on sidenav in Investment Sales and Property Disposition
        if (($("div#pageWrap").hasClass("investment-sales")) || ($("div#pageWrap").hasClass("property-disposition")) || ($("div#pageWrap").hasClass("dartmouth-urban"))) {
            $("#leftCol a.client-list").addClass("reallyhide");
        }
    }

    // hide "Client List" on dropdown menus of Investment Sales and Property Disposition
    $("li.property-disposition div.dropdown a.client-list").addClass("reallyhide");
    $("li.investment-sales div.dropdown a.client-list").addClass("reallyhide");
    $("li.dartmouth-urban div.dropdown a.client-list").addClass("reallyhide");

    //******** merged from /styles/properties/general.js ***********//
    $("#hpsearch").focus(function() {
        $("#hpsearch").addClass("focus");
        if (this.value == 'Search By Zip Code') {
            this.value = "";
        }
    }).blur(function() {
        if (!this.value.length) {
            this.value = 'Search By Zip Code';
        }
    }).keypress(function(e) {
        return numbersOnly(e);
    });


    $("#searchResults .hot").live("click", function() {
        window.location.href = $(this).attr("pid") + ".aspx"
    });

    $("#pagination a").live("click", function() {
        var p = $(this).attr("page");
        dbAJAX("/scripts/yoddle/ui.aspx?", "action=page&page=" + p + salt(), pageResults);
        return false;
    });

    $("#searchResults table tr th").live("click", function() {
        var sort = $(this).attr("sort");
        if (sort != undefined) {
            dbAJAX("/scripts/yoddle/ui.aspx?", "action=sort&sort=" + sort + salt(), refreshResults);
        }
    });

    $("#enlarge_controlbar").live("click", function() {
        $("#wrapper").removeClass("overlay");
        $("#enlarge_layer").fadeOut(300);
    });


    $(".asset").live("click", function() {

        var imgw = 800;
        var imgh = 600;
        if ($(this).hasClass("googlemap") == true) {
            $("#enlarge_image").hide();
            $("#enlarge_map").appendTo($("#enlarge_layer"));
            $("#enlarge_map").show();
            //$(".enlarge").attr("target", "locus");
            $("#enlarge_controlbar h5").html("LOCUS MAPS");

        } else {
            var imgurl = $(this).attr("href");
            var imgthumb = $(this).attr("thumb");
            var os = 0;
            imgw = $(this).attr("imgw");
            imgh = $(this).attr("imgh");

            $("#enlarge_image").html("<img src='/assets" + imgurl + "'/>")
            if (imgw > imgh) {

                if (imgw > 800) {
                    os = imgw / 800;
                    imgw = imgw / os;
                    imgh = imgh / os;
                }
                $("#enlarge_image img").attr("width", imgw);

            } else {

                if (imgh > 600) {
                    os = imgw / 600;
                    imgw = imgw / os;
                    imgh = imgh / os;
                }
                $("#enlarge_image img").attr("height", imgh);
            }
            $("#enlarge_layer").show();
            var title = $(this).siblings("label").html();
            $(".enlarge").attr("target", "");

            $("#enlarge_controlbar h5").html(title);
            $("#enlarge_map").hide();
            $("#enlarge_map").appendTo($("#farfaraway"));

            $("#enlarge_image").show();
            //$("#asset_thumb").html("<img src='" + imgthumb + "'/>")
            //$("#asset_thumb").show();

        }

        var tar = "#enlarge_layer";
        var ypos = (($(window).height() / 2) + $(window).scrollTop()) - (imgh / 2);
        var xpos = ($(window).width() / 2) - (imgw / 2);
        if (ypos < 10) { ypos = 20 };

        $(tar).css("top", ypos + "px");
        $(tar).css("left", xpos + "px");
        $(tar).hide();
        $("#wrapper").addClass("overlay");
        $(tar).fadeIn(300);

        //for IE but it still doesn't work.  Sigh
        //$("#enlarge_image").hide();
        //$("#enlarge_map").hide();
        //$("#enlarge_layer").hide();
    });
});

//******************** Functions *************************//

//AJAX FORM SUBMISSIONS
function submitForm(theToken) {
    var f = $("#" + theToken);
    var serializedForm = f.serialize();
    var action = "formsprocessor.aspx";
    $.post(action, serializedForm, webFormHandler);
}

function webFormHandler(r) {
    var ra = r.split("||");
    if ((ra[0] == "OK") || (ra[0] == "HasErrors")) {
        if ((ra[2].charAt(0) == "@") && (ra[0] == "OK")) {
            window.location.href = ra[2].substr(1) + "?" + ra[1];
        } else {
            var f = "#" + ra[1]
            $(f).html(ra[2]);
            location = f;
        }
    }
    return false;
}

function ajaxHandler(r) {
    var ra = r.split("||");

    if ((ra[0] == "OK") || (ra[0] == "HasErrors")) {
        switch (ra[1]) {
            case 'getslides':
                SlideArray = ra[2].split("^^");
                break;
        }
    }
    return false;
}

//Bug Reporting
function showBugForm(r) {
    $("form#bugReporter, #bugMask").remove();
    $("body").append(r);

    $("form#bugReporter #levelID option").css({ "color": "white","width":"100%"});
    $("form#bugReporter #levelID option:eq(0)").css({"color": "black", "background-color": "white"});
    $("form#bugReporter #levelID option:eq(1)").css("background-color", "red");
    $("form#bugReporter #levelID option:eq(2)").css("background-color", "orange");
    $("form#bugReporter #levelID option:eq(3)").css("background-color", "gold");
    $("form#bugReporter #levelID option:eq(4)").css("background-color", "blue");
    $("form#bugReporter #levelID option:eq(5)").css("background-color", "green");
    $("form#bugReporter #levelID").attr("style", $("form#bugReporter #levelID option:selected").attr("style"));
}

//Set the Columns tp Equal Height
function setEqualHeight(whatever) {
    var tallestColumn = 0;
    whatever.each(function() {
        var currentPixels = $(this).height();
        var currentHeight = currentPixels / 12;
        if (currentHeight > tallestColumn) {
            tallestColumn = currentHeight;
        }
    });
    whatever.height(tallestColumn + "em");
}

function slideshow() {

    // retrieve array of slide info
    dbAJAX("/scripts/yoddle/ui.aspx?", "action=getSlides", ajaxHandler);

    // initiate timer object
    t = new Timer();
    t.Interval = 50;
    t.Tick = slideshowFade;
    t.Start();
}

function slideshowFade() {

    // after initial loop, lengthen wait
    if (t.Interval < 1000) {t.Stop(); t.Interval = 5000;t.Start(); }

    // fade div1 & reload & show
    $("div.slide#ss1").fadeOut(2500, function() {
        $("div.slide#ss1").html($("div.slide#ss2 div.bgImage").clone());
        $("div.slide#ss1 div.bgImage").css('background', $("div.slide#ss2 div.bgImage").css('background'));
        $("div.slide#ss1").show();
    });

    // reload div2
    var nextSlide = SlideArray[SlideArrayCount].split("^");
    var path = 'url(' + nextSlide[3] + ') no-repeat scroll 50% 50% #385902';    
    $("div.slide#ss2 div.bgImage").css('background', path);
    $("div.slide#ss2 h4").html(nextSlide[1] + "<br><a href='" + nextSlide[2] + "'>Client information »</a>")
    
    // increment counter
    SlideArrayCount++;
    if (SlideArrayCount == (SlideArray.length - 1)) { SlideArrayCount = 0; }
};

//****************** Merged from /styles/property/general.js ******************//

function refreshResults(r) {
    var ra = r.split("||");

    if (ra[0] == "OK") {
        $("#lit_searchResults").html(ra[1]);
        $("#pagination").html(ra[2]);
        $("#searchResults").show();
    }
}
function pageResults(r) {
    var ra = r.split("||");

    if (ra[0] == "OK") {
        $("#lit_searchResults").html(ra[1]);
        $("#pagination").html(ra[2]);
        $("#searchResults").show();
    }
}
function clearForm(form) {

    $(':input', form).each(function() {
        var type = this.type;
        var tag = this.tagName.toLowerCase();
        // normalize case       
        // it's ok to reset the value  attr of text inputs,      
        // password inputs, and  textareas       
        if (type == 'text' || type == 'password' || tag == 'textarea') this.value = "";
        // checkboxes and radios need  to have their checked state cleared       
        // but should *not* have  their 'value' changed       
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        // select elements need to  have their 'selectedIndex' property set to -1       
        // (this works for both  single and multiple select elements)       
        else if (tag == 'select')
            this.selectedIndex = -1;

    })
}

