/*
Filename:	common.js
Path:		\\testserver3\mamut\mamut\controls\shop\shared\includes
			AND
			\\inetnas1.world.mamut.com\nlb1data\Inetpub\www.guruworld.com\controls\shop\shared\includes
Created:	Olivia Heller - 21.03.2006
Purpose:	contains quantity validation JavaScript functions 
Used by:	all webshop templates
*/

// doSubmit
//		- true, when a form may be submitted (i.e. the quantity in its input-field er valid)
//		- used as a "public" variable in the SubmitForm and OnEnterHandler funtions
var doSubmit = false;


// Function:	SubmitForm
//
// Created:		Andre Angeltun & Olivia Heller - 07.09.2006
// Description:	execute submit-operation for a certain form
// Parameters:
//				- formName = the name of the object-form to submit
// Returns:		
//				- false, if the form can't be submitted
//				- otherwise submits the form and returns true
// Updated:	
// NB!			This function MUST have formName as parameter. It doesn't work with a formToSubmit parameter (where formToSubmit = this.form)
//
function SubmitForm( formName )
{
	if ( doSubmit == true )
		formName.submit();
	else
		return false;
}


// Function:	OnEnterHandler
//
// Created:		Olivia Heller - 05.09.2006
// Description:	validates a given value by using regular expressions and "format" it according to nr.of decimals and separator
//
// Parameters:
//				- existAtLeastTwoProductLines = refers to nr.of product lines in the "detailed basket"
//					- true, when nr. of product lines in basket >= 2
//					- false for all other cases (also when validation is not performed in basket-xsl)
//				- e = event
//				- formName = form name as a string (ex: 'addToCart')
//				- field = a field object within a <form>-tag
//				- nrOfDecimals = integer; indicates the number of decimals to be validate
//				- separator = string; separator symbol for the number typed in the field
//				- msgNotInteger = string; error message for non integer values
//				- msgNotDecimal = string; error message for non decimal values
//				- msgWasRounded = string; warning message indicated that the string in the quantity-field has been formatted (f.ex for integers, formatting means from "23.456" to "23")
//
// Returns:		the formatted value of the field
// Updated:	
//
function OnEnterHandler( existAtLeastTwoProductLines, e, formName, field, nrOfDecimals, separator, msgNotInteger, msgNotDecimal, msgWasRounded )
{
	if ( IsKeyEnterAndNotNetscape(e) )
	{
		//alert( "in OnEnterHandler, IsKeyEnterAndNotNetscape" );
		
		if ( IsValidField( field ) )
		{
			//alert( "in IsValidField" );
			
			field.value = ValidateAndFormatField( field, nrOfDecimals, separator, msgNotInteger, msgNotDecimal, msgWasRounded );
			
//			if ( formToSubmit != null )
//			{				
				if ( existAtLeastTwoProductLines )	// at least 2 product lines in the basket
				{
					// used when we have at least 2 quant-input, and only one "Buy"-button			
					document.forms[formName].submit();
				}
				else
				{			
					// used when we have quant-input followed by a "Buy"-button
					doSubmit = true;					
					SubmitForm( formName );					
				}
//			}
		}
		else
		{	
			doSubmit = false;
			field.value = ValidateAndFormatField( field, nrOfDecimals, separator, msgNotInteger, msgNotDecimal, msgWasRounded );
		}
	}
}



// Function:	IsKeyEnterAndNotNetscape
//
// Created:		Olivia Heller - 04.09.2006
// Description:	Decides whether the key down is "Enter" and browser type is "Netscape" 
//
// Parameters:
//				- e = event
//
// Returns:		true, if the key down is "Enter" and browser type is "Netscape" 
// Updated:	
//
function IsKeyEnterAndNotNetscape( e )  
{  
	return ( ( e.keyCode == 13 && navigator.appName != "Netscape" ) ? true : false ) 
}


// Function:	IsValidField
//
// Created:		Olivia Heller - 30.08.2006
// Description:	validates fields against the given regular expression
//
// Parameters:
//				- field = a field object within a <form>-tag
//
// Returns:		true, if the field is numeric
// Updated:		Olivia, 01.09.06
//
function IsValidField( field )
{
	var strRegExpr;								// string containing the regular expression to be used
	var fieldValue = field.value;				// remembers the input-field value 
	
	// The reg.expr. string under matches one of the following:
	//	. ||| , ||| 0. or 0, ||| xxxx. or xxxx, (at least one non zero x) ||| xxx.xxx or xxx,xxx (at least one non zero x)
	// 
	strRegExpr = "/(^(0{0,1})[.,]([0-9]*)$)|(^([1-9]{1})([0-9]*)[.,]([0-9]*)$)|(^([1-9]{1})([0-9]*)$)/" ;
	
	return IsMatchingRegExpr( fieldValue, strRegExpr );
}


// Function:	ValidateAndFormatField
//
// Created:		Olivia Heller - 21.03.2006
// Description:	validates a given value by using regular expressions and "format" it according to nr.of decimals and separator
//
// Parameters:
//				- field = a field object within a <form>-tag
//				- nrOfDecimals = integer; indicates the number of decimals to be validate
//				- separator = string; separator symbol for the number typed in the field
//				- msgNotInteger = string; error message for non integer values
//				- msgNotDecimal = string; error message for non decimal values
//				- msgWasRounded = string; warning message indicated that the string in the quantity-field has been formatted (f.ex for integers, formatting means from "23.456" to "23")
//
// Returns:		the formatted value of the field
// Updated:		Olivia, 31.08.06
//
function ValidateAndFormatField( field, nrOfDecimals, separator, msgNotInteger, msgNotDecimal, msgWasRounded  )
{		
	var fieldValue = field.value;	// remembers the input-field value 
	var indexOfUsedSeparator;		// the position of "." or "," in the fieldValue.substring
	var strRegExpr;					// string containing the regular expression to be used
	var regExpr;					// results by evaluating the reg.expr. against the input value
	var isValid = true;				// is true if the input value matches the reg.expr.
	
	// replaces eventually comma in fieldValue with . because we use parseFloat . This function accepts "." as decimal separator
	fieldValue = fieldValue.replace( ",", "." );
	
	// The strRegExpr string under matches one of the following:
	//	. ||| , ||| 0. or 0, ||| xxxx. or xxxx, (at least one non zero x) ||| xxx.xxx or xxx,xxx (at least one non zero x)
	// 
	strRegExpr = "/(^(0{0,1})[.,]([0-9]*)$)|(^([1-9]{1})([0-9]*)[.,]([0-9]*)$)|(^([1-9]{1})([0-9]*)$)/" ;
	isValid = IsMatchingRegExpr( fieldValue, strRegExpr );
	
	if ( !isValid )										// if the input value doesn't match the regular expression			
	{
		// t.o.m. 13.09.06: det ble vist feilmelding for ugyldig tall, avhengig av type tall
		//if ( nrOfDecimals == 0 )						// for integer values
		//	alert( msgNotInteger );
		//else											// for decimal values
		//	alert( msgNotDecimal );
		
		// Olivia 14.09.06
		// Etter en diskusjon med Øyvind, ble det bestemt at det skal vises samme melding for ugyldige tall for både hel- og desimal tall
		// For å ikke endre i alle malene, valgte jeg å sette msgNotInteger = msgNotDecimal ("Tast inn et gyldig tall")
		msgNotInteger = msgNotDecimal
		alert( msgNotDecimal );
		
		//field.focus(); -- this doesn' work with FireFox and alike.
		setTimeout(function(){field.focus()}, 10);
		
		return ReturnUnit( nrOfDecimals, separator );	// returns 1 / 1.0 (or 1,0) / 1.00 (or 1,00) depending on "nrOfDecimals" og "decimals" parameters
	}
	else
	{			
		if( isNaN( parseFloat( fieldValue ) ))			// is fieldValue numeric ?
		{
			// t.o.m. 13.09.06: det ble vist feilmelding for ugyldig tall, avhengig av type tall
			//if ( nrOfDecimals == 0 )						// for integer values
			//	alert( msgNotInteger );
			//else											// for decimal values
			//	alert( msgNotDecimal );
			
			// Olivia 14.09.06
			// Etter en diskusjon med Øyvind, ble det bestemt at det skal vises samme melding for ugyldige tall for både hel- og desimal tall
			// For å ikke endre i alle malene, valgte jeg å sette msgNotInteger = msgNotDecimal ("Tast inn et gyldig tall")
			msgNotInteger = msgNotDecimal
			alert( msgNotDecimal );
						
			fieldValue = ReturnUnit( nrOfDecimals, "." );
		}
		else
		{
			if ( parseFloat( fieldValue ) <= 0 )		// is fieldValue negative or zero ?
			{
				// t.o.m. 13.09.06: det ble vist feilmelding for ugyldig tall, avhengig av type tall
				//if ( nrOfDecimals == 0 )						// for integer values
				//	alert( msgNotInteger );
				//else											// for decimal values
				//	alert( msgNotDecimal );
				
				// Olivia 14.09.06
				// Etter en diskusjon med Øyvind, ble det bestemt at det skal vises samme melding for ugyldige tall for både hel- og desimal tall
				// For å ikke endre i alle malene, valgte jeg å sette msgNotInteger = msgNotDecimal ("Tast inn et gyldig tall")
				msgNotInteger = msgNotDecimal
				alert( msgNotDecimal );
			
				fieldValue = ReturnUnit( nrOfDecimals, "." );
			}
			else			
				fieldValue = FormatField( fieldValue, nrOfDecimals, msgWasRounded );
		}			

		// replace "." with the actually separator
		fieldValue = fieldValue.replace( ".", separator );
	
		return fieldValue;
	}
}



// Function:	FormatField
//
// Created:		Olivia Heller - 10.04.2006
// Description:	formats the value in the input field, according to parameters
// Parameters:
//				- fieldValue = string; the value in the field
//				- nrOfDecimals = integer; the number of decimals
//				- separator = string; separator symbol
//
// Returns:		a string containing the formatted value	
// Updated:		Olivia, 30.08.06
//
function FormatField( parsedValue, nrOfDecimals, msgWasRounded )
{
	var stringParsedValue = new String( parsedValue );
	
	var formattedNumber;
	var indexOfUsedSeparator;
	var decimalPart;
				
	indexOfUsedSeparator = stringParsedValue.indexOf( ".", 0 );
	decimalPart = CalculateDecimalPart( parsedValue, nrOfDecimals, indexOfUsedSeparator, msgWasRounded );
	
	formattedNumber = 
		( indexOfUsedSeparator == -1 ?	stringParsedValue : stringParsedValue.substring( 0, indexOfUsedSeparator )) + 
		( nrOfDecimals > 0 ? "." : "" ) + decimalPart;
	
	if ( formattedNumber == "0" || formattedNumber == "0.0" || formattedNumber == "0.00" )
		formattedNumber = ReturnUnit( nrOfDecimals, "." );
		
	return formattedNumber;			
}



function CalculateDecimalPart(  parsedValue, nrOfDecimals, indexOfUsedSeparator, msgWasRounded )
{
	var decimalPart = new String( parsedValue );

	// "calculate" the entire decimal part
	decimalPart = ( indexOfUsedSeparator == -1 ? "" :
					decimalPart.substring( decimalPart.indexOf( ".", 0 ) + 1, decimalPart.length ));
	
	if ( decimalPart.length >= nrOfDecimals )
	{
		if ( decimalPart.length > nrOfDecimals && HasZerosAfterDecSeparator( parsedValue ) == false )			
			alert( msgWasRounded );
			
		decimalPart = decimalPart.substring( 0, nrOfDecimals );
	}
	else
	{
		if ( nrOfDecimals == 1 )		// so decimalPart.length = 0
			decimalPart = decimalPart + "0";
		else if ( nrOfDecimals == 2 )	// so decimalPart.length = 0 or decimalPart.length = 1
		{
			if ( decimalPart.length == 0 )
				decimalPart = decimalPart + "00";
			else if ( decimalPart.length == 1 )
				decimalPart = decimalPart + "0";
			else
				alert( "Unexpected error: unknown value for decimalPart." );
		}
		else
			alert( "Unexpected error: unknown value for nrOfDecimals." );				
	}
	
	return decimalPart;
}


// Function:	ReturnUnit
//
// Created:		Olivia Heller - 10.04.2006
// Description:	returns "a unit", that is one of: 1 / 1.0 (or 1,0) / 1.00 (or 1,00) depending on parameters
// Parameters:
//				- nrOfDecimals = number of decimals
//				- separator = separator symbol
//
// Returns:		1 / 1.0 (or 1,0) / 1.00 (or 1,00) depending on "nrOfDecimals" og "decimals" parameters
// Updated:		Olivia, 31.08.06
//
function ReturnUnit( nrOfDecimals, separator )
{
	var returnValue;
	returnValue = "1" + ( nrOfDecimals > 0 && separator != "" ? separator : "" ) + ( nrOfDecimals == 1 ? "0" : "" ) + ( nrOfDecimals == 2 ? "00" : "" );
	
	return returnValue;
}	


// Function:	HasZerosAfterDecSeparator
//
// Created:		Olivia Heller - 30.08.2006
// Description:	validates a given value by using regular expressions
// Parameters:	fieldValue = string; the value in the field
// Returns:		true, if the value in the field has at least one zero after "." or "," 
//				Ex.: accepted values are f.ex.: 2,00 123.0 234.0000
// Updated:		Olivia, 31.08.06
//
function HasZerosAfterDecSeparator( fieldValue )
{
	var returnValue = fieldValue;
	var strRegExpr;
	
	strRegExpr = "/^([1-9]+)[.|,](0+)$/" ;	
	
	return IsMatchingRegExpr( fieldValue, strRegExpr );
}


// Function:	IsMatchingRegExpr
//
// Created:		Olivia Heller - 31.08.2006
// Description:	matches a given string against a given regular expression
//
// Parameters:
//				- strToMatch = a field object within a <form>-tag
//				- strRegExpr = integer; indicates the number of decimals to be validate
//
// Returns:		true, if the string matches the regular expression
// Updated:
//
function IsMatchingRegExpr( strToMatch, strRegExpr )
{
	var regExpr;								// results by evaluating the reg.expr. against the input value
	regExpr = eval( strRegExpr );				// evaluates the Java Script code in strRegExpr
	
	return regExpr.test( strToMatch );
}


// Function:	SetCookie
// Created:		Olivia Heller - 26.06.08, MIND #553644
function SetCookie( cookieName, cookieValue, expiresDays, path, domain )
{   
    var currentDate = new Date();
    currentDate.setTime( currentDate.getTime() );
    
    // expire time expressed in days
    if ( expiresDays )
        expiresDays = expiresDays * 1000 * 60 * 60 * 24;
        
    var expiresDate = new Date( currentDate.getTime() + (expiresDays) );  
    
    document.cookie = 
                cookieName + "=" + escape( cookieValue ) + 
                ( (expiresDays) ? ";expires=" + expiresDate.toGMTString() : "" ) +
                ( (path) ? ";path=" + path : "" ) + 
                ( (domain) ? ";domain=" + domain : "" );
}

// Function:	GetCookie
// Created:		Olivia Heller - 26.06.08, MIND #553644
function GetCookie( cookieName )
{    
    var startNamePosition;
    var endCookiePosition;
 
    if (document.cookie.length > 0 )
    {
        startNamePosition = document.cookie.indexOf( cookieName + "=" );

        if ( startNamePosition != -1 )
        {
            startNamePosition = startNamePosition + cookieName.length + 1;     
            endCookiePosition = document.cookie.indexOf( ";", startNamePosition )
            
            if ( endCookiePosition == -1 )
                endCookiePosition = document.cookie.length ;
                    
            return unescape( document.cookie.substring( startNamePosition, endCookiePosition )); 
        }
    }    
    return null;
}

// Function:	CheckCookiesEnabled
// Created:		Olivia Heller - 26.06.08, MIND #553644
function IsCookieEnabled( cookieName, path, domain )
{     
    SetCookie( cookieName, 'True', '', path, domain );
    
    if ( GetCookie( cookieName ) )
    {
        // Deletes cookie
        SetCookie( 'buyButtonCookie', '', -1, path, domain );
        
        return true;
    }
    else
    {
        alert( "This function uses cookies. Please enable cookies in your browser." );            
        return false;
    }    
}