// http://www.thefutureoftheweb.com/blog/adddomloadevent
addDOMLoadEvent=(function(){var e=[],t,s,n,i,o,d=document,w=window,r='readyState',c='onreadystatechange',x=function(){n=1;clearInterval(t);while(i=e.shift())i();if(s)s[c]=''};return function(f){if(n)return f();if(!e[0]){d.addEventListener&&d.addEventListener("DOMContentLoaded",x,false);/*@cc_on@*//*@if(@_win32)d.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");s=d.getElementById("__ie_onload");s[c]=function(){s[r]=="complete"&&x()};/*@end@*/if(/WebKit/i.test(navigator.userAgent))t=setInterval(function(){/loaded|complete/.test(d[r])&&x()},10);o=w.onload;w.onload=function(){x();o&&o()}}e.push(f)}})();

addDOMLoadEvent(initPage);


function initPage() {
	if (!document.getElementById) { return false; }
	
	//addRoundCorners( document.getElementById('ShoppingCart') );
	//addRoundCorners( document.getElementById('Catalogues') );
	addRoundCorners( getElementsByClassName('InfoBox','div','Wrapper') );
	addRoundCorners( getElementsByClassName('Item','div','ProductCatalog') );
	addRoundCorners( getElementsByClassName('CategoryDesc','div','ProductCatalog') );
	
	//externalLinks();
	
	if (document.getElementsByTagName('html')[0].id != 'index') {
		var randomnumber = Math.floor(Math.random()*7) +1;
		document.getElementById('Header').style.backgroundImage='url(/images/bg_header_kids_'+randomnumber+'.png)';
	}
	
	initFlashvideo();
		
	// add icons to links
	allLinks = document.getElementById('Content').getElementsByTagName('a');

	for (i=0; i<allLinks.length; i++) {
		node = allLinks[i];
		if (node.parentNode.nodeName.toLowerCase() == 'p') {
			nodeLink = node.href;
			// alert(i +" - " + node + " - " + nodeLink.substr(nodeLink.length - 4) + " - " + nodeLink.indexOf('.flv') );
			// if ( nodeLink.indexOf('.pdf') == nodeLink.length - 4 ) { classTool('add',node,'Download-pdf'); }
			if ( nodeLink.indexOf('/video/') != -1 ) { classTool('add',node,'Video'); }
		}
	}
}


jQuery(function($) {
	if (!document.getElementById('Banner')) { return false; }
	// Fetch image paths from hidden links
	var BannerImages = new Array();
	$( "#Banner a" ).each(
		function( intIndex ){
			ThisImage = $(this).attr('href');
			ThisArray = {'src':ThisImage};
			BannerImages.push(ThisArray);
		}
	);
	if (BannerImages.length == 0) { return false; }
	// Initialize image rotation
	$('#Banner').crossSlide({
		sleep: 2, //in sec
		fade: 1   //in sec
		}, 
		BannerImages
	);
});

/*
	$('#Banner').crossSlide({
	  sleep: 2, //in sec
	  fade: 1   //in sec
	}, [
	  { src: '/upload/images/banner_sqrl-cykler.jpg' },
	  { src: '/upload/images/banner_bord_baenk.jpg' },
	  { src: '/upload/images/banner_garderobe.jpg' }
	]);
});
*/

function initFlashvideo() {
	if (!document.getElementById('FlashContent')) { return false; }
		
	if (!document.getElementById('FlashContent').className == '' ) {
		flashFile = document.getElementById('FlashContent').className;
	} else {
		// Figure out requested flash video, based on page url
		/* http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript */
		urlPathParts = location.pathname.split('/');
		htmlFile = urlPathParts[urlPathParts.length-1];
		flashFile = htmlFile.replace(/.html/,'.flv');
	}


	// SWFObject 2.1 dynamic embedding
	var flashvars = {
		file: "/images/"+flashFile
	};
	var params = {
		allowfullscreen: "true",
		wmode: "opaque"
	}
	var attributes = {
		id: "JW_Player",
		name: "JW_Player"
	};
	swfobject.embedSWF("/images/player.swf", "FlashContent", "462", "336", "9.0.0","/images/expressInstall.swf", flashvars, params, attributes);
	
	// Generate a back link, but only if referer is not external
	currentHost = location.host.replace(/www./,'');
	currentPath = location.pathname;
	currentBase = location.protocol+'//'+location.host;
	referrerPath = document.referrer.replace(currentBase,'');
	if (document.referrer.indexOf(currentHost) > -1 && referrerPath.indexOf('/video/') != 0) { 
		backLink = document.createElement('p');
		backLink.setAttribute('id','Backlink');
		insertAfter( document.getElementById('FlashPlayer'), backLink );
		var linkHtml = '<a href="'+document.referrer+'">Tilbage</a>';
		setInnerHTML( backLink, linkHtml );			
	}
	
	
}



// Functions for shopping cart

function disableInputsInDiv( id )
{
	if( document.getElementById )
	{
		if( div = document.getElementById( id ) )
		{
			div.setAttribute( "class", "disabled" );
			div.setAttribute( "className", "disabled" ); // for IE

			if( elements = div.getElementsByTagName( "input" ) )
			{
				var i;
			
				for( i = 0 ; i < elements.length ; i++ )
				{
					elements[i].disabled = true;
				}
			}
		}
	}
}

function enableInputsInDiv( id )
{
	if( document.getElementById )
	{
		if( div = document.getElementById( id ) )
		{
			div.setAttribute( "class", "enabled" );
			div.setAttribute( "className", "enabled" ); // for IE
		
			if( elements = div.getElementsByTagName( "input" ) )
			{
				var i;
				var focusSet = false;
			
				for( i = 0 ; i < elements.length ; i++ )
				{
					elements[i].disabled = false;
					
					if( !focusSet && elements[i].value == "" )
					{
						elements[i].focus();
						
						focusSet = true;
					}
				}
			}
		}
	}
}








	// Open external links in new window
	// http://cssglobe.com/post/1281/open-external-links-in-new-window-automatically
	// http://www.sitepoint.com/print/standards-compliant-world/
	// http://www.w3.org/TR/WCAG20-TECHS/SCR24.html
	this.externalLinks = function(){
		var hostname = window.location.hostname;
		//hostname = hostname.replace("www.","").toLowerCase();
		var a = document.getElementsByTagName("a");	
		this.check = function(obj){
			var href = obj.href.toLowerCase();
			return (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? true : false;				
		};
		this.set = function(obj){
			//obj.target = "_blank";
			obj.rel = "external";
			obj.className = "ExternalLink";
			
			obj.onclick = function(event){return launchWindow(this, event);}
			// UAAG requires that user agents handle events in a device-independent manner
			// but only some browsers do this, so add keyboard event to be sure
			obj.onkeypress = function(event){return launchWindow(this, event);}			
		};	
		for (var i=0;i<a.length;i++){
			if(check(a[i])) set(a[i]);
		};		
	}

	function launchWindow(objAnchor, objEvent)
	{
	  var iKeyCode, bSuccess=false;
	
	  // If the event is from a keyboard, we only want to open the
	  // new window if the user requested the link (return or space)
	  if (objEvent && objEvent.type == 'keypress')
	  {
		if (objEvent.keyCode)
		  iKeyCode = objEvent.keyCode;
		else if (objEvent.which)
		  iKeyCode = objEvent.which;
	
		// If not carriage return or space, return true so that the user agent
		// continues to process the action
		if (iKeyCode != 13 && iKeyCode != 32)
		  return true;
	  }
	
	  bSuccess = window.open(objAnchor.href);
	
	  // If the window did not open, allow the browser to continue the default
	  // action of opening in the same window
	  if (!bSuccess)
		return true;
	
	  // The window was opened, so stop the browser processing further
	  return false;
	}



function addRoundCorners(e)
{
	if (!e || e == null || e == undefined) { return false };
	if (!isArray(e)) e = new Array(e);

	for (j=0; j<e.length; j++) {
	
	if (classTool('check', e[j], 'NoCorners') == false && classTool('check', e[j].parentNode, 'NoCorners') == false) {
		newDiv = document.createElement('div');
		newDiv.className = "CornerTL";
		e[j].appendChild(newDiv);
		newDiv = document.createElement('div');
		newDiv.className = "CornerTR";
		e[j].appendChild(newDiv);        			
		newDiv = document.createElement('div');
		newDiv.className = "CornerBL";
		e[j].appendChild(newDiv);
		newDiv = document.createElement('div');
		newDiv.className = "CornerBR";
		e[j].appendChild(newDiv);
		}
	}
}




// Written by Jonathan Snook, http://www.snook.ca/jonathan
// Add-ons by Robert Nyman, http://www.robertnyman.com
//http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
function getElementsByClassName(strClassName, strTagName, oElm){
	if (isString(oElm)) { oElm = document.getElementById(oElm); }
	if (oElm == null) { oElm = document; }
	if (strTagName == null) { strTagName = '*'; }
	var arrElements = (strTagName == '*' && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}


// http://www.planetpdf.com/developer/article.asp?ContentID=testing_for_object_types_in_ja
function isString() {
	if (typeof arguments[0] == 'string') return true;
	if (typeof arguments[0] == 'object') {
		var criterion = arguments[0].constructor.toString().match(/string/i);
		return (criterion != null);
	}
	return false;
}

// http://thinkweb2.com/projects/prototype/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]'; 
}


function insertAfter( referenceNode, newNode )
{
	referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}


function setInnerHTML(target, content) {
	if (!SI) { var SI = new Object(); };
	if (SI.IE && (target.nodeName == 'TBODY' || target.nodeName == 'TABLE'))
	{
		SI.IE.fixInnerHTML(target, content);
	} else {
		target.innerHTML = content;
	}
};


function classTool(a,o,c1,c2)
// This function takes four parameters:
// a = defines the action you want to perform
// o = the object in question
// c1 = the name of the first class
// c2 = the name of the second class
//
// Possible actions are:
// swap		= replaces class c1 with class c2 in object o
// add		= adds class c1 to the object o
// remove	= removes class c1 from the object o
// check	= tests if class c1 is already applied to object o and return true or false
{
	switch (a)
	{
		case 'swap':
			o.className=!classTool('check',o,c1)?o.className.replace(c2,c1):
			o.className.replace(c1,c2);
		break;
		case 'add':
			if(!classTool('check',o,c1)) {o.className+=o.className?' '+c1:c1;}
		break;
		case 'remove':
			var rep=o.className.match(' '+c1)?' '+c1:c1;
			o.className=o.className.replace(rep,'');
		break;
		case 'check':
			return new RegExp('\\b'+c1+'\\b').test(o.className);
		break;
	}
}
