var timerID = 0;

/* Temporary parameter used for testing */
var imgPath = "http://kanabanana.com/microsites/sk/img/tmp/";


/*************************************************************

jQuery onload functions

*************************************************************/

$(document).ready(function() {
    
    /* Function for standarizing the popup window */
    /*$.extend($.modal.defaults, {
    closeClass: "pu-close",
    overlayId: "pu-overlay",
    containerId: "pu-container"
    });*/


    /* Functioin for generating global menu items width */
    var tmpWidth = 0;
    var totWidth = 0;
    var tmpCounter = 0;
    jQuery.each($("a.global-menu-item"), function() {
        tmpCounter += 1;
        tmpWidth = $(this).innerWidth();
        totWidth += tmpWidth;
    });
    calculateWidth(totWidth, tmpCounter);

    /* Function for generating project flow menu items width */
    var tmpWidth = 0;
    var totWidth = 0;
    var tmpCounter = 0;
    jQuery.each($("a.flow"), function() {
        tmpCounter += 1;
        tmpWidth = $(this).innerWidth();
        totWidth += tmpWidth;
    });
    calculateWidth2(totWidth, tmpCounter);
		adjustMetaBoxProjectFlowHeight();
    
    /* Function for generating project form items width */
    var tmpWidth = 0;
    var totWidth = 0;
    var tmpCounter = 0;
    jQuery.each($("a.form-item"), function() {
        tmpCounter += 1;
        tmpWidth = $(this).innerWidth();
        totWidth += tmpWidth;
    });
    calculateWidth3(totWidth, tmpCounter);



    /* Function for generating vertical borders in the footer */
    var returnHeight = 0;
    var tmpHeight = 0;
    jQuery.each($("#sitemap").children(), function() {
        tmpHeight = $(this).outerHeight();
        if (tmpHeight > returnHeight) {
            returnHeight = tmpHeight;
        }
    });
    $("div.link-list > ul").css("height", (returnHeight - 50) + "px")


    /* Show that element has submenus. Must be done in backend*/
    $("li.level-one-container").filter(":has(div)").find("a.level-one").addClass("hasChildren");

    /* Page menu sliding funksjon */

    $("li.level-one-container > div").css("display", "none"),
    /*Added to imitate selected item in left menu. Must be remove!!*/
    $("li.level-one-container > div.expanded").css("display", "block"),

    // Filter below selects only li.level-one-container with elements and which is not already selected
    $("li.level-one-container:has(div) a.level-one:not(.selected)").parent().hover(
	  function() {
	      $(this).children("a").addClass("active");
	      $(this).addClass("active");
	      timerID = setTimeout("slideDownMenu('" + $(this).children("div").attr("id") + "')", 300);
	      $("li.active >a.level-one").addClass("expanded-item");


	  },
	 function() {
	     clearTimeout(timerID);
	     $("li.active >a.level-one").removeClass("expanded-item");
	     $(this).children("a").removeClass("active");
	     $(this).removeClass("active");
	     $(this).children("div").slideUp("fast");

	 }
	);
	
	
	/* Faq slide functionality*/

    $("li.faq-item > div.answer").css("display", "none");
    jQuery.each($("li.faq-item"), function() {
        var itemID = $(this).attr("id").slice(5, $(this).attr("id").length);
        $("#item-" + itemID + " > div.show-hide").click(
	        function() {
	        if ($("#item-" + itemID + " > div.answer").is(":hidden")) {
	         $("#item-" + itemID + "> div.answer").slideDown();
	         $("#item-" + itemID + " > div.show-hide").children("img").attr("src", "/img/temp/te/pluss.png");
	         $("#item-" + itemID + " >div.questionhead > h3").replaceWith("<h2>" + $("#item-" + itemID + "> div.questionhead > h3").text() + "</h2>");

	        }
	        else {
	         $("#item-" + itemID + " > div.answer").slideUp();
	         $("#item-" + itemID + " > div.show-hide").children("img").attr("src", "/img/plussmenu.png");
	         $("#item-" + itemID + " >div.questionhead > h2").replaceWith("<h3>" + $("#item-" + itemID + "> div.questionhead > h2").text() + "</h3>");

	        }

	    });
	    
        $("#item-" + itemID + " > div.questionhead").click(
	        function() {
	        if ($("#item-" + itemID + " > div.answer").is(":hidden")) {
	         $("#item-" + itemID + "> div.answer").slideDown();
	         $("#item-" + itemID + " > div.show-hide").children("img").attr("src", "/img/temp/te/pluss.png");
	         $("#item-" + itemID + " >div.questionhead > h3").replaceWith("<h2>" + $("#item-" + itemID + "> div.questionhead > h3").text() + "</h2>");
	      
	        }
	        else {
	         $("#item-" + itemID + " > div.answer").slideUp();
	         $("#item-" + itemID + " > div.show-hide").children("img").attr("src", "/img/plussmenu.png");	       
	         $("#item-" + itemID + " >div.questionhead > h2").replaceWith("<h3>" + $("#item-" + itemID + "> div.questionhead > h2").text() + "</h3>");

	        }
	    });
    });//jQuery.each



    /* Site list dropdown */
    $("ul.site-list").css("display", "none"),
    $(".site-dropdown").hover(
			function() { $("ul.site-list").slideDown("fast"); },
	  	function() { $("ul.site-list").slideUp("fast"); }
		);


    /* ie6 fallback. */
		var isIE6 = (!!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1)) && /MSIE 6/i.test(navigator.userAgent);
		if(isIE6){
			/* specify ie6. */
			$("body").addClass("ie6");
			
			/* Global menu hover  */
			$("div.global-elements > ul > li").hover(
	  		    function() { $(this).addClass("hover"); },
	  		    function() { $(this).removeClass("hover"); }
			);
			if($(".sk-table").get(0)){
			    $(".sk-table th:first-child").addClass("first-child");
			    $(".sk-table td:first-child").addClass("first-child");
			}
		}


    /* Function for closing the image popup */
    $(this).keypress(function(e) {
        if (e.which == 27) {
            $.modal.close();
        }
    });


    /* Function displaying content tools */
    $("span.footer-link").click(
		function() {
		    var boxID = $(this).attr("id").slice(4, $(this).attr("id").length);
		    //Added by Olga
		    if (boxID == "subscribe" || boxID == "print") {
		        $("#lnk-" + boxID).css("color", "#00395d");
		    }
		    else
		    //end Added by Olga
		        showFooterBox(boxID);
		}
	);


    /* Adding the blue plus icon to section boxes */
    $("div.section-box").hover(
		function() {
		    $(this).append("<img class='section-box-plus' src='/img/ico_blue_plus.png' alt='Read more'/>");
		},
		function() {
		    $("img.section-box-plus").remove();
		}
	);

    /* Add no-image class on section-boxes with no-image */
    if($('.section-box').not('img').get(0)){
        $('.section-box').not('img').addClass("no-image");
    }
    
    // Two-Col List Element Fix 
    if($('.two-col-element').get(0)){
        $('.two-col-element').filter(function(index){
          return !($(this).next().hasClass('.two-col-element'));
        }).addClass('two-col-last-element');
    }
});                               /* End jQuery load check */


/*************************************************************

Misc functions

*************************************************************/

/* Calculating the width of each menu element */
function calculateWidth(width, count) {
    if (width > 0 && count > 1) {
        var restWidth = 940 - width - count;
        var tmp = Math.floor(restWidth / count);
        var tmpRest = restWidth - (tmp * count);
        $("a.global-menu-item").css("padding-right", 30 + tmp -1 + "px");
        $("a.global-menu-item:last").css("padding-right", 30 + tmp-1 + tmpRest + "px");
        $("a.global-menu-item:last").css("border", "0");
    }
    else {

        $("a.global-menu-item").css("padding-right", 30 + width + "px");


    }
}
/* Calculating the width of each process flow tab element */
function calculateWidth2(width, count) {
    if (width > 0) {
        var restWidth = 700 - width - count;-165
        var tmp = Math.floor(restWidth / count);
        var tmpRest = restWidth - (tmp * count);
				var tmpHeight = $('#tabs .project-flow-tab-strip').innerHeight();
				
        $("a.flow").css("padding-right", 1 + tmp + "px");
        $("a.flow:last").css("padding-right", 2 + tmp + tmpRest + "px");
        $("a.flow:last").css("border", "0");
				
				// Adjust the Height by removing padding on the last element until it has the correct height.
				if(tmpHeight > 0){
					if($('#tabs .project-flow-tab-strip').innerHeight() > tmpHeight){
						tmp = tmp + tmpRest;
						while($('#tabs .project-flow-tab-strip').innerHeight() > tmpHeight){
							$("a.flow:last").css("padding-right", tmp + "px");
							tmp--;
						}
					}
				}
    }
}
/* Calculating the width of each form tab element */
function calculateWidth3(width, count) {
    if (width > 0) {
        var restWidth = 460 - width - count;
        var tmp = Math.floor(restWidth / count);
        var tmpRest = restWidth - (tmp * count);
				$("#tabs")
        $("a.form-item").css("padding-right", 1 + tmp + "px");
        $("a.form-item:last").css("padding-right", 1 + tmp + tmpRest + "px");
        $("a.form-item:last").css("border", "0");
    }
}

/* Adjust Meta Box Project Flow Height to have the highest height, avoding jumping in the page. */
function adjustMetaBoxProjectFlowHeight(){
	var maxHeight = 0, 
			height = 0;
	var activeElement = $('.metabox-project-flow > div').not('.ui-tabs-hide');
	$('.metabox-project-flow > div').addClass('ui-tabs-hide');
	$('.metabox-project-flow > div').each(function(index, element){
			height = 0;
			$(element).removeClass('ui-tabs-hide');
			$(element).children().each(function(index, child){
				height += $(child).innerHeight();
			});
			// 1. Compare the total height off all child elements vs. the element innerHeight.
			// 2. See if the height > maxHeight ? new height : maxHeight. 
			height = (height > $(element).innerHeight() ? height : $(element).innerHeight()); 
			maxHeight = (height > maxHeight ? height : maxHeight);
	    $(element).addClass('ui-tabs-hide');
	});
	if(maxHeight > 0){
		$('.metabox-project-flow').css('height', maxHeight + "px");
	}
	$(activeElement).removeClass('ui-tabs-hide');
}

/* Timeout function so the slidedown dosen't get out of control. */
function slideDownMenu(el) {
    $("#" + el).slideDown("fast");
}

/* Function for displaying large images in article body. */
function showLargeImage(imgID) {
    var tmpImg = new Image();
    tmpImg.src = imgPath + imgID + "_900.jpg";
    var tmpContent = "<div id='largeImage'><img src='" + tmpImg.src + "' alt='Alternative text'/><p style='padding: 5px;'>Image text</p>";
    $.modal(tmpContent, {
        closeHTML: "<a href='#'>Klikk for &aring; lukke vinduet</a>",
        opacity: 70,
        containerCss: {
            height: tmpImg.height + 50,
            width: tmpImg.width
        }
    });
}




/*************************************************************

Article footer styles

*************************************************************/

function showFooterBox(boxID) {
    var container = "content-" + boxID + "-container";
    var isVisible = false;
    var divVisible = "";


    jQuery.each($("div.footer-placeholders").children(), function() {
        if ($(this).css("display") == "block") {
            isVisible = true;
            divVisible = $(this).attr("id");
        }
    });

    if (isVisible) {

        if (divVisible == container) {
            $("span.footer-link").css("color", "#00395d");
            $("#" + divVisible).slideUp("fast");
        } else {
            $("span.footer-link").css("color", "#00395d");

            $("#lnk-" + boxID).css("color", "#00a6d3");

            $("#" + divVisible).hide();
            $("#" + container).show();
            if (boxID == "tip") $("#txt-email-to").focus();
            if (boxID == "contact") $("#txt-firstname").focus();
        }
    } else {
        $("#lnk-" + boxID).css("color", "#00a6d3");
        $("#" + container).slideDown("fast");
        if (boxID == "tip") $("#txt-email-to").focus();
        if (boxID == "contact") $("#txt-firstname").focus();
    }

}