/*
	kodmyran02.js
	
	This is a JavaScript file that contains small utility functions for the kodmyran02 template.
	It requires the prototype library as a prerequsite.
	
	Written by Erik Lundgren 2009-07-10
*/

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 initKodmyran02()
{
	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 );
		
	// 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 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( $('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( $F('usertype') == 'company' )
					{
						$('company').value = response[1];
						$('firstname').value = "";
						$('lastname').value = "";
					}
					else
					{
						$('firstname').value = response[1];
						$('lastname').value = response[2];
					}
			
					$('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;									
					}					
				}
				else
					alert( "Det gick inte att hämta information för detta personnummer, kontrollera att du valt privatperson/företag rätt" );
			}
		});
}

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').getElementsByTagName("SELECT");		

		for( i=0; i < allInputs.length; i++ )
			if( allInputs[i].name=='country' )
			{
				Element.extend( allInputs[i] );
				allInputs[i].observe( 'change', qcCountryChange );
			}
	}
}

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 productNotify( ev )
{
	relem=ev.element().up( '.info' ).down( '.buy' );	
	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 CheckMultiple4(frm, name) 
{
	for (var i=0; i < frm.length; i++)
	{
		fldObj = frm.elements[i];
		fldId = fldObj.id;

		if( fldId )
		{
			var fieldnamecheck=fldObj.id.indexOf(name);

			if( fieldnamecheck != -1) 
				if(fldObj.checked)
					return true;
		}
	}
	
	return false;
}

function CheckForm4(f) 
{
	var email_re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i

	if (!email_re.test(f.email.value)) 
	{
		alert("Du måste ange din e-post adress");
		f.email.focus();
		return false;
	}
        
	if (f.format.selectedIndex == -1) 
	{
		alert("Välj vilket format som du vill ha på dina nyhetsbrev");
		f.format.focus();
		return false;
	}
                    
	if( f.captcha.value == "" )
	{
		alert("Du måste ange den visade säkerhetskoden");
		f.captcha.focus();
		return false;
	}
            
	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 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;
					}
				}
			}
		}
	}
}

if (window.addEventListener)
	window.addEventListener("load", initKodmyran02, false);
else if (window.attachEvent)
	window.attachEvent("onload", initKodmyran02 );
