﻿$(function()
{

	$(".aModuleNormalListItemLink[href$='.pdf']").addClass('aModuleNormalListItemLink pdf');

	$(".Documents .Category .Category_plus .plus").click(function(){

		$(this).parent().parent().next().toggleClass('Lokad');

		$(this).parent().parent().toggleClass('Lokad');

		var src = ($(this).find('img').attr("src") === "Themes/Landsnet2008/Images/document/document_minus.gif") ? "Themes/Landsnet2008/Images/document/document_plus.gif" : "Themes/Landsnet2008/Images/document/document_minus.gif";

		$(this).find('img').attr("src",src);
      
		return false;     
	});

});

$(document).ready(function()
{
	fixBrokenLinks();
	conceptList();
	clickZoomImages();
	fixPngs();
	populateSearchbox();
	populateSearchboxEN();
	fontsizer();
	DDBlinds();

	if ($('.RightPane #SModulePostList').length) fixPostListGap();
	if ($('.netmali .col dl').length) setEqHeights();
	if ($('#SearchBox input[type=text]').length) altSearchBoxOnSearchsite();
	if ($('#SearchBoxEN input[type=text]').length) altSearchBoxOnSearchsiteEN();
	if ($('.LNMessages').length) openMsg();
	if ($('.LNContactForm').length) contactFormValidation();

	/* Hijack the __doPostBack function from asp.net to be able to use jQuery.submit(fn) event */
	window.__doPostBack = function(eventTarget, eventArgument)
	{
		var originalvalues = [
             theForm.__EVENTTARGET.value,
             theForm.__EVENTARGUMENT.value
         ];
		theForm.__EVENTTARGET.value = eventTarget;
		theForm.__EVENTARGUMENT.value = eventArgument;
		try
		{
			$(theForm).submit();
		}
		finally
		{
			theForm.__EVENTTARGET.value = originalvalues[0];
			theForm.__EVENTARGUMENT.value = originalvalues[1];
		}
	}
});

// this is put in place to fix download links and image links that don't begin with a slash (/) and so are
// broken because of the friendly url. Mainly for links in news and LNMessages that are legacy content of the old site
function fixBrokenLinks()
{
	$('a').each(function()
	{
		if (typeof $(this).attr('href') != 'undefined')
		{
			if ($(this).attr('href').search(/uploads/i) == 0) $(this).attr('href', '/' + $(this).attr('href'));
		}
	});

	$('img').each(function()
	{
		if (typeof $(this).attr('src') != 'undefined')
		{
			if ($(this).attr('src').search(/uploads/i) == 0) $(this).attr('src', '/' + $(this).attr('src'));
		}
	});
}

// a generic script to embed flash
function embedFlash(flashurl, width, height, elementid)
{
	if (!document.getElementById(elementid))
	{
		alert("Flash element does not exist on page, flash will not be inserted");
		return false;
	}

	var flashvars = {};
	var params = {
		wmode: 'transparent'
	};

	swfobject.embedSWF(flashurl, elementid, width, height, "9.0.0", "/Themes/Landsnet2008/flash/playerProductInstall.swf", flashvars, params);
}

// to run flashvideos on site, not called on load above, rather by inline script on the site supposed to play the video
function runVideo(videourl, width, height, elementid, preview)
{
	if (typeof elementid == 'undefined' || elementid == '') elementid = 'flashvid';
	if (typeof preview == 'undefined') preview = '/Uploads/videos/previews/defaultpreview.png';

	if (width > 695) width = 695;
	height = Number(height) + 19; // account for player gui

	var flashvars = {
		file: videourl,
		image: preview
	};
	var params = {
		allowfullscreen: 'true',
		allowscriptaccess: 'always',
		wmode: 'transparent'
	};

	swfobject.embedSWF("/Themes/Landsnet2008/flash/player.swf", elementid, width, height, "9.0.0", "/Themes/Landsnet2008/flash/playerProductInstall.swf", flashvars, params);	
}

// this is a bit of a hack for the post list modules that are in the right column of the site. This is done to enable a content module
// with description above the postlist module. This requires two modules on the right, but this script makes it appear as one module
// visually, cutting the bottom shadow of the upper module and setting padding to zero so the bottom module goes up to the lower one
// and they form a unity visually
function fixPostListGap()
{
	if ($('#SModulePostList').prev().is('div.ContentDisplay')) $('#SModulePostList').prev().css('background', 'transparent none').css('padding', '0').css('margin', '0');
}

// some functionality for the search box on the search results site
function altSearchBoxOnSearchsite()
{
	var box = $('#SearchBox input[type=text]');
	var location = document.location.href;

	// make the box work on enter
	box.keypress(function(e)
	{
		if (e.which == 13)
		{
			if (location.indexOf('query=') > 0)
			{
				document.location = location.substring(0, location.indexOf('query=')) + 'query=' + $(box).val();
			}
			else
			{
				document.location = location + '?query=' + $(box).val();
			}
			return false;
		}
	});

	// translate the search button
	$('#SearchBox input[type=submit]').attr("value", "Leita").css("text-indent", 0);

	// put text in box
	var text = "Sláðu inn leitarorð til að endurtaka leit";
	
	box.val(text);

	box.focus(function()
	{
		if (box.val() == text) box.val('');
	});

	box.blur(function()
	{
		if (box.val() == '') box.val(text);
	});
}

// some functionality for the search box on the search results site
function altSearchBoxOnSearchsiteEN()
{
	var box = $('#SearchBoxEN input[type=text]');
	var location = document.location.href;

	// make the box work on enter
	box.keypress(function(e)
	{
		if (e.which == 13)
		{
			if (location.indexOf('query=') > 0)
			{
				document.location = location.substring(0, location.indexOf('query=')) + 'query=' + $(box).val();
			}
			else
			{
				document.location = location + '?query=' + $(box).val();
			}
			return false;
		}
	});

	// translate the search button
	$('#SearchBoxEN input[type=submit]').attr("value", "Search").css("text-indent", 0);

	// put text in box
	var text = "Enter new term and repeat the search";
	
	box.val(text);

	box.focus(function()
	{
		if (box.val() == text) box.val('');
	});

	box.blur(function()
	{
		if (box.val() == '') box.val(text);
	});
}

// sets equal heights to columns in netmali
function setEqHeights()
{
	var cols = $('.netmali .col dl');
	var dlHeight = 0;

	cols.each(function()
	{
		if ($(this).height() > dlHeight) dlHeight = $(this).height();
	});
	
	cols.css('height', dlHeight);
}

// sets a default text in searchbox in header of site
function populateSearchbox()
{
	if (!$('#GlobalSearch .SearchBox').length) return false;

	var searchbox = $('#GlobalSearch .SearchBox');

	var text = "Leita á landsnet.is";

	if ($('#GlobalSearch').hasClass('englishSearch'))
	{
		text = "Search Landsnet";
	}

	searchbox.val(text);

	searchbox.focus(function() 
	{
		if (searchbox.val() == text) searchbox.val('');
	});

	searchbox.blur(function()
	{
		if (searchbox.val() == '') searchbox.val(text);
	});

	$("form").bind("submit", function()
	{	
		if (searchbox.val() == text) searchbox.val('');
	});
}

// sets a default text in searchbox in header of site
function populateSearchboxEN()
{
	if (!$('#GlobalSearchEN .SearchBox').length) return false;

	var searchbox = $('#GlobalSearchEN .SearchBox');
	var text = "Search on landsnet.is";

	searchbox.val(text);

	searchbox.focus(function() 
	{
		if (searchbox.val() == text) searchbox.val('');
	});

	searchbox.blur(function()
	{
		if (searchbox.val() == '') searchbox.val(text);
	});

	$("form").bind("submit", function()
	{	
		if (searchbox.val() == text) searchbox.val('');
	});
}

// fix pngs in content for IE6
function fixPngs() 
{
	if (!$('.subsite-maincontent img').length) return false;
	if ($('#landsnet-content a.clickzoomimage').length) return false;

	// beware that jquery returns '6.0' as user agent version for IE7 vista home, therefore we use this condition
	if ($.browser.msie && /MSIE 6\.0/i.test(window.navigator.userAgent) && !/MSIE 7\.0/i.test(window.navigator.userAgent))
	{
		$(document).pngFix();
	}
}

// function for the zoom images function, attaches the fancybox plugin to imagelinks with class clickzoomimage
function clickZoomImages()
{
	if (!$('#landsnet-content a.clickzoomimage').length) return false;

	if ($('#landsnet-content div.img-collection').length)
	{
		$('#landsnet-content div.img-collection>span').remove().appendTo($('#landsnet-content div.img-collection>a:first'));
	}
	
	var clickzoomimages = $('#landsnet-content a.clickzoomimage');

	clickzoomimages.fancybox({
		'hideOnContentClick': true,
		'zoomSpeedIn': 250,
		'zoomSpeedOut': 400
	});
}

// functions for concept list and QnA, makes enter button work in searchbox and handes some cosmetic issues
function conceptList()
{
	if (!$("#conceptList").length) return false;

	//$("#conceptList div.ConceptDetail").css("display", "none");
	
	var adminLinks = $(".ConceptItemAdminLinks, .ConceptItemLinks");
	var searchBox = $(".ConceptSearchbox");
	var searchBtn = $(".ConceptBtn");
	
	adminLinks.each(function()
	{
		if ($(this).children().length == 0) $(this).css("display", "none");
	});

	searchBox.keypress(function(e)
	{
		if (e.which == 13)
		{
			document.location = searchBtn.attr("href");
			return false;
		}
	});
}

// function to slide open divs containing more information on a term, used for example on the concept list and
// the LNMessages list. DDBlinds is a generic class collection assigned to all elements supposed to have this functionality
function DDBlinds()
{
	if (!$('.DDBlindsContainer .DDBlindsTrigger').length) return false;
	
	$('.DDBlindsContainer .DDBlindsTrigger').click(function()
	{
		$(this).next().slideToggle("fast").toggleClass("open").end().toggleClass("open");

		return false;
	});
}

// takes a message id in an url parameter and opens the corresponding msg in the LNMessages section
function openMsg()
{
	var params = document.location.search;

	if (params.toLowerCase().indexOf('messageid=') > 0)
	{
		var id = params.substr(params.toLowerCase().indexOf('messageid=') + 10);
	}

	$('#' + id + ' .DDBlinds').css('display', 'block');
}

// basic javascript validation for the contact form
function contactFormValidation()
{
	$('.LNContactFormSend').click(function()
	{
		if ($('.LNContactForm #errors').length)
		{
			$('.LNContactFormFields :text, .LNContactFormFields textarea').removeClass('warning');
			$('.LNContactForm #errors').remove();
		}

		var errors = 0;
		$('.LNContactFormFields :text, .LNContactFormFields textarea').each(function()
		{
			if ($(this).val() == '')
			{
				if (errors == 0) $('<div id="errors"><p>Athugaðu að fylla út í alla reiti</p></div>').prependTo('.LNContactFormFields');
				$(this).addClass('warning');
				errors++;
			}
		});
		return (errors === 0);
	});
}

/** FONT RESIZING FUNCTIONS **/
// handles font resizing functions
function fontsizer()
{
	var txtBigger = "Smelltu til að stækka letur";
	var txtSmaller = "Smelltu til að minnka letur";

	// Athuga tungumal.. athugad med klasa á leitarglugga
	if ($('#GlobalSearch').hasClass('englishSearch'))
	{
		txtBigger = "Click here for larger fonts";
		txtSmaller = "Click here for smaller fonts";
	}	




	var container = $(".header-links");
	if (!container.length) return false;

	container.append("<li><a href=\"/\" title=\"" + txtBigger + "\" class=\"font-larger\">A +</a><a href=\"/\" title=\"" + txtSmaller + "\" class=\"font-smaller\">A -</a></li>");

	var linksmaller = $("a.font-smaller");
	var linkbigger = $("a.font-larger");

	var cookie = readCookie("landsnet.is-fontsize");
	if (cookie)
	{
		setSize(cookie);

		if (cookie == 2) makeInactive(linkbigger);
		if (cookie == 0) makeInactive(linksmaller);
	}
	else makeInactive(linksmaller);


	linksmaller.click(function()
	{
		if (getSize() == 1)
		{
			setSize(0);
			makeInactive(linksmaller);
		}
		if (getSize() == 2)
		{
			setSize(1);
			makeActive(linkbigger);
		}

		return false;
	});

	linkbigger.click(function()
	{
		if (getSize() == null)
		{
			setSize(1);
			makeActive(linksmaller);
		}
		else if (getSize() == 1)
		{
			setSize(2);
			makeInactive(linkbigger);
		}

		return false;
	});
}

// puts class inactive on the element sent in
function makeInactive(elem)
{
	elem.addClass("inactive");
}

// removes class inactive on the element sent in
function makeActive(elem)
{
	elem.removeClass("inactive");
}

function getSize()
{
	var body = $('body');

	if (body.hasClass('fontsize1')) return 1
	else if (body.hasClass('fontsize2')) return 2
	else return null;
}

function setSize(size)
{
	var body = $('body');

	if (size == 1) body.removeClass('fontsize2').addClass('fontsize1');
	else if (size == 2) body.removeClass('fontsize1').addClass('fontsize2');
	else body.removeClass('fontsize1').removeClass('fontsize2');

	createCookie("landsnet.is-fontsize", size, 365);
}

// Cookie functions
function createCookie(name, value, days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}
//end cookie functions
/** END OF FONT RESIZING FUNCTIONS **/

/* FUNCTIONS FOR LNSCHEDULEOVERVIEW */
function showDetail(node, html)
{
	var detailview = $('#detailView');
	var node = $(node);
	
	// highlight table cell and add html into popup
	node.addClass('highlight');
	document.getElementById('detailView').innerHTML = html; /* IE is retarded, something went wrong in injecting this with jQuery, works the old way */

	// find position of table cell, make variables representing the coordinates of the popup
	var nodepos = node.position();
	var popuptoppos = nodepos.top - 30;
	var popupleftpos = nodepos.left + node.outerWidth() - 8;

	// find table boundaries
	var tablepos = $('#schedule').position();
	var tableoffset = $('#schedule').offset();
	var tableboundaryright = tableoffset.left + $('#schedule').width();
	var tableboundarybottom = tableoffset.top + $('#schedule').height();

	// find popup boundaries, so it doesn't go outside the viewport
	var popupboundaryright = tableoffset.left + popupleftpos + detailview.outerWidth() + 10;
	var popupboundarybottom = tableoffset.top - tablepos.top + popuptoppos + detailview.outerHeight() + 10;

	// change popups position so it doesn't go outside the viewport
	if (popupboundaryright > tableboundaryright) popupleftpos = popupleftpos - node.outerWidth() - detailview.width();
	if (popupboundarybottom > tableboundarybottom || popupboundarybottom > $(window).height()) 
		popuptoppos = nodepos.top - detailview.outerHeight() + node.outerHeight() + 5;
	
	// set position and display popup
	detailview.css('top', popuptoppos + 'px').css('left', popupleftpos + 'px').css('display', 'block');

	// color first row and heading
	node.parent().find(':first-child').addClass('highlightRow');

	var children = $.makeArray(node.parent().children());
	var i = 0; do { i++; } while (!$(children[i]).hasClass('highlight')); i = i + 1;
	$('#schedule th:nth-child(' + i + ')').addClass('highlightCol');
	
}
function hideDetailView(node)
{
	$('#detailView').css('display', 'none');
	$(node).removeClass('highlight');
	$(node).parent().find(':first-child').removeClass('highlightRow');
	$('#schedule th').removeClass('highlightCol');
}
/* END OF FUNCTIONS FOR LNSCHEDULEOVERVIEW */
