﻿/*/***************************************************************************************************************************
/// <name>     TrueBridge - Common Java Script Library</name>
/// <summary>  This JavaScript provides common functions for the menu and other dynamic navigation functionality.</summary>
/// <history>
///            Konrad Kyc [2009 © Vantagesoft.ca] - 2009-10-15 - Created.
/// </history>
/// <notes>
/// </notes>
///***************************************************************************************************************************/

var homePovImages = new Array(6);
var isIphone = navigator.userAgent.toLowerCase().indexOf('iphone') != -1;

// When the Document Loads, call the initialize on load function
$(document).ready(function() {
    InitializeOnLoad();
});

///**********************************************************************************
/// <name>    InitializeOnLoad </name>
/// <summary> Initialize function that loads on PageLoad.</summary>
///**********************************************************************************
function InitializeOnLoad() 
{
    // Register a click for the items that have a sub menu
    $("ul.SubMenu").parent().click(function () {
        // Expand/Collapse the sub-menu
        var subMenuItems = $("ul.SubMenu");
        var selectedMenuItem = $("ul.SubMenu", this);

        // collapse all the other items (but the currently chosen one)
        for (var i = 0; i < subMenuItems.length; i++) 
        {
            if (selectedMenuItem[0] != subMenuItems[i])
                $(subMenuItems[i]).slideUp("normal");
        }

        $("ul.SubMenu", this).slideToggle("normal");
    });

    // When the E-mail This Page is clicked, show the Send-To box
    $("#emailThisPage").click(function () {
        if ($(".EmailThisPagePopup").is(':visible')) {
            //$(".EmailThisPagePopup").animate({ width: "0px", height: "0px" }, 600, function () { $(this).hide(); });
            $(".EmailThisPagePopup").fadeOut("slow");
        }
        else {
            //$(".EmailThisPagePopup").animate({ width: "155px", height: "60px" }, 600, function () { });
            $(".EmailThisPagePopup").fadeIn("slow");
        }

        return false;
    });

    // On Email Page link click, e-mail this page to the specified user (using an AJAX call)
    $("#emailPageLink").click(function () {
        var checkEmailFilter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
        var emailFromAddress = $("#emailPageFromAddress").val();
        var emailToAddress = $("#emailPageToAddress").val();

        // Make sure that the E-mail From address is ok.
        if (!checkEmailFilter.test(emailFromAddress)) {
            alert("Please specify a valid e-mail address in the 'Email Page From' field.");
        }
        // Make sure that the E-mail To address is ok.
        else if (!checkEmailFilter.test(emailToAddress)) {
            alert("Please specify a valid e-mail address in the 'Email Page To' field.");
        }
        else {
            var url = location.href;

            // Determine whether to add the ? or the & at the end of the URL
            if (url.indexOf("?") > 0)
                url += "&";
            else
                url += "?";

            // Add the Email Query string values
            url += "CallbackAction=SendEmail&EmailTo=" + emailToAddress + "&EmailFrom=" + emailFromAddress + "&Message=" + escape($("#emailPageMessage").val());

            // Show the "Sending in-progress" info
            $("#emailForm").fadeOut("slow", function () { $(".EmailSendingStatus").fadeIn("slow"); });

            $.ajax({
                url: url,
                success: function (data) {
                    // Hide the Email page box.
                    $(".EmailThisPagePopup").fadeOut("slow", function () {
                        $("#emailForm").show();
                        $(".EmailSendingStatus").hide();
                        $("#emailPageFromAddress").val("");
                        $("#emailPageToAddress").val("");
                        $("#emailPageMessage").val("");

                        // If the response Data is not OK, then display the error message
                        if (data != "OK")
                            alert(data);
                    });
                }
            });
        }

        return false;
    });
    
    hdsfWhatIsShown = false;

    // Stop propagation of the click event in the parent when sub menu items are clicked (i.e. to prevent the menu from sliding up/down).
    $("ul.SubMenu li").click(function(event) { event.stopPropagation(); });
    
    PageInitOnLoad();
}

function PageInitOnLoad(){} // Virtual Function
function PageInit(){}       // Virtual Function
function PreparePrint() { } // Virtual Function

///**********************************************************************************
/// <name>    PrintPage </name>
/// <summary> Prints the current page.</summary>
///**********************************************************************************
function PrintPage() {
    // Prepare the page for printing
    PreparePrint();
    window.print();
}

///**********************************************************************************
/// <name>    ToggleHomePOVItem </name>
/// <summary> Expands/Collapses the Home Insight/Access/Partnership sections.</summary>
///**********************************************************************************
function ToggleHomePOVItem(item) {
    var itemToExpand = $(item).parent().attr('class'); //i.e. Insight, Access or Partnership
    var isExpanded = $(item).hasClass("HomePOVMenuItem-" + itemToExpand + "-on");

    if (!isExpanded) {
        // Find the expanded item
        var expandedItemParent = $(".HomePOVContent-on").parent();
        var expandedParentClass = $(expandedItemParent).attr('class'); //i.e. Insight, Access or Partnership
        var expandedItem = $(".HomePOVMenu", expandedItemParent);


        // Collapse the alread expanded item
        $(expandedItem).removeClass("HomePOVMenuItem-" + expandedParentClass + "-on").addClass("HomePOVMenuItem-" + expandedParentClass);
        $(".HomePOVContent-on", expandedItemParent).slideUp("slow", function () { $(this).removeClass("HomePOVContent-on") });

        // Expand the selected item
        var parentContext = $(item).parent();
        var detailsSection = $(".HomePOVContent", parentContext);
        $(detailsSection).slideDown("slow", function () { $(this).addClass("HomePOVContent-on"); });
        $(item).removeClass("HomePOVMenuItem-" + itemToExpand).addClass("HomePOVMenuItem-" + itemToExpand + "-on");

        // Change the POV image
        var randomNumber = 1;

        // For now do not provide a second image for partnership
        if (itemToExpand != 'Partnership')
            randomNumber = RandomInRange(1, 2);

        var imagePath = 'Images/Home/POV-' + itemToExpand + '-0' + randomNumber + '.jpg';

        $("#imgPOV").fadeTo("slow", 0.0, function() {
            $(this).attr('src', imagePath);
            $(this).fadeTo("slow", 1.0);
        });
    }
}

///**********************************************************************************
/// <name>    PreloadHomeImages </name>
/// <summary> Pre-loads the home page images, including featured company logos.</summary>
///**********************************************************************************
function PreloadHomeImages() {
    homePovImages[0] = new Image(481, 328);
    homePovImages[1] = new Image(481, 328);
    homePovImages[2] = new Image(481, 328);
    homePovImages[3] = new Image(481, 328);
    homePovImages[4] = new Image(481, 328);
    homePovImages[5] = new Image(481, 328);

    homePovImages[0].src = "Images/Home/POV-Insight-01.jpg";
    homePovImages[1].src = "Images/Home/POV-Insight-02.jpg";
    homePovImages[2].src = "Images/Home/POV-Access-01.jpg";
    homePovImages[3].src = "Images/Home/POV-Access-02.jpg";
    homePovImages[4].src = "Images/Home/POV-Partnership-01.jpg";
    homePovImages[5].src = "Images/Home/POV-Partnership-02.jpg";

    // Load the featured logos
    var featuredLogos = new Array(projectData.featuredCompanies.length);
    
    for (i = 0; i < projectData.featuredCompanies.length; i++) {
        featuredLogos[i] = new Image(481, 328);
        featuredLogos[i].src = projectData.featuredCompanies[i].imagePath;
    }
}

///**********************************************************************************
/// <name>    ChangeFeaturedCompanyLogo </name>
/// <summary> Changes the featured company logo on the home page in the given direction ("Forward"
///           or "Backwards"). This will fade-out the old and fade-in the new image.</summary>
///**********************************************************************************
function ChangeFeaturedCompanyLogo(direction) {
    if (direction == "Backwards") {
        if (projectData.selectedItemPosition.featuredCompany > 0)
            projectData.selectedItemPosition.featuredCompany--;
        else
            projectData.selectedItemPosition.featuredCompany = projectData.featuredCompanies.length - 1;
    }
    else {
        if (projectData.selectedItemPosition.featuredCompany < projectData.featuredCompanies.length - 1)
            projectData.selectedItemPosition.featuredCompany++;
        else
            projectData.selectedItemPosition.featuredCompany = 0;
    }

    var currentPosition = projectData.selectedItemPosition.featuredCompany;
    var companyName = projectData.featuredCompanies[currentPosition].name;
    var logoPath = projectData.featuredCompanies[currentPosition].imagePath;


    $("#imgFeaturedCompany").fadeOut("normal", function() {
        var hrefLink = 'Strategy.aspx#Company' + (currentPosition + 1);
        $("#hrefFeaturedCompanyLogo").attr('href', hrefLink);
        $("#hrefFeaturedCompany").attr('href', hrefLink);
        $(this).attr('src', logoPath).attr('alt', companyName).fadeIn("normal");
    });

}

///**********************************************************************************
/// <name>    AnimateFeaturedCompanies </name>
/// <summary> Animates the featured company logos on the home page.</summary>
///**********************************************************************************
function AnimateFeaturedCompanies() {
    if (projectData.featuredCompanyPlay) {
        ChangeFeaturedCompanyLogo("Forward");
        setTimeout('AnimateFeaturedCompanies()', 3000);
    }
}

///**********************************************************************************
/// <name>    PlayPauseAnimation </name>
/// <summary> Handles the Play/Pause animation event, which controls the featured 
///           company animation.</summary>
///**********************************************************************************
function PlayPauseAnimation(element) {
    if (projectData.featuredCompanyPlay) {
        projectData.featuredCompanyPlay = false;
        $(element).attr('src', 'Images/Global-NextButton.gif');
        $(element).attr('alt', 'Play Animation');
    }
    else {
        projectData.featuredCompanyPlay = true;
        AnimateFeaturedCompanies();
        $(element).attr('src', 'Images/Global-DividerButton.gif');
        $(element).attr('alt', 'Pause Animation');
    }
}

///**********************************************************************************
/// <name>    ChangeReasearchLinks </name>
/// <summary> Changes the Research links on the home page.</summary>
///**********************************************************************************
function ChangeReasearchLinks() {
    $("#divResearchText").fadeOut("normal", function() { $(this).html(projectData.researchData[0].text).fadeIn("normal"); });
    $("#divResearchMoreLink").fadeOut("normal", function() {
        var newHtml = '<div class="LeftItem"><a id="hrefDownloadLink" target="_blank" href="' + projectData.researchData[0].downloadLink + '" class="MoreLink"><span id="spanResearchLinkTitle">' + projectData.researchData[0].linkTitle + '</span> <img src="Images/Global-GreenArrowAngleDown.gif" alt=""></a></div><div class="RightItem"><img src="Images/Global-PreviousButton.gif" alt="Previous" class="VPreviousResearch" />&nbsp;&nbsp;&nbsp;<img src="Images/Global-NextButton.gif" alt="Next" class="VNextResearch" /></div><div style="clear: both;" class="ClearFF"></div>';

        $(this).html(newHtml).fadeIn("normal", function() {
            $(".VNextResearch").click(function() {

                if (projectData.selectedItemPosition.researchData < projectData.researchData.length - 1)
                    projectData.selectedItemPosition.researchData++;
                else
                    projectData.selectedItemPosition.researchData = 0;

                var currentPosition = projectData.selectedItemPosition.researchData;
                var text = projectData.researchData[currentPosition].text;
                var linkTitle = projectData.researchData[currentPosition].linkTitle;
                var downloadLink = projectData.researchData[currentPosition].downloadLink;

                $("#divResearchText").fadeOut("normal", function() {
                    $(this).html(text).fadeIn("normal");
                });

                $("#hrefDownloadLink").fadeOut("normal", function() {
                    $("#spanResearchLinkTitle").html(linkTitle);
                    $(this).attr("href", downloadLink).fadeIn("normal");
                });
            });

            $(".VPreviousResearch").click(function() {
                if (projectData.selectedItemPosition.researchData > 0)
                    projectData.selectedItemPosition.researchData--;
                else
                    projectData.selectedItemPosition.researchData = projectData.researchData.length - 1;

                var currentPosition = projectData.selectedItemPosition.researchData;
                var text = projectData.researchData[currentPosition].text;
                var linkTitle = projectData.researchData[currentPosition].linkTitle;
                var downloadLink = projectData.researchData[currentPosition].downloadLink;

                $("#divResearchText").fadeOut("normal", function() {
                    $(this).html(text).fadeIn("normal");
                });

                $("#hrefDownloadLink").fadeOut("normal", function() {
                    $("#spanResearchLinkTitle").html(linkTitle);
                    $(this).attr("href", downloadLink).fadeIn("normal");
                });
            });
        });
    });

    return false;
}

///**********************************************************************************
/// <name>    ToggleAboutSection </name>
/// <summary> Toggles the sections (i.e. Access/Insight/Partnership) in the About page.</summary>
///**********************************************************************************
function ToggleAboutSection(item) {
    var itemToExpand = $(item).parent().attr('class'); //i.e. Insight, Access or Partnership
    var isExpanded = $(item).hasClass("AboutSubSectionItem-" + itemToExpand + "-on");

    // Find the expanded item
    var expandedItemParent = $(".AboutSubSectionContent-on").parent();
    var expandedParentClass = $(expandedItemParent).attr('class'); //i.e. Insight, Access or Partnership
    var expandedItem = $(".AboutSubSection", expandedItemParent);

    // Collapse the already expanded item
    $(expandedItem).removeClass("AboutSubSectionItem-" + expandedParentClass + "-on").addClass("AboutSubSectionItem-" + expandedParentClass);
    $(".AboutSubSectionContent-on", expandedItemParent).removeClass("AboutSubSectionContent-on").slideUp("slow");

    if (!isExpanded) {
        // Expand the selected item
        var parentContext = $(item).parent();
        var detailsSection = $(".AboutSubSectionContent", parentContext);
        $(detailsSection).slideDown("slow", function() { $(this).addClass("AboutSubSectionContent-on"); });
        $(item).removeClass("AboutSubSectionItem-" + itemToExpand).addClass("AboutSubSectionItem-" + itemToExpand + "-on");
    }
}

///**********************************************************************************
/// <name>    ToggleLeftTeamMatrixItem </name>
/// <summary> Toggles the view of the Team image matrix (left facing images) on a 
///           mouse-over. The selected image is faded-in.</summary>
///**********************************************************************************
function ToggleLeftTeamMatrixItem(item) {
    ToggleTeamMatrixItem(item, true);
}

///**********************************************************************************
/// <name>    ToggleRightTeamMatrixItem </name>
/// <summary> Toggles the view of the Team image matrix (right facing images) on a 
///           mouse-over. The selected image is faded-in.</summary>
///**********************************************************************************
function ToggleRightTeamMatrixItem(item) {
    ToggleTeamMatrixItem(item, false);
}

///**********************************************************************************
/// <name>    ToggleTeamMatrixItem </name>
/// <summary> Toggles the view of the Team image matrix  on a 
///           mouse-over. The selected image is faded-in.</summary>
///**********************************************************************************
function ToggleTeamMatrixItem(item, isLeftFacing) {
    if (isIphone) {
        ToggleTeamMatrixItemIPhone(item, isLeftFacing);
    }
    else {
        //get the position of the placeholder element 
        var pos = $(item).offset();
        var width = $(item).width();

        var itemId = $(item).attr("id");
        var itemState = GetTeamMatrixElementState(itemId);

        if (!itemState) {
            //show the menu directly over the placeholder
            var onImage = $(".TeamMatrixOnImage", item);
            SetTeamMatrixElementState(itemId, true);

            var leftPosition = pos.left;

            // Calculate the position based on which side the image should be facing
            if (!isLeftFacing)
                leftPosition = ((pos.left + width) - 407);

            $(onImage).css({ "left": leftPosition + "px", "top": pos.top + "px" });

            $(onImage).fadeIn("slow");
            $(onImage).mouseout(function () {
                $(onImage).fadeOut("slow", function () {
                    SetTeamMatrixElementState(itemId, false);
                    $(onImage).css({ "display": "", "left": "", "top": ""});
                });
            });
        }
    }
}

///**********************************************************************************
/// <name>    ToggleTeamMatrixItemIPhone </name>
/// <summary> Toggles the view of the Team image matrix  on a 
///           mouse-over. The selected image is faded-in.</summary>
///**********************************************************************************
function ToggleTeamMatrixItemIPhone(item, isLeftFacing) {
    //get the position of the placeholder element
    var pos = $(item).offset();
    var width = $(item).width();

    var itemId = $(item).attr("id");
    var itemState = GetTeamMatrixElementState(itemId);

    if (!itemState) {
        //show the menu directly over the placeholder
        var onImage = $(".TeamMatrixOnImage", item);
        SetTeamMatrixElementState(itemId, true);

        var leftPosition = pos.left;

        // Calculate the position based on which side the image should be facing
        if (!isLeftFacing)
            leftPosition = ((pos.left + width) - 407);

        $(onImage).css({ "left": leftPosition + "px", "top": pos.top + "px" });

        // Hide any matrix items that may be showing.
        HideTeamMatrixItems();

        $(onImage).fadeIn("slow", function() { $(this).addClass("TeamMatrixOnImageEnabled"); });
        $(onImage).mouseout(function() {
            if ($(onImage).hasClass("TeamMatrixOnImageEnabled")) {
                $(onImage).removeClass("TeamMatrixOnImageEnabled");
                $(onImage).fadeOut("slow", function() {
                    $(onImage).css({ "left": "-1000px" });
                    SetTeamMatrixElementState(itemId, false);
                });
            }
        });
    }
}


///**********************************************************************************
/// <name>    HideTeamMatrixItems </name>
/// <summary> Hides any Team Matrix Items that may be showing</summary>
///**********************************************************************************
function HideTeamMatrixItems() {
    $(".TeamMatrixOnImageEnabled").each(function(index) {
        var itemId = $(this).parent().attr("id");
        $(this).removeClass("TeamMatrixOnImageEnabled");
        $(this).fadeOut("slow", function() {
            $(this).css({ "left": "-1000px" });
            SetTeamMatrixElementState(itemId, false);
        });
    });
}

///**********************************************************************************
/// <name>    GetTeamMatrixElementState </name>
/// <summary> Gets the state for a team matrix element (to solve concurrency issue).</summary>
///**********************************************************************************
function GetTeamMatrixElementState(id) {
    switch (id) {
        case "divMatrixEdwin":
            return projectData.teamMatrixItemState.edwin;
            break;
        case "divMatrixMel":
            return projectData.teamMatrixItemState.mel;
            break;
        case "divMatrixRob":
            return projectData.teamMatrixItemState.rob;
            break;
        case "divMatrixJosh":
            return projectData.teamMatrixItemState.josh;
            break;
        case "divMatrixStuart":
            return projectData.teamMatrixItemState.stuart;
            break;
        case "divMatrixAlanna":
            return projectData.teamMatrixItemState.alanna;
            break;
        case "divMatrixLyndsay":
            return projectData.teamMatrixItemState.lyndsay;
            break;
        case "divMatrixMac":
            return projectData.teamMatrixItemState.mac;
            break;
    }
}

///**********************************************************************************
/// <name>    SetTeamMatrixElementState </name>
/// <summary> Sets the state for a team matrix element (to solve concurrency issue).</summary>
///**********************************************************************************
function SetTeamMatrixElementState(id, state) {
    switch (id) {
        case "divMatrixEdwin":
            projectData.teamMatrixItemState.edwin = state;
            break;
        case "divMatrixMel":
            projectData.teamMatrixItemState.mel = state;
            break;
        case "divMatrixRob":
            projectData.teamMatrixItemState.rob = state;
            break;
        case "divMatrixJosh":
            projectData.teamMatrixItemState.josh = state;
            break;
        case "divMatrixStuart":
            projectData.teamMatrixItemState.stuart = state;
            break;
        case "divMatrixAlanna":
            projectData.teamMatrixItemState.alanna = state;
            break;
        case "divMatrixLyndsay":
            projectData.teamMatrixItemState.lyndsay = state;
            break;
        case "divMatrixMac":
            projectData.teamMatrixItemState.mac = state;
            break;
    }
}

///**********************************************************************************
/// <name>    ExpandSelectedFeaturedCompany </name>
/// <summary> Expands a given featured company section on the Strategy page.</summary>
///**********************************************************************************
function ExpandSelectedFeaturedCompany(selectedCompany) {
    var selectedCompanyElement = $("#divCompany" + selectedCompany);
    var scrollLocation = $("#divCompanyLogo" + selectedCompany).offset().top - 20;

    // Scroll To the selected item
    $.scrollTo(scrollLocation, 800);
    $(selectedCompanyElement).slideDown("slow");
    $(".StrategyFCLogo", selectedCompanyElement.parent()).addClass("StrategyFCLogo-on");
}

///**********************************************************************************
/// <name>    ExpandSelectedFeaturedCompany </name>
/// <summary> Toggles the display of the featured company on the Strategy page.</summary>
///**********************************************************************************
function ToggleFeaturedCompanies(item) {
    var expanded = $(item).hasClass("StrategyFCLogo-on");

    // Collapse other items
    var expandedItem = $(".StrategyFCLogo-on");
    $(expandedItem).removeClass("StrategyFCLogo-on");
    $(".StrategyFCDetailsSection", expandedItem.parent()).slideUp("slow");

    if (!expanded) {
        // Expand the selected item
        var parentContext = $(item).parent();
        var detailsSection = $(".StrategyFCDetailsSection", parentContext);
        $(detailsSection).slideDown("slow");
        $(item).addClass("StrategyFCLogo-on");
    }
}

///**********************************************************************************
/// <name>    InitializeMap </name>
/// <summary> Initializes Google Map on the contact page.</summary>
///**********************************************************************************
function InitializeMap() 
{
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(35.908197, -79.005000), 14);
        map.setUIToDefault();
        
        // Add the Company Location
        var point = new GLatLng(35.907162, -79.022855);
        var marker = new GMarker(point);
        map.addOverlay(marker);

        var html = "<table><tr><td><img src='Images/Global-LogoSmall.gif' alt='' /></td><td style='font-family: Georgia; padding-left: 10px;'><strong>Directions</strong></td></tr><tr><td></td><td style='padding-left: 10px;  padding-top: 10px;'><span style='color: #666666; font-weight: bold; font-size: 12px; line-height: 16px; font-family: Arial, Verdana;'>From:&nbsp;&nbsp;</span><input id='txtDirectionsFrom' onkeyup='javascript:GetDirections(true, event);' size='20'/></td></tr><tr><td></td><td style='padding-left: 10px; padding-top: 10px;'><a onclick='javascript:GetDirections(false, event); return false;' href='http://maps.google.com/maps?f=d&hl=en&geocode=&daddr=1350+Environ+Way,+Chapel+Hill,+NC+27517' target='_blank' class='MoreLink'>Get Directions <img src='Images/Global-GreenArrow.gif' alt='' /></a></td></tr></table>";
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(html);
        });
        
        // Automatically open the marker
        marker.openInfoWindowHtml(html);
    }
}

///**********************************************************************************
/// <name>    RandomInRange </name>
/// <summary> Generates a random number in the given range.</summary>
///**********************************************************************************
function RandomInRange(minVal, maxVal) {
    var randVal = minVal + (Math.random() * (maxVal - minVal));
    return Math.round(randVal);
}

///**********************************************************************************
/// <name>    GetDirections </name>
/// <summary> Opens Google Maps with the directions to TrueBridge Office, from the
///           specified location.</summary>
///**********************************************************************************
function GetDirections(isKeyPress, event) {
    var showDirections = false;

    if (isKeyPress) {
        var pressedKey;

        if (window.Event == null) {   // ie
            pressedKey = event.which;
        }
        else  // mozilla
        {
            pressedKey = event.keyCode;
        }

        // When 'Enter' is pressed from the textbox, show the directions.
        if (pressedKey == 13) {
            showDirections = true;  // Enter
        }
    }
    else
        showDirections = true;

    if (showDirections) {
        var directionsFrom = $("#txtDirectionsFrom").val();
        var directionsTo = '&daddr=1350+Environ+Way,+Chapel+Hill,+NC+27517';

        // Open the directions to HDSF in a new window
        OpenNewWindow('http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=' + directionsFrom + directionsTo, null, null);
    }
}

///**********************************************************************************
/// <name>    OpenNewWindow </name>
/// <summary> Opens a new window with the specified parameters.</summary>
///**********************************************************************************
function OpenNewWindow(url, width, height) 
{
    OpenNewWindow(url, width, height, false);
}

///**********************************************************************************
/// <name>    OpenNewWindow </name>
/// <summary> Opens a new window with the specified parameters.</summary>
///**********************************************************************************
function OpenNewWindow(url, width, height, scrollbars) 
{
    if(width != null && width > 0 && height != null && height > 0)
    {
        if(scrollbars)
            window.open(url,'','height=' + height + ',width=' + width + ',scrollbars=yes,status=no,menubar=no,toolbar=no,location=no');
        else
            window.open(url,'','height=' + height + ',width=' + width + ',status=no,menubar=no,toolbar=no,location=no');
    }
    else
        window.open(url,'','');      
}

///**********************************************************************************
/// <name>    FindPosition </name>
/// <summary> Finds the position (returns an [x,y] array) of the given element.</summary>
///**********************************************************************************
function FindPosition(element) 
{
	var curLeft = curTop = 0;
	
	if (element.offsetParent) 
	{
	    do {
		    curLeft += element.offsetLeft;
		    curTop += element.offsetTop;
        } while (element = element.offsetParent);
    }
    return [curLeft, curTop];
}


///**********************************************************************************
/// <name>    BrowserSupportsModals </name>
/// <summary> Determines whether the broswer can support the imitated modal overlays.
///           if the browser does not support modals, then a regular pop-up will be
///           open.</summary>
///**********************************************************************************
function BrowserSupportsModals()
{
    try
    {
        if(BrowserDetect.browser == "Explorer" && BrowserDetect.majorVersion < 6)
            return false;
        else if(BrowserDetect.browser == "Firefox" && BrowserDetect.majorVersion < 1)
            return false; 
        else if(BrowserDetect.browser == "Netscape" && BrowserDetect.majorVersion < 6)
            return false;
        else if(BrowserDetect.browser == "Mozilla" && BrowserDetect.majorVersion < 2)
            return false;        
        else if(BrowserDetect.browser == "Safari" && BrowserDetect.majorVersion < 3)
            return false;
        else if(BrowserDetect.browser == "Opera" && BrowserDetect.majorVersion < 8)
            return false;                               
        else
        {
            // For anything else, return true by default.
            return true;
        }
    }
    catch(e)
    {
        // return false when error occurs
        return false;
    }
}

///**********************************************************************************
/// <name>    BrowserSupportsJQuery </name>
/// <summary> Determines whether the broswer can support the JQuery functionality.
///           if the browser does not support JQuery, then features such as animtaion
///           will not be initiated.</summary>
///**********************************************************************************
function BrowserSupportsJQuery()
{
    try
    {
        if(BrowserDetect.browser == "Explorer" && BrowserDetect.majorVersion < 6)
            return false;
        else if(BrowserDetect.browser == "Firefox" && BrowserDetect.majorVersion < 1)
            return false; 
        else if(BrowserDetect.browser == "Netscape" && BrowserDetect.majorVersion < 6)
            return false;
        else if(BrowserDetect.browser == "Mozilla" && BrowserDetect.majorVersion < 2)
            return false;        
        else if(BrowserDetect.browser == "Safari" && BrowserDetect.majorVersion < 3)
            return false;
        else if(BrowserDetect.browser == "Opera" && BrowserDetect.majorVersion < 8)
            return false;                               
        else
        {
            // For anything else, return true by default.
            return true;
        }
    }
    catch(e)
    {
        // return false when error occurs
        return false;
    }
}

///**********************************************************************************
/// <name>    GetElementObject </name>
/// <summary> Gets an element object based on the given ID (depending on the browser).</summary>
///**********************************************************************************
function GetElementObjectById(elementName)
{
    var elementObject;
    
	if (ns4) 
	{
		elementObject = GetObjNN4(document, elementName);
	} 
	else 
	{
		if(document.getElementById) 
		{
			elementObject = document.getElementById(elementName);
		} 
		else if (document.all)
		{
			elementObject = document.all[elementName];
		}
    }
    return elementObject;
}

///**********************************************************************************
/// <name>    GetElementHeight </name>
/// <summary> Gets the given element's height.</summary>
///**********************************************************************************
function GetElementHeight(element) 
{
	if (ns4) 
	{
		return element.clip.height;
	} 
	else 
	{
	    var elementHeight = 0;
	    
		if (op5) 
		{ 
			elementHeight = element.style.pixelHeight;
		} 
		else 
		{
			elementHeight = element.offsetHeight;
		}
		
		return elementHeight;
	} 
}

///**********************************************************************************
/// <name>    GetElementWidth </name>
/// <summary> Gets the given element's width.</summary>
///**********************************************************************************
function GetElementWidth(element) 
{
	if (ns4) 
	{
		return element.clip.width;
	} 
	else 
	{
        var elementWidth = 0;
        
        if (op5) 
        {
	        elementWidth = element.style.pixelWidth;
        } 
        else 
        {
	        elementWidth = element.offsetWidth;
        }

        return elementWidth;
	}
}

///**********************************************************************************
/// <name>    GetObjNN4 </name>
/// <summary> Gets the element for Netscape 4.</summary>
///**********************************************************************************
function GetObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}

///**********************************************************************************
/// <name>    Browser Detection </name>
/// <summary> Detects which browser the user is using.</summary>
/// <credit>  http://www.quirksmode.org/js/detect.html</credit>
///**********************************************************************************
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.majorVersion = (this.version.toString()).split(".")[0];
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		
		var extractedVersion = dataString.substring(index+this.versionSearchString.length+1);
		
		try 
		{
		    var cleansedVersion = extractedVersion.match(/^\d*(\.\d+)?/)[0];		    
		    return parseFloat(cleansedVersion);
        }
		catch(e) {return parseFloat(extractedVersion);}
		
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{ 	string: navigator.userAgent,
			subString: "Chrome",
			versionSearch: "Chrome",
			identity: "Chrome"
		},		
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();

var ie = document.all;
var ns4 = document.layers;
var ns6 = document.getElementById && !document.all;
var op5 = BrowserDetect.browser == "Opera" && BrowserDetect.majorVersion == 5;
