﻿/// <reference path="jquery-1.3.2-vsdoc2.js" />

var PAR = {};

PAR.History = {
    scroller: null,

    init: function() {
        this.scroller = jQuery('div.scrollable');
        if (this.scroller)
            jQuery(this.scroller).scrollable({size: 3, clickable: false}).mousewheel();
    }
};

PAR.OilFieldCycle = {
    instance: null,
    element: null,
    flag: null,
    init: function() {
        this.element = jQuery("#oil-field-cycle");
        if (this.element)
            this.setBehavior();
    },
    setBehavior: function() {
        instance = this;
        jQuery("#of-time-nav a").hover(function() {
            if (jQuery(this).hasClass("selected")) {
                jQuery(this).removeClass("selected");
                instance.flag = jQuery(this).attr('class');
            }
            else
                instance.flag = '';
            jQuery(this).addClass("selected");
        }, function() {
            jQuery(this).removeClass("selected");
            if (instance.flag == jQuery(this).attr('class'))
                jQuery(this).addClass("selected");
        });
        jQuery("#of-navigator a").hover(function() {
            elemClass = jQuery(this).attr("class");
            jQuery("#of-time-nav ." + elemClass).addClass("selected");
        }, function() {
            elemClass = jQuery(this).attr("class");
            jQuery("#of-time-nav ." + elemClass).removeClass("selected");
        });

        jQuery("#of-time-nav a").click(function(e) {
            instance.clearSelection();
            elemClass = jQuery(this).attr("class");
            instance.flag = elemClass;
            instance.setContent(elemClass);
        });
        jQuery("#of-navigator a").click(function(e) {
            instance.clearSelection();
            elemClass = jQuery(this).attr("class");
            instance.setContent(elemClass);
        });
    },
    setContent: function(elemClass) {
        jQuery("#of-time-nav ." + elemClass).addClass("selected");
        jQuery("#of-text-content ." + elemClass).addClass("display");
        jQuery("#of-navigator ." + elemClass).addClass("selected");
    },
    clearSelection: function() {
        jQuery("#of-time-nav a").removeClass("selected");
        jQuery("#of-navigator a").removeClass("selected");
        jQuery("#of-text-content div").removeClass("display");
    }
};

PAR.OperationsHelper = {
    makeRequest: function(pid, content, target) {
        jQuery(target).append('<img class="loader" src="/Media/Images/ajax-loader.gif" alt="Loading" />');
        jQuery(target).animate(
            {
                opacity: 0
            },
            300,
            function() {
                jQuery.ajax({
                    type: "POST",
                    url: "/Templates/Public/WebServices/AjaxService.asmx/GetPageContent",
                    data: "{'pageid':'" + pid + "','content':'" + content + "','lang':'" + jQuery('html').attr('lang') + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    processData: false,
                    cache: false,
                    success: function(msg, status) {
                        jQuery(target).remove('.loader');
                        // Replace the div's content with the page method's return.
                        jQuery(target).html(msg.d);
                        jQuery(target).animate({
                            opacity: 1
                        }, 500); 
                    },
                    error: function(xhr, msg, e) {
                        alert(msg + ', ' + e); //Error Callback
                    },
                    complete: function(xhr, status) {
                    }
                });
            }
        );
    }
};

PAR.GetAreaInfo = function(pid) {
    var innerH = jQuery('#InnerArea').height();
    var e = $('#InnerArea');

    PAR.OperationsHelper.makeRequest(pid, 'body', '#operation-body');
    PAR.OperationsHelper.makeRequest(pid, 'heading', 'h1 .sIFR-alternate');
    setTimeout(function() {
        PAR.OperationsHelper.makeRequest(pid, 'number', '#operation-quote');
    }, 200);
    setTimeout(function() {
        PAR.OperationsHelper.makeRequest(pid, 'image', '#operation-image');
        var heading = jQuery('h1 .sIFR-alternate').text().toUpperCase();
        try {
        sIFR.replacements[0].replaceText(heading, heading);
        } catch(err) {}
    }, 400);
    setTimeout(function() {
        PAR.OperationsHelper.makeRequest(pid, 'table', '#operation-table');
    }, 600);
};

PAR.ImagePresentation = {
    init: function() {
        $("#imagepresentation").addClass("presentationList");
        //$("#imagepresentation .info").css("display", "none");


        // enable tooltip for imagepresentation element
        $("#imagepresentation .bigimage").tooltip({
            effect: 'toggle', //toggle, fade
            tip: 'div.tooltip',
            bounce: false,
            offset: [15, -5]
        });

        //enable trigger for overlay, sets the overlay to the element id set in the rel-attribute.
        $("#imagepresentation .bigimage[rel]").overlay({
            color: '#000',
            left: 'center',
            top: 300,
            // some expose tweaks suitable for modal dialogs
            expose: {
                color: '#000',
                loadSpeed: 400,
                opacity: 0.3
            }
        });

        // image opacity effect
        $('#imagepresentation li .bigimage').css({ 'opacity': 0.5 });


        //hover
        $("#imagepresentation li").hover(function() {
            //image
            $(this).find('.bigimage').animate({ 'opacity': 1 }, 300).css('cursor','pointer');
        },
        function() {
            // onmouseout
            $(this).find('.bigimage').animate({ 'opacity': 0.5 }, 100);
            //        $(this).find('.tooltip').css({ 'display': 'none' });
        });
    }
};

PAR.CorpGovernancePyramid = {
    init: function() {
        $.fn.maphilight.defaults = {
            fill: true,
            fillColor: 'cccccc',
            fillOpacity: 0,
            stroke: true,
            strokeColor: 'ff0000',
            strokeOpacity: 1,
            strokeWidth: 10,
            fade: true,
            alwaysOn: false
        };

        // http://davidlynch.org/js/maphilight/docs/
        // http://davidlynch.org/blog/2008/03/maphilight-image-map-mouseover-highlighting/
        // http://github.com/kemayo/maphilight - IE8 fix
        $("img[usemap]").maphilight();
    }
};

$(document).ready(function () {
    $('#disclaimer').click(function () {
        $('#show, h1').hide();
        $('#hide, h1').show();
    });
    PAR.OilFieldCycle.init();
    PAR.History.init();
    PAR.ImagePresentation.init();
    PAR.CorpGovernancePyramid.init();


    enableGoogleChartsTables();
    $("div.tabs").tabs();
    $("#accordion,div.accordion").accordion({ active: false, collapsible: true });
    $("#production-report-show-year").change(function () {
        var select = $(this);

        select.attr("disabled", true);

        var url = select.val();

        if (select.is(".ajax")) {
            $.get(url, undefined, function (html) {
                select.attr("disabled", false);

                var newHtml = $(html).find("div.production-report-content").html();

                $("div.production-report-content").html(newHtml);
            }, "html");
        } else {
            location.href = location.href.match(/http:\/\/[^\/]+/)[0] + url;
        }

        setTimeout(function () {
            select.attr("disabled", false);
        }, 2000);
    });

    $("> a[href$=\".pdf\"]", "li, li > span").addClass("link-icon link-icon-pdf").closest("li").addClass("contains-link-icon").parent("ul").addClass("contains-link-icons");
    $("> a[href$=\".xls\"]", "li, li > span").addClass("link-icon link-icon-excel").closest("li").addClass("contains-link-icon").parent("ul").addClass("contains-link-icons");

    $.fn.equalizeHeights = function () {
        var maxHeight = 0;

        this.each(function () {
            var height = $(this).height();

            maxHeight = Math.max(height, maxHeight);
        });

        this.height(maxHeight);
    }

    $("#ContentAreaTwoColumns.convertible-landing-page div.panel-teaser").equalizeHeights();

    $("div.production-report-content table tr.month-total").hover(function () {
        $(this).addClass("hover");
    }, function () {
        $(this).removeClass("hover");
    });

    enableMegaMenus();

    enableStartpageSlideshow();

    $("#ContentAreaTwoColumns.about-area div.first-row div.panel").equalizeHeights();

    $("body.page-type-rss-feeds table tr td a").each(function () {
        var link = $(this);
        link.attr("title", link.text());
    });

    (function () {
        function openHeading(heading) {
            var panel = heading.next("dd");

            heading.removeClass("closed").addClass("open");
            panel.slideDown();
        }

        function closeHeading(heading) {
            var panel = heading.next("dd");

            heading.removeClass("open").addClass("closed");
            panel.slideUp();
        }

        var definitionTitles = $("body.page-type-presentationer dl dt")

        definitionTitles.click(function () {
            var heading = $(this);

            if (heading.is(".open")) {
                closeHeading(heading);
            } else if (heading.is(".closed")) {
                openHeading(heading);
            }
        });

        closeHeading(definitionTitles.not(":first"));
    })();

    enableKeyFiguresTable();
});

function enableKeyFiguresTable() {
    var keyFiguresTableWrapper = $("#keyfigures-table");

    keyFiguresTableWrapper.find("*").removeAttr("width");

    keyFiguresTableWrapper.find("tr td:first-child").wrapInner("<div class=\"table-header-wrapper\"></div>");

    keyFiguresTableWrapper.children("div").css("width", ((keyFiguresTableWrapper.find("table tr:first").children().length-1) * 100 + 192) + "px");

    var keyFiguresTableClone = keyFiguresTableWrapper.find("table").clone();

    keyFiguresTableClone.find("tr td:not(:first-child)").remove();

    $("<div></div>").attr("id", "keyfigures-overlay-table").append(keyFiguresTableClone).insertAfter(keyFiguresTableWrapper);

    $("body.page-type-key #ContentAreaTwoColumns input[type=\"radio\"]").click(function () {
        location.href = $(this).siblings("a").attr("href");
    });
}

function enableGoogleChartsTables() {
    $("#ContentAreaTwoColumns.about-area div.first-row div.second-col table").each(function () {
        var table = $(this);

        table.find("br").remove();
        table.removeAttr("style").find("*").removeAttr("style");

        if (table.children("thead").length == 0) {
            var tbody = table.children();
            var thead = $(table[0].createTHead());

            var firstRow = tbody.find("tr").first();

            firstRow.find("td").each(function () {
                var cell = $(this);

                $("<th/>").append(cell.html()).insertBefore(cell);

                cell.remove();
            });

            firstRow.appendTo(thead);

            tbody.find("td:first-child").each(function () {
                var cell = $(this);

                $("<th/>").append(cell.html()).insertBefore(cell);

                cell.remove();
            });
        }

        // remove thousands separator
        table.find("td").each(function () {
            this.innerHTML = this.innerHTML.replace(/(\d)[, ](\d\d\d)/g, "$1$2");
        });

        // convert decimal separator
        table.find("td").each(function () {
            this.innerHTML = this.innerHTML.replace(",", ".");
        });

        //

        var hasDecimals = false;

        table.find("td").each(function () {
            if (this.innerHTML.indexOf(".") != -1) {
                hasDecimals = true;
            }
        });

        //

        if ($("html").attr("lang") == "sv") {
            groupingSymbol = " ";
        } else {
            groupingSymbol = ",";
        }

        //

        table.gvChart({
            chartType: 'ColumnChart',
            numberFormat: {
                groupingSymbol: groupingSymbol,
                fractionDigits: hasDecimals ? 1 : 0
            },
            gvSettings: {
                colors: ["#a5d8db", "#ee7f01", "#006583"],
                width: 300,
                height: 180,
                legend: "none",
                vAxis:{minValue:0},
                "backgroundColor": { fill: "none" }
            }
        });
    });

    $("html[lang=\"sv\"] div.gvChart iframe").each(function () {
        $(this).contents().find("text[x=\"46\"]").each(function () {
            var element = $(this);
            element.text(element.text().replace(/(\d),(\d\d\d)/g, "$1 $2"));
        });
    }).each(function () {
        $(this).contents().find("textpath").each(function () {
            this.outerHTML = this.outerHTML.replace(/(\d),(\d\d\d)/g, "$1 $2");

        });
    });
}

function enableStartpageSlideshow() {
    var slideshow = $("#StartPage ul.startpage-slideshow-items");

    var slideshowItems = slideshow.children();

    var control = $("<ul></ul>").addClass("startpage-slideshow-control").insertBefore(slideshow);

    var controlItem = $("<li></li>").click(function () {
        var controlItem = $(this);
        var index = controlItem.index();
        var correspondingSlideshowItem = slideshowItems.eq(index);

        ticker.showElement(
            ticker,
            slideshowItems.filter(":visible"),
            correspondingSlideshowItem,
            function () {
                ticker._startTicker.apply(ticker._this, Array(ticker));
            }
        );
    });

    slideshowItems.each(function () {controlItem.clone(true).appendTo(control);});

    var controlItems = control.children();

    controlItems.eq(0).addClass("current").click(function () { });

    var ticker = slideshowItems.ticker({
        showElement: function (options, oldElement, newElement, done) {
            var indexOfNewElement = options._indexOfItem(newElement, slideshowItems);

            setTimeout(function () {
                controlItems.removeClass("current").eq(indexOfNewElement).addClass("current");
            }, 1000);

            oldElement.fadeOut(2000);
            newElement.fadeIn(2000, function () {
                done();
            });
        },
        timeout:8000
    });
}

function enableMegaMenus(){
    var megaMenus = $("#MainMenu div.mega-menu");
    var deferredAction;

    megaMenus.find("li:first-child a").addClass("first");

    function defer(action, timeout){
        if(deferredAction){
            clearTimeout(deferredAction);
        }

        deferredAction = setTimeout(action, timeout);
    }

    function showMegaMenu(menuItem) {
        var megaMenu = menuItem.next("div.mega-menu");

        if (megaMenu.length == 0) {
            return;
        }

        //$("#MainMenu a.mega-menu-enabled").removeClass("mega-menu-enabled");

        megaMenus.not(megaMenu).stop().css("height", "").hide();

        megaMenu.not(":visible").slideDown();
    }

    function deferredShowMegaMenu(menuItem) {
        defer(function () {
            showMegaMenu(menuItem);
        }, 300);
    }

    function hideMegaMenu() {
        megaMenus.stop().css("height", "").hide();
    }

    function deferredHideMegaMenu() {
        defer(function () {
            hideMegaMenu();
        }, 100);
    }

    $("#MainMenu > ul > li").hover(function () {
        var menuItem = $(this).children("a");

        if (menuItem.siblings("div.mega-menu").length == 0) {
            deferredHideMegaMenu();
            return;
        }

        menuItem.addClass("mega-menu-enabled");

        deferredShowMegaMenu(menuItem);
    }, function () {
        var menuItem = $(this).children("a");

        menuItem.removeClass("mega-menu-enabled");

        deferredHideMegaMenu();
    });
}

function XMLToString(oXML) {
    if (window.ActiveXObject) {
        return oXML.xml;
    } else {
        return (new XMLSerializer()).serializeToString(oXML);
    }
}
