	/* EVENTHANDLER FOR DOMONLOAD
/* ADD FUNCTIONS THAT SHOULD RUN ON DOM LOAD
----------------------------------------------------*/
$(document).ready(function() {
	//##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>##

	$('#promo').RenderPromo();
	$('#aside').RenderSubNavigation();
	$('div.history-list').RenderHistoryNavigation();
	$('table.linear').RenderLinearTables();
	$('.timeline').RenderTimeLine();
	$('.modal-image').RenderImageModal();

	$('div#latest').append('<div id="latest-footer">&nbsp;</div>');
	$('a.ext').attr({
		target: '_blank',
		title: 'Denna sida kommer öppnas i ett nytt fönster.'
	})

	$('.overview-data table').addClass('tbl');
	$('.overview-data table:nth-child(2)').addClass('even');
	$('.overview-data table tr :last-child').addClass('num');

	$('#header,li.other').TextfieldPlaceholders();

	$('a[class*=modal]').ModalPopUp('470');

	$('#latest .dual h2:eq(1)').addClass('dual');

	//##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>##
});


/* RENDER IMAGE MODAL
----------------------------------------------------*/
(function($) {
	$.fn.RenderImageModal = function() {
		$(this).each(function() {
			$(this).bind('click', function(e) {

				var $imageSrc = $(this).attr('href');

				//## CONTAINER
				$('body').append('<div id="modal-container"><a href="javascript:;" id="modal-close"><img src="/templates/images/btn-close.png" alt="" /></a><img src="' + $imageSrc + '" alt="" /></div>');
				$('#modal-container').center();

				//## DIALOG
				$('body').append('<div id="modal-dialog">&nbsp;</div>');
				$('#modal-dialog').css({
					'height': $('body').height(),
					'width': '100%',
					'opacity': '0.7'
				}).bind('click', function(e) {
					$('#modal-container').remove();
					$('#modal-dialog').remove();
				});
				$('#modal-close').bind('click', function(e) {
					$('#modal-container').remove();
					$('#modal-dialog').remove();
				});
				return false;
			});
		});
	};
})(jQuery);


/* CENTER ELEMENT IN VIEWPORT
----------------------------------------------------*/
(function($) {
	$.fn.center = function() {
		return this.each(function() {
			var t = $(this);
			t.css({
				position: 'absolute',
				left: '50%',
				top: '50%'
			}).css({
				marginLeft: '-' + parseInt(t.outerWidth() / 2) + 'px',
				marginTop: '-' + parseInt(t.outerHeight() / 2) + 'px'
			}).css({
				marginTop: parseInt(t.css('marginTop'), 10) + $(window).scrollTop(),
				marginLeft: parseInt(t.css('marginLeft'), 10) + $(window).scrollLeft()
			});
		});
	};
})(jQuery);


/* RENDER TIME LINE
----------------------------------------------------*/
(function($) {
	$.fn.RenderTimeLine = function() {
		$(this).each(function() {
			var $timeline = $(this);
			var $steps = $timeline.find('li').length;
			switch ($steps) {
				case 2: $timeline.find('li').slice(0, 1).addClass('overlap'); break;
				case 3: $timeline.find('li').slice(0, 2).addClass('overlap'); break;
			}
		});
	};
})(jQuery);


/* RENDER LINEAR TABLES
----------------------------------------------------*/
(function($) {
	$.fn.RenderLinearTables = function() {
		var defaults = {

			VisibleColumns: 3

		};
		var options = $.extend(defaults, options);
		var colspan = (options.VisibleColumns + 4);
		$(this).each(function() {
			var $table = $(this);
			$table.find('.graph-col').remove();
			var $cols = $table.find('tr:first').children().length;
			if ($cols >= options.VisibleColumns) {
				$table.find('tr').each(function() {
					var $tr = $(this);
					$tr.children(':first-child').addClass('first');
					$tr.children(':not(:first-child)').addClass('align-right');
					$tr.children().slice(1).addClass('item');
					$tr.children().slice(options.VisibleColumns + 1).hide();
					$tr.children('td:gt(0):not(.hidden):even').addClass('bg');
					if (this.parentNode.tagName.toLowerCase() == 'tbody') {
						var $a = $('<a href="javascript:;">' + $tr.find('th').html() + '</a>');
						var rowId = $tr.attr('id');
						$tr.find('th').html($a);
						$a.bind('click', function(e) {
							var next = $(this).parent().parent().next();
							if (next.attr('id')) {
								$table.find('.graph-col').remove();
								$table.find('.open').removeClass('open');
								$(this).parent().parent().after('<tr class="graph-col" style="display:none;"><td colspan="100"><div id="diagram"></div></td></tr>');
								loadDiagram(rowId);
								$(this).parent().parent().next(':hidden').fadeIn('slow');
							} else {
								$(this).parent().parent().next(':visible').fadeOut('slow');
								$(this).parent().parent().next().remove();
							}
							$(this).toggleClass('open');
						});
					}
				});
				$table.find('thead tr:not(.graph-col) :nth-child(2)').before('<th class="prev"><img src="/templates/images/ico-prev.png" alt="" /></th>');
				$table.find('tbody tr:not(.graph-col) :nth-child(2)').before('<td>&nbsp;</th>');
				$table.find('thead tr:not(.graph-col)').append('<th class="next"><img src="/templates/images/ico-next.png" alt="" /></th>');
				$table.find('tbody tr:not(.graph-col)').append('<td>&nbsp;</th>');
				$table.find('th.prev').bind('click', function(e) {
					if ($(this).next().css('display') == 'none') {
						$table.find('.bg').removeClass('bg');
						$table.find('tr').each(function() {
							$(this).children('.item:visible:last').hide();
							$(this).children('.item:visible:first').prev().show();
							$(this).children('td.item:visible:even').addClass('bg');
						});
					}
				});
				$table.find('th.next').bind('click', function(e) {
					if ($(this).prev().css('display') == 'none') {
						$table.find('.bg').removeClass('bg');
						$table.find('tr:not(.graph-col)').each(function() {
							$(this).children('.item:visible:last').next().show();
							$(this).children('.item:visible:first').hide();
							$(this).children('td.item:visible:even').addClass('bg');
						});
					}
				});
			}
			$table.find('.graph-col td').attr('colspan', colspan).html('<div>' + $table.find('.graph-col td').html() + '</div>')
		});
	};
})(jQuery);


/* loadDiagram - FusionCharts
----------------------------------------------------*/
var loadDiagram = function(rowId) {
	var myChart = new FusionCharts('/Templates/Images/Line.swf', 'lineDiagram', '700', '300', '0', '0');
	var dateStart = $('.timeline').find('select:eq(0) :selected').text();
	var dateEnd = $('.timeline').find('select:eq(1) :selected').text();
	var excelUrl = $('.download-excel').find('a').attr('href');
	excelUrl = Url.encode(excelUrl.substr(excelUrl.indexOf('/')));
	var linkToData = '/Templates/Handlers/ChartData.ashx?path=' + excelUrl + '|lineDiagramNetAssetValue|' + rowId + '|' + dateStart + '|' + dateEnd + '|ExcelUrl';
	if ($('.download-excel').find('a').attr('class').indexOf('pivot') > -1)
		linkToData = linkToData + "|transposed";
	Console.Info('/Templates/Handlers/ChartData.ashx?path=' + excelUrl + '|lineDiagramNetAssetValue|' + rowId + '|' + dateStart + '|' + dateEnd + '|ExcelUrl');
	myChart.setDataURL(linkToData);
	myChart.render(document.getElementById('diagram'));
};


/* RENDER PAGE PROMO
----------------------------------------------------*/
(function($) {
	$.fn.RenderPromo = function() {
		var defaults = {
			FolderPath_DefaultImage: '/templates/images/',
			FolderPath_HoverImage: '/templates/images/color/'
		};
		var options = $.extend(defaults, options);
		var $promo = $(this);
		var $tree = $promo.find('li');
		var $box = $('<div id="promobox"></div>');
		$tree.find('div.text').hide();
		$promo.find('h2 span').css('padding-top', ($promo.find('h2').height() / 2) - $promo.find('h2 span').height() / 2);
		$tree.each(function() {
			$(this).bind('mouseenter', function(e) {
				if ($(this).find('div#promobox').length == 0) {
					var pos = $(this).position();
					$box.css({
						'display': 'block',
						'top': pos.top,
						'left': pos.left
					});
					$box.html($(this).html());
					var currSrc = $box.find('img').attr('src').toString();
					currSrc = options.FolderPath_HoverImage + currSrc.substr(currSrc.lastIndexOf('/') + 1).toString();
					$box.find('div.text').removeAttr('style');
					$box.find('img').attr('src', currSrc);
					$promo.append($box);
				}
			});
		});
		$('#promo').bind('mouseleave', function(e) {
			$('#promobox').delay(2000).fadeOut('fast');
		});
	};
})(jQuery);


/* RENDER SUB NAVIGATION
----------------------------------------------------*/
(function($) {
	$.fn.RenderSubNavigation = function() {
		var $tree = $(this);
		var $triggers = $tree.find('a');
		$tree.find('ul li ul').not('ul.open').hide();
		$tree.find('ul li a + ul').prev().addClass('parent');
		$tree.find('ul.open').prev(':eq(0)').addClass('selected');
		$tree.find('ul.open').prev().not(':eq(0)').addClass('active');
		$triggers.each(function() {
			$(this).bind("click", function(e) {
				var subSections = $(this).parent().find('ul').length;
				if (subSections == 0) {
					return;
				}
				$(this).blur();
				if ((this.className.indexOf('selected') != -1) || (this.className.indexOf('active') != -1)) {
					$(this).parent().find('ul').slideUp('normal');
					$(this).parent().find('a').removeClass('selected');
					$(this).parent().find('a').removeClass('active');
					return;
				}
				var triggerPos = $(this).parents('ul').length;
				if (triggerPos > 0) {
					CancelEvent(e);
					if (triggerPos == 1) {
						$tree.find('ul li ul').slideUp('slow');
						$tree.find('a').removeClass('selected');
						$tree.find('a').removeClass('active');
						$(this).toggleClass('selected');
						var foo = $(this).parent().find('ul').eq(0);
						if (foo[0]) {
							foo[0].style.left = $(this).parent().eq(0).position().left + 'px';
							$(this).parent().find('ul').eq(0).slideDown('slow');
						}
					} else {
						$(this).parent().parent().find('ul').slideUp('slow');
						$(this).parent().find('ul').eq(0).slideDown('slow');
						$(this).parent().parent().find('a').removeClass('active');
						if ($(this).next('ul').length > 0) {
							$(this).toggleClass('active');
						}
					}
				}
			});
		});
	};
})(jQuery);


/* RENDER HISTORY NAVIGATION
----------------------------------------------------*/
(function($) {
	$.fn.RenderHistoryNavigation = function() {
		var defaults = {

			VisibleColumns: 5

		};
		var options = $.extend(defaults, options);
		var colspan = (options.VisibleColumns - 1);

		var $parent = $(this);
		if ($parent.length == 0) return;
		var $ul = $parent.find('ul');
		var maxWidth = parseInt($($ul).parent().width());
		var currList = $ul.html();
		var index = 0;
		$($ul).html('<li class="prev"><a href="javascript:;"><span>Föregående</span></a></li><li class="years"><ul>' + currList.toString() + '</ul></li><li class="next"><a href="javascript:;"><span>Nästa</span></a></li>');
		var scrollWidth = parseInt(maxWidth - parseInt($($ul).find('.prev').width())) - parseInt($($ul).find('.next').width());
		var currWidth = $ul.find('li.years').width();
		$ul.find('li.years').css('width', scrollWidth);
		$ul.find('li.years ul').css('width', currWidth);

		var activeYear = $ul.find('li.active');
		if (activeYear.size) {
			var next = activeYear.nextAll();
			var prev = activeYear.prevAll();
			var nextSize = parseInt(next.length);
			var nextIndex = 2;
			var prevSize = parseInt(prev.length);
			var prevIndex = 2;
			if (nextSize < 3) {
				switch (nextSize) {
					case 2: prevIndex = 2; break;
					case 1: prevIndex = 3; break;
					case 0: prevIndex = 4; break;
				}
			}
			if (prevSize < 3) {
				switch (prevSize) {
					case 2: nextIndex = 2; break;
					case 1: nextIndex = 3; break;
					case 0: nextIndex = 4; break;
				}
			}
			next.hide().filter(function(index) {
				if (index < nextIndex) $(this).show();
			})
			prev.hide().filter(function(index) {
				if (index < prevIndex) $(this).show();
			})
		} else {
			$ul.find('li.years ul li').each(function(cnt) {
				if (cnt > colspan) {
					$(this).hide();
				}
			});
		}
		$ul.find('li.prev a').click(function(e) {
			CancelEvent(e);
			var next = $ul.find('li.years ul li:visible:first').prev().size();
			if (next == 1) {
				$ul.find('li.years ul li:visible:first').prev().show();
				$ul.find('li.years ul li:visible:last').hide();
			}
		});
		$ul.find('li.next a').click(function(e) {
			CancelEvent(e);
			var next = $ul.find('li.years ul li:visible:last').next().size();
			if (next == 1) {
				$ul.find('li.years ul li:visible:first').hide();
				$ul.find('li.years ul li:visible:last').next().show();
			}
		});
	};
})(jQuery);


/* Textfield Placeholders - jQuery Plugin
* Author: Palle Zingmark, www.palleman.nu
* Released with the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
	$.fn.TextfieldPlaceholders = function() {
		return this.each(function() {
			var $parent = $(this);
			$parent.find('input:text[value=""]').each(function(i) {
				var $input = $(this);
				var $placeholder = $($input).attr('placeholder');
				var $basecolors = ['#000000', 'rgb(0, 0, 0)'];
				var $color = $($input).css('color');
				var $hascolor = jQuery.inArray($color, $basecolors);
				if (typeof $placeholder == 'undefined' || $placeholder == '') {
					$placeholder = $parent.find('label[for="' + $($input).attr('id') + '"]').text();
				}
				if (typeof $placeholder == 'string' || $placeholder != '') {//## OR ABORT
					$($input).attr('value', $placeholder);
					$($input).attr('title', $placeholder);
					if ($hascolor || $hascolor != -1) {
						$(this).css('color', '#aeaeae');
					}
					$($input).bind('focus', function() {
						if ($(this).attr('value') == $placeholder) {
							$(this).attr('value', '');
							$(this).css('color', $color);
						}
					}).bind('blur', function() {
						if ($(this).attr('value') == $placeholder || $(this).attr('value') == '') {
							$(this).attr('value', $placeholder);
							if ($hascolor || $hascolor != -1) {
								$(this).css('color', '#aeaeae');
							}
						}
					});
				}
			});
		});
	};
})(jQuery);


/* MODAL POPUP
---------------------------------------------------*/
(function($) {
    $.fn.ModalPopUp = function(modalWidth) {
        $(this).each(function() {
            $(this).bind('click', function(e) {
                var $class = $(this);
                $('body').append('<div id="fade"></div>');
                var $fade = ('#fade');
                $($fade).css({ width: $(window).width(), height: $(document).height(), opacity: 0 });
                $($fade).fadeTo('normal', 0.7, function() {
                    $('body').append('<div id="modal" class="modal"><span id="close"><span>Close X</span></span></div>');
                    var $modal = ('#modal');
                    var $close = ('#close');
                    $($modal).css({
                        top: '200px',
                        left: $(window).width() / 2 - modalWidth / 2 + 'px',
                        width: modalWidth + 'px'
                    });
                    if ($class.hasClass('modal-form-selector')) {
                        $.ajax({
                            type: "GET",
                            url: "/Templates/Javascript/form-selector.js",
                            cache: false,
                            data: "{ }",
                            contentType: "applicationjson; charset=utf-8",
                            dataType: "json",
                            beforeSend: function() {
                                $($modal).addClass('loading');
                            },
                            error: function() {
                                $($modal).append('<span class="error">Something went wrong. Please update your browser</span>');
                            },
                            success: function(result) {
                                $(result).each(function(i, obj) {
                                    $($modal).append(obj.header);
                                    $($modal).append(obj.body);
                                    $($modal).append('<ul id="form-selector"><li><a href="#" title="' + obj.pri + '">' + obj.pri + '</a></li><li class="pro"><a href="#" title="' + obj.pro + '">' + obj.pro + '</a></li></ul>');
                                });
                            },
                            complete: function() {
                                $($modal).removeClass('loading');
                            }
                        });
                    }
                    $(window).resize(function() {
                        $($fade).css({ width: $(window).width(), height: $(document).height() });
                        $($modal).css({ left: $(window).width() / 2 - modalWidth / 2 });
                    });
                    $($fade + ', #close').bind('click', function() {
                        $($fade).nextAll().remove();
                        $($fade).remove();
                    });
                });
                return false;
            });
        });
    };
})(jQuery);


/* DELAY
----------------------------------------------------*/
(function($) {
	$.fn.delay = function(time, callback){
		jQuery.fx.step.delay = function(){};
		return this.animate({delay:1}, time, callback);
	};
})(jQuery);


/* WRITE TO FIREBUG CONSOLE
----------------------------------------------------*/
var Console = function() {
	return {
		Log: function(msg, args) { if (typeof console == 'undefined') return false; if (!args) args = ''; console.log(msg, args) },
		Info: function(msg, args) { if (typeof console == 'undefined') return false; if (!args) args = ''; console.info(msg, args) },
		Warn: function(msg, args) { if (typeof console == 'undefined') return false; if (!args) args = ''; console.warn(msg, args) },
		Error: function(msg, args) { if (typeof console == 'undefined') return false; if (!args) args = ''; console.error(msg, args) }
	}
} ();


/* CANCEL EVENT
----------------------------------------------------*/
function CancelEvent(e) {
	try {
		if (e) {
			e.returnValue = false;
			e.cancelBubble = true;
			if (e.stopPropagation) {
				e.stopPropagation();
			}
			if (e.preventDefault) {
				e.preventDefault();
			}
		}
	} catch (c) { alert(c); }
	return false;
}


/* GET QUERYSTRING
----------------------------------------------------*/
var getQuerystring = function(attrib) {
	var x = window.location.search.substring(1);
	var z = x.split('&');
	for (var i = 0, n = z.length; i < n; i++) {
		var hit = z[i].split('=');
		if (hit[0] == attrib) {
			return hit[1];
		}
	}
};


/* URL ENCODE
----------------------------------------------------*/
var Url = {
	encode: function(string) {
		return escape(this._utf8_encode(string));
	},
	decode: function(string) {
		return this._utf8_decode(unescape(string));
	},
	_utf8_encode: function(string) {
		string = string.replace(/\r\n/g, "\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}else if ((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},
	_utf8_decode: function(utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while (i < utftext.length) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if ((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i + 1);
				c3 = utftext.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}
