
// private functions
function showErrorMsg(parent, errorMsg, errorContainerId)
{
    if(errorContainerId)
    {
        var errorContainer = $(errorContainerId);
        errorContainer.innerHTML = errorMessage;
	    errorContainer.show();
    }
    else
    {
        if(parent.tagName == "DIV" || parent.tagName == "TD")
        { 
            if(parent.getElementsByClassName("ErrorDiv").length == 0)
            {
                new Insertion.Bottom(parent, "<div class='Required Error ErrorDiv'>" + errorMsg + "</div>");
            }
        }
    }
}

function hideErrorMsg(parent, errorContainerId)
{
    if(errorContainerId)
    {
        $(errorContainerId).hide();
    }
    else
    {
        var errorDiv = parent.getElementsByClassName("ErrorDiv")[0];
        if(errorDiv)
        {
            errorDiv.remove();
        }
    }
}


/**
* ==================================
* Length
* ==================================
*/
function validateLength(elem, errorContainerId, minLength, maxLength, errorMessage, Error, errorMsgToMatch )
{
    var errorContainer = $(errorContainerId);
    if(elem == null) 
    {
        throw  "Element not found";
    } 
    if(errorContainer == null)
    {
        throw  "Error Container not found";
    }
    if(elem.value.length < minLength || elem.value.length > maxLength)
	{
	    Error.found = true;
	    if(Error.elementToFocus == null)
	    {
	       Error.elementToFocus = elem;
		}
		errorContainer.innerHTML = errorMessage;
		errorContainer.show();
		return false;
	}
	else
	{
//	    if(errorMsgToMatch != undefined)
//	    {
//	        if(errorContainer.innerHTML != errorMsgToMatch)
//	            errorContainer.hide();
//	        else
//	            return false;    
//	    }
//	    else
	        errorContainer.hide();
	    return true;
	}
}


function validateCheckboxsChecked(options)
{
    if(options.elem == null)
    {
        return;
    }
    var parent = options.elem.up();  
    var errorMsg = "Please choose at least one type";  
	var checkboxes = options.elem.getElementsBySelector('input[type=checkbox]');
	var checkboxesSelected = false;
	for(var i = 0; i < checkboxes.length; i++)
    {
        if(checkboxes[i].checked)
        {
            checkboxesSelected = true;
            break;
        }
    }
    
    if(!checkboxesSelected)
    {
        showErrorMsg(parent, errorMsg, options.errorContainerId);
        options.Error.found = true;
        
	    if(options.Error.elementToFocus == null)
	    {
	        options.Error.elementToFocus = checkboxes[0];
	    }
    }
    else
    {
        hideErrorMsg(parent, options.errorContainerId);
    }
}

function validateIngredientIdsHash(options)
{
    if(options.elem == null)
    {
        return;
    }
    var parent = options.elem.up();  
    var errorMsg = "Please choose at least one ingredient";  
//    var arr = options.hash.keys();
//    for(var j = 0; j < arr.length; j++)
//    {
//        alert(arr[i]);
//    }
    //alert("options.hash.keys().length = " + options.hash.keys().length);
    if(options.hash.keys().length == 0)
    {
        showErrorMsg(parent, errorMsg, options.errorContainerId);
        options.Error.found = true;
        
	    if(options.Error.elementToFocus == null)
	    {
	        options.Error.elementToFocus = $$('#HerbChooserOuter input[type=checkbox]')[0];
	    }
    }
    else
    {
        hideErrorMsg(parent, options.errorContainerId);
    }	
}
/**
* ==================================
* NotEmpty
* ==================================
*/
function validateNotEmpty2(options)
{
    if(options.elem == null)
    {
        return;
    }
    var parent = options.elem.up();
    if(options.elem.alt)
    {
        var errorMsg = options.elem.alt;
    }
    else
    {
        var errorMsg = options.fieldName ? "Please fill in " + options.fieldName : "This field cannot be empty";
    }
    
    if(options.valToExclude)
    {
        var notValid = (options.elem.value.length == 0) || (options.elem.value == options.valToExclude);
    }
    else
    {
        var notValid = (options.elem.value.length == 0);
    }
    
    if(notValid)
    {
        showErrorMsg(parent, errorMsg, options.errorContainerId);
        options.Error.found = true;
	    if(options.Error.elementToFocus == null)
	    {
	        options.Error.elementToFocus = options.elem;
	    }
    }
    else
    {
        hideErrorMsg(parent, options.errorContainerId);
    }
}

function validateDoesntContain(elem, faultyChars, errorContainerId, errorMessage, Error )
{
    var ret = true;
    var errorContainer = $(errorContainerId);
    
    for(var i = 0;i<faultyChars.length;i++)
    {           
        if (elem.value.indexOf(faultyChars.substring(i,i+1)) >= 0)
            ret=false;
    }
    
    if(ret)
	    errorContainer.hide();
    else
    {
	    Error.found = true;
	    if(Error.elementToFocus == null)
	       Error.elementToFocus = elem;
		errorContainer.innerHTML = errorMessage;
		errorContainer.show();
    }
    return ret;
}

function validateNotEmpty(elem, errorContainerId, errorMessage, Error )
{
    var val = elem.value;
    var errorContainer = $(errorContainerId);
    if(val.length == 0)
	{
	    Error.found = true;
	    if(Error.elementToFocus == null)
	       Error.elementToFocus = elem;
		errorContainer.innerHTML = errorMessage;
		errorContainer.show();
		return false;
	}
	else
	{
	    errorContainer.hide();
	    return true;
	}
}

// elem
// Error
// fieldName
function validateSelect(options)
{
    if(options.elem == null)
    {
        return;
    }
    var parent = options.elem.up();
    if(options.elem.alt)
    {
        var errorMsg = options.elem.alt;
    }
    else
    {
        var errorMsg = "Please select a " + options.fieldName;
    }
    
    if(options.valToValidate)
    {
        var toValidate = (options.elem.options[options.elem.selectedIndex].value == options.valToValidate);
    }
    else
    {
        var toValidate = options.elem.selectedIndex == 0;
    }
    
    
    if(toValidate)
    {
        showErrorMsg(parent, errorMsg, options.errorContainerId);
        options.Error.found = true;
	    if(options.Error.elementToFocus == null)
	    {
	        options.Error.elementToFocus = options.elem;
	    }
    }
    else
    {
        hideErrorMsg(parent, options.errorContainerId);
    }
}

/**
* ==================================
* Password
* ==================================
*/
function validatePassword(elem, errorContainerId, Error)
{
    var pattern = /^[\S]{6,15}$/;
	return validateRegEx(elem, errorContainerId, 
	    "Enter a password that is 6 to 15 characters long with no spaces", pattern, Error);
}

/**
* ==================================
* Strings Match
* ==================================
*/
function validateFieldsOnTheFly(retypedToValidate, stringToValidateId, errorContainerId, errorMessage)
{
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;
    var errorContainer = $(errorContainerId);
    var errorFound = false;
    
    var stringToValidate = $(stringToValidateId);
    var stringToValidateValue = stringToValidate.value;
    var retypedToValidateValue = retypedToValidate.value;
    
    if(retypedToValidateValue.length > stringToValidateValue.length)
    {
        errorFound = true;
    }
    else
    {
        for(var i = 0; i < retypedToValidateValue.length; i++)
        {
            if(stringToValidate.value.charAt(i) != retypedToValidate.value.charAt(i))
            {
                errorFound = true;
                break;
            }
        }
    }
    
    if(errorFound === true)
	{
		Error.found = true;
		if(Error.elementToFocus == null)
	       Error.elementToFocus = retypedToValidate;
	    errorContainer.innerHTML = errorMessage;
	    errorContainer.show();
	}
	else
	{
	    errorContainer.hide();	   
    }
}

function validateStringsMatchOnTheFly(stringToValidate, retypedStringToValidate, 
	errorContainerId, errorMessage)
{
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false;
    retypedStringToValidate = $(retypedStringToValidate);
    validateStringsMatch(stringToValidate, retypedStringToValidate, 
	    errorContainerId, errorMessage, Error);
}

function validateStringsMatch(stringToValidate, retypedStringToValidate, 
	errorContainerId, errorMessage, Error)
{
	var errorContainer = $(errorContainerId);
	var str = stringToValidate.value;
	var retypedStr = retypedStringToValidate.value;
	var errorContainer = $(errorContainerId);
	if(str != retypedStr)
	{
		Error.found = true;
		if(Error.elementToFocus == null)
	       Error.elementToFocus = retypedStringToValidate;
	    errorContainer.innerHTML = errorMessage;
	    errorContainer.show();
	}
	else
	{
	    errorContainer.hide();	
    }
}

/**
* ==================================
* User Agreement
* ==================================
*/
function validateUserAgreement(elementToValidate, errorContainerId, errorMessage, Error)
{
	var errorContainer = $(errorContainerId);
	if(!elementToValidate.checked)
	{
	    Error.found = true;
		if(Error.elementToFocus == null)
	       Error.elementToFocus = elementToValidate;
	    errorContainer.innerHTML = errorMessage;
	    errorContainer.show();
	}
	else
	    errorContainer.hide();	
}

/**
* ==================================
* RegEx
* ==================================
*/
// options.elem
// options.errorMsg || options.elem.alt
// options.errorContainerId || null
// options.Error
// options.pattern
function validateRegEx2(options)
{
	if(options.elem == null)
    {
        return;
    }
    var parent = options.elem.up();
    if(options.elem.alt)
    {
        var errorMsg = options.elem.alt;
    }
    else
    {
        var errorMsg = options.errorMsg;
    }
    
    if(options.elem.value.length == 0 || options.elem.value.match(options.pattern) == null)
    {
        showErrorMsg(parent, errorMsg, options.errorContainerId);
        options.Error.found = true;
	    if(options.Error.elementToFocus == null)
	    {
	        options.Error.elementToFocus = options.elem;
	    }
	    return false;
    }
    else
    {
        hideErrorMsg(parent, options.errorContainerId);
        return true;
    }
}

function validateRegEx(elem, errorContainerId, errorMessage, pattern, Error)
{
	var errorContainer = $(errorContainerId);
	if(elem == null) 
    {
        throw  "Element not found";
    } 
    if(errorContainer == null)
    {
        throw  "Error Container not found";
    }
	
	
	var str = elem.value;
	if(str.length == 0 || str.match(pattern) == null)
    {    
	 	Error.found = true;
	    if(Error.elementToFocus == null)
	       Error.elementToFocus = elem;
		errorContainer.innerHTML = errorMessage;
		errorContainer.show();
		return false;
    }
	else
	{
		errorContainer.hide();
		return true;
	}
}

/**
* ==================================
* Email
* ==================================
*/
function validateEmail(elem, errorContainerId, errorMessage, Error)
{
	var emailPattern = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,6}(\.[a-zA-Z]{2})?$/;
	return validateRegEx(elem, errorContainerId, errorMessage, emailPattern, Error);
}

function validateEmail2(options)
{
	options.pattern = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,6}(\.[a-zA-Z]{2})?$/;
	return validateRegEx2(options);
}

/**
* ==================================
* Email Value
* ==================================
*/
function validateEmailValue(emailValue, elem, errorContainer, errorMessage, Error)
{
	var emailPattern = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,6}(\.[a-zA-Z]{2})?$/;
	if(emailValue.length == 0 || !emailPattern.test(emailValue))
    {    
	 	Error.found = true;
	    if(Error.elementToFocus == null)
	       Error.elementToFocus = elem;
		errorContainer.innerHTML = errorMessage;
		errorContainer.show(errorMessage);
		return false;
    }
	else
	{
		errorContainer.hide();
		return true;
	}
}

/**
* ==================================
* Emails
* ==================================
*/
function validateEmails(elem, errorContainerId, errorMessage, Error)
{
    var errorContainer = $(errorContainerId);
    if(elem.value.length == 0)
    {    
        Error.found = true;
        if(Error.elementToFocus == null)
           Error.elementToFocus = elem;
        errorContainer.innerHTML = errorMessage;
        errorContainer.show();
        return;
    }
    else
        errorContainer.hide();
		        
    var regex = new RegExp("\\s*,\\s*");
    var emails = elem.value.split(regex);
    //var emails = elem.value.split(",");
    for(var i = 0; i < emails.length; i++)
    {
        if(emails[i].trim().length > 0)
        {
            var newRecipient = emails[i].trim();
            var recipientIndex = newRecipient.indexOf('<');
            if (recipientIndex > 0)
            {
                var newRecipientLength = newRecipient.length-1;
                newRecipient = newRecipient.substring(recipientIndex + 1, newRecipientLength);
            }       
            var isValid = validateEmailValue(newRecipient, elem, errorContainer, errorMessage, Error)
            if(!isValid)
                return;
        }
    }    
}

/**
* ==================================
* CaptchaCode
* ==================================
*/
function validateCaptchaCode(captchaCode, errorContainerId, type)
{
    var _type = "reg";
    if(type != null)
    {
        _type = type;
    }
	var params= 'captchaCode=' + captchaCode.value + "&type=" + _type + "&isAjax=true"; 			
 	new Ajax.Request(siteRoot + "/Users/ValidateCaptchaCode.aspx",
        {
            parameters: params,          
            onFailure: function(t){
                showServiceMessage("Error. Please try again");
            },
            onSuccess: function(t){
				if(t.responseText == "wrong")
				{
					var errorContainer = $(errorContainerId);
					errorContainer.innerHTML = 
						"Please enter the code shown in the image";
					errorContainer.show();
				}
				else if(t.responseText == "ok")
				{
					var errorContainer = $(errorContainerId);
					errorContainer.innerHTML = "";
					errorContainer.hide();
				}
            }
        });
}


/**
* ==================================
* param Exist
* ==================================
*/
var UsernameError = {};
    UsernameError.elementToFocus = null;
    UsernameError.found = false;    
function validateExist(elem, errorContainerId, error, paramName)
{
    if(elem.value != null && elem.value.length > 0)
    {
	    var params= paramName + '=' + elem.value + "&isAjax=true"; 			
 	    new Ajax.Request(siteRoot + "/Users/Validate" + paramName + "Exist.aspx",
            {
                parameters: params,          
                onFailure: function(t){
                    showServiceMessage("Error. Please try again");
                },
                onSuccess: function(t){
                    var errorContainer = $(errorContainerId);
				    if(t.responseText == "wrong")
				    {
					    errorContainer.innerHTML = 
						    "This " + paramName + " is already taken. Please choose another";
					    errorContainer.show();
					    error.found = true; 
					    error.elementToFocus = elem; 
				    }
				    else if(t.responseText == "ok")
				    {
					    errorContainer.innerHTML = "";
					    errorContainer.hide();
					    
					    error.found = false; 
					    error.elementToFocus = null; 
				    }
                }
            });
        }
}


/**
* ==================================
* Survey
* ==================================
*/
function validateSurvey(errorContainerId, errorMessage, Error)
{
    var result = true;
    var question = $('pollQuestion');
    var elem = question;
    if (question.value=="") result = false
    var options = $$('#PollDiv .caPollOption');
    options.each(function (option)
        {
            if (option.value=="") {
                result = false;
                elem=option;
            } 
        }
    );
    
    var errorContainer = $(errorContainerId);
    if (result==false)
    {
        Error.found = true;
        if(Error.elementToFocus == null) Error.elementToFocus = elem;
        errorContainer.innerHTML = errorMessage;
        errorContainer.show();
    }
    else
	    errorContainer.hide();
}

/**
* ==================================
* Conditions
* ==================================
*/
function validateItemSelected(Error, i, newItems, errorContainerId, scrollToPageTop)
{
    var found = false;
    var errorContainer = $(errorContainerId);
	for(var j = 0; j < newItems.length; j++)
	{
	    if(!found)
	    {
	        var val = $F(newItems[j]);
	        if(val == '0')
	        {
	            errorContainer.innerHTML = "Please enter at least one item";
	            errorContainer.show();
//	            alert(errorContainer.id);
//	            alert(errorContainer.style.display);
	            if(scrollToPageTop)
	            {
	                Element.scrollTo('pageTop');
	            }
	            if(!Error.found)
	            {
	                Error.found = true;
	                Error.elementToFocus = $(newItems[j]);
	            }
	        }
	        else
	        {
	            errorContainer.hide();    
	            found = true;
	        }
	    }
	}
}

/**
* ==================================
* Ingredients
* ==================================
*/
function validateIngredientSelected(Error, i, newIngredients)
{
    var found = false;
    var errorContainer = $('IngredientErrorContainer');
	var j;
	for(j = 0; j < i; j++)
	{
	    if(!found)
	    {
	        var val = $F(newIngredients[j]);
	        if(val == '0')
	        {
	            errorContainer.innerHTML = "Please enter at least one ingredient";
	            errorContainer.show();
	            Element.scrollTo('pageTop');
	            if(!Error.found)
	            {
	                Error.found = true;
	                //Error.elementToFocus = $(newIngredients[j]);
	            }
	        }
	        else
	        {
	            errorContainer.hide();    
	            found = true;
	        }
	    }
	}
}

/**
* ==================================
* Links
* ==================================
*/
function validateLinks(errorContainerId, errorMessage, Error)
{
    var errorContainer = $(errorContainerId);
    
    var links = $$("#RelatedLinksContainer .RelatedLinksDiv");
    links.each(function(link) 
    {   
        var link = $(link);
        var linkTitle = link.down('.LinkTitle');
        var linkHref = link.down('.LinkHref');
        validateLink(linkTitle, linkHref, errorContainer, errorMessage, Error);
    });
}

function validateLink(linkTitle, linkHref, errorContainer, errorMessage, Error)
{
    if( linkTitle.value.length > 0 && linkHref.value.length == 0 || 
        linkHref.value.length > 0 && linkTitle.value.length == 0 ) 
	{
	    Error.found = true;
	    if(Error.elementToFocus == null)
	    {
	        if(linkHref.value.length == 0)
	            Error.elementToFocus = linkHref;
		    else
		        Error.elementToFocus = linkTitle;
		}
		errorContainer.innerHTML = errorMessage;
		errorContainer.show();
	}
	else if(Error.found == false)
	{
	    errorContainer.hide();
    }
}

function validateReferences(options)// errorContainerId, errorMessage, Error)
{
    var errorContainer = $(options.errorContainerId);
        
    var links = $$("#RelatedLinksContainer .RelatedLinksDiv");
    links.each(function(link) 
    {   
        var link = $(link);
        var linkTitle = link.down('.LinkTitle');
        var linkHref = link.down('.LinkHref');
        var linkSource = link.down('.LinkSource');        
        validateRefernce(linkTitle, linkHref, linkSource, errorContainer, options.errorMessage, options.Error);
    }); 
}

function validateRefernce(linkTitle, linkHref, linkSource, errorContainer, errorMessage, Error)
{
    if( (//linkTitle.value.length == 0 && linkHref.value.length == 0 && linkSource.value.length == 0 || 
        linkHref.value.length > 0 && linkTitle.value.length > 0) &&
        Error.found == false ) 
	{
        errorContainer.hide();
	}
	else if(Error.found == false)
	{
	    Error.found = true;
	    if(Error.elementToFocus == null)
	    {
	        if(linkTitle.value.length == 0)
		        Error.elementToFocus = linkTitle;
	        else if(linkHref.value.length == 0)
	            Error.elementToFocus = linkHref;
		    //else if(linkSource.value.length == 0)
		    //    Error.elementToFocus = linkSource;
		}
		errorContainer.innerHTML = errorMessage;
		errorContainer.show();
    }
}
