var intRotationCount = -1;
var intRotationItems = 0;
var rotationTimer;
var rotationTimeInSeconds = 10;
var rotationLastNavigationEvent = "";

var ie7 = (navigator.userAgent.toLowerCase().indexOf("msie 7") != -1) ? true : false;

$(document).ready(function () {

    $('h1').each(function () { subsupreplace(this); });
    $('h2').each(function () { subsupreplace(this); });
    $('h3').each(function () { subsupreplace(this); });
    $('a').each(function () { subsupreplace(this); });

    //replace mypalsgaard with <b>my</b>Palsgaard
    //NB: this has to be the first in this function, otherwise other functions will stop working
    //NB: you cannot hightlight using the body-tag as reference; use a container div inside the body tag instead
    //NB: if there is an aspnet form, do not touch it. IE8 (only!) does not like that.
    hls_query = "myPalsgaard";
    hls_query2 = "®";
    if ($('form .aspNetHidden').length == 0) {
        if (typeof (hls_query) != 'undefined') { $("#site").highlightMyPalsgaard(hls_query, 1); }
        if (typeof (hls_query2) != 'undefined') { $("#site").superscriptCopyright(hls_query2, 1); }
    } else {
        if (typeof (hls_query) != 'undefined') {
            $("#top").highlightMyPalsgaard(hls_query, 1);
            $("#bottom").highlightMyPalsgaard(hls_query, 1);
            $(".cntPalsgaardAddresses").highlightMyPalsgaard(hls_query, 1);
            $(".cntMap").highlightMyPalsgaard(hls_query, 1);
            $(".contact h2").highlightMyPalsgaard(hls_query, 1);
        }
        if (typeof (hls_query2) != 'undefined') {
            $("#top").superscriptCopyright(hls_query2, 1);
            $("#bottom").superscriptCopyright(hls_query2, 1);
            $(".cntPalsgaardAddresses").superscriptCopyright(hls_query2, 1);
            $(".cntMap").superscriptCopyright(hls_query2, 1);
            $(".contact h2").superscriptCopyright(hls_query2, 1);
        }
    }

    prepareFormFieldsLabelInside();
    showFingerPrint();
    addShadowOnOverview();
    init_rotation();

    //$('.submitParentForm').click(function () { $(this).parents('form').submit(); });

    if ($('.navSub1 li').length == 0) { $('.navMain').addClass('noLevel2'); }

    makeSelectedArrow($('.navMain a.selected'), 'insideBottom');

    $('.navMain a:not(.selected)').mouseover(function () {
        makeSelectedArrow($(this), 'insideBottom');
    }).mouseout(function () { removeSelectedArrow($(this), 'insideBottom'); });

    makeSelectedArrow($('.navSub1 a.selected'), 'insideBottom');
    makeSelectedArrow($('.navSub2 a.selected'), 'insideBottom');
    makeSelectedArrow($('.navSub3 a.selected'), 'insideBottom');

    $('.navSub a:not(.selected)').mouseover(function () {
        makeSelectedArrow($(this), 'insideBottom');
    }).mouseout(function () { removeSelectedArrow($(this), 'insideBottom'); });

    makeSelectedArrow($('#rotationNav a.selected'), 'outsideTop');

    $('#rotationNav a').mouseenter(function () {
        rotationLastNavigationEvent = "mouseenter"
        stopRotation();
        showNewRotationItem($(this).parent().index());
    }).mouseleave(function () {
        if (rotationLastNavigationEvent != "mouseleave")//because IE keeps firing event
        {
            intRotationCount--;
            if (intRotationCount < -1)
                intRotationCount = intRotationItems - 2;
            playRotation();
            rotationLastNavigationEvent = "mouseleave"
        }
    });

    $('.extraBox .btnForgotPw').click(function () { $('.extraBox > div > div').toggleClass('elementVisHide'); });
    $('.coverLogin .btnForgotPw').click(function () { $('.coverLogin > div').toggleClass('elementVisHide'); });

    if (ie7) {
        $('.diagram .dItem').prepend($('<div class="cornerFixIe7"><div class="cntDiagramCornersTop"><div class="cornerTL"></div><div class="cornerTR"></div></div></div>')).append($('<div class="cornerFixIe7"><div class="cntDiagramCornersBottom"><div class="cornerBL"></div><div class="cornerBR"></div></div></div>'));
    }
    else {
        $('.diagram .dItem').prepend($('<div class="cntDiagramCornersTop"><div class="cornerTL"></div><div class="cornerTR"></div></div>')).append($('<div class="cntDiagramCornersBottom"><div class="cornerBL"></div><div class="cornerBR"></div></div>'));
    }

    $('#linkOrganizationOfNexus').click(function () {
        $('#diagramOrganizationOfNexus').toggleClass('elementHide');
        $(this).toggleClass('foldedOut');
        if ($(this).hasClass('foldedOut')) {
            $('#diagramOrganizationOfPalsgaard').addClass('elementHide');
            $('#linkOrganizationOfPalsgaard').removeClass('foldedOut');
            $('#salesLevel').addClass('elementHide');
            $('#linkOrganizationOfSales').removeClass('foldedOut');
        }

    });
    $('#linkOrganizationOfPalsgaard').click(function () {
        $('#diagramOrganizationOfPalsgaard').toggleClass('elementHide');
        $(this).toggleClass('foldedOut');
        if ($(this).hasClass('foldedOut')) {
            $('#diagramOrganizationOfNexus').addClass('elementHide');
            $('#linkOrganizationOfNexus').removeClass('foldedOut');
        }
        else {
            $('#salesLevel').addClass('elementHide');
            $('#linkOrganizationOfSales').removeClass('foldedOut');
        }
    });

    $('#linkOrganizationOfSales').click(function () {
        $('#salesLevel').toggleClass('elementHide');
        $(this).toggleClass('foldedOut');

    });

    $('.extraFeaturesBottom li:last-child').addClass('last_child');

    if (ie7) {
        $('.extraBox a').click(function () { $(this).blur(); });
        $('.coverLogin a').click(function () { $(this).blur(); });
    }

    $('.listResults li:nth-child(odd)').addClass('rowOdd');

    $('.sitemapList li').has('ul').addClass('hasChildren');
    $('.sitemapList li:last-child').addClass('last_child');


    $('.bottomBoxes > li > ul').each(function (index, value) {
        if ($(this).find("li li").size() > 0) {
            $(this).addClass('languageVersions');
        }
    });

    //$('.navDownloads > li > ul > li:nth-child(even)').addClass('rowEven');

    //    $('.downloadSubCategory').click(function () {
    //        $('.downloadSubCategoryItem[data-idparent="' + $(this).attr('id') + '"]').toggleClass('elementHide');
    //    });

    //If no content exists in the right narrow column, widen the content text.
    var node = $('.colNarrow');
    if (node.length == 1) {
        if ($.trim(node.html()) == '') {
            node.hide();
            $('.textWide').addClass('textWider');
        }
    }

    $('ul.navDownloadsInner').hide();
    $('h3').click(function () {
        $(this).next('ul').slideToggle(500);
    });
    $('li.current_page_item').parent().show();

    if ($('.textOnTopExtraIe7 .textOnTop .preHeader').html() == '' && $('.textOnTopExtraIe7 .textOnTop .header').html() == '')
        $('.textOnTopExtraIe7 .textOnTop').hide();
});

function subsupreplace(node) {
    jqNode = $(node);
    var html = jqNode.html();
    if (html != null) {
        var newHtml = html;
        newHtml = newHtml.replace('[sub]', '<sub>').replace('[/sub]', '</sub>');
        newHtml = newHtml.replace('[sup]', '<sup>').replace('[/sup]', '</sup>');
        if (html != newHtml)
            jqNode.empty().append(newHtml); //Using jqNode.html(newHtml); adds <a xmlns="http://www.w3.org/1999/xhtml"></a> inside "a" tags in firefox < v4
    }
}

function activateFancyBoxTopWidget() {
    $(document).ready(function () {
        $("a#topWidget").fancybox();
    });
}

function activatePresentationVideo() {
    $(document).ready(function () {
        $(".presentationFlashVideo").fancybox();
    });
}

function removeSelectedArrow(argObj) {
    $(argObj).removeClass().find(".selectedArrow").remove();
}
function makeSelectedArrow(argObj, argStrPlacement) {
    var html = "";
    html += '\t\t\t\t<span class="row row1">\n';
    html += '\t\t\t\t\t<span class="op02"></span>\n';
    html += '\t\t\t\t</span>\n';
    html += '\t\t\t\t<span class="row row2">\n';
    html += '\t\t\t\t\t<span class="op04"></span>\n';
    html += '\t\t\t\t\t<span class="op05"></span>\n';
    html += '\t\t\t\t</span>\n';
    html += '\t\t\t\t<span class="row row3">\n';
    html += '\t\t\t\t\t<span class="op02"></span>\n';
    html += '\t\t\t\t\t<span class="op22"></span>\n';
    html += '\t\t\t\t\t<span class="op50"></span>\n';
    html += '\t\t\t\t\t<span class="op06"></span>\n';
    html += '\t\t\t\t</span>\n';
    html += '\t\t\t\t<span class="row row4">\n';
    html += '\t\t\t\t\t<span class="op10"></span>\n';
    html += '\t\t\t\t\t<span class="op72"></span>\n';
    html += '\t\t\t\t\t<span class="op96"></span>\n';
    html += '\t\t\t\t\t<span class="op24"></span>\n';
    html += '\t\t\t\t\t<span class="op04"></span>\n';
    html += '\t\t\t\t</span>\n';
    html += '\t\t\t\t<span class="row row5">\n';
    html += '\t\t\t\t\t<span class="op04"></span>\n';
    html += '\t\t\t\t\t<span class="op38"></span>\n';
    html += '\t\t\t\t\t<span class="op100 w2"></span>\n';
    html += '\t\t\t\t\t<span class="op72"></span>\n';
    html += '\t\t\t\t\t<span class="op14"></span>\n';
    html += '\t\t\t\t</span>\n';
    html += '\t\t\t\t<span class="row row6">\n';
    html += '\t\t\t\t\t<span class="op17"></span>\n';
    html += '\t\t\t\t\t<span class="op86"></span>\n';
    html += '\t\t\t\t\t<span class="op100 w3"></span>\n';
    html += '\t\t\t\t\t<span class="op38"></span>\n';
    html += '\t\t\t\t\t<span class="op10"></span>\n';
    html += '\t\t\t\t</span>\n';
    html += '\t\t\t\t<span class="row row7">\n';
    html += '\t\t\t\t\t<span class="op06"></span>\n';
    html += '\t\t\t\t\t<span class="op56"></span>\n';
    html += '\t\t\t\t\t<span class="op100 w4"></span>\n';
    html += '\t\t\t\t\t<span class="op83"></span>\n';
    html += '\t\t\t\t\t<span class="op23"></span>\n';
    html += '\t\t\t\t</span>\n';
    html += '\t\t\t\t<span class="row row8">\n';
    html += '\t\t\t\t\t<span class="op25"></span>\n';
    html += '\t\t\t\t\t<span class="op95"></span>\n';
    html += '\t\t\t\t\t<span class="op100 w5"></span>\n';
    html += '\t\t\t\t\t<span class="op50"></span>\n';
    html += '\t\t\t\t</span>\n';

    var newElement = $('<span></span>');
    newElement.addClass("selectedArrow");
    if (argStrPlacement == 'outsideTop') {
        var mTop = -16;
    }
    else {
        var mTop = $(argObj).height() - 8;
    }
    var mLeft = ($(argObj).width() / 2) - 4;
    newElement.css('margin-top', mTop + "px");
    newElement.css('margin-left', mLeft + "px");
    newElement.append(html);
    argObj.prepend(newElement);
}

function addShadowOnOverview() {
    var rightShadow = $('<div></div>').addClass('rightShadow');
    $('.navOverview li:nth-child(3n)').prepend($(rightShadow));
    $('.navOverview li:last-child').prepend($(rightShadow));
}
function prepareFormFieldsLabelInside() {
    $('textarea[title]').focus(function () { showHideInputValue($(this)) }).blur(function () { showHideInputValue($(this)) });
    $('input[type=text][title]').focus(function () { showHideInputValue($(this)) }).blur(function () { showHideInputValue($(this)) });
    $.each($('input[type=password][title]').parent().next(), function (indexInArray, valueOfElement) { showHidePasswordLabel($(this)); });
    $('input[type=password]').parent().next().focus(function () { showHidePasswordLabel($(this)) }).blur(function () { showHidePasswordLabel($(this)) });

    // we can't use title attribute because of contour 
    // but there is a <small> tag after the control where the tooltip text is.

    $('.contact textarea').focus(function () { showHideInputValueContour($(this)) }).blur(function () { showHideInputValueContour($(this)) });
    $('.contact input[type=text]').focus(function () { showHideInputValueContour($(this)) }).blur(function () { showHideInputValueContour($(this)) });
    
}
function showFingerPrint() {
    var fingerPrintDiv = $('<div></div>');
    $(fingerPrintDiv).addClass('divFingerprint');
    $(fingerPrintDiv).html($('.extraFeaturesBottom > li:nth-child(3)').html());
    $('.extraFeaturesBottom > li:nth-child(3)').html($(fingerPrintDiv));
}

function init_rotation() {
    showRotationNavigation();
    showNewRotationItem(intRotationCount);
    intRotationItems = $('#rotationNav > li').size();
    playRotation();
}
function stopRotation() {
    clearTimeout(rotationTimer);
}
function playRotation() {
    intRotationCount++;
    if (intRotationCount > intRotationItems - 1)
        intRotationCount = 0;

    showNewRotationItem(intRotationCount);
    rotationTimer = setTimeout(function () { playRotation() }, rotationTimeInSeconds * 1000);
}
function showNewRotationItem(argInt) {
    removeSelectedArrow($('#rotationNav li a.selected'))

    intNth = intRotationCount + 1;
    intNth = argInt + 1;
    $('#rotationNav li:nth-child(' + intNth + ') a').addClass('selected');
    makeSelectedArrow($('#rotationNav a.selected'), 'outsideTop');

    argInt++;
    var contentHolder = $("#cntRotation2 li:nth-child(" + argInt + ")");

    /*build item*/
    var item = $('<div></div>');
    var itemImage = $('<div></div>');
    var itemPreHeader = $('<span></span>');
    var itemHeader = $('<h2></h2>');
    var itemText = $('<p></p>');

    $(itemImage).addClass('image');
    $(itemPreHeader).addClass('preHeader');

    $(itemImage).html($(contentHolder).find('.image').html());
    $(itemPreHeader).html($(contentHolder).find('.preHeader').html());
    $(itemHeader).html($(contentHolder).find('h2').html());
    $(itemText).html($(contentHolder).find('.text').html());

    $(item).append($(itemImage))
    if ($(contentHolder).find('.preHeader').html() != "")
        $(item).append($(itemPreHeader))
    $(item).append($(itemHeader)).append($(itemText));

    /*show item*/
    $('#cntRotation').prepend($(item));

    /*tidy up - remove previously shown item*/
    $('#cntRotation div:nth-child(2)').remove();
}
function showRotationNavigation() {
    $('#rotationNav').html('');
    $("#cntRotation2 li").each(function (liIndex, liValue) {
        var objLi = $('<li></li>').html($(liValue).find('h2').html());
        if (liIndex == 0)
            $(objLi).find('a').addClass("selected");
        $('#rotationNav').append($(objLi));
    });
}
function showHidePasswordLabel(argObj) {
    var objDiv = $('<div></div>');
    objDiv.addClass('clear');
    var objLabel = $('<label></label>');
    objLabel.addClass('labelPassword');
    objLabel.text($(argObj).attr('title'));
    var mTop = ($(argObj).css('margin-bottom').replace("px", "") * 1) + $(argObj).height();
    objLabel.css('margin-top', "-" + mTop + 'px');
    objLabel.css('width', $(argObj).width() + 'px');
    objLabel.css('height', $(argObj).height() + 'px');
    objLabel.css('line-height', '1.9');
    objLabel.css('padding-left', ($(argObj).css('padding-left').replace("px", "") * 1) + 'px');
    objLabel.attr('for', $(argObj).attr('id'));
    objDiv.append(objLabel)
    if ($(argObj).val() == "" && $(argObj).next().attr('class') != 'clear') {
        $(argObj).after($(objDiv))
    }
    else {
        $(argObj).next('div').remove()
    }
}
function showHideInputValue(argObj) {
    if ($(argObj).val() == $(argObj).attr('title'))
        $(argObj).val('')
    else if ($(argObj).val() == "")
        $(argObj).val($(argObj).attr('title'))
}

function showHideInputValueContour(argObj) {
    if ($(argObj).val() == $(argObj).parent().next().html())
        $(argObj).val('')
    else if ($(argObj).val() == "")
        $(argObj).val($(argObj).parent().next().html())
}

$.fn.extend({
    highlightMyPalsgaard: function (search, insensitive) {
        if (this.length == 0)
            return this;

        var regex = new RegExp("(<[^>]*>)|(\\b" + search.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1") + ")", insensitive ? "ig" : "g");

        //return this.html(this.html().replace(regex, function (a, b, c) {
        //    return (a.charAt(0) == "<") ? a : '<b>my</b>Palsgaard';
        //}));

        var html = $(this).html();
        var newHtml = html.replace(regex, function (a, b, c) {
            return (a.charAt(0) == "<") ? a : '<b>my</b>Palsgaard';
        });
        if (html != newHtml)
            this.empty().append(newHtml);

        return this;
    },

    superscriptCopyright: function (search, insensitive) {
        if (this.length == 0)
            return this;

        var regex = new RegExp("(<[^>]*>)|(\\b" + search.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1") + ")", insensitive ? "ig" : "g");

        //return this.html(this.html().replace(regex, function (a, b, c) {
        //    return (a.charAt(0) == '<') ? a : '<sup>&reg;</sup>';
        //}));

        var html = this.html();
        var newHtml = html.replace(regex, function (a, b, c) {
            return (a.charAt(0) == '<') ? a : '<sup>&reg;</sup>';
        });
        if (html != newHtml)
            this.empty().append(newHtml);

        return this;
    }
});
