$().ready(function(){

	
	$("#footerContacts select").jListbox();
	
	if (jQuery.browser.msie)
	{
		var browserVersion = parseInt(jQuery.browser.version);
		if (browserVersion < 7)
		{
			var imgSrc = new String($("#logo").attr("src"));
			imgSrc = imgSrc.replace(".png", "_ie.png");
			$("#logo").attr("src", imgSrc);
		}
	}
	
	// Nyhetsbrev
	$("form#footerNewsletter input[type='text']").each(function() {
	
		if($(this).val() === '') {
			$(this).val($(this).attr('title'));
		}
	
		$(this).focus(function() {
			if($(this).val() === $(this).attr('title')) {
				$(this).val('').addClass('focused');
			}
		});
	
		$(this).blur(function() {
			if($(this).val() === '') {
				$(this).val($(this).attr('title')).removeClass('focused');
			}
		});
	});
	
	
	$(".offerFront").each(function(){
		
		var url = $(this).find("h2 a").attr("href");
		var offer = ($(this).parent().hasClass("mainOffer")) ? $(this).parent() : $(this);

		offer.click(function() {
			window.location = url;
		})
		
	});
	
	
	$(".article").each(function(){
		
		var url = $(this).find("h2 a").attr("href");

		$(this).click(function() {
			window.location = url;
		})
		
	});	
	
	
	$("form#footerContacts select").change(function(){
		if ($(this).find("select").val() != 0)
		{
			window.location = $(this).find("select").val();
		}
		return false;
	});
	
	
	$("form#footerNewsletter").submit(function()
	{
		
		$(this).find("input[type='text']").each(function() {
			if($(this).val() == $(this).attr('title')) 
			{
				$("form#footerNewsletter .messageContainer").html("Begge feltene må være korrekt utfyllt").show();
				alert("feil");
				return false;
			}
		});
		
		var email = $(this).find("input[name='email']").val();
		var name = $(this).find("input[name='name']").val();
		
		if (!validateEmail(email) || name == '')
		{
			$(this).find(".messageContainer").html("Begge feltene må være korrekt utfyllt").show();
			return false;
		}
		
		else
		{
			$(this).find(".messageContainer").html("Sender påmelding...").show();
			$(this).find("input").attr("disabled", "disabled").fadeTo(500, 0.25).css({backgroundColor: "#444"});

			$.post(
				$(this).attr("action"),
				{
					action: "ajaxNewsletter",
					email: email,
					name: name
				},
				function(data, textStatus)
				{
					if (textStatus == 'success' && data == 'OK')
					{
						$("form#footerNewsletter").find(".messageContainer").html("Takk for din påmelding!");
						$("form#footerNewsletter").find("input").removeAttr("disabled").fadeTo(500, 1).css({backgroundColor: "#000"});
					}
					else
						$("form#footerNewsletter").find(".messageContainer").html("Det oppstod en feil");
				}
			);
			
			return false;
		}
		
	});
	
	
});



function validateEmail(emailAddress) 
{
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);				
}



var curtainAction = false;

function setStyle(style, add, change)
{
	if (style == '' && !add)
		return '';
		
	styleArray = style.split(' ');
	newStyleArray = new Array();
	
	for (var n=0; n<styleArray.length; n++)
		if (styleArray[n] != change)
			newStyleArray[newStyleArray.length] = styleArray[n];
			
	if (add)
		newStyleArray[newStyleArray.length] = change;
		
	var	newStyle = '';
	for (var n=0; n<newStyleArray.length; n++)
	{
		if (newStyle != '')
			newStyle = newStyle + ' ';
		newStyle = newStyle + newStyleArray[n];
	}
	
	return newStyle;				
}

function setStyleById(id, classId, add)
{
	
	var element = document.getElementById(id);

	if (element)
		element.className = setStyle(element.className, add, classId);
	
}



function showGallery(targetId, galleryId)
{
	menuId = targetId + 'Menu';
	var menu = document.getElementById(menuId);
	menu.style.display = "none";

	var div = document.getElementById(targetId);
	setStyleById(targetId, 'largeImageGallery', true);

	fadeGallery(targetId, galleryId, true);
}


function fadeGallery(targetId, galleryId, show)
{

	var id = targetId;

	var div = document.getElementById(id);
	var image = document.getElementById(id + 'StartImage');
		
	var targetHeight = 440;	
	var targetOpacity = 0;
	
	var heightPx = new String(div.style.height);
	var heightPx = heightPx.substr(0, 3);
	var height = heightPx * 1;
	
	if(height < 300)
		height = 300;

	var	newHeight = height;
	
	var diffHeight = Math.ceil((targetHeight - height) / 3);
	
	newHeight = height + diffHeight;
	newOpacity = 100 - Math.floor(((newHeight - 300) / (targetHeight - 300)) * 100);

	if (Math.abs(newHeight - targetHeight) <= 1)
	{
		newHeight = targetHeight;
		newOpacity = targetOpacity;
	}

	div.style.height = newHeight + 'px';

	setOpacity(image, newOpacity);

	if (Math.abs(newHeight - targetHeight) <= 1)
		startGallery(targetId, galleryId);
	else
		window.setTimeout("fadeGallery('" + targetId + "','" + galleryId + "','" + show + "')", 1);	
	
}

function setOpacity(object, opacity)
{

	if (!object)
		return;
	
	object.style.filter = "alpha(opacity:" + opacity + ")";	// IE/Win
	object.style.KHTMLOpacity = opacity / 100;				// Safari<1.2, Konqueror
	object.style.MozOpacity = opacity / 100;					// Older Mozilla and Firefox
	object.style.opacity = opacity / 100;					// Safari 1.2, newer Firefox and Mozilla, CSS3
}


function startGallery(targetId, galleryId)
{

	var containerDivId = galleryId + '_container';

	// Flytter galleri til startposisjon
	var galleryImages = document.getElementById(galleryId + '_images');
	galleryImages.style.left = '700px';
	
	
	// Henter inn div fra content
	var targetDiv = document.getElementById(targetId);
	var containerDiv = document.getElementById(containerDivId);
	
	// Putter startbilde i content
	var content = containerDiv.innerHTML;
	containerDiv.innerHTML = targetDiv.innerHTML;	
	
	// Legger galleri i target
	targetDiv.innerHTML = content;
	
	// Flytter innhold til høyre
	galleryNext(galleryId);
	
}


function galleryGetInfo(galleryId)
{

	var divId = galleryId + '_images';
	var div = document.getElementById(divId);

	// posisjon
	var posPx = new String(div.style.left);
	posPx = posPx.substr(0, posPx.length - 2);
	var pos = posPx * 1;

	// bredde
	var widthPx = new String(div.style.width);
	widthPx = widthPx.substr(0, widthPx.length - 2);
	var width = widthPx * 1;
	
	// antall bilder
	var imgCount = Math.ceil(width / 700);
	
	// bildeNo
	var imgNo = Math.floor(0 - pos / 700) + 1;
	
	// i bevegelse
	var moving = (0 - ((imgNo - 1) * 700) != pos);
	
	var result = new Array(imgNo, imgCount, pos, width, moving);
	
	return result;

}


function galleryGetPos(galleryId)
{

	var divId = galleryId + '_images';
	var div = document.getElementById(divId);

	var posPx = new String(div.style.left);
	var posPx = posPx.substr(0, posPx.length - 2);
	var pos = posPx * 1;

	return pos;

}


function galleryNext(galleryId)
{
	var info = galleryGetInfo(galleryId);
	
	if (info[4] || info[0] == info[1])
		return false;
		
	// skjuler knapp hvis siste bilde
	var button = document.getElementById(galleryId + '_next');
	button.style.display = (info[0] > info[1] - 3) ? 'none' : 'inline';

	button = document.getElementById(galleryId + '_prev');
	button.style.display = (info[0] < 1) ? 'none' : 'inline';
	
	var newPos = 0 - (info[0] * 700);

	galleryScroll(galleryId, info[2], newPos, true, info[0] + 1, info[0]);

}


function galleryPrev(galleryId)
{
	var info = galleryGetInfo(galleryId);

	if (info[4] || info[0] <= 1)
		return false;

	// skjuler knapp hvis siste bilde
	var button = document.getElementById(galleryId + '_prev');
	button.style.display = (info[0] <= 2) ? 'none' : 'inline';

	button = document.getElementById(galleryId + '_next');
	button.style.display = 'inline';
	
	var newPos = 0 - ((info[0] - 2) * 700);
	
	galleryScroll(galleryId, info[2], newPos, true, info[0] - 1, info[0]);
}


function galleryScroll(galleryId, startPos, stopPos, start, showPicNo, hidePicNo)
{
	var divId = galleryId + '_images';
	var div = document.getElementById(divId);
	
	var dir = (startPos > stopPos);
	
	if (start)
		window.galleryScrollDirection = dir;
	else if (window.galleryScrollDirection != dir)
	{
		alert('feilveg');
		return false;
	}

	var showPic = document.getElementById(galleryId + '_image' + showPicNo);
	var hidePic = document.getElementById(galleryId + '_image' + hidePicNo);

	// Skjuler bilde som skal vises
	if (start)
		setOpacity(showPic, 0)
	
	var posPx = new String(div.style.left);
	var posPx = posPx.substr(0, posPx.length - 2);
	var pos = posPx * 1;
	
	if (isNaN(pos))
		return;
		
	// Finner ny opacity
	var newOpacityOut = Math.floor(((Math.abs(pos - stopPos) * 3) / Math.abs(startPos - stopPos)) * 100);
	var newOpacityIn = 100 - Math.floor(((Math.abs(pos - stopPos) * 2) / Math.abs(startPos - stopPos)) * 100);

	setOpacity(showPic, newOpacityIn);
	
	if(hidePic)
		setOpacity(hidePic, newOpacityOut);
	
	diffPos = Math.ceil((pos - stopPos) / 5);

	if (diffPos == 0)
		diffPos = -1;

	pos -= diffPos;
		
	div.style.left = pos + 'px';
	
	if (pos != stopPos)
		window.setTimeout("galleryScroll('" + galleryId + "', " + startPos + "," + stopPos + ", false," + showPicNo + "," + hidePicNo + ")", 10);	
	
}






var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{	// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 	// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();

function browserOk()
{
	
	switch (BrowserDetect.browser)
	{
		case 'Opera':
			return (BrowserDetect.version >= 9);
			
		case 'Explorer':
			return (BrowserDetect.version >= 6);
			
		case 'Firefox':
			return true;
			
		case 'Safari':
			return true;
			
		default:
			return false;
	}
		
}

function logoswap(id, active)
{ 
	var image = document.getElementById("logo" + id);
	var activefilename = (active) ? '_active' : '';
	image.src = "/graphics/" + id + activefilename + ".png";
}

function showCurtain() 
{
	if (!browserOk())
		return;
		
	var obj = document.getElementById("curtain");
	obj.style.display = "block";
	fadeInCurtain(0);
	
	switch (BrowserDetect.browser)
	{
		case 'Opera':
		case 'Firefox':
		case 'Safari':
			setInterval("moveCurtain()", 1000);
			break;
	}
}

var curtainOpacity = 0;
var curtainFadeIn = true;

function hideCurtain() 
{
	fadeOutCurtain();
}


function setOpacity(obj, opacity) 
{
	opacity = (opacity == 100) ? 99.999 : opacity;

	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
	// Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}

function fadeInCurtain()
{
	curtainFadeIn = true;
	fadeCurtain();
}

function fadeOutCurtain()
{
	curtainFadeIn = false;
	fadeCurtain();
}

function fadeCurtain()
{
	obj = document.getElementById("curtain");

	if (curtainFadeIn && curtainOpacity <= 0)
		obj.style.display = "block";

	if (!curtainFadeIn && curtainOpacity > 0)
	{
		setOpacity(obj, curtainOpacity);
		curtainOpacity -= 20;
		window.setTimeout("fadeCurtain()", 10);
	}

	else if (!curtainFadeIn && curtainOpacity <= 0)
		obj.style.display = "none";

	else if (curtainFadeIn && curtainOpacity < 60)
	{
		setOpacity(obj, curtainOpacity);
		curtainOpacity += 20;
		window.setTimeout("fadeCurtain()", 10);
	}

}

function moveCurtain()
{
	var obj = document.getElementById("curtain");
	obj.style.top = window.pageYOffset + "px";

	if (curtainOpacity > 5)
		window.setTimeout("moveCurtain()", 200);
}



function showMessage(title, text)
{

	curtainAction = 'message';
	
	div = document.getElementById('message');
	div.innerHTML = '<h1>' + title + '</h1><p>' + text + '</p><p><img src="/graphics/searching.gif"></p><p><a href="" onClick="stopPageload();hideMessage();return false;">Avbryt</a>';
	div.style.display = "block";

	setStyleById('message', 'hidden', true);
	showCurtain();


}

function hideMessage()
{

	div = document.getElementById('message');
	div.innerHTML = '';
	div.style.display = "none";

	if (curtainAction == 'message')
		curtainAction = false;
		
	hideCurtain();
}

function stopPageload()
{


	switch (BrowserDetect.browser)
	{
		case 'Opera':
		case 'Firefox':
		case 'Safari':
			window.stop();
			return;
	}

	document.execCommand("Stop");
}

function obUpdateRowExtra(object, isSelect, price, rowNo)
{

	var oldPrice = obExtraValues[rowNo];
	
	// Finner felt
	var noField = document.getElementById('obExtraNo_' + rowNo);
	var priceField = document.getElementById('obExtraTotal_' + rowNo);
	var totalField = document.getElementById('obTotal');
	
	var no=0;
	
	if (isSelect)
		no = object.options[object.selectedIndex].value;
	else
		no = object.value;
		
	noField.innerHTML = no;
	priceField.innerHTML = (no * price);
	
	var diff = (no * price) - oldPrice;
	
	obExtraValues[rowNo] = (no * price);
		
	var total = totalField.innerHTML * 1;
	total += diff;

	totalField.innerHTML = total;
	
}
