//*****************************************************************
//*----------------------------------------------------------------
//* Licenced Material - Property of Theilgaard Mortensen a/s
//*
//* XXXX-XXX
//*
//* (c) Copyright Theilgaard Mortensen a/s. 2004
//*     All rights reserved.
//*
//* Danish Goverment Users Restricted Rights - Use, duplication or 
//* disclosure by contract with Theilgaard Mortensen a/s.
//*
//*-----------------------------------------------------------------
//*****************************************************************

/*
	Classes in this js file:
	- KeyManager
	- StoreManager
	- CatalogManager
	- UserManager
	- ShopcartManager
	- CookieManager
	- ValidationManager
	- SignupManager
	- HistoryManager
	- PrintManager
	- MediaManager
	- StringManager
*/

//*-----------------------------------------------------------------
// KeyManager class
//*-----------------------------------------------------------------

function KeyManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////

	this.handleEnterKey = handleEnterKey;

////////////////////////////////////////////////////////////////////
// Calls the given function call, if the Enter key is pressed
////////////////////////////////////////////////////////////////////

	function handleEnterKey(enterFuncCall) {
		var code = 0;

		var NS4 = false;	

		alert(event.which)
		if (NS4)
			code = event.which;
		else
			code = event.keyCode;
		if (code==13)
			setTimeout(enterFuncCall, 1);
	}
}

//*-----------------------------------------------------------------
// StoreManager class
//*-----------------------------------------------------------------
function StoreManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////
	this.gotoStore = gotoStore;

////////////////////////////////////////////////////////////////////
// Redirect to the selected store
////////////////////////////////////////////////////////////////////
	function gotoStore(storeId) {
		//
	}
}

//*-----------------------------------------------------------------
// CatalogManager class
//*-----------------------------------------------------------------
function CatalogManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////
	this.gotoCategory = gotoCategory;
	this.gotoProduct = gotoProduct;

////////////////////////////////////////////////////////////////////
// Redirect to the selected category
////////////////////////////////////////////////////////////////////
	function gotoCategory(storeId, catalogId, categoryId) {
		//
	}

////////////////////////////////////////////////////////////////////
// Redirect to the selected product
////////////////////////////////////////////////////////////////////
	function gotoCategory(storeId, catalogId, productId) {
		//
	}
}


//*-----------------------------------------------------------------
// UserManager class
//*-----------------------------------------------------------------
function UserManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////
	this.isMember = isMember;

////////////////////////////////////////////////////////////////////
// Checks to see if the user is a member
////////////////////////////////////////////////////////////////////
	function isMember() {
		return true;
	}
}

//*-----------------------------------------------------------------
// ShopcartManager class
//*-----------------------------------------------------------------
function ShopcartManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////
	var busyAdd2Shopcart = false;

	this.add2Shopcart = add2Shopcart;

////////////////////////////////////////////////////////////////////
// Add product to basket
////////////////////////////////////////////////////////////////////
	function add2Shopcart(form, productId)
	{
		if (!busyAdd2Shopcart) {
			busyAdd2Shopcart = true;
			form.catEntryId.value = productId;	
			form.action="OrderItemAdd";
			form.URL.value='ShopcartCalculateView?URL=OrderItemDisplay';
			form.submit();
		}
	}

}

//*-----------------------------------------------------------------
// CookieManager class
//*-----------------------------------------------------------------
function CookieManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////
	this.setCookie = setCookie;
	this.getCookie = getCookie;
	this.removeCookie = removeCookie;
	this.computeExpireDateFromDays = computeExpireDateFromDays;
	
////////////////////////////////////////////////////////////////////
// Compute expire date from days, to expire (returns the GMT string version of the date)
////////////////////////////////////////////////////////////////////
	function computeExpireDateFromDays( days ) {
		var _today = new Date();
		var _expire = new Date();

		if (days==null || days==0) {
			days=1;
		}
 		_expire.setTime(_today.getTime() + 3600000*24*days);
		
		return _expire.toGMTString()
	}
	
////////////////////////////////////////////////////////////////////
// Sets a cookie
////////////////////////////////////////////////////////////////////
	function setCookie( name, value, path, expires, domain ) {
		var cook = name + '=' + escape(value)+'; path=' + path+'; expires=' + expires;
		if (domain && domain != "") {
			 cook += '; domain=' + domain;
		 }
		 document.cookie = cook + "; secure=true";
	}
	
////////////////////////////////////////////////////////////////////
// Gets a cookie
////////////////////////////////////////////////////////////////////
	function getCookie( name) {
		var index = -1;

		if(document.cookie) {
			index = document.cookie.indexOf( name);
		}
	
		if (index != -1) {
			var key = name + '=';
			var countbegin = (document.cookie.indexOf( key, index) + key.length);
			var countend = document.cookie.indexOf(';', index);
	
			if (countend == -1) {
				countend = document.cookie.length;
			}
			return unescape(document.cookie.substring(countbegin, countend));
	
		}
		return '';
	}
////////////////////////////////////////////////////////////////////
// Remove cookie
////////////////////////////////////////////////////////////////////
	function removeCookie (name, path, domain) {
		var c = getCookie(name);
		var e = this.computeExpireDateFromDays(-1);
		cook = name + '=' + c + '; path=' + path+'; expires=' + e;
		if (domain && domain != '') {
			cook += "; domain=" + domain;
		}
		document.cookie = cook;
	}
}

//*-----------------------------------------------------------------
// ValidationManager class
//*-----------------------------------------------------------------
function ValidationManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////
	this.validateMemberInfo = validateMemberInfo;
	
////////////////////////////////////////////////////////////////////
// Validates a member info form
////////////////////////////////////////////////////////////////////
	function validateMemberInfo(theForm) {
		return true;
	}

}

//*-----------------------------------------------------------------
// SignupManager class
//*-----------------------------------------------------------------
function SignupManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////
	var maxItems = 0;
	var currentItemCount = 0;	
	//var itemName = "selectItem";
	var callbackNoMoreMethod = null;
	
	this.setCallbackNoMoreItems = setCallbackNoMoreItems;
	//this.setItemName = setItemName;
	this.setMaxItems = setMaxItems;
	this.getMaxItems = getMaxItems;	
	this.hasMoreItemsAvailable = hasMoreItemsAvailable;
	this.computeCurrentItemCount = computeCurrentItemCount;
	this.getCurrentItemCount = getCurrentItemCount;
	this.saveSelections = saveSelections;
	
	
////////////////////////////////////////////////////////////////////
// Used to save selected offers, in cookies
////////////////////////////////////////////////////////////////////
	function saveSelections(form, selectItem, targetItem) {
		var item = "";
		var items = "";

		var whichitem = 0;

		if (typeof( selectItem.length ) != 'number') {
			if (selectItem.checked) {
				items += selectItem.value;
			}
		} else {
			while (whichitem < selectItem.length) {
				item = selectItem[whichitem];
				if (item.checked) {
					// Found one checked item, increase the counter.
					if(items == "") {
						items += item.value;
					} else {
						items += "," + item.value;
					}
	  			}	// if checked
	  			whichitem++;
			}	// while
		}
		
		if( item != null && item.value!= "" && item.value!= 'undefined') {
			targetItem.value = items;
		} else {
			alert("Selections is empty");
		}

	}

////////////////////////////////////////////////////////////////////
// Used to callback in concern to languagedependant ui code...
////////////////////////////////////////////////////////////////////
	function setCallbackNoMoreItems(_callback_signup_no_more_items) {
		callbackNoMoreMethod = _callback_signup_no_more_items;
	}
	
////////////////////////////////////////////////////////////////////
// Sets the the name of the item to validate
////////////////////////////////////////////////////////////////////
	//function setItemName(theItemName) {
	//	itemName = theItemName;
	//}
	
////////////////////////////////////////////////////////////////////
// Sets the max number of items, that can selected
////////////////////////////////////////////////////////////////////
	function setMaxItems(theMaxItems) {
		maxItems = theMaxItems;
	}

////////////////////////////////////////////////////////////////////
// Registers the number of selected items
////////////////////////////////////////////////////////////////////
	function computeCurrentItemCount(form, selectItem, item) {
		currentItemCount = 0;

		var whichitem = 0;

		while (whichitem < selectItem.length) {
			if (selectItem[whichitem].checked) {
				// Found one checked item, increase the counter.
				currentItemCount++;
  			}	// if checked
  			whichitem++;
		}	// while

		if( !(currentItemCount <= maxItems)) {
	
			// Check to see if we should callback, to present the user with some info...
			if( callbackNoMoreMethod!= null && callbackNoMoreMethod != "") {
				eval(callbackNoMoreMethod);
			}
			
			// Unselect the item, because the user has selected the maximum number of items.
			item.checked = false;
		}
	}
	
////////////////////////////////////////////////////////////////////
// Returns the max number of items
////////////////////////////////////////////////////////////////////
	function getMaxItems() {
		return maxItems;
	}
	
////////////////////////////////////////////////////////////////////
// Returns the current item count
////////////////////////////////////////////////////////////////////
	function getCurrentItemCount() {
		return currentItemCount;
	}	

////////////////////////////////////////////////////////////////////
// Returns true if the user can select more items
////////////////////////////////////////////////////////////////////
	function hasMoreItemsAvailable() {
		return (maxItems > currentItemCount);
	}

}

//*-----------------------------------------------------------------
// HistoryManager class
//*-----------------------------------------------------------------
function HistoryManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////
	this.goBack = goBack;
	this.goBackTo = goBackTo;
	
////////////////////////////////////////////////////////////////////
// Goes one step back
////////////////////////////////////////////////////////////////////
	function goBack() {
		history.back(-1);
	}

////////////////////////////////////////////////////////////////////
// Goes X steps back
////////////////////////////////////////////////////////////////////
	function goBackTo( count) {
		history.back(count);
	}
}


//*-----------------------------------------------------------------
// PrintManager class
//*-----------------------------------------------------------------
function PrintManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////
	this.printDialog = printDialog;	
	
////////////////////////////////////////////////////////////////////
// Prints the current page, via the browser specific methods
////////////////////////////////////////////////////////////////////
	function printDialog() {
		var win;
		if (location.href.indexOf("?") > 0) {
			win = window.open(location.href + "&doPrint=1", "_blank", "width=600,height=400,scrollbars=yes");
		}
		else {
			win = window.open(location.href + "?doPrint=1", "_blank", "width=600,height=400,scrollbars=yes");
		}
		if (navigator.appName == "Microsoft Internet Explorer") {win.print();}
	}

}

//*-----------------------------------------------------------------
// MediaManager class
//*-----------------------------------------------------------------
function MediaManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////

	this.setDefaultImage = setDefaultImage;	
	
////////////////////////////////////////////////////////////////////
// Set a default image, when an error occurs on load of the image
////////////////////////////////////////////////////////////////////
	function setDefaultImage(img, imgDefault, imgWidth, imgHeight) {
		img.src = imgDefault;
		if(imgWidth != null) {
			img.width = imgWidth;			
		}
		if(imgHeight != null) {
			img.height = imgHeight;
		}

	}

}

//*-----------------------------------------------------------------
// StringManager class
//*-----------------------------------------------------------------
function StringManager() {

////////////////////////////////////////////////////////////////////
// Member properties and prototypes
////////////////////////////////////////////////////////////////////
	this.trim = trim;	
	
////////////////////////////////////////////////////////////////////
// Trims the string from all spaces
////////////////////////////////////////////////////////////////////
	function trim( str) {
		if(str.length < 1) {
			return"";
		}

		str = trimLeft(str);
		str = trimRight(str);		

		if(str=="") {
			return "";
		} else{
			return str;
		}
	}

////////////////////////////////////////////////////////////////////
// Trims the string from left spaces
////////////////////////////////////////////////////////////////////
	function trimLeft(str) {
		var w_space = String.fromCharCode(32);
		if(v_length < 1){
			return"";
		}
		
		var v_length = str.length;
		var strTemp = "";

		var iTemp = 0;

		while(iTemp < v_length){
			if(str.charAt(iTemp) != w_space){
				strTemp = str.substring(iTemp,v_length);
				break;
			}
			iTemp = iTemp + 1;
		} //End While
		
		return strTemp;
	}

////////////////////////////////////////////////////////////////////
// Trims the string from right spaces
////////////////////////////////////////////////////////////////////
	function trimRight(str) {
		var w_space = String.fromCharCode(32);
		var v_length = str.length;
		var strTemp = "";

		if(v_length < 0) {
			return"";
		}

		var iTemp = v_length -1;

		while(iTemp > -1){

			if(str.charAt(iTemp) != w_space){
				strTemp = str.substring(0,iTemp +1);
				break;
			}
			iTemp = iTemp-1;

		} //End While
		
		return strTemp;
	}

}

function checkDigits (Eanstr) 
{
	var i = 0;
	var sum = 50;
	var rest = 0;
	var pos = 0;
	var ulige = true;
	if (Eanstr.length != 13)
	{
		alert("EAN kode skal være 13 cifre");
		return;		
	}
	
	for (i = Eanstr.length - 2; i >= 0; i--)
	{	
		if (ulige)
		{
			sum += parseInt(Eanstr.substr(i,1)) * 3;
			ulige = false;
		}
		else
		{
			sum += parseInt(Eanstr.substr(i,1));
			ulige = true;
		}
	}
	rest = sum % 10;
	if (rest > 0)
		rest = 10 - rest;
	pos = Eanstr.length - 1;
	if (rest != parseInt(Eanstr.substr(pos,1))){
		alert( "EAN-nr ikke korrekt" );
		return false;
	}
	
	return true;
}


//*-----------------------------------------------------------------
// Functions for showing and hiding the publisher price info box
//*-----------------------------------------------------------------

function findCoords(e) {
	if( !e ) {
		e = window.event;
	} 
	if( !e || ( typeof( e.pageX ) != 'number' && typeof( e.clientX ) != 'number' ) ) {
		return [ 0, 0 ];
	}

   	if( typeof( e.pageX ) == 'number' ) { 
   		return [ e.pageX, e.pageY ];
   	} else {
      	var posX = e.clientX; var posY = e.clientY;
      	if( !( ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) || ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) || window.navigator.vendor == 'KDE' ) ) {
         	if( document.documentElement && ( document.documentElement.scrollTop || document.documentElement.scrollLeft ) ) {
            	posX += document.documentElement.scrollLeft; posY += document.documentElement.scrollTop;
         	} else if( document.body && ( document.body.scrollTop || document.body.scrollLeft ) ) {
            	posX += document.body.scrollLeft; posY += document.body.scrollTop;
         	}
      	}
	   	return [ posX, posY ];
   	}

}

function getElementStyle(id) {
	if(!document.getElementById) {
		return document.all[id].style;
    }
	else {
		return document.getElementById(id).style;
	}	
}

function showPublisherPriceInfo(e) {
	var popupStyle = getElementStyle('publisherPriceInfo');
	var coords = findCoords(e);
	popupStyle.top = coords[1]+"px";
	popupStyle.left = coords[0]+"px";
	popupStyle.visibility = "visible";
}

function hidePublisherPriceInfo() {
	var popupStyle = getElementStyle('publisherPriceInfo');
	popupStyle.visibility = "hidden";
}

function showOrdinaryProductInfo(e) {
	var popupStyle = getElementStyle('ordinaryProductInfo');
	var coords = findCoords(e);
	popupStyle.top = coords[1]+"px";
	popupStyle.left = coords[0]+"px";
	popupStyle.visibility = "visible";
}

function hideOrdinaryProductInfo() {
	var popupStyle = getElementStyle('ordinaryProductInfo');
	popupStyle.visibility = "hidden";
}

//*-----------------------------------------------------------------
// Initialize the global JS helper classes...
//*-----------------------------------------------------------------
var historyMgr = new HistoryManager();
var printMgr = new PrintManager();	
var cookieMgr = new CookieManager();
var shopcartMgr = new ShopcartManager();
var mediaMgr = new MediaManager();

//*-----------------------------------------------------------------
// Popup image windows with approximately correct size
//*-----------------------------------------------------------------


// Script Source: CodeLifter.com
// Copyright 2003
// Do not remove this notice.
// Modified 21.08.06 MMP
// Modified 23.02.09 TB

// SETUPS:
// ===============================

// Set the horizontal and vertical position for the popup

PositionX = 100;
PositionY = 100;

// Set these value approximately 20 pixels greater than the
// size of the largest image to be used (needed for Netscape)

defaultWidth  = 500;
defaultHeight = 500;

// Set autoclose true to have the window close automatically
// Set autoclose false to allow multiple popup windows

var AutoClose = true;

// Do not edit below this line...
// ================================
if (parseInt(navigator.appVersion.charAt(0))>=4){
var isNN=(navigator.appName=="Netscape")?1:0;
var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}
var optNN='scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
var optIE='scrollbars=no,width=150,height=100,left='+PositionX+',top='+PositionY;

function popImage(imageURL,imageTitle, noImageURL){
	if (isNN){imgWin=window.open('about:blank','',optNN);}
	if (isIE){imgWin=window.open('about:blank','',optIE);}
	with (imgWin.document){
	writeln('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">');
	writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>');
	writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
	writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
	writeln('function reSizeToImage(){');
	writeln('if (isIE){');
	writeln('window.resizeBy(document.images[0].width-document.documentElement.clientWidth, document.images[0].height-document.documentElement.clientHeight+20);}');
	writeln('if (isNN){');       
	writeln('window.innerWidth=document.images["gyldendalPopup"].width;');writeln('window.innerHeight=document.images["gyldendalPopup"].height+20;}}');
	writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>');
	if (!AutoClose) writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
	else writeln('</head><body bgcolor="FFFFFF" scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
	writeln('<center><img name="gyldendalPopup" src=\"'+imageURL+'\" onerror="this.src=\''+noImageURL+'\'\;" style="display:block;" onclick="javascript:window.close();"></center></body></html>');
	writeln('<center><a href="#" style="color: #000000;" onClick="javascript:window.close();">Luk</a></center>');
	close();		
	}
}