// hess.js common javascript utils Nov. 6/08
// NOTE: some code depends on jquery/jquery ui

var rotatingCounter = 2;
var myInterval;

function Navigate(link){
    
    $("#areaStage").animate({ height: '110px' }, 1000, null, function() {
        window.location.href = link.href;
    });

}
function HideEmptyPTags() {
    // mark all empty elements with a CSS class so that they can be hidden because empty <p> tags are causing layout issues.
    $("p:empty").addClass("emptyElement");
}
function PreLoadImages() {
    $.preloadImages("/_layouts/images/hess/navigation/",
        "careers.jpg",
        "careers_active.gif",
        "careers_over.gif",
        "company.jpg",
        "company_active.gif",
        "company_over.gif",
        "customers.jpg",
        "customers_active.gif",
        "customers_over.gif",
        "investors.jpg",
        "investors_active.gif",
        "investors_over.gif",      
        "operations.jpg",
        "operations_active.gif",
        "operations_over.gif",  
        "sustainability.jpg",
        "sustainability_active.gif",
        "sustainability_over.gif",           
        "technology.jpg",
        "technology_active.gif",
        "technology_over.gif",   
        "values.jpg",
        "values_active.gif",
        "values_over.gif"                                     
        );
}
function ResizeImageCaptions() {
    // resize all image captions so that they are the correct widths.
    $('.wpImageCaption').each(function() {
        
        var caption = $(this);
        var imgWidth = caption.prev().width();
        
        if (imgWidth == null || imgWidth < 1)
            imgWidth = 320;     
        
        caption.width(imgWidth);
        
    });
}
function Page() {
    page = this;
    this.stageOpen = false; // state of main stage area
    this.currentRollover = null;
    this.navMoving = null;  // delay timer, handles bug going from nav parent to rollover
    this.currentNav = null;
    
    ResizeImageCaptions();             
    
    HideEmptyPTags();        
    
    PreLoadImages();
            
    this.LoadMasterPage = function() {
        
        var pathname = window.location.pathname;
        var re = new RegExp("\/reports\/sustainability\/", "i");
        if (pathname.match(re))
        {
            $(".breadcrumb").children("a").hide();
            $(".breadcrumb").children("img").hide();
            $("#areaGlobalNav").hide();
        }
                
        // flash or static?    
        if(/http:\/\/([^/]*)\/default.aspx/i.exec(location.href)) // regex, if '/default.aspx'...
        {
            hasFlash = isFlashAvailable();
            if (!hasFlash)
            {
                $("#NoFlash").show();
                $("#areaStage").hide();
                $("#exploreMap").hide();
                $("#seeouroperations").hide();
            }
            ShowVideo(hasFlash);
        }
        else
        { 
            $("#areaStage").height('110px');
            $("#homepageStatic").show();
            LoadBanner();            
        }

        page.WireUpNav();
        page.WireUpSearch();

        // wire up accordions if present
        page.WireUpAccordions();

        // wire up searchBar if present...
        page.WireupSearchBar();

        // run page load function if present on page...
        if (typeof (dom_ready) != 'undefined') dom_ready();
    },

    this.WireUpAccordions = function() {

        $('.accordionParent').click(function() {
            if ($(this).hasClass('wpTitleOn')) {
                // already open, close current item    
                $(this).removeClass('wpTitleOn').next('.accordionChild').slideUp();
            }
            else {
                // close previous if exists, open new
                $('.wpTitleOn').removeClass('wpTitleOn').next('.accordionChild').slideUp();
                $(this).addClass('wpTitleOn').next('.accordionChild').slideDown();    // open
            }
        });
    },


    this.ShowPreview = function() {
        // hide any elements where class contains 'admin'
        $('.admin').css('display', 'none');
    },

    this.LoadHomepage = function() {
        // wire up carousel...
        
        
        myInterval = setInterval("page.setUpCarouselRotator()", 6000);      
          
        $('div.itemNav').attr("animating", "false");
        currentNewsItem = 1;
        $('#newsNavLeft').click(function(e) {
            clearInterval(myInterval);
            if (currentNewsItem > 1) { page.CarouselClick(currentNewsItem - 1) }
        });
        $('#newsNavRight').click(function(e) {
            clearInterval(myInterval);
            if (currentNewsItem < 3) { page.CarouselClick(currentNewsItem + 1) }
        });
        
        
    },
    
    this.setUpCarouselRotator = function() {
        
        if(rotatingCounter > 3)
            rotatingCounter = 1;
            
        rotatingCounter++;
                
        page.CarouselClick(rotatingCounter - 1);

    },

    this.CarouselClick = function(i) {
        var dots = $('div.itemNav');        
        if (dots.attr("animating") == "true")
            return;
        dots.attr("animating", "true");
        var dot = $('#pager' + currentNewsItem);
        dot.attr('src', '/_layouts/images/hess/news_dot_off.gif');
        $('#newsItem' + currentNewsItem).fadeOut(function(e) {
            currentNewsItem = i;
            $('#newsItem' + currentNewsItem).fadeIn(150);
            $('#pager' + currentNewsItem).attr('src', '/_layouts/images/hess/news_dot_on.gif');
            dots.attr("animating", "false");
        });        
    },

    this.WireUpNav = function() {
        $('.navItem').hover(page.NavOnHov, page.NavOffHov); 

        // set active nav item
        path = location.pathname.split('/');       

        if (path.length > 2) {
            var itemid = "#nav" + path[1];
            if ($(itemid).length > 0)
            {
                var p = $(itemid).parent();
                $(p).addClass("active");
                //$(itemid).addClass("navactive");
                //alert($(itemid).css("background-image"))
            }
        }

    },

    this.NavOnHov = function() {
        $(this).children("a").addClass('navHover');

        if ($('.HasSubNav')) {
            if ($("#" + this.id).parent().hasClass('btmNav'))
                e = $("#" + this.id + " .rollout")[0];
            else
                e = $("#" + this.id + " .rollout")[1];
                
            $(e).css("display","block");
        }
    },

    this.NavOffHov = function() {
        $(this).children("a").removeClass('navHover');  // clear hover

        e = $("#" + this.id + " .rollout:visible")

        $(e).css("display","none");
    },

    this.WireUpSearch = function() {
        // wire up search...
        $('#searchField').focus(function() {
            if ($('#searchField').val() == "Search")
                $('#searchField').val('');
        });

        setAutoComplete("searchField", "results", "");

    },

    this.IsNotEnterKey = function(e) {
        var characterCode;
        if (e && e.which) { e = e; characterCode = e.which } //character code is contained in NN4's which property
        else { e = event; characterCode = e.keyCode } //character code is contained in IE's keyCode property

        searchText = $('#txtSearch').val(); // search text typed in so far...

        // check for enter key in search box, draw character if not
        if (characterCode == 13)
            return false
        else
            return true;

    },

    this.WireupSearchBar = function() {

        // is searchbar present?
        if ($('.searchBar')) {

            // wire up icon
            $('.searchBar_icon').click(function(n) {
                page.submitSearchBar();
                return false;
            });

            // wire up search field
            $('#searchTxt').focus(function() {
                if ($('#searchTxt').val() == "search...")
                    $('#searchTxt').val('');
            });

            $('#searchTxt').keyup(function(e) {
                var keyCode = e.keyCode || window.event.keyCode;
                if (keyCode == 13)
                    page.submitSearchBar();
            });
        }
    },

    this.submitSearchBar = function() {
        txt = $('#searchTxt').val();
        if (txt != '' && txt != 'search...') {
            document.body.style.cursor = 'wait';
            window.location.href = "/HessSearchPage.aspx?q=" + escape(txt);
        }
    }


}

function ReadMoreToggle(el, href, el2) {
    $('#' + el).toggle();
    if (href.innerHTML == "Read More") {
        href.innerHTML = "Close";
        document.getElementById(el2).innerHTML = "<img src=\"/_layouts/images/hess/icon_link_green_up.gif\"  class=\"wpArrow\"/>&nbsp;";
        
    }
    else {
        href.innerHTML = "Read More";
        document.getElementById(el2).innerHTML = "<img src=\"/_layouts/images/hess/icon_link_green_down.gif\"  class=\"wpArrow\"/>&nbsp;";
    }

}

function ToggleAccordion(el) {
        
    $('.accordionActive').slideUp(); // clear previous
    $('.wpTitleOn').removeClass('wpTitleOn');
    $(el).addClass('wpTitleOn');
    div = $(el).next('.accordionChild');
    div.slideDown();
    div.addClass('accordionActive');
}

function locationPage(pg) {
    $('.locationActive').hide().removeClass('locationActive');
    $('#locationPage' + pg).show().addClass('locationActive');
}

function PrintPage() {
    if (window.print) window.print() ;
    else {
        var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
        document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
        WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box WebBrowser1.outerHTML = "";
    }
}

function EmailPage() {
    subject = 'Hess.com';
    body = '(FPO)Please take a look at the following page: ' + document.location.href;
    mailto = "mailto:?subject=" + subject + "&body=" + escape(body);
    window.open(mailto);
}

function SetStageSize(size) {
    if (size != null)
        $("#areaStage").animate({ height: size }, 1000);
}

function SetOverlay(state) {
    if (state == 'on') $('#mainArea').fadeTo(500, .33);
    else
        $('#mainArea').fadeTo(500, 1);
}

function ShowVideo(hasFlash) {

    var navigation = document.getElementById("Navigation");    
    if (navigation != null)
        navigation.className = "btmNav";
    
    if (hasFlash == undefined)
        hasFlash = isFlashAvailable();
    
    if (!hasFlash)
        return;
    
    ChangeBanner("/_layouts/images/hess/nyc.jpg");
    
    isHomePage = IsSiteHomePage();
    
    size = "470px";
        
    $("#areaStage").animate({ height: size }, 1000, "linear", function() {
        PlayVideo(!isHomePage);
    });    
}

function IsSiteHomePage() {
    
    var isHomePage = false; 
    
    if (window.location.pathname == "/default.aspx")
        isHomePage = true;        
        
    return isHomePage;        
}

function PlayVideo(skipIntro) {
       
    var flashvars = {
                skipIntro: skipIntro,
                introSWF: 'http://hess.cachefly.net/hess_build_intro.swf',
                mainSWF: 'http://hess.cachefly.net/hess_build_main.swf',
                //introSWF: '/flash/hess_build_intro.swf',
                //mainSWF: '/flash/hess_build_main.swf',
                playvideo: 'true'
    };
                          
    var params = {
                wmode : "transparent",
                allowScriptAccess : "always"
    };
    
    var attributes = { 
                id: "hessMainFlash", 
                name: "hessMainFlash" 
    };

    swfobject.embedSWF("http://hess.cachefly.net/hess_build_loader.swf", "flashControl", "980", "470", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
    //swfobject.embedSWF("/flash/hess_build_loader.swf", "flashControl", "980", "470", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
}

function LoadBanner(){

    // this function relies on the URL being the in the "http://domain/name of banner/" format.
    // for example, a URL of "http://hess.com/technology/default.aspx" would load the technology.jpg banner.

    var currentUrl = window.location.pathname;
    var sections = String(currentUrl).split('/');
    
    if (sections.length > 2)
    {
        hasFlash = isFlashAvailable();
        var image = sections[1];
        if (!hasFlash)
            image = image + "_noflash";
        image = "/_layouts/images/hess/banners/" + image + ".jpg";
        ChangeBanner(image);
        if (!hasFlash)
        {
            var banner = document.getElementById("homepageStatic"); 
            banner.className = "disabled";
            banner.setAttribute("onclick", ""); 
        }
    }
}

function ChangeBanner(image){
    
    var banner = document.getElementById("homepageStatic");    
    banner.src = image;
}

function isFlashAvailable() {

    var requiredMajorVersion = 9;
    var requiredMinorVersion = 0;
    var requiredRevision = 0;

    var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);        
    
    return hasReqestedVersion;
}

var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
    versionStr = GetSwfVer();
    if (versionStr == -1) {
        return false;
    } else if (versionStr != 0) {
        if (isIE && isWin && !isOpera) {
            // Given "WIN 2,0,0,11"
            tempArray = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
            tempString = tempArray[1]; 		// "2,0,0,11"
            versionArray = tempString.split(","); // ['2', '0', '0', '11']
        } else {
            versionArray = versionStr.split(".");
        }
        var versionMajor = versionArray[0];
        var versionMinor = versionArray[1];
        var versionRevision = versionArray[2];

        // is the major.revision >= requested major.revision AND the minor version >= requested minor
        if (versionMajor > parseFloat(reqMajorVer)) {
            return true;
        } else if (versionMajor == parseFloat(reqMajorVer)) {
            if (versionMinor > parseFloat(reqMinorVer))
                return true;
            else if (versionMinor == parseFloat(reqMinorVer)) {
                if (versionRevision >= parseFloat(reqRevision))
                    return true;
            }
        }
        return false;
    }
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer() {
    // NS/Opera version >= 3 check for Flash plugin in plugin array
    var flashVer = -1;

    if (navigator.plugins != null && navigator.plugins.length > 0) {
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
            var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
            var descArray = flashDescription.split(" ");
            var tempArrayMajor = descArray[2].split(".");
            var versionMajor = tempArrayMajor[0];
            var versionMinor = tempArrayMajor[1];
            if (descArray[3] != "") {
                tempArrayMinor = descArray[3].split("r");
            } else {
                tempArrayMinor = descArray[4].split("r");
            }
            var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
            var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
        }
    }
    // MSN/WebTV 2.6 supports Flash 4
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
    // WebTV 2.5 supports Flash 3
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
    // older WebTV supports Flash 2
    else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    else if (isIE && isWin && !isOpera) {
        flashVer = ControlVersion();
    }
    return flashVer;
}

function ControlVersion() {
    var version;
    var axo;
    var e;

    // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

    try {
        // version will be set for 7.X or greater players
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        version = axo.GetVariable("$version");
    } catch (e) {
    }

    if (!version) {
        try {
            // version will be set for 6.X players only
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

            // installed player is some revision of 6.0
            // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
            // so we have to be careful. 

            // default to the first public version
            version = "WIN 6,0,21,0";

            // throws if AllowScripAccess does not exist (introduced in 6.0r47)		
            axo.AllowScriptAccess = "always";

            // safe to call for 6.0r47 or greater
            version = axo.GetVariable("$version");

        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 4.X or 5.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = axo.GetVariable("$version");
        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 3.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = "WIN 3,0,18,0";
        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 2.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            version = "WIN 2,0,0,11";
        } catch (e) {
            version = -1;
        }
    }

    return version;
}

/*
Image Pre-loading.
*/
jQuery.preloadImages = function()
{
    var folder = arguments[0];

    for(var i = 1; i < arguments.length; i++)
    {
        var file = folder + arguments[i];
        jQuery("<img>").attr("src", file);
    }
}
