/*
	kodmyran03.js
	
	This is a JavaScript file that contains small utility functions for the kodmyran03 template.
	It requires the prototype library as a prerequsite.
	
	Written by Erik Lundgren 2009-07-10
*/

var postOfficeLocatorXHR=null;
var oldPOffice="";

function climateCompensateToggle()
{
	if( $('climateCompensate'))
	{
		if( $('climateCompensate').checked )
			ajaxCartAdd( 799 );
		else
			ajaxCartRemove( 799 );
	}
}

function drawPopup( tag, noclose )
{
	ajaxLoadOn();	
	
	new Ajax.Request( "/ajax.php?c=getpanel&id="+tag, { 
			onFailure: function() {
				alert( "Misslyckades med AJAX anrop!" );
			},			
			onSuccess: function( transport ) {
				ajaxLoadOff();
				
				if( !$('ajaxPopupWindow'))
				{
					// Doesn't exist yet, we need to create it
					d = new Element( 'div' );
					d.addClassName( 'ajaxWindow' );
					d.style.display = "none";
					d.id = 'ajaxPopupWindow';
					d.style.width = "400px";
					
					if( !noclose )
						d.style.height = "400px";
					else
						d.style.height = "365px";
												
					// Attach it to the end of the body
					b = $$('body');
					b[0].insert( d );
				}
				
				data = '<div class="ajaxWindowHeader"></div>'+'<div class="ajaxWindowContent">'+transport.responseText+'</div>';
				
				if( !noclose )
					data = data+'<div class="ajaxWindowBottom"><input type="button" name="St&auml;ng" value="St&auml;ng" onclick="ajaxWindowDown();" /></div>';
				
				$('ajaxPopupWindow').innerHTML = data;
				showWindow( $('ajaxPopupWindow'));
				
				$('transparencyLayer').observe( 'click', ajaxWindowDown );
			}
		});	
}

function setGiftWrap( ev )
{
	// Find new giftwrap option	
	var gwrap = this.select( 'input' );
	var t;
	var nwrap=0;
	
	for( t=0; t < gwrap.length; t++ )
		nwrap = gwrap[t].value;
		
	setGiftWrap2( nwrap );	
}

function ajaxWindowDown()
{
	hideWindow( $('ajaxPopupWindow'));	
}

function showWindow( ref )
{
	w = document.viewport.getWidth();
   h = document.viewport.getHeight();

	a=document.viewport.getScrollOffsets();
	w2 = a[0];
	h2 = a[1];
	
	w3 = w+w2;
	h3 = h+h2;
	
	// Before showing the popup dialog window we'll place a layer in between to gray out the background to avoid confusion
	if( !$('transparencyLayer'))
	{
		d = new Element( 'div' );
		d.style.display = "none";
		d.style.position = "absolute";
		d.style.top = 0;
		d.style.left = 0;
		d.id = 'transparencyLayer';
		d.style.background="#000000";
		
		b = $$('body');
		b[0].insert( d );
	}
	
	// Find the height of the current document (not the viewport)
	b = $$('body')[0];
	
	$('transparencyLayer').style.zIndex = 100;
	$('transparencyLayer').style.height = b.getHeight()+'px';
	$('transparencyLayer').style.width = b.getWidth()+'px';
	$('transparencyLayer').setOpacity( 0.6 );
	$('transparencyLayer').style.display = "block";
	
	t = h2 + h/2 - (ref.getHeight()/2);
	l = w2 + w/2 - (ref.getWidth()/2);
	
	ref.style.top = t+"px";
	ref.style.left = l+"px";
	ref.style.display = "block";
	ref.style.zIndex = 200;
}

function hideWindow( ref )
{
	ref.style.display = "none";
	$('transparencyLayer').style.display = "none";
}

function reloadProduct( e )
{
	prodno=resolveAssocs();
		
	if( parseInt( prodno ) >= 1000 )
	{
		ajaxLoadOn();
		
		// Before using the old style version and letting the store do the redirect (which doesn't work with adv. lookups)
		// we will consult the complexProductList (if found) and extract the proper URL from there instead
		if( $('complexProductList'))
		{
			var as = $('complexProductList').select( 'a' );
			
			for( var i=0; i < as.length; i++ )
			{
				if( as[i].rel == prodno )
				{
					window.location.href = as[i].href;
					return;
				}
			}			
		}
		
		window.location.href = "/product.php/"+prodno;
	}
}

function resolveAssocs()
{	
	elems = $$('input,select');
	el1=null;
	el2=null;
	el3=null;
	
	for( i=0; i < elems.length; i++ )
	{
		if( elems[i].name == "associd1" )
			el1 = elems[i];

		if( elems[i].name == "associd2" )
			el2 = elems[i];

		if( elems[i].name == "associd3" )
			el3 = elems[i];
	}
			
	// The above took care of the simple case, however if there are multiple options on this page we may have to spend a little more time
	// to figure out the true case. However first handle the case when there is only one...
	if( el1 && !el2 && !el3 )
		return el1.value;
		
	// Ok, it is the more complex case - we don't handle the triple selection case here so we only have to care about two...	
	x=0;
	result=[];
	
	if( el1 )
	{
		ee1=el1.value.split(',');
		x=1;
	}
	else
		ee1=[];
		
	if( el2 )
	{
		ee2=el2.value.split(',');
		x=2;
	}
	else
		ee2=[];
	
	if( el3 )
	{
		ee3=el3.value.split(',');
		x=3;
	}
	else
		ee3=[];
		
	ea=[];
	
	for( i=0; i < ee1.length; i++ )
	{
		n = ee1[i];
		
		if( ea[n] )
			ea[n]++;
		else
			ea[n] = 1;
	}

	for( i=0; i < ee2.length; i++ )
	{
		n = ee2[i];
		
		if( ea[n] )
			ea[n]++;
		else
			ea[n] = 1;
	}

	for( i=0; i < ee3.length; i++ )
	{
		n = ee3[i];
		
		if( ea[n] )
			ea[n]++;
		else
			ea[n] = 1;
	}

	for( i=0; i < ea.length; i++ )
		if( ea[i] )
		{
			if( ea[i] == x )
				result.push( i );
		}
		
	if( result.length == 1 )
		return result[0];

	alert( "Den kombination av val som du gjort med t.ex. modell, storlek eller färg finns inte eller är inte tillgänglig.\n\nVänligen välj en annan kombination." );	

	return 0;
}

function IsNumeric( strString )
{
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;

	if( strString.length == 0 )
		return false;

	for( i=0; i < strString.length && blnResult == true; i++ )
	{
		strChar = strString.charAt(i);

		if (strValidChars.indexOf(strChar) == -1)
			blnResult = false;
	}
			
	return blnResult;
}

function ajaxLoadOn()
{
	d = document.getElementById( 'ajaxLoader' );

	w = window.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);
   h = window.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);

	t = h/2 - 60;	
	l = w/2 - 175;
  
	d.style.top = t+"px";
	d.style.left = l+"px";
	d.style.display = "block";
	
	// Block the "next/continue" button
//	document.getElementById( 'buttonOrder' ).disabled=true;
}

function ajaxLoadOff()
{
	d = document.getElementById( 'ajaxLoader' );
	d.style.display = "none";	
//	document.getElementById( 'buttonOrder' ).disabled=false;
}

function currencyChange()
{
	currLoc=window.location.href.split( "\?" );
	window.location = currLoc[0]+"?cmd=setcurrency&currencyid="+$F('currency-box');
}

function langChange()
{
	currLoc=window.location.href.split( "\?" );
	window.location = currLoc[0]+"?cmd=setlang&lang="+$F('lang-box');
}

function assocChange( el )
{
	type=0;
	loadElement=null;
			
	for( a=el.element(); a.parentNode; a = a.parentNode )
	{
		if( a.className == 'catalog-list' )
		{
			type=1;
			break;
		}		
	
		if( a.nodeName == 'LI' )
			loadElement = a;			
	}

	if( !type )
		window.location = "/product.php/"+$F('prodno');
	else
	{
		new Ajax.Request( '/ajax.php', { 
								parameters: { c: 'drawsnippet',
								id: 'categoryProduct',
								a: el.element().value },
								onSuccess: function( transport ) {
									loadElement.innerHTML = transport.responseText;
									
									e = document.getElementsByName( "prodno" );
	
									for( a=0; a < e.length; a++ )
										if( e[a].nodeName == "SELECT" )
											$(e[a]).observe( 'change', assocChange );
											
									allPageTags=document.getElementsByTagName("*");  
	
									for( i=0; i < allPageTags.length; i++ )
										if( allPageTags[i].className=='notify' )
										{
											Element.extend( allPageTags[i] );
											allPageTags[i].observe( 'click', productNotify );
										}
								}
							});
	}
}

function displaycountChange1()
{
	currLoc=window.location.href.split( "\?" );
	window.location = currLoc[0]+"?prodcount="+$F('displaycount1');	
}

function displaycountChange2()
{
	currLoc=window.location.href.split( "\?" );
	window.location = currLoc[0]+"?prodcount="+$F('displaycount2');	
}

function starHandler( ev )
{
	rating=0;
	
	switch( ev.element().className )
	{
		case 'one-star':
			rating=1;
			break;
			
		case 'two-stars':
			rating=2;
			break;

		case 'three-stars':
			rating=3;
			break;

		case 'four-stars':
			rating=4;
			break;

		case 'five-stars':
			rating=5;
			break;
	}

	if( rating > 0 )
	{
		ajaxLoadOn();

		new Ajax.Request( '/ajax.php?ajax=1&c=setvote&id='+$F('prodno')+'&a='+rating, { 
			onSuccess: function( transport ) {
				ajaxLoadOff();
				
				response = transport.responseText.split( "\n" );
						
				if( response[0] != "OK:OK" )
					alert( "Det gick inte att registrera din röst "+transport.responseText );
				else
					alert( "Din röst är registrerad" );
			}
		});
	}
}

function fetchAddr( ev )
{
	pno = $F('qcPno');
			
	if( pno.length != 11 && pno.length != 10 )
	{
		alert( "Ogiltigt personnummer, måste anges som xxxxxx-yyyy" );
		return;
	}
	
	if( pno.length == 10 )
	{
		n1=pno.substr( 0, 6 );
		n2=pno.substr( 6, 4 );
		pno = n1+'-'+n2;
		$('qcPno').value = pno;
	}
	else
	{
		n = pno.split( "-" );
		n1=n[0];
		n2=n[1];
	}
			
	if( n1.length != 6 || !IsNumeric( n1 ))
	{
		alert( "Ogiltigt personnummer, måste anges som xxxxxx-yyyy" );
		return;
	}

	if( n2.length != 4 || !IsNumeric( n2 ))
	{
		alert( "Ogiltigt personnummer, måste anges som xxxxxx-yyyy" );
		return;
	}

	if( $F('usertype') == 'company' )
		rstr = '/ajax.php?ajax=1&c=getaddresses&business=1&id='+pno;
	else
		rstr = '/ajax.php?ajax=1&c=getaddresses&id='+pno;

	ajaxLoadOn();
	
	new Ajax.Request( rstr, { 
			onSuccess: function( transport ) {
				ajaxLoadOff();
				
				response = transport.responseText.split( "\n" );
						
				if( response[0] == "OK:OK" )
				{
					if( response[7].length )				// This is a company
					{					
						$('company').value = response[7];
						$('firstname').value = "";
						$('lastname').value = "";						
						$('companynamerow').style.display = "block";
						$('usertype').value = "company";
					}
					else
					{
						$('firstname').value = response[1];
						$('lastname').value = response[2];
						$('companynamerow').style.display = "none";						
						$('usertype').value = "user";
					}
			
					$('address').value = response[3];
					$('zipcode').value = response[4];
					$('city').value = response[5];
					
					for( i=0; i < $('qcCountry').length; i++ )
					{
						if( $('qcCountry').options[i].value == response[6] )
							$('qcCountry').selectedIndex = i;									
					}
					
					qcZipcodeChange( null );
				}
				else
					alert( "Det gick inte att hämta information för detta personnummer, kontrollera att du valt privatperson/företag rätt. Servern svarade: "+transport.responseText );
			}
		});
}

function qcZipcodeChange( ev )
{
	var rawzip="";
	var newzip="";
	var rawfield=null;	

	if( !$('qcPostOfficeSelector'))
		return;

	$('qcPostOfficeSelector').disabled = true;
	$('qcPostOfficeSelector').innerHTML = '<option value="">&lt;&lt; Ange ditt postnummer så kan du välja utlämningsställe &gt;&gt;</input>';

	// Delivery country must be Sweden	
	// Check if alternate address is in use
	if( $('qcDeliveryOther') && $('qcDeliveryOther').checked )
	{
		// If the changed field is the buyers zip and alternate delivery adress is in use we just ignore the request
		if( ev && ev.element().name == "zipcode" )
			return;
			
		if( $F('adCountry') != 'se' )
			return;
			
		rawzip = $F('adZip');
		rawfield = $('adZip');			
	}
	else
	{
		if( $F('qcCountry') != 'se' )
			return;
			
		rawzip = $F('zipcode');
		rawfield = $('zipcode');
	}
	
	// Extract numbers only from this field	
	for( i=0; i < rawzip.length; i++ )
	{
		switch( rawzip.charAt( i ))
		{
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				newzip += rawzip.charAt( i );
				break;
		}
	}
	
	// If the length of the zipcode is <> 5 chars skip the rest
	if( newzip.length != 5 )
		return;
		
	rawfield.value = newzip;
	
	// Add an indicator to tell the customer that we are getting the list
	$('qcPostOfficeSelector').insert( { after: '<img id="ajaxLoaderSmall" src="/templates/kodmyran03/images/ajax-loader-small.gif" />' } );
	
	// Trigger the Ajax call
	// First check if another call is already in progress, if so we need to abort it
	if( postOfficeLocatorXHR )
		postOfficeLocatorXHR.abort();
	
	postOfficeLocatorXHR	= new Ajax.Request( '/ajax.php', { 
							parameters: { 	c: 'postofficelookup',
												id: 'SE',
												a: newzip },
							onFailure: function( transport ) {
								$('ajaxLoaderSmall').remove();
								alert( "AJAX anrop misslyckades!" );
							},
							onSuccess: function( transport ) {
								$('ajaxLoaderSmall').remove();
								
								// Ok, parse the response XML
								if( transport.responseXML.getElementsByTagName('status')[0].firstChild.nodeValue == "OK" )
								{
									var officeids = transport.responseXML.getElementsByTagName('officeid');
									var names = transport.responseXML.getElementsByTagName('name');
									var addresses = transport.responseXML.getElementsByTagName('address');
									var zipcodes = transport.responseXML.getElementsByTagName('zipcode');
									var cities = transport.responseXML.getElementsByTagName('city');
									var countries = transport.responseXML.getElementsByTagName('country');
									var telephones = transport.responseXML.getElementsByTagName('telephone');
									var latitudes = transport.responseXML.getElementsByTagName('latitude');
									var longitudes = transport.responseXML.getElementsByTagName('longitude');
									
									var desc="";
									var dval="";
									var txt="";
									var fPOffice="";

									$('qcPostOfficeSelector').innerHTML = "";									
									txt = '<option value="">&lt;&lt; Mitt n&auml;rmaste utl&auml;mningsst&auml;lle &gt;&gt;</option>';
									$('qcPostOfficeSelector').insert( { top: txt } );
									
									for( var x=0; x < officeids.length; x++ )
									{
										desc = names[x].firstChild.nodeValue + ' / ' + addresses[x].firstChild.nodeValue + ' / ' + cities[x].firstChild.nodeValue;
										
										if( fPOffice == "" )
											fPOffice = officeids[x].firstChild.nodeValue;
											
										e = new Element( 'option', { value: officeids[x].firstChild.nodeValue } );
										
										if( officeids[x].firstChild.nodeValue == oldPOffice )																				
											e.selected = true;
										else
											e.selected = false;
											
										e.innerHTML = desc;										
										$('qcPostOfficeSelector').insert( { bottom: e } ); 	
									}
									
									$('qcPostOfficeSelector').disabled = false;
									oldPOffice = $F('qcPostOfficeSelector');									
								}
							}
						});	
}

function initCashierHooks()
{
	if( $('qcDynamic'))
	{
		allInputs=$('qcDynamic').getElementsByTagName("INPUT");		

		for( i=0; i < allInputs.length; i++ )
		{
			if( allInputs[i].name=='paymentmethod' )
			{
				Element.extend( allInputs[i] );
				allInputs[i].observe( 'click', qcPaymentChange );
			}
		
			if( allInputs[i].name=='freightmethod' )
			{
				Element.extend( allInputs[i] );
				allInputs[i].observe( 'click', qcFreightChange );
			}
		}
	}
	
	if( $('qcashierAddressPane'))
	{
		allInputs=$('qcashierAddressPane').select( "select,input" );		

		for( i=0; i < allInputs.length; i++ )
		{
			if( allInputs[i].name=='country' )
				allInputs[i].observe( 'change', qcCountryChange );
			
			if( allInputs[i].name=='zipcode' )
				allInputs[i].observe( 'blur', qcZipcodeChange );			
		}
	}
	
	if( $('qcDeliveryAddressBox'))
	{
		if( $('adZip'))
			$('adZip').observe( 'blur', qcZipcodeChange );			
	}	
	
	if( $('qcDeliveryOther'))
		$('qcDeliveryOther').observe( 'click', qcDeliveryChange );
		
	if( $('adPreviousSelect'))
		$('adPreviousSelect').observe( 'change', adPreviousSelectFunc );
		
	if( $('qcPostOfficeSelector'))
	{
		$('qcPostOfficeSelector').observe( 'change', function( ev ) {
				oldPOffice = $F('qcPostOfficeSelector');			
			});
		
		qcZipcodeChange( null );
	}

	// Watch giftwrapping
	if( $('giftwrapEnable'))
		$('giftwrapEnable').observe( 'click', qcGiftWrapChange );
	
	if( $('qcGiftWrapSelection'))
	{
		allInputs=$('qcGiftWrapSelection').select( "li" );		

		for( i=0; i < allInputs.length; i++ )
			allInputs[i].observe( 'click', setGiftWrap );
	}
}

function qcGiftWrapChange( ev )
{	
	if( this.checked )
	{
		var e = $('qcGiftWrapSelection').select( 'li input' );		
		setGiftWrap2( e[0].value );
	}
	else
		setGiftWrap2( 0 );
}

function setGiftWrap2( prodno )
{
	ajaxLoadOn();

	new Ajax.Request( '/ajax.php?ajax=1&c=setgiftwrap,drawsnippet&id='+prodno+',qcDynamic', { 
				onSuccess: function( transport ) {
					ajaxLoadOff();
					
					// Check the return status, the first three characters must be 'OK:' or an error has occured
					if( transport.responseText.substring( 0, 3 ) != 'OK:' )
						alert( "The giftwrap type could not be changed (comm error).\nData returned: "+transport.responseText );
					else
					{
						$('qcDynamic').innerHTML = transport.responseText.substring( transport.responseText.indexOf( '\n' ));
						initCashierHooks();
					}
				}
			});	
}

function doQAjaxCall( ev, ajaxType )
{
	ajaxLoadOn();
	
	new Ajax.Request( '/ajax.php?ajax=1&c=set'+ajaxType+',drawsnippet&id='+ev.element().value+',qcDynamic', { 
				onSuccess: function( transport ) {
					ajaxLoadOff();
					
					// Check the return status, the first three characters must be 'OK:' or an error has occured
					if( transport.responseText.substring( 0, 3 ) != 'OK:' )
						alert( "The "+ajaxType+" method could not be changed (comm error).\nData returned: "+transport.responseText.substring( 0, transport.responseText.indexOf( '\n' )));
					else
					{
						$('qcDynamic').innerHTML = transport.responseText.substring( transport.responseText.indexOf( '\n' ));
						initCashierHooks();
					}
				}
			});	
}

function qcCountryChange( ev )
{
	doQAjaxCall( ev, 'country' );
}

function qcPaymentChange( ev )
{
	doQAjaxCall( ev, 'payment' );
}

function qcFreightChange( ev )
{
	doQAjaxCall( ev, 'freight' );
}

function qcDeliveryChange( ev )
{
	if( $('qcDeliveryAddressBox'))
	{
		if( $('qcDeliveryOther').checked  )
			$('qcDeliveryAddressBox').style.display = "block";
		else
			$('qcDeliveryAddressBox').style.display = "none";
	}
}

/*
function productNotify( ev )
{	
	relem=ev.element().up( '.popUpInfo' ).down( '.popUpNotify' );	
	selem=relem.down( 'select' );
	
	if( !selem )
		relem = relem.down( 'input' );
	else
		relem = selem;
	
	if( relem == null )
		return;
		
	ajaxLoadOn();
		
	new Ajax.Request( '/ajax.php?ajax=1&c=drawsnippet&id=notifyPopup&a='+$F(relem), { 
				onSuccess: function( transport ) {
					notifyWidth = 370;
					notifyHeight = 146;
					
					ajaxLoadOff();
		
					middleX = document.viewport.getWidth()/2;
					middleY = document.viewport.getHeight()/2;
					newX = Math.round(middleX-(notifyWidth/2));
					newY = Math.round(middleY-(notifyHeight/2));
					
					// Now add the scroll offset to ensure it can be seen within our viewport
					newX = newX + document.viewport.getScrollOffsets().left;
					newY = newY + document.viewport.getScrollOffsets().top;
					
					newX = newX+"px";
					newY = newY+"px";
		
					$('notifyPopup').style.left = newX;
					$('notifyPopup').style.top = newY;
					$('notifyPopup').style.zIndex = 200;
					$('notifyPopup').innerHTML = transport.responseText;
					$('notifyPopup').style.display = 'block';
					
					notifyInit();
				}
			});
	
	return false;
}
*/
function productNotify( ev )
{
	relem=ev.element().up( '.purchaseBar' );	
	selem=relem.down( 'select' );
	
	if( !selem )
		relem = relem.down( 'input' );
	else
		relem = selem;
	
	if( relem == null )
		return;
		
	ajaxLoadOn();

	new Ajax.Request( '/ajax.php?ajax=1&c=drawsnippet&id=notifyPopup&a='+$F(relem), { 
				onSuccess: function( transport ) {
					notifyWidth = 370;
					notifyHeight = 146;
					
					ajaxLoadOff();

					middleX = document.viewport.getWidth()/2;
					middleY = document.viewport.getHeight()/2;
					newX = Math.round(middleX-(notifyWidth/2));
					newY = Math.round(middleY-(notifyHeight/2));
					
					// Now add the scroll offset to ensure it can be seen within our viewport
					newX = newX + document.viewport.getScrollOffsets().left;
					newY = newY + document.viewport.getScrollOffsets().top;
					
					newX = newX+"px";
					newY = newY+"px";

					$('notifyPopup').style.left = newX;
					$('notifyPopup').style.top = newY;
					$('notifyPopup').style.zIndex = 200;
					$('notifyPopup').innerHTML = transport.responseText;
					$('notifyPopup').style.display = 'block';

					notifyInit();
				}
			});
	
	return false;
}

function notifyInit()
{
	if( $('notifyPopupPane'))
	{
		$('notifyPopupOk').observe( 'click', notifySend );
		$('notifyPopupCancel').observe( 'click', notifyDown );
	}
}

function notifyDown()
{
	$('notifyPopup').style.zIndex = -100;
	$('notifyPopup').style.display = "none";
}

function notifySend()
{
	new Ajax.Request( '/ajax.php?ajax=1&c=productnotify&e='+$F( 'notifyEmail' )+'&id='+$F( 'notifyProdno' ), { 
				onSuccess: function( transport ) {
					response = transport.responseText.split( ":" );
				
					if( response[0] != "OK" )
						alert( "Det gick inte att lägga till e-post adressen, kontrollera att du skrivit rätt.\n\nServern svarade: "+response[1] );
					else
					{
						notifyDown();
						alert( "Tack för visat intresse.\nDu kommer att få ett mail så snart varan åter finns i lager." );
					}
				}
			});
}

function initPage()
{
	var n = document.getElementById("category");
	if (n)
	{
		var lis = n.getElementsByTagName("li");
		for (var i = 0; i < lis.length; i++)
		{
			if (lis[i].getElementsByTagName("ul").length)
			{
				var a = lis[i].getElementsByTagName("a").item(0);
				if (a)
				{
					a.onclick = function ()
					{
						var p = this.parentNode;
						if (p.className.indexOf("active") != -1)
							p.className = p.className.replace("active", "");
						else
							p.className += " active";
							
						return true;
					}
				}
			}
		}
	}
}

function initTabs()
{
	var sets = document.getElementsByTagName("ul");
	for (var i = 0; i < sets.length; i++)
	{		
		if (sets[i].className.indexOf("tabset") != -1)
		{			
			var tabs = [];
			var links = sets[i].getElementsByTagName("a");
			for (var j = 0; j < links.length; j++)
			{
				if (links[j].className.indexOf("tab") != -1)
				{
					tabs.push(links[j]);
					links[j].tabs = tabs;
					var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

					//reset all tabs on start
					if(c)
					{
						if(links[j].className.indexOf("active") != -1)
							c.style.display = "block";
						else
							c.style.display = "none";
					}

					links[j].onclick = function ()
					{
						var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
						if (c)
						{
							//reset all tabs before change
							for (var i = 0; i < this.tabs.length; i++)
							{
								document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1)).style.display = "none";
								this.tabs[i].className = this.tabs[i].className.replace("active", "");
							}
							this.className += " active";
							c.style.display = "block";
							return false;
						}
					}
				}
			}
		}
	}
}

function addBonusProduct( w )
{
	var prodno=0;
	var blpid=0;
	
	// We need to locate which product to add, fortunately that is not too hard - we walk up one level in the DOM tree and
	// then scan downwards again for a select or input field named 'prodno'
	// Begin by extending the current event object	
	Element.extend( w );
	
	elems = w.up().up().select( '.f3 input', '.f3 select' );
	
	for( i=0; i < elems.length; i++ )
	{
		if( elems[i].name == "prodno" )		
			prodno = elems[i].value;	

		if( elems[i].name == "blpid" )
			blpid = elems[i].value;	
	}
	
	ajaxLoadOn();

	new Ajax.Request( '/ajax.php', { 
							parameters: { c: 'bonusadd,drawsnippet',
							id: blpid+',qcDynamic',
							a: prodno+',' },
							onFailure: function () {
								alert( "AJAX anrop misslyckades!" );
							},
							onSuccess: function( transport ) {
										ajaxLoadOff();
					
										// Check the return status, the first three characters must be 'OK:' or an error has occured
										if( transport.responseText.substring( 0, 3 ) != 'OK:' )
										{
											alert( "Ett fel uppstod i anropet mot servern, mottagen feltext: "+
															transport.responseText );
										}
										else
										{
											$('qcDynamic').innerHTML = transport.responseText.substring( transport.responseText.indexOf( '\n' ));
											initCashierHooks();
										}									
								}
						});
}

function ajaxCartAdd( prodno )
{
	ajaxLoadOn();

	new Ajax.Request( '/ajax.php', { 
							parameters: { c: 'add,drawsnippet',
							id: prodno+',qcDynamic',
							a: '1,' },
							onFailure: function () {
								alert( "AJAX anrop misslyckades!" );
							},
							onSuccess: function( transport ) {
										ajaxLoadOff();
					
										// Check the return status, the first three characters must be 'OK:' or an error has occured
										if( transport.responseText.substring( 0, 3 ) != 'OK:' )
											alert( "Ett fel uppstod i anropet mot servern, mottagen feltext: "+transport.responseText );
										else
										{
											$('qcDynamic').innerHTML = transport.responseText.substring( transport.responseText.indexOf( '\n' ));
											initCashierHooks();
										}									
								}
						});
}

function ajaxCartRemove( prodno )
{
	ajaxLoadOn();

	new Ajax.Request( '/ajax.php', { 
							parameters: { c: 'remove,drawsnippet',
							id: prodno+',qcDynamic',
							a: '1,' },
							onFailure: function () {
								alert( "AJAX anrop misslyckades!" );
							},
							onSuccess: function( transport ) {
										ajaxLoadOff();
					
										// Check the return status, the first three characters must be 'OK:' or an error has occured
										txt = transport.responseText.substring( 0, 3 );
										
										if( txt != 'OK:' && txt != 'RD:' )
											alert( "Ett fel uppstod i anropet mot servern, mottagen feltext: "+transport.responseText );
										else
										{
											if( txt == "RD:" )
											{
												response = transport.responseText.substring( 0, transport.responseText.indexOf( '\n' ));
												elems = response.split( ':' );
												loc = elems[1]+':'+elems[2];
												window.location.href = loc;
											}
											else
											{
												$('qcDynamic').innerHTML = transport.responseText.substring( transport.responseText.indexOf( '\n' ));
												initCashierHooks();
											}
										}									
								}
						});
}

function ajaxCartBonusRemove( blpid )
{
	ajaxLoadOn();

	new Ajax.Request( '/ajax.php', { 
							parameters: { c: 'bonusdel,drawsnippet',
							id: blpid+',qcDynamic',
							a: '1,' },
							onFailure: function () {
								alert( "AJAX anrop misslyckades!" );
							},
							onSuccess: function( transport ) {
										ajaxLoadOff();
					
										// Check the return status, the first three characters must be 'OK:' or an error has occured
										if( transport.responseText.substring( 0, 3 ) != 'OK:' )
											alert( "Ett fel uppstod i anropet mot servern, mottagen feltext: "+transport.responseText );
										else
										{
											$('qcDynamic').innerHTML = transport.responseText.substring( transport.responseText.indexOf( '\n' ));
											initCashierHooks();
										}									
								}
						});
}

function initKodmyran02()
{
	// Extend prototype...
	Ajax.Request.prototype.abort = function() {
	    this.transport.onreadystatechange = Prototype.emptyFunction;
   	 this.transport.abort();
   	 Ajax.activeRequestCount--;
	};	

	initPage();
	initTabs();
	
	if( $('currency-box') )
		$('currency-box').observe( 'change', currencyChange );

	if( $('lang-box') )
		$('lang-box').observe( 'change', langChange );

	e = document.getElementsByName( "prodno" );
	
	for( a=0; a < e.length; a++ )
		if( e[a].nodeName == "SELECT" )
			$(e[a]).observe( 'change', assocChange );

	if( $('displaycount1') && $('displaycount1').nodeName == "SELECT" )
		$('displaycount1').observe( 'change', displaycountChange1 );

	if( $('displaycount2') && $('displaycount2').nodeName == "SELECT" )
		$('displaycount2').observe( 'change', displaycountChange2 );

	// Do we have any sort objects too?
	var elems = $$('.paging .paging-display select.sortChooser');
	var i;

	for( i=0; i < elems.length; i++ )
	{
		elems[i].observe( 'change', function( ev ) {
				window.location.href = "?cmd=setsortorder&sortorder="+this.value;
			});
	}
		
	// Find the productNotify objects
	allPageTags=document.getElementsByTagName("*");  
	
	for( i=0; i < allPageTags.length; i++ )
		if( allPageTags[i].className=='notify' )
		{
			Element.extend( allPageTags[i] );
			allPageTags[i].observe( 'click', productNotify );
		}
		
	// Attach an event to the headbar operations dropdown
	if( $('headOperations'))
	{
		$('headOperations').observe( 'change', function() {
				hr = $F('headOperations');	
	
				if( hr.length > 0 )
					window.location.href = $F('headOperations');								 
		});
	}
		
	// Attach an event to the usertype selection when creating a new user
	if( $('usertype'))
	{
		if( $F('usertype') == "company" )
			$('companynamerow').style.display = "block";
		else
			$('companynamerow').style.display = "none";									 

		$('usertype').observe( 'change', function() {
			if( $F('usertype') == "company" )
				$('companynamerow').style.display = "block";
			else
				$('companynamerow').style.display = "none";
		});
	}
	
	initCashierHooks();
	
	if( $('qcFetchAddr'))
		$('qcFetchAddr').observe( 'click', fetchAddr );
		
	// Hooks on the product page
	if( $('star-rating'))
	{
		elems = $('star-rating').getElementsByTagName("A");
		
		for( i=0; i < elems.length; i++ )
		{
				Element.extend( elems[i] );
				elems[i].observe( 'click', starHandler );
		}
	}	

}

function adPreviousSelectFunc()
{	
	xo = $F('adPreviousSelect');
	
	if( xo=="" )
		return;
		
	addrs = $$('#altaddrs ul');
	adb = addrs[xo].select( 'li' );
	
	elems = $$('input,select');
		
	for( i=0; i < elems.length; i++ )
	{
		if( elems[i].name == "adContact" )
			elems[i].value = adb[0].innerHTML;

		if( elems[i].name == "adAddress1" )
			elems[i].value = adb[1].innerHTML;

		if( elems[i].name == "adAddress2" )
			elems[i].value = adb[2].innerHTML;

		if( elems[i].name == "adZip" )
			elems[i].value = adb[3].innerHTML;

		if( elems[i].name == "adCity" )
			elems[i].value = adb[4].innerHTML;

		if( elems[i].name == "adCountry" )
			elems[i].value = adb[5].innerHTML;
	}
}

if (window.addEventListener)
	window.addEventListener("load", initKodmyran02, false);
else if (window.attachEvent)
	window.attachEvent("onload", initKodmyran02 );

