/**
*     Writen by S Boylen - Copyright Re-Scan Ltd 2008
*/

/**
*  Open a new window at the anchor passes in the params
*/
function opennewWindow(pURL,pAnchor)
{

	newWindow = window.open(encodeURI(pURL + '#' + pAnchor),'newWin','toolbar=no,location=no,scrollbars=yes,width=400,height=450')
}



/**
*  Open a new window and gets it ready for the print job
*/
function openPrintWindow()
{

	newWindow = window.open('print_window.html','newWin','toolbar=no,location=no,scrollbars=yes,width=600,height=450')
}
// Same as above but the php page
function openPrintWindow2(aParam)
{

	newWindow = window.open('print_window2.php?' + encodeURI(aParam),'newWin','toolbar=no,location=no,scrollbars=yes,width=600,height=450')
}



//end function


/**
* the mouse over action for the nav tabs
*/
function tabMouseOver(pTabNo)
{
	try
	{
		    var currentClass = document.getElementById('tab' + pTabNo).className;
		    var classOver    = ' navTabOver';
			document.getElementById('tab' + pTabNo).className		=   currentClass + classOver;
	}
   catch(e){}
}
//end function


/**
* the mouse out action for the nav tabs
*/
function tabMouseOut(pTabNo)
{
	
	try
	{
		    var currentClass = document.getElementById('tab' + pTabNo).className;
		    var classArray   = currentClass.split(' ');
		    var classOver    = 'navTabOver';
		    currentClass='';
		    //build class list
		    for (var i=0; i<=classArray.length-1; i++)
		    {
			   if ((classArray[i] != classOver) && (classArray[i] != '')) 
			   {
				    currentClass += classArray[i] + ' ';
			   }
		    }
		    
			document.getElementById('tab' + pTabNo).className		=   currentClass;
	}
   catch(e)  {  }	
}
//end function


/**
*  Checks if the input is a int number
*/
function isNumeric(aItem)
{
	if ((isNaN(aItem.value)) || (aItem.value<0) || (aItem.value>9999) || (aItem.value.length==0) )
	{
		alert('The quantity must be a valid positive number.\n');
		aItem.value = '0';
		return false;
	}
	else
	{
	   // check that its a whole number	
	   if (aItem.value.indexOf('.') != -1)
	   {
		   alert('The quantity must be a whole number.\n');
		   try
		   {
		      aItem.value = parseInt(aItem.value);
	       }catch (e){
		       aItem.value = 0;
	       }
		   return false;   
	   }else{	
	       return true;
       }
    }
}

/**
*    Checks that the passwords match and are ok length
**/
function passwordCheck(passwordOld,passwordNew,passwordRetype)
{

	try
	{
		var error = '';
		
		if (passwordOld.value.length == 0)
		{
			error = 'Please enter your current password into the space provided.\n';
		}
		if (passwordNew.value.length == 0)
		{
			error = 'Please enter your new password into the space provided.\n';
		}
		if (passwordRetype.value.length == 0)
		{
			error = 'Please re-type your new password into the space provided.\n';
		}
		if (passwordRetype.value != passwordNew.value)
		{
			error = 'Your new password does NOT match the re-typed one.\n';
		}
		if (passwordOld.value == passwordNew.value)
		{
			error = 'The new password can NOT be the same as the old one.\n';
		}
		if (passwordNew.value.length <= 3)
		{
			error = 'New password must be longer the 4 characters.\n';
		}
	
	
		if (error.length != 0)
		{
			alert(error);
		    return false;	
		}else{
		    return true;	
		}
	}
	catch(e)
	{
		return true;
	}
}

function confirmComplete(aQuestion)
{
	return confirm(aQuestion);
}

// check register info
function registerCheck()
{
	try
	{
		var error = '';

		if (document.rm_register.surname.value.length == 0)
		{
			error = 'Please enter a your surname.\n';
		}
		if (document.rm_register.firstname.value.length == 0)
		{
			error = 'Please enter a first name.\n';
		}
		if (document.rm_register.tel1.value.length == 0)
		{
			error = 'Please enter a contact telephone number.\n';
		}
		if (document.rm_register.postcode.value.length == 0)
		{
			error = 'Please enter your postcode.\n';
		}
		if (document.rm_register.town.value.length == 0)
		{
			error = 'Please enter your town.\n';
		}
		if (document.rm_register.add1.value.length == 0)
		{
			error = 'Please enter complete address line 1.\n';
		}
		if (document.rm_register.aemail.value.length == 0)
		{
			error = 'Please enter an e-mail address.\n';
		}else{
			error = isEmail(document.rm_register.aemail.value);
		}
	
		if (error.length != 0)
		{
			alert(error);
		    return false;	
		}else{
		    return true;	
		}
	}
	catch(e){ return true;	}
}

// Adds aNumber to aQtyFild (if aNumber is neg the it is subtracted)
function qtyUpdate(aQtyFild,aNumber)
{
	if (isNumeric(aQtyFild))
	{
		var l_qty = parseInt(aQtyFild.value) + aNumber;
		if (l_qty >= 0)
		{
			aQtyFild.value = l_qty;
		}else{
		    aQtyFild.value = '0';	
		}
	}
}

// Checks there is info in the ref
function checkRef(aField)
{
	if (aField.value.length <= 4)
	{
		alert('The reference code should be 4 or more characters in length');
		return false;
	}else{ 
		return true; 
	}
}

// Sets the items per page cookie, to show the users requested ipp
function itemsPerPage(ipp)
{
	if ((isNaN(ipp)) || (ipp>200) || (ipp<5))
	{
	    ipp = 50;	
	}
	
	    var date = new Date();
		date.setTime(date.getTime()+(365*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
        document.cookie = 'cIpp='+ipp+expires+"; path=/";
        alert('Default items per page changed to ' + ipp + '.\nYou must refresh your browser for this to take effect');
}


// Swap the img src with the one passed in the params
function imgSwap(imgName,imgID){
	
	   //Get the Img Element
	    if(document.getElementById) {
		    var divObj = document.getElementById(imgID);
	    } else if (document.all){
		    var divObj = document.all[imgID];
	    }
	    if (divObj != null){
		    currentImg = divObj.src;
		    i = currentImg.lastIndexOf('/'); 
		    if (i != -1)
		    {
			    currentImg = currentImg.substring(0,i);
		        divObj.src = currentImg + '/' + imgName;  
	        }   
	    }
}


 /**
*  checks email addresses
*  Reurns a str to say the error found ('' is no error)
*/
function isEmail(l_email)
{
    atSymbol   = '@';
    dotSymbol  = '.';
    var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
    eArray = l_email.split(atSymbol); //There shouldonly be 2 parts, name and domain  
    error = '';
    
    if (eArray.length != 2){
        error = (''  + (eArray.length-1) + ' @ symbols found');
    }
    else if ((l_email.indexOf('.@') != -1)
           || (l_email.indexOf('..') != -1)
           || (l_email.indexOf('@.') != -1)
           || (l_email.indexOf('@@') != -1))
    {
        error = ('invalid format');
    }
    else if (eArray[0].length == 0)
    {
	    error = ('Name is to short');    
    }
    else if (eArray[1].length == 0)
    {
	    error = ('Domain is to short');    
    }
    else if ( (eArray[1].indexOf('.') == -1) || (eArray[1].lastIndexOf('.') == (eArray[1].length-2)) )
    {
	    error = ('Domain must contain a valid suffix');    
    }
    else if ( (eArray[1].indexOf('.') < 2) )
    {
	    error = ('Invalid domain name');    
    }
    else
    { 
			    	    	    	    
		for (i=0; i<invalidChars.length; i++) {
		   if (l_email.indexOf(invalidChars.charAt(i),0) > -1) {
		        error = ('email address contains invalid characters');
		   }
		}  
		        
    }
    
    return error;

    
}//endfunction

//Start J-Query : See http://docs.jquery.com/
$(document).ready(function(){
	var lastmenu = '';
	
	          //url regex
	          $("div#topmessage").fadeOut("fast");

	          
              $("#product_holder span a").click(JQPopupwindow);
              $("#product_brands a").click(JQPopupwindow);
              $("#recommended a").click(JQPopupwindow);
              
              function JQPopupwindow()
              {
	              
	              l_url = $(this).html();
                  l_urlArray = $(this).attr("href").split("?");                  
	              
	              if (l_urlArray.length > 0)
	              {
		              
		              l_qsArray = l_urlArray[1].split('&');		              
		              l_value   = l_qsArray[0].split('=');
		              
	                  $("#divObj").addClass("hidden_div").load("productpopup.php?ean=" + l_value[1]);  
					   //set the pop-up's title
	                  $("#divObj").attr("title",l_url);
	                  $("#divObj").removeClass("hidden_div").dialog({ 
    				    	modal: true, 
    					    overlay: { 
        				    opacity: 0.5, 
        				    background: "black" 
    					    },
    					    height:300,
    					    width:450
					    }); 
					    
					    return false; 
				  }
              }
              
              
              // Add item to an order
              $("#product_holder div form").submit(function()
              {
	              var l_ean = $(this).children("input#ean").attr("value");
	              var l_qty = $(this).children("input#qty").attr("value");
	              if (isNaN(l_qty))  { l_qty = 0; }
	              
	              $("div#topmessage").text('Please wait.');
	              $("div#topmessage").load('order_additem_popup.php?ean=' + l_ean + '&qty=' + l_qty,'',updateBasket).slideDown();//.show("slow");

	              return false; 
              });
              
              // Add item to an order 
              $("#divObj form").submit(function()
              {
	              alert('Can not add products from here');
	              $("#divObj").dialog("close");
	              
	              return false; 
              });
              
              // Updats the basket section of the screen
              function updateBasket(responseText, textStatus, XMLHttpRequest) {
                   $("div#basket_body").fadeOut("fast").load('order_basket_popup.php').slideDown();
              }
              
              
             
              $("#productgroupside ul li a").click(JQShowSubGroups);
              
	          
              $("#productgroupside ul li ul").hide();
              
              function JQShowSubGroups()
              { 
	              var thisid = '#' + $(this).attr('id') + ' + ul'; 
	              
	              
	              if ($(thisid).html() == null)
	              {
		            return true;   
	              }
	              else
	              {
	              
		              $(lastmenu).slideUp();
		              
		              if (thisid != lastmenu)
		              {	              
		                  $(thisid).slideDown(); 
	                  }else{
		                  thisid = ''; 
	                  }
		              
		              lastmenu = thisid;
		              
		              return false;
	              }
              }


              
});
//End J-query
