/*------------------------------------------------------------------
 File:			functions.js
 Use:			Collection of clients functions.
 
 
-------------------------------------------------------------------*/

//-----------------------------------------------------------------------
// Function:	IsDate
// Use:			Return true if value is date formated as dd/mm/yyyy
//				and 2030-12-31 > value > 1990-1-1 
//
// Details	
// Parameters: 
//	Name				Description
// -------------------------------------------------------------------
//	p_value				String to be search in
//
// Author:    Assaf
// Date:      
//----------------------------------------------------------------------
function IsDate(p_value) {
	var d = new String(p_value);
	var arTmp = new Array();
	arTmp = d.split("/");
	if (arTmp.length != 3)
		return false;
	if (/\d+/.test(arTmp[2])) {
		if (arTmp[2] < 1900 || arTmp[2] > 2030)
			return false;
	} else {
		return false;
	}
	if (/\d+/.test(arTmp[1])) {
		if (arTmp[1] < 1 || arTmp[1] > 12)
			return false;
	} else {
		return false;
	}
	if (/\d+/.test(arTmp[0])) {
		if (arTmp[0] < 1 || arTmp[0] > 31)
			return false;
	} else {
		return false;
	}
	return true;
}

//-----------------------------------------------------------------------
// Function:	IsTime
// Use:			Return true if value is time formated as hh:mm
//
// Details	
// Parameters: 
//	Name				Description
// -------------------------------------------------------------------
//	p_value				String to be search in
//
// Author:    Assaf
// Date:      
//----------------------------------------------------------------------
function IsTime(p_value) {
	var d = new String(p_value);
	var arTmp = new Array();
	arTmp = d.split(":");
	if (arTmp.length != 2)
		return false;
	if (/\d+/.test(arTmp[0])) {
		if (arTmp[0] < 0 || arTmp[2] > 23)
			return false;
	} else {
		return false;
	}
	if (/\d+/.test(arTmp[1])) {
		if (arTmp[1] < 0 || arTmp[1] > 59)
			return false;
	} else {
		return false;
	}
	return true;
}

//-----------------------------------------------------------------------
// Function:	IsPhoneNumber
// Use:			Return true if value is a Phone number
//
// Details	
// Parameters: 
//	Name				Description
// -------------------------------------------------------------------
//	p_value				String to be search in
//
// Author:    Assaf
// Date:      
//----------------------------------------------------------------------
function IsPhoneNumber(p_value){
	/*
	if (p_value!=""){
		if(p_value.length > 11 || p_value.length < 9){
			return false;
		}
		for(i=0;i<p_value.length;i++){
			if((p_value.charAt(i)<"0")||(p_value.charAt(i)>"9")){ 
				if(p_value.charAt(i)!="-"){
					return false;
				} 
			}
		}
		return true;
	}
	*/
	return /^\+?[-0-9(). #]+$/.test(p_value);
}

function IsEmail(p_value)
{
	return (/^[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).test(p_value);
}
/*-----------------------------------------------------------------
	Validate a form's elements according to varius attributes.
	Parameters: 
    Name				Description
    -------------------------------------------------------------------
    form				form object
    title				alert title to be displayed
    submit				True or false : To submit the form or not.
    validclass	
    invalidclass		Initialize the variable.		
------------------------------------------------------------------*/
function getValidationInfo(input)
{
	var vi = {
			"type": input.getAttribute("v:validation"),
			"required": (input.getAttribute("v:required") == "true"),
			"requirechange": (input.getAttribute("v:requirechange") == "true"),
			"name": input.getAttribute("v:name") || input.title,
			"rangemin": input.getAttribute("v:rangemin"),
			"rangemax": input.getAttribute("v:rangemax"),
			"maxlength": input.getAttribute("maxlength"),
			"elref": input.getAttribute("v:elref"),
			"nodetail": (input.getAttribute("v:nodetail") == "true"),
			toString: function()
			{
				var x= ['input=', input.name];
				for (var o in this)
				{
					if (typeof this[o] == "function" || typeof this[o] == "object") continue;
					x.push(',', o, '=',  this[o]);
				}
				return x.join("");
			}
		};
		
	return vi;
}
function validateForm(form, title, submit, validclass, invalidclass)
{
	var i, j, u, sum;
	var input;
	var valid;
	var sErrorMsg = "";
	var failureReason;

	if (invalidclass)
	{
		for (i=0; i<document.styleSheets(0).rules.length; i++)
			if (document.styleSheets(0).rules.item(i).selectorText.toLowerCase() == "." + invalidclass.toLowerCase())
			{
				invalidclass = document.styleSheets(0).rules.item(i).style;
				break;
			}
	}

	if (hasClassName(form, "captcha-protected"))
	{
		var captcha_field = form.elements['recaptcha_response_field'];
		if (!captcha_field || captcha_field.value.length == 0)
		{
			sErrorMsg += "You have not entered the CAPTCHA challenge (type in the words in the image)\n";
		}
	}

	for (i=0; i<form.elements.length; i++)
	{
		
		input = form.elements[i];
		// skip inputs without types
		if (!input.type) continue;
		
		// skip input when it's not rendered (ie. parent display:none)
		if (input.offsetHeight == 0) continue;
		valid = true;
		failureReason = null;

		var vi = getValidationInfo(input);

		if (!vi.type) vi.type = "string";
		vi.type = vi.type.toLowerCase();

		
		// Validate value according to element type and validation type
		switch (input.type.toLowerCase())
		{
		case "text":
		case "password":
		case "textarea":
		case "file":
			if (!vi.required && (input.value.length == 0)) continue;
			switch (vi.type)
			{
			case "string":
				if (input.value.length == 0)
				{
					valid = false;
					failureReason = "cannot leave empty";
				}
				if (vi.requirechange && (input.value == input.defaultValue))
				{
					valid = false;
					failureReason = "must specify a value";
				}
				break;
			case "password":
				if (input.value.length == 0)
				{
					valid = false;
					failureReason = "cannot leave empty";
				}
				break;
			case "integer":
				if (!/\d+/.test(input.value))
				{
					valid = false;
					failureReason = "must be a number";
				}
				break;
			case "email":
				if (!IsEmail(input.value))
				{
					valid = false;
					failureReason = "must be a valid e-mail address";
				}
				break;
			case "phone":
				if (!IsPhoneNumber(input.value))
				{
					valid = false;
					failureReason = "must be a valid phone number";
				}
				break;
			case "date":
				if (!IsDate(input.value))
				{
					valid = false;
					failureReason = "must be a valid date";
				}
				break;
			case "time":
				if (!IsTime(input.value))
				{
					valid = false;
					failureReason = "must be a valid time";
				}
				break;
			case "id":
				j = input.value.toString();
				input.value = j.replace(/\D/g, "");
				if (/\d+/.test(input.value))
				{
					sum = 0;
					for (j=0; j<input.value.length; j++)
					{
						u = (j % 2 ? 2 : 1) * parseInt(input.value.charAt(input.value.length - j - 1));
						sum += u > 9 ? Math.floor(u / 10) + u % 10 : u;
					}
					if (sum % 10) 
					{
						valid = false;
					}
				}
				else
				{
					valid = false;
				}
				if (!valid) failureReason = "must be a valid ID";
				break;
			case "compare":
				// Check the compareInput attribute
				if (vi.elref)
				{
					var targetEl = form.elements[vi.elref];
					if (input.value != targetEl.value)
					{
						var target_vi = getValidationInfo(targetEl);
						if (target_vi.name)
							targetName = target_vi.name;
						else
							targetName = targetEl.name;
						valid = false;
						failureReason = "does not match " + targetName;
					}
				}
				break;
			case "order-number":
				vi.nodetail = true;			
				vi.rangemin = 6;
				// make sure there are no more than 5 consecutive character repeats
				if (/(\w)\1{5,}/.test(input.value))
				{
					valid = false;
					failureReason = "too many repeating characters";
				}
				break;
			case "product-key":
				input.nodetail = true;
				input.rangemin = 32;
				input.rangemax = 36;
				break;
			}

			// Validate max and min according to validation type
			if (valid == true)
			{
				switch (vi.type)
				{
				case "integer":
					var range = "";
					if (vi.rangemin)
					{
						range = vi.rangemin;
						if (parseInt(input.value) < parseInt(vi.rangemin))
							valid = false;
					}					
					if (vi.rangemax)
					{
						if (range.length != 0) 
							range += "-";
						range += vi.rangemax;
						if (parseInt(input.value) > parseInt(vi.rangemax))
						{
							valid = false;
						}
					}

					if (!valid) failureReason = "the number is outside the range (" + range + ")"; 
					break;
				default:
					var maxchars;
					if (vi.rangemax)
					{
						if (input.value.length > vi.rangemax) 
						{
							maxchars = vi.rangemax;
							valid = false;
						}
					}
					if (input.maxlength)
					{
						if (input.value.length > input.maxlength) 
						{
							maxchars = input.maxlength;
							valid = false;
						}
					}
					if (!valid) failureReason = "the value is too long (cannot be over " + maxchars.toString() + " characters long)";
					if (valid && vi.rangemin)
					{
						if (input.value.length < vi.rangemin) 
						{
							valid = false;
							failureReason = "the value is too short (must be at least " + vi.rangemin.toString() + " characters long)";
						}
					}
					break;
				}
			}
			break;
		case "select-one":
			if (vi.required && (input.selectedIndex == 0))
			{
				valid = false;
				failureReason = "must select a value";
			}
			break;
		case "select-multiple":
			sum = 0;
			for (j=0; j<input.options.length; j++)
			{
				if (input.options[j].selected) 
					sum++;
			}
			if ((!vi.rangemin) && (!vi.rangemax))
			{
				if (sum == 0) valid = false;
				failureReason = "must select at least one value";
			}
			else
			{
				var range = "";
				if (vi.rangemin)
				{
					range = vi.rangemin;
					if (sum < vi.rangemin) valid = false;
				}
				if (vi.rangemax)
				{
					if (range.length != 0) range += "-";
					range += vi.rangemax;
					if (sum > vi.rangemax) valid = false;
				}
				if (!valid) failureReason = "you should select between " + range + " items";
			}
			break;
		case "checkbox":
			if (vi.required && !input.checked)
			{
				valid = false;
				failureReason = "must be checked";
			}
			break;
		}

	
		if (!valid)
		{
			if (vi.name)
			{
				sErrorMsg += vi.name;
			}
			else
			{
				sErrorMsg += "Error in field " + input.name;
			}
			if (!vi.nodetail)
				sErrorMsg += ": " + failureReason;
			else
				sErrorMsg += ": invalid value";
			sErrorMsg += "\n";
			
			if (invalidclass)
			{
				if (typeof(input.originalColor) == "undefined") input.originalColor = input.style.color;
				if (typeof(input.originalBackgoundColor) == "undefined") input.originalBackgoundColor = input.style.backgroundColor;
				input.style.color = invalidclass.color;
				input.style.backgroundColor = invalidclass.backgroundColor;
			}
		}
		else
		{
			if (typeof(input.originalColor) != "undefined") input.style.color = input.originalColor;
			if (typeof(input.originalBackgoundColor) != "undefined") input.style.backgroundColor = input.originalBackgoundColor;
		}
	}
	if (sErrorMsg.length)
	{
		alert(title + "\n" + sErrorMsg);
		return(false);
	}
	else
	{
		if (submit)
		{
			form.submit();
		}
		return(true);
	}
}



/*-----------------------------------------------------------------
	Return the Previous Link from the links box.
	If the link that shown is the first then 
	the function return the last link
------------------------------------------------------------------*/
function ShowPreviousLink()
{
	if (g_nLinkCounter == 0)
	{
		g_nLinkCounter = g_nAmountOfLinks - 1
	}
	else
	{
		g_nLinkCounter--;
	}
	
	document.getElementById("Links").innerHTML = "<A href=\"javascript:void(0);\" onclick=\"clickMenu(this, g_LinksID[g_nLinkCounter]); return(false)\" class=\"NewsMessages\" TargetRef=\"" + g_LinksTargetRef[g_nLinkCounter] + "\" TypeRef=\"" + g_LinksTypeRef[g_nLinkCounter] + "\" Link=\"" + g_LinksUrl[g_nLinkCounter] + "\">" + g_Links[g_nLinkCounter] + "</A>"
	
}

/*-----------------------------------------------------------------
	Return the next Link from the links box.
	If the link that shown is the last then 
	the function return the first link
------------------------------------------------------------------*/
function ShowNextLink()
{
	
	if (g_nLinkCounter == g_nAmountOfLinks - 1)
	{
		g_nLinkCounter = 0
	}
	else
	{
		g_nLinkCounter++;
	}
	
	document.getElementById("Links").innerHTML = "<A href=\"javascript:void(0);\" onclick=\"clickMenu(this, g_LinksID[g_nLinkCounter]); return(false)\" class=\"NewsMessages\" TargetRef=\"" + g_LinksTargetRef[g_nLinkCounter] + "\" TypeRef=\"" + g_LinksTypeRef[g_nLinkCounter] + "\" Link=\"" + g_LinksUrl[g_nLinkCounter] + "\">" + g_Links[g_nLinkCounter] + "</A>"
	
}


function LoadWebsite(p_Site){
	if(p_Site != "")
		window.location.href = p_Site;
}

