/// <reference path="jquery-vsdoc.js" />
var litium = {};

litium.templates = {
    framework: (function() {
        var self = {};

        self.setcolheights = function() {
            //Reset height of elements that get height set when adjusting col heights
            $("#subnav").css("height", "auto");
            $("#middle").css("height", "auto");
            $("#lefttop").css("height", "auto");
            $("#right").css("height", "auto");

            var leftTopHeight = $("#lefttop").outerHeight(true);
            var rightHeight = $("#right").outerHeight(true);
            var insideStoryHeight = $("#leftbottom").outerHeight(true);
            var leftTotalHeight = leftTopHeight + insideStoryHeight + 15;
            var addHeight;

            if (insideStoryHeight == null || insideStoryHeight == 0) {
                $("#lefttop, #right").equalizeCols();
            }
            else {
                if (rightHeight > leftTotalHeight) {
                    //Get the height that should be added to right column
                    addHeight = rightHeight - leftTotalHeight;

                    //Get height without margin and padding
                    leftTopHeight = $("#lefttop").height();

                    //Set new height to right column
                    $("#lefttop").css("height", leftTopHeight + addHeight);
                }
                else {
                    //Get the height that should be added to right column
                    addHeight = leftTotalHeight - rightHeight;

                    //Get height without margin and padding
                    rightHeight = $("#right").height();

                    //Set new height to right column
                    $("#right").css("height", rightHeight + addHeight);
                }
            }

            //Equalize subnav to middle content
            $("#subnav, #middle").equalizeCols();
            $("#subnav").css("height", $("#lefttop").height() - 2);
        }

        $(document).bind("fontresize", function() {
            litium.templates.framework.setcolheights();
        });

        return self;
    })(),
    include: (function() {
        var self = {};
        var defaults = { iframeHeight: '600px' };

        self.resize = function(iframe, iframeHeight) {
            try {
                iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
            } catch (e) {
                iframe.style.height = iframeHeight;
            }
        };

        self.init = function(options) {
            ///<summary>
            /// Initialises the resizing of iframes in the document.
            /// Parameters: options: { iframeHeight: height declaration, e.g. '600px' }
            ///</summary>
            var i;
            var iframe;
            var iframes = document.getElementsByTagName('iframe');
            var settings = jQuery.extend({}, defaults, options);
            var onloadValue = 'litium.templates.include.resize(this, \'' + settings.iframeHeight + '\');'

            for (i = 0; iframe = iframes[i]; i++) {
                iframe.setAttribute('onload', onloadValue);
            }
        };

        return self;
    })(),
    intranetStart: (function() {
        var self = {};
        var defaults = {  };

        self.initRssPagination = function(params) {
            $("#" + params.elementId).find("div[class='container']").each(
				function()
				{
					$(this).children(".pager").pagination($(this).children().length -1, {
						callback: handleRssPaginationClick,
						items_per_page: 2,
						num_edge_entries: 0,
						ellipse_text: null,
						next_text: 'n',
						prev_text: 'p',
						prev_show_always: false,
						next_show_always: false
					});
				}
			);
        };
        
        self.initJboPagination = function(params) {
			$("#" + params.elementId).parent().children(".paging").pagination($("ul.jbo li").length, {
						callback: handleJboPaginationClick,
						items_per_page: 3,
						num_edge_entries: 0,
						ellipse_text: null,
						next_text: 'n',
						prev_text: 'p',
						prev_show_always: false,
						next_show_always: false
					});
					
			$("#newsblog ul.tabs li h2 a").click(
				function() {
					equalizeBastards();
				}
			);
        }
        
        function handleJboPaginationClick(new_page_index, pagination_container)
        {
			var children = $("ul.jbo li");
			
			var minIndex = new_page_index * 3;
			var maxIndex = minIndex + 2;
			
			children.each(
				function()
				{
					var currentIndex = $(this).index();
					if(currentIndex >= minIndex && currentIndex <= maxIndex)
						$(this).show();
					else
						$(this).hide();
				}
			);
			
			equalizeBastards();
			
			return false;
		}
		
		function equalizeBastards()
		{
			var focusHeight = 342;
		
			$("#focus").height("auto");
			$("#newsblog").height("auto");
			
			var fHeight = $("#focus").height();
			var nHeight = $("#newsblog").height();
			
			var newHeight = 0;
			if(nHeight > focusHeight)
				newHeight = nHeight + "px";
			else
				newHeight = focusHeight + "px";
			
			
			$("#focus").height(newHeight);
			$("#newsblog").height(newHeight);
		}
        
        function handleRssPaginationClick(new_page_index, pagination_container)
        {
            var children = $(pagination_container).parent().children("div[class*=item]");
			
			var firstIndex = (new_page_index * 2);
			var secondIndex = firstIndex + 1;
			
			children.each(
				function()
				{
					var currentIndex = $(this).index();
					if(currentIndex == firstIndex || currentIndex == secondIndex)
						$(this).show();
					else
						$(this).hide();
				}
			);
			
			equalizeBastards();
			
			return false;
		}

        return self;
    })(),

    orderhistory: (function() {
        var self = {};

        var showOrder = function() {
            var orderId = document.location.hash;
            if (orderId.length > 1) {
                var $order = $(document.location.hash);
                if ($order.length) {
                    $(document.location.hash).show();
                    window.self.location = orderId;
                }
            }
        };

        self.init = function(options) {
            ///<summary>
            /// Initialises the links to order details.
            ///</summary>
            $(document).ready(function() {
                $('ul.orders > li').hide();
                showOrder();

                $('ul.ordermenu > li > a').each(function() {
                    $(this).click(function() {
                        $('ul.orders > li:visible').hide();
                        $($(this).attr('href')).show();
                    });
                });
            });
        };

        return self;
    })(),

    eventList: (function(litium) {
        var that = {};
        var defaults = { currentMonth: 1, selectedMonthFieldId: null, noEventsText: '' };
        var settings = null;

        that.init = function(options) {
            settings = jQuery.extend({}, defaults, options);

            that.initEventMenu();

            var button = $("#c_linkButton" + settings.currentMonth);
            var month = settings.currentMonth;
            while (!button) {
                month++;
                button = $("#c_linkButton" + month);

                if (month > 12)
                    break;
            }

            if (button)
                button.click();
        };

        that.initEventMenu = function() {
            $("body.p-eventlist .selector .months ul li span a").each(function() {
                var href = $(this).attr("href");
                var month = href.replace("?month=", "");
                var count = $(".month_" + month).length;
                if (count == 0) {
                    var text = $(this).text();
                    $(this).parent().empty().text(text).addClass("disabled");
                }
            }
			);
        }

        /// <summary>
        /// Shows all events in provided month and hides the rest
        /// </summary>
        that.showEvents = function(month, sender) {
            $("#" + settings.selectedMonthFieldId).val(month);

            // Select current mont
            $("body.p-calendarlist .selector .months ul li").removeClass("selected");
            $(sender).parent().parent().addClass("selected");

            // Fetch new items to show
            var newItems = $("#hiddenEvents .month_" + month).clone();
            $("#events").empty().append(newItems);

            $("#noEventsMessage").text("");

            // Init the pagination
            if (newItems.length > 10) {
                $(newItems).hide();
                $(".paginationContainer").show();
                that.initPagination(newItems.length);
            }
            else {
                if (newItems.length > 0) {
                    $('#events div.event:first').addClass("first");
                    $(newItems).show();
                    $(".paginationContainer").hide();
                }
                else {
                    $("#noEventsMessage").text(settings.noEventsText);
                }
            }
        }

        that.pageselectCallback = function(page_index, jq) {
            var numPerPage = 10;
            var currentPage = page_index;

            var items = $('#events div.event');
            var lt = $('#events div.event:lt(' + (currentPage * numPerPage) + ')');
            var gt = $('#events div.event:gt(' + ((currentPage + 1) * numPerPage - 1) + ')');

            $('#events div.event').show().end();
            $(lt).hide().end();
            $(gt).hide().end();

            $(items).removeClass("visible").removeClass("first").addClass("visible");
            $(lt).removeClass("visible");
            $(gt).removeClass("visible");
            $('#events div.event.visible:first').addClass("first");

            $("#events div.event:visible").css("border", "1p solid lime");

            return false;
        }

        that.initPagination = function(num_entries) {
            $(".paginationContainer").pagination(num_entries, {
                callback: that.pageselectCallback,
                items_per_page: 10,
                num_edge_entries: 0,
                ellipse_text: null,
                next_text: null,
                prev_text: null
            });
        }

        return that;
    })()
};
