/*
	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 getHTTPObject()
{   
	if( window.ActiveXObject )
		return new ActiveXObject( "Microsoft.XMLHTTP" );
	else
	{
		if( window.XMLHttpRequest )
			return new XMLHttpRequest();
		else
		{
			alert( "Din web läsare verkar vara väldigt gammal, det går inte att göra AJAX anrop!" );
			return null;
		}
	}
}

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()
{
	eWidth = 350;
	eHeight = 120;
	
	middleX = document.viewport.getWidth()/2;
	middleY = document.viewport.getHeight()/2;
	newX = Math.round(middleX-(eWidth/2));
	newY = Math.round(middleY-(eHeight/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;
					
	d = document.getElementById( 'ajaxLoader' );

	d.style.top = newY+"px";
	d.style.left = newX+"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 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( $('qcCountry'))
		$('qcCountry').observe( 'change', qcCountryChange );

	if( $('qcLogin'))
		$('qcLogin').observe( 'click', qcLogin );

	// Watch fetch address
	if( $('qcFetchAddr'))
		$('qcFetchAddr').observe( 'click', fetchAddr );		

	// Watch fetch address
	if( $('textCoupon'))
		$('textCoupon').observe( 'keyup', checkCoupon );		

/*
	if( $('qcDeliveryOther'))
		$('qcDeliveryOther').observe( 'click', qcDeliveryChange );
*/
}

function qcLogin()
{
	ajaxLoadOn();
	
	new Ajax.Request( '/ajax.php?ajax=1&c=login&login='+$F('qcLoginId')+'&password='+$F('qcLoginPwd'), { 
				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( "Inloggning misslyckades!" );
					else
					{
						// Ok, things are fine - lets redraw the entire cashier...
						ajaxLoadOn();
						
						new Ajax.Request( '/ajax.php?ajax=1&c=drawsnippet&id=qcPane', { 
							onSuccess: function( transport ) {
								ajaxLoadOff();
								$('qcForm').innerHTML = transport.responseText;
								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( '.categoryProduct' );	
	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 assocChange( ev )
{
	if( $('mpAttribs'))		// On product details page
		window.location = "/product.php/"+$F('mpProdnoSelector');
	else
	{
		// We're in category view.	
		loadElement=null;
		
		for( a=ev.element(); a.parentNode; a = a.parentNode )
		{
			if( a.className == 'categoryProduct' && a.nodeName == 'DIV' )
			{
				loadElement = a;
				break;
			}	
		}

		new Ajax.Request( '/ajax.php', { 
							parameters: { c: 'drawsnippet',
							id: 'categoryProduct',
							a: ev.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 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 buildTree()
{
	t = document.getElementById('contentLeftTablinks');
		
	if( t )
	{
		uls = t.getElementsByTagName( 'LI' );
	
		for( i=0; i < uls.length; i++ )
		{
			t2 = uls[i].getElementsByTagName( 'UL' );
		
			// If t2 contains any entries it means children exists, then we must ensure the class of this
			// node contains the tag wChildren
		
			if( t2.length )
				if( uls[i].className.indexOf("wChildren") == -1)
					uls[i].className += " wChildren";
					
			if( uls[i].className.indexOf( "active" ) != -1 )
			{
				// We must enable all UL tags above this entry up until we reach contentLeftTablinks
				// There are actually two different conditions, if it is a subzero level list we must
				// expand it upwards. If it is a zero level menu we must expand it downwards, one level.
				
				for( tg = uls[i].parentNode; tg && tg.id != "contentLeftTablinks"; tg = tg.parentNode )
				{
					if( tg.tagName == "UL" )
						tg.style.display = "block";
				}
				
				for( q=0; q < t2.length; q++ )
					t2[q].style.display = "block";
			}
		}
	}
}

function mypageTabTrigger( ev )
{
	u=-1;
	l = ev.target.href.split( '#' );
	d = l[1];
	
	elems = $('mypageContent').childElements();
	
	// Disable the old container and activate the new
	for( i=0; i < elems.length; i++ )
	{
		if( elems[i].id == d )
		{
			elems[i].addClassName( 'active' );
			u=i;
		}
		else
			elems[i].removeClassName( 'active' );
	}
		
	// Move the active tab
	links = $('mypageTabset').getElementsByTagName( 'LI' );
		
	for( a=0; a < links.length; a++ )
	{
		if( a == u )
			links[a].addClassName( 'active' );
		else
			links[a].removeClassName( 'active' );		
	}
}

function initTabs()
{
	buildTree();
}

function toggleReview( ev )
{
	if( $('mpReview').style.display == "block" )
		$('mpReview').style.display = "none";
	else
		$('mpReview').style.display = "block";	
}

function toggleTipFriend( ev )
{
	if( $('mpTipFriend').style.display == "block" )
		$('mpTipFriend').style.display = "none";
	else
		$('mpTipFriend').style.display = "block";	
}

function checkCoupon()
{
	e1=$('buttonRecalc');
	e2=$('textCoupon');
	
	if( e2.value.length > 0 )
		e1.disabled = false;
	else
		e1.disabled = true;
}

function newsLetterOn()
{
	eWidth = 400;
	eHeight = 310;
	
	newX = Math.round((document.viewport.getWidth()/2)-(eWidth/2)); //+document.viewport.getScrollOffsets().left;
	newY = Math.round((document.viewport.getHeight()/2)-(eHeight/2)); // +document.viewport.getScrollOffsets().top;

	$('newsLetterLoader').style.top = newY+"px";
	$('newsLetterLoader').style.left = newX+"px";
	$('newsLetterLoader').style.display = "block";
}

function newsLetterOff()
{
	$('newsLetterLoader').style.display = "none";
}

function initSwecat()
{
	initPage();
	initTabs();
	
	// Init the click links
	if( $('mypageTabset'))
	{
		links = $('mypageTabset').getElementsByTagName( 'A' );
		
		for( a=0; a < links.length; a++ )
			links[a].observe( 'click', mypageTabTrigger );
	}
	
	e = document.getElementsByName( "prodno" );
	
	for( a=0; a < e.length; a++ )
	{
		if( e[a].nodeName == "SELECT" )
			$(e[a]).observe( 'change', assocChange );
			
		if( e[a].nodeName == "INPUT" )
		{
			x=e[a].up( '.categoryProduct' );
			k=null;
			
			if( x )
				k=x.down( '.notify' );
			
			if( k )
				k.observe( 'click', productNotify );
		}
	}
		
	if( $('crPAP1'))
		$('crPAP1').observe( 'click', toggleReview );

	if( $('crPAP2'))
		$('crPAP2').observe( 'click', toggleReview );

	if( $('crPAP3'))
		$('crPAP3').observe( 'click', toggleTipFriend );

	if( $('crPAP4'))
		$('crPAP4').observe( 'click', toggleTipFriend );
		
	// Triggers in cashier page
	initCashierHooks();
	
	// Find the newsletter object and apply the link
	if( $('cnLNlink'))
		$('cnLNlink').observe( 'click', newsLetterOn );	

	if( $('nlCancel'))
		$('nlCancel').observe( 'click', newsLetterOff );
		
	// If there is a continue to cashier button apply a Javascript trigger
	if( $('toCashier'))
	{
		$('toCashier').observe( 'click', function() {
											window.location.href = "/cashier.php";
									  });
	}
	
	as = $('pageContent').getElementsByTagName( 'A' );
	
	for( i=0; i < as.length; i++ )
		if( as[i].className == "blank" )
		{
			Element.extend( as[i] );
			
			as[i].observe( 'click', function( ev ) {
								window.open( ev.target.href );								
								ev.stop();
						});
		}
	
	return;	
}

if (window.addEventListener)
	window.addEventListener("load", initSwecat, false);
else if (window.attachEvent)
	window.attachEvent("onload", initSwecat );
