var isIE = navigator.userAgent.indexOf ( 'MSIE' ) > 0 ? true : false;

/**
 * Change the quantity
**/
function shopChangeQuantity ( oid, qty, varmode, reload )
{
	if ( !varmode ) varmode = 'id';
	var l = document.location + '';
	l = l.split ( '?' );
	l = l[ 0 ];
	var link = l + '?action=alterchart&pid=' + oid + '&qty=' + qty + '&mode=' + varmode;
	
	if ( !reload )
	{
		if ( !document.chjax ) document.chjax = new Array ( );
		var jax = new bajax ( );
		jax.openUrl ( link, 'get', true );
		jax.onload = function ( )
		{
			for ( var a = 0; a < document.chjax.length; a++ )
			{
				if ( document.chjax[ a ].index == this.index )
				{
					document.chjax[ a ] = false;
					return;
				}
			}
		}
		document.chjax[ document.chjax.length ] = jax;
		jax.index = document.chjax.length - 1;
		jax.send ( );
	}
	else
	{
		top.location.href = link;
	}
}

/**
 * Finalize checkout on the checkout form
**/
function executeCheckout ( redirectUrl )
{
	if ( !redirectUrl ) redirectUrl = false;
	
	if ( document.checkoutform.UseWebuserAddress && document.checkoutform.UseWebuserAddress.value != '1' )
	{
		if ( document.checkoutform.deliveryName.value.length < 2 )
		{
			alert ( 'Du må fylle inn navn på person som mottar leveringen.' );
			document.checkoutform.deliveryName.focus ( );
			return false;
		}
		if ( document.checkoutform.deliveryAddress.value.length < 2 )
		{
			alert ( 'Du må fylle inn leveringsadresse.' );
			document.checkoutform.deliveryAddress.focus ( );
			return false;
		}
		if ( document.checkoutform.deliveryPostcode.value.length < 2 )
		{
			alert ( 'Du må fylle inn leverings postnummer.' );
			document.checkoutform.deliveryPostcode.focus ( );
			return false;
		}
		if ( document.checkoutform.deliveryCity.value.length < 2 )
		{
			alert ( 'Du må fylle inn leverings poststed.' );
			document.checkoutform.deliveryCity.focus ( );
			return false;
		}
	}
	else if ( !document.checkoutform.UseWebuserAddress )
	{
		if ( document.checkoutform.userName.value.length < 2 )
		{
			alert ( 'Du må fylle inn navnet ditt.' );
			document.checkoutform.userName.focus ( );
			return false;
		}
		if ( document.checkoutform.userAddress.value.length < 2 )
		{
			alert ( 'Du må fylle inn adressen din.' );
			document.checkoutform.userAddress.focus ( );
			return false;
		}
		if ( document.checkoutform.userPostcode.value.length < 2 )
		{
			alert ( 'Du må fylle inn postnummeret ditt.' );
			document.checkoutform.userPostcode.focus ( );
			return false;
		}
		if ( document.checkoutform.userCity.value.length < 2 )
		{
			alert ( 'Du må fylle inn poststedet ditt.' );
			document.checkoutform.userCity.focus ( );
			return false;
		}
		if ( document.checkoutform.userTelephone.value.length < 2 )
		{
			alert ( 'Du må fylle inn telefon nummeret ditt.' );
			document.checkoutform.userTelephone.focus ( );
			return false;
		}
		if ( document.checkoutform.userEmail.value.length < 2 )
		{
			alert ( 'Du må fylle inn e-post adressen din.' );
			document.checkoutform.userEmail.focus ( );
			return false;
		}
		if ( document.checkoutform.SameAsPersonal.value < 1 )
		{
			if ( document.checkoutform.deliveryName.value.length < 2 )
			{
				alert ( 'Du må fylle inn navn på person som mottar leveringen.' );
				document.checkoutform.deliveryName.focus ( );
				return false;
			}
			if ( document.checkoutform.deliveryAddress.value.length < 2 )
			{
				alert ( 'Du må fylle inn leveringsadresse.' );
				document.checkoutform.deliveryAddress.focus ( );
				return false;
			}
			if ( document.checkoutform.deliveryPostcode.value.length < 2 )
			{
				alert ( 'Du må fylle inn leverings postnummer.' );
				document.checkoutform.deliveryPostcode.focus ( );
				return false;
			}
			if ( document.checkoutform.deliveryCity.value.length < 2 )
			{
				alert ( 'Du må fylle inn leverings poststed.' );
				document.checkoutform.deliveryCity.focus ( );
				return false;
			}
		}
	}
	if ( document.getElementById ( 'subscriptionaccept' ) )
	{
		if ( document.getElementById ( 'subscriptionaccept' ).value != '1' )
		{
			alert ( 'Du må bekrefte at du aksepterer abonnementsbetingelsene våre.\nHvis du ikke gjør det må du fjerne abonnementsproduktet fra\nhandlekurven.' );
			return false;
		}
	}
	if ( redirectUrl )
		document.checkoutform.action = redirectUrl;
	document.checkoutform.submit ( );
}

/**
 * For use with the checkout form
**/
function shopGhostDelivery ( doit )
{
	if ( doit )
	{
		document.ghostedDelivery = true;
		document.getElementById ( 'DeliveryAddress' ).style.display = 'none';
	}
	else
	{
		document.ghostedDelivery = false;
		document.getElementById ( 'DeliveryAddress' ).style.display = '';
	}
}

/**
* Set opacity on an element (compatible with most, cross browser (except konqueror))
**/
function shopSetOpacity ( ele, op )
{
	if ( !ele ) return;
	if ( ele.opacity && ele.opacity == op ) return;
	
	if ( op == false ) op = 0
	
	ele.opacity = op;
	
	if ( isIE )
	{
		ele.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + ( op * 100 ) + ')';
	}
	else
	{
		ele.style.opacity = op;
	}
}

/**
 * Show attribute box
**/

/**
 * Return an array of the script code
**/
function webshopExtractScripts ( html )
{
	var scripts = html.split ( '</script>' );
	var resultArray = new Array ( );
	for ( var a = 0; a < scripts.length; a++ )
	{	
		var script = scripts[ a ].split ( '<script>' );
		script = script[ 1 ];
		if ( script )
		{
			resultArray[ resultArray.length ] = script;
		}
	}
	return resultArray;
}

/**
 * Remove scripts
**/
function webshopRemoveScripts ( html )
{
	var tc = html.split ( '<script' );
	for ( var a = 0; a < tc.length; a++ )
		html = html.replace ( /<script\b[^>]*>(.*?)<\/script>/i, '' );
	return html;
}

// Set the attribute product price from html
function setAttrProductPrice ( pricehtml )
{
	var tds = document.getElementsByTagName ( 'td' );
	for ( var a = 0; a < tds.length; a++ )
	{
		if ( tds[ a ].className == 'Price' )
		{
			tds[ a ].firstChild.innerHTML = pricehtml;
			break;
		}
	}
}

// Set the price by attribute id
function setAttrProductPriceById ( attrid )
{
	var location = document.location + '';
	location = location.split ( '?' );
	var attjax = new bajax ( );
	attjax.openUrl ( location[ 0 ] + '?action=showattrproductpricebyid&attrid=' + attrid, 'get', true );
	attjax.onload = function ( )
	{
		if ( this.getResponseText ( ) != 'FAIL' ) 
			setAttrProductPrice ( this.getResponseText ( ) );
	}
	attjax.send ( );
}

/**
 * Shows the attribute values for a product and updates the displayed
 * product image if the attribute provides one.
**/
function showAttrValue ( val, p )
{
	removeImageEnlargementLink ( );
	
	if ( !document.wsar ) document.wsar = new Array ( );
	var obj = new Object ( );
	var index = document.wsar.length;
	obj.index = index;
	document.wsar[ index ] = obj;
	
	// Load in attributes for product p under attribute val.
	obj.sjax = new bajax ( );
	var location = document.location + '';
	location = location.split ( '?' );
	var attrUrl = location[ 0 ] + '?action=showattrvalue&pid=' + val + '&p=' + 
		document.getElementById ( 'productattributesselect' + p ).value;
	obj.sjax.openUrl ( attrUrl, 'get', true );
	obj.sjax.onload = function ( )
	{
		// Retrieve attributes loaded and execute scripts that might be supplied
		var html = webshopRemoveScripts ( this.getResponseText ( ) );					
		document.getElementById ( 'productattributes' + p ).innerHTML = html;
		var scripts = webshopExtractScripts ( this.getResponseText ( ) );
		for ( var a = 0; a < scripts.length; a++ )
		{
			eval ( scripts[ a ] );
		}	
	}
	obj.sjax.send ( );
	
	// Load in attribute image
	obj.ijax = new bajax ( );
	obj.ijax.openUrl (
		location[ 0 ] + '?action=showattrimage&pid=' + val + '&p=' + 
		document.getElementById ( 'productattributesselect' + p ).value, 
		'get', true 
	);
	
	var detailimage = getWebshopDetailImage ( );
	if ( !detailimage )
		return;
	
	var detailimagePosition = getElementPosition ( detailimage.childNodes[ 0 ] );
	var test;

	// Show user that we are busy loading an image	
	if ( ( test = document.getElementById ( 'wsloadingindicator' ) ) )
	{
		detailimage.removeChild ( test );
	}
	var loading = document.createElement ( 'div' );									
	
	loading.id = 'wsloadingindicator';
	loading.innerHTML = i18n ( 'loading' ) + '...';
	detailimage.appendChild ( loading );
	
	obj.ijax.loading = loading;
	obj.ijax.img = detailimage;
	
	// When the image is loaded..
	obj.ijax.onload = function ( )
	{
		var img = this.img;
		var html = '';
		
		// If we get an image back from the image load test
		if ( html = this.getResponseText ( ) )
		{
			var reg = /([0-9]*).(jpg|gif|png|jpeg|JPG|GIF|PNG|JPEG)/;
			// See if the image is the same as the shown one, and then, don't update
			
			// ..prepare to replace the current image with the new one
			if ( img )
			{
				// unless the current image is the same as the new one
				var original = reg.exec ( img.innerHTML );
				original = original[ 1 ];
				var imagenew = reg.exec ( html );
				imagenew = imagenew[ 1 ];
				if ( parseInt ( imagenew ) == parseInt ( original ) )
				{
					return 0;
				}
			}
			
			var newA = document.createElement ( 'div' );
			newA.innerHTML = html;
			
			// Preload image and then show it when it has loaded
			reg = /[\w\W]*src="(.*)"/;
			var arr = reg.exec ( html ); arr = arr[ 1 ];
			arr = arr.split ( '"' ); arr = arr[ 0 ];

			document.loadimg = new Image ( );
			document.loadimg.loading = this.loading;
			document.loadimg.index = this.index;
			document.loadimg.onload = function ( )
			{
				// remove loading indicator div
				var test;
				if ( test = document.getElementById ( 'wsloadingindicator' ) )
				{
					test.parentNode.removeChild ( test );
				}
				
				var a = newA.getElementsByTagName ( 'a' );
				img.parentNode.replaceChild ( a[ 0 ], img );
				
				// make image clickable for big version through blestbox
				addOnload ( function ( ){ wsinitBlestBoxClick ( ); } );
				wsinitBlestBoxClick ( );
				addImageEnlargementLink ( );
				
				// remove this load from the list
				var out = new Array ( );
				for ( var a = 0; a < document.wsar.length; a++ )
				{
					if ( a != this.index )
					{
						out[ out.length ] = document.wsar[ a ];
					}
				}
				// done remove
				document.wsar = out;
			}
			document.loadimg.src = arr;
		}
		// If we have no image result
		else
		{
			// remove loading indicator div
			var test;
			if ( ( test = document.getElementById ( 'wsloadingindicator' ) ) )
			{
				test.parentNode.removeChild ( test );
			}
			var out = new Array ( );
			
			// remove this load from the list
			for ( var a = 0; a < document.wsar.length; a++ )
			{
				if ( a != this.index )
				{
					out[ out.length ] = document.wsar[ a ];
				}
			}
			// done remove
			document.wsar = out;
		}
		addImageEnlargementLink ( );
	}
	obj.ijax.send ( );
}



function removeImageEnlargementLink ( )
{
	var ele = getElementsByClassName ( 'DetailImage' );
	ele[ 0 ].style.cursor = 'wait';
	var test;
	
	// Remove enlargement hint
	if ( test = document.getElementById ( 'clickableimage' ) )
	{
		test.parentNode.removeChild ( test );
	}
}

function addImageEnlargementLink ( )
{
	if ( typeof ( document.translations ) == 'object' )
	{
		var detailimage = getElementsByClassName ( 'DetailImage' );
		detailimage = detailimage[ 0 ];
		detailimagePosition = getElementPosition ( detailimage.childNodes[ 0 ] );
	
		// Show user that we can click the small image
		if ( test = document.getElementById ( 'clickableimage' ) )
		{
			detailimage.removeChild ( test );
		}
		var clickableimage = document.createElement ( 'div' );
		clickableimage.id = 'clickableimage';
		clickableimage.innerHTML = '» ' + i18n ( 'enlarge image' ) + ' «';
		setOpacity ( clickableimage, 0.5 );
		detailimage.appendChild ( clickableimage );
		detailimage.style.cursor = 'normal';
	}
	else
	{
		setTimeout ( 'addImageEnlargementLink ( )', 50 );
	}
}

// FUNCTION: Get the element that has the detailed product image
function getWebshopDetailImage ( )
{
	var imgs = document.body.getElementsByTagName ( 'a' );
	var img = false;
	for ( var a = 0; a < imgs.length; a++ )
	{
		var classes = imgs[ a ].className.split ( ' ' );
		for ( var b = 0; b < classes.length; b++ ) 
		{
			if ( classes[ b ] == 'DetailImage' )
			{
				img = imgs[ a ];
				break;
			}
		}
		if ( img ) break;
	}
	return img;
}

function wsinitBlestBoxClick (  )														// FUNCTION: Init the blestbox on the detail image for the webshop
{
	if ( typeof ( _bbelementCache ) != 'undefined' )
	{
		var eles = document.body.getElementsByTagName ( 'a' );
		for ( var a = 0; a < eles.length; a++ )
		{
			if ( hasClass ( eles[ a ], 'DetailImage' ) )
			{
				if ( eles[ a ].href.indexOf ( 'script' ) <= 0 )
				{
					_bbelementCache[ 0 ] = eles[ a ].href;
					eles[ a ].href = 'javascript: void ( 0 )';
					eles[ a ].bbtype = 'image';
					BlestBoxInitClick ( eles[ a ], 0 );
				}
			}
		}
	}
	else
	{
		setTimeout ( 'wsinitBlestBoxClick ( )', 50 );
	}
}

/**
 * Set the form value of an attribute
**/
function setAttrValue ( id )
{
	var ele = document.getElementById ( id );
	if ( ele )
	{
		if ( document.getElementById ( 'Attribute_' + ele.name ) )
		{
			document.getElementById ( 'Attribute_' + ele.name ).value = ele.value;
		}
		else
		{
			setTimeout ( 'setAttrValue ( \'' + id + '\' )', 50 );
		}
	}
}

/**
 * Alter cart
**/
function AlterCart ( baseurl )
{
	if ( !baseurl )
	{
		var base = document.getElementsByTagName ( 'base' );
		baseurl = base[ 0 ].href;
	}
	var eles = document.getElementsByTagName ( 'input' );
	for ( var a = 0; a < eles.length; a++ )
	{
		if ( eles[ a ].className == 'webshop' )
		{
			eles[ a ].onchange ( );
		}
	}
	document.location = baseurl + 'cart/?alter=' + Math.random () * 100;
}

function CheckCartEvents ( )
{
	var base = document.getElementsByTagName ( 'base' );
	document.ejax = new bajax ( );
	document.ejax.openUrl ( base[ 0 ].href + 'ue=webshop&action=checkcartevents', 'get', true );
	document.ejax.onload = function ( )
	{
		if ( this.getResponseText ( ) == 'ERRORS' )
		{
			styledDialog ( base[ 0 ].href + 'ue=webshop&action=showerrors', 'get', true );
		}
		document.ejax = 0;
	}
	document.ejax.send ( );
}

var initwebshoponloadretries = 20;
function initWebshopOnLoad ()
{
	if ( document.body && document.getElementById ( 'WebModule__' ) )
	{
		CheckCartEvents ( );
		var ele = getElementsByClassName ( 'DetailImage' );
		if ( ele.length )
		{
			addImageEnlargementLink ( );
		}
	}
	else if ( initwebshoponloadretries-- ) setTimeout ( 'initWebshopOnLoad()', 70 );
}
initWebshopOnLoad ( );


