//==================================================================
// form class
//==================================================================

function form(id, required, hilite)
{
	//--------------------------------------------------------------
	// variables
	//--------------------------------------------------------------		
	this._id		= id;
	this._errors	= [];
	this._required	= [];
	
	this._regex 	= {
		
		postal_code: 	/^[abceghjklmnprstvxyABCEGHJKLMNPRSTVXY][0-9][abceghjklmnprstvwxyzABCEGHJKLMNPRSTVWXYZ] {0,1}[0-9][abceghjklmnprstvwxyzABCEGHJKLMNPRSTVWXYZ][0-9]$/
	};

	//--------------------------------------------------------------
	// private methods
	//--------------------------------------------------------------
	
	//	init
	this._init		= function()
	{
		this._set();
	}
	
	//	set variables, objects and elements
	this._set		= function()
	{
		this._required	= required;	
		
		// deprecated
		//--------------------------
		this._hilite	= hilite;			
		//--------------------------
	}
	
	this._appendErrors = function()
	{
		var errorContainer 	= $("#" + this._id + " .error_container");
		var curHeight 		= $(errorContainer).height();
		
		errorContainer.empty();

//		build error list		
		var html = "<ul>";
		for(var i = 0; i < this._errors.length; i++)
		{
			html += "<li>" + this._errors[i].msg + "</li>";
		}
		
		html += "</ul>";
		
		errorContainer.append(html);
		
		if(curHeight <= 0)
		{			
//			the error container is empty, so just add the entire height of error container
			var newHeight = $("#lightbox .popup").height() + $(errorContainer).height();
		}
		else
		{	
//			the error container is already visible so only add any additional error conatiner height
			var heightDiff = $(errorContainer).height() - curHeight;
			
			var newHeight = $("#lightbox .popup").height() + heightDiff;		
		}	
		
//		var newHeight = $("#lightbox .popup").height() + $(errorContainer).height();
		
		PopupController.manualResize(null, newHeight, this);
	}
		
	//--------------------------------------------------------------
	// public methods
	//--------------------------------------------------------------
	
	//called from PopupController
	this.resizeFinished	= function()
	{
		$("#" + this._id + " .error_container").fadeIn("slow");
	}
	
	//	check form prior to submit
	this.check	= function()
	{
		this._errors	= [];
				
		for(var r = 0; r < this._required.length; r++)
		{
			var field 		= $("#" + this._id + " #" + this._required[r].id);
			
			var errorMsg	= $("label[@for=" + this._required[r].id + "] > code").html();
			var value		= null;
			
			switch(field.attr("type"))
			{
				case	"text":
					value	= field.val();
				break;
				case	"radio":
					$("input[@name=" + field.attr("name") + "]:checked").length <= 0 ? value = false : value = true;
				break;
				case	"checkbox":				
					value	= field.attr("checked");
				break;
			}
				
			if(value.length < 1 || !value)
			{	
				this._errors.push({ input:field , msg:errorMsg });
			}
			else if(this._required[r].regex)
			{
				
				if (!this._regex[this._required[r].regex].test(value))
					this._errors.push({ input:field , msg:errorMsg });
			}
		}
		
		if(this._errors <= 0)
		{	
//			form is valid submit it
			$("#" + this._id).submit();
//			return false;
		}
		else
		{
			var popup = $("#" + this._id).parent("#popup_wrapper");
			
			if(popup.length > 0)
			{
//				console.log("!!!INVALID Form in POPUP: " + this._errors);
//				form was in a popup so append errors to popup				
				this._appendErrors();
			}
			else
			{
//				console.log("!!!INVALID Form in FROM PAGE: " + popup);
				//form was in main page open errors in a popup
				//alert("open pop-up");
			}
			
			return false;
		}
		
		
		/*if(this._error)
		{
			count	= 1
			html	= "<ol>";
			for(error in this._errors)
			{
				html += this.item(this._errors[error]);
				count++;
			}			
			html	+= "</ol>";
			$("#" + this._id + " .error").html(html);
			$("#" + this._id + " .error").fadeIn(
				'slow'
			);
		}
		else
		{
			$("#" + this._id).submit();
		}*/
	}
	
	//	hilite error effect
	this.hilite		= function(id)
	{
		$("#" + id).animate(
			{
				borderColor:"#F7C9A6",
				backgroundColor:"#FFF3D8"
			}
		)
	}
	
	//	error list item
	this.item		= function(copy)
	{
		return	"<li><strong>Error " + count + ":</strong> " + copy + "</li>";
	}
	
	//	run this 
	this._init();
};





function togglePostalCodeTexbox(pCode)
{
	
	//alert("CboX Value:" + document.getElementById("cBox").checked);
	//alert("txtPCode Value:" + document.getElementById("txtPCode").checked);
	if(document.getElementById("registerNewsletterCBox").checked)
	{
		if(pCode != null)
		{
			document.getElementById("registerPostalCodeTextbox").value=pCode;
		}
		document.getElementById("registerPostalCodeTextbox").disabled=false;
	}
	else
	{
		document.getElementById("registerPostalCodeTextbox").value=" ";
		document.getElementById("registerPostalCodeTextbox").disabled=true;
	}
}


//list of invalid chars
var invalidChars = new Array('!','@','#','$','%','^','&','(',')'); 

//function to validate search term
function validateSearchQuery()
{				
	var argv = validateSearchQuery.arguments;
	var searchTerm = argv[0];
	searchTerm = trim(searchTerm);
	var len=searchTerm.length;
	if(searchTerm == "Search" || searchTerm == "Recherche")
	{
		//alert("DT");
		PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/searchLightBox.jsp?errorMsg=default',12345,contextPathVal+'/jsp/lightbox_content');
		return false;
	}	
	
	
	var lengthErrorFlag = false;
	var invalidCharErrorFlag = false;
	
	for(i=0;i<len;i++)
	{
		var temp=searchTerm.charAt(i);
		for(j=0;j<invalidChars.length;j++)
		{
			if(temp==invalidChars[j])
			{
				invalidCharErrorFlag = true;
				PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/searchLightBox.jsp?errorMsg=invalid',12345,contextPathVal+'/jsp/lightbox_content');
				return false;
			}
		}					
		if(temp == "*")
		{
			len=len-1;
		}
	}				
	if(len<3)
	{
		lengthErrorFlag = true;
		PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/searchLightBox.jsp?errorMsg=len',12345,contextPathVal+'/jsp/lightbox_content');
		return false;
	}
	return true;
}
		
function validateSearchQueryTop()
{
	var argv = validateSearchQueryTop.arguments;
	var postalCode = argv[0];
	var searchQuestion = argv[1];
	
	//check if search term is valid or not
	var isSearchQuestionValid = validateSearchQuery(searchQuestion);
	if(!isSearchQuestionValid) {
		return false;
	}
	
	if(postalCode == "")
	{
		PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/postalCodeLightBox.jsp?searchQuestion='+searchQuestion,12345,contextPathVal+'/jsp/lightbox_content');
		//PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/searchLightBox.jsp?errorMsg=postal',12345,contextPathVal+'/jsp/lightbox_content');
		return false;
	}
	
	
}		
		
function validateSearchQueryBottom()
{
	//check for postal code
	var argv = validateSearchQueryBottom.arguments;
	var searchQuestion = argv[0];
	return validateSearchQuery(searchQuestion);
}

	/* This method checks for Alphabets in the String
	   input parametes: String
	   output         : boolean
	   Author         : Animesh
	*/
	
	function isAlpha()
	{
		var argv = isAlpha.arguments;
		var aString = argv[0];
		if (aString.length != 0)
		{
			var indexLimit = aString.length;
			var character = ' ';
			for (var i=0; i<indexLimit; i++)
			{
				character = aString.charAt(i);
				//alert(character);
				if (((character < 'A') || ((character > 'Z') && (character < 'a')) || (character > 'z')))
				{
					 return false;
				}
			}
		}
		return true;
	}
	
	/* isAlpha method ends */

	/* This method checks for Numbers in the String
	   input parametes: String
	   output         : boolean
	   Author         : Animesh
	*/

	function isNumeric() 
	{
		var argv = isNumeric.arguments;
		var value = argv[0];
		var nums = "0123456789";
		if (value.length != 0)
		{
			if ((nums.indexOf(value))==-1)
			{
				return false;
			}
			else
			{
				return true;
			}
		}
	}
	
	/* isNumeric method ends */


	/*
		This method checks for proper format for Postal Codes. The format is (ANANAN) A= Alphabet , N = Numeric
		input parametes: Postal Code
	   	output         : boolean
		Author         : Animesh
	*/
	
	function validatePostalCode()
	{
		var argv = validatePostalCode.arguments;
		var postalCode = argv[0];
	
		if (postalCode == "" || postalCode==null)
		{	
			PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/postalCodeValidLightBox.jsp?errorMsg=invalid',12345,contextPathVal+'/jsp/lightbox_content');
			return false;
		}
		var strPostal = postalCode;

		if (strPostal.length==6)
		{
			for (i=0;i<6;i++)
			{
				var check = strPostal.charAt(i);

				if (i % 2 == 0)
				{
					if (!(isAlpha(check)))
					{
						PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/postalCodeValidLightBox.jsp?errorMsg=invalid',12345,contextPathVal+'/jsp/lightbox_content');
						return false;
					} 
				}
				else if (i % 2 != 0)
				{
					if ((isNumeric(check))== false)
					{
						PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/postalCodeValidLightBox.jsp?errorMsg=invalid',12345,contextPathVal+'/jsp/lightbox_content');
						return false;
					}
				}
				else
					return true;
				
			}
			
		}
		else if (strPostal.length==7)
		{
			if(postalCode.charAt(3)== ' ')
			{
				var temp1 = postalCode;
				var temp2 = postalCode;
					
				temp1=postalCode.substring(0,3);
				temp2=postalCode.substring(4,7);

				postalCode = temp1 + temp2;
				var strPostal = postalCode;
				for(i=0;i<6;i++)
				{
					var check = strPostal.charAt(i);
					if (i % 2 == 0)
					{
						if (!(isAlpha(check)))
						{	
							PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/postalCodeValidLightBox.jsp?errorMsg=invalid',12345,contextPathVal+'/jsp/lightbox_content');
							return false;
						} 
					}
					if (i % 2 != 0)
					{
						if ((isNumeric(check))== false)
						{
							PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/postalCodeValidLightBox.jsp?errorMsg=invalid',12345,contextPathVal+'/jsp/lightbox_content');
							return false;
						}
					}
				}
			}
			else
			{
				PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/postalCodeValidLightBox.jsp?errorMsg=invalid',12345,contextPathVal+'/jsp/lightbox_content');
				return false;
			}
		}
		else 
		{
			PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/postalCodeValidLightBox.jsp?errorMsg=invalid',12345,contextPathVal+'/jsp/lightbox_content');
			return false;
		}
	}
	
	/* validatePostalCode method ends */

	/*
		This method internally get called to display the error messages on the change postal light box itself.
		input parametes: Postal Code
	   	output         : boolean
		Author         : Animesh
	*/

	function validatePostalCodeBlank()
	{
		var argv = validatePostalCodeBlank.arguments;
		var postalCode = argv[0];
		$('#errorBlank').hide();
		$('#errorFormat').hide();
		$('#errorLength').hide();
		
		if (postalCode == "" || postalCode==null)
		{	
			$('#errorBlank').show();
			$("#lightbox .popup").css("height","auto");
			return false;
		}

		var strPostal = postalCode;
		if (strPostal.length==6)
		{
			for (i=0;i<6;i++)
			{
				var check = strPostal.charAt(i);
				if (i % 2 == 0)
				{
					if (!(isAlpha(check)))
					{
						$('#errorFormat').show();
						$("#lightbox .popup").css("height","auto");
						return false;
					} 
				}
				else if (i % 2 != 0)
				{
					if ((isNumeric(check))== false)
					{
						$('#errorFormat').show();
						$("#lightbox .popup").css("height","auto");
						return false;
					}
				}
				else 
					return true;
			}
		}
		else if (strPostal.length==7)
		{
			if(postalCode.charAt(3)== ' ')
			{
				var temp1 = postalCode;
				var temp2 = postalCode;
				
				temp1=postalCode.substring(0,3);
				temp2=postalCode.substring(4,7);

				postalCode = temp1 + temp2;
				var strPostal = postalCode;
				for(i=0;i<6;i++)
				{
					var check = strPostal.charAt(i);
					if (i % 2 == 0)
					{
						if (!(isAlpha(check)))
						{	
							$('#errorFormat').show();
							$("#lightbox .popup").css("height","auto");
							return false;
						} 
					}
					if (i % 2 != 0)
					{
						if ((isNumeric(check))== false)
						{
							$('#errorFormat').show();
							$("#lightbox .popup").css("height","auto");
							return false;
						}
					}
				}
			}
			else
			{
				$('#errorFormat').show();
				$("#lightbox .popup").css("height","auto");
				return false;;
			}
		}
		else 
		{
			$('#errorLength').show();
			$("#lightbox .popup").css("height","auto");
			return false;
		}
		return true;
	}

	/* validatePostalCodeBlank method ends */
	
	
	/*
		Function for Empty Postal Code in Session
	   	Output         : boolean		
		Author		   : Viral
	*/
	function validatePostalCodeForHeader(url)
	{
		//alert('in');
		//alert(document.getElementById("postalCode").value);
		//alert('url: ' + url);
		
		if ( (document.getElementById("postalCode").value == "") || (document.getElementById("postalCode").value==null) || (document.getElementById("postalCode").value=='null'))
		{	
			PopupController.openPopup(contextPathVal+'/jsp/lightbox_content/postalCodeLightBox.jsp?catURL='+url+'',12345,contextPathVal+'/jsp/lightbox_content');
			return false;
		}
	}



	/*Validate SendEamilAttributes Method starts */
	/*
	    Function for Email To Friend Validation 
		Author : Soni Vimal
	*/
	
	 
function validateSendEmailAttributes()
{  
  var argv = validateSendEmailAttributes.arguments;
  var recipientName=argv[0];
  var recipientEmail=argv[1];
  var SenderName=argv[2]; 
  var yourEmail=argv[3]; 
  var personalMessage =argv[4]; 
  
  var err=new Boolean(false);
  
  // Clear The divs
  
  
 $('#err').hide(); 
 
 $('#recptname').hide(); 
 $('#recptinvalidname').hide();  
 $('#recptemail').hide();  
 
 $('#urname').hide(); 
 $('#urinvalidname').hide();  
 $('#uremail').hide();
 
 $('#invalidrecptemailerror').hide();
 $('#invaliduremailerror').hide();   
 $('#invalidPersonalMessage').hide(); 
 
  /*
  $('#recipientName').hide();  
  $('#recipientEmail').hide();  
  $('#SenderName').hide();  
  $('#yourEmail').hide();  
  $('#personalMessage').hide();  */
     
  
   function isAlpha2()
	{
		var argv = isAlpha2.arguments;
		var aString = argv[0];
		if (aString.length != 0)
		{
			var indexLimit = aString.length;
			var character = ' ';
			for (var i=0; i<indexLimit; i++)
			{
				character = aString.charAt(i); 
				if (((character < 'A') || ((character > 'Z') && (character < 'a')) || (character > 'z')) && (character != ' '))
				{
					 return false;
				}
			}
		}
		return true;
	} 
  
  if(recipientName == "" || recipientName == null)
  {
    
    $('#test1').hide();
  	$('#recptname').show();
  	$('#recipientName').addClass("errorFld");
	$("#lightbox .popup").css("height","auto");
	err=true;
  } 
  
  else
  { 
	if(recipientName != null)
	{
		 
		if (!(isAlpha2(recipientName)))
		{   
		  $('#test1').hide();
		  $('#recptinvalidname').show();
		  $('#recipientName').addClass("errorFld");
		  $("#lightbox .popup").css("height","auto");
		  err=true; 
		}
	   else
	   {
		 $('#recipientName').removeClass("errorFld");
	   }		
	}
	
	
	  
  } 
 
 if(recipientEmail == "" || recipientEmail == null )
	{
		 
		$('#test1').hide();
		$('#recptemail').show();
		$('#recipientEmail').addClass("errorFld");
		$("#lightbox .popup").css("height","auto");
		err=true;
	}
	else
	{ 
		if(recipientEmail != null)
		{
		   var reg =/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/ ;  
		   var address = recipientEmail;
		    
		   if(reg.test(address) == false) 
		   {
		     
		     $('#test1').hide();
			 $('#invalidrecptemailerror').show();
			 $('#recipientEmail').addClass("errorFld");
			 $("#lightbox .popup").css("height","auto");
		     err=true;
		   }
		   
		   if(reg.test(address) == true) 
		   { 
		     $('#test1').hide(); 
			 $('#recipientEmail').removeClass("errorFld");  
		   }

		}

	}
	
	if(SenderName == "" ||  SenderName == null)
	 { 
		 
		$('#test1').hide();
		$('#urname').show();
		$('#SenderName').addClass("errorFld");
		$("#lightbox .popup").css("height","auto");
	    err=true;
	  }
       else
		{  
			if(SenderName != null ||SenderName.length>0)
			{  
				if (SenderName.length>0)
				{
					if (!(isAlpha2(SenderName)))
					{ 
						$('#test1').hide();
						$('#urinvalidname').show();
						$('#SenderName').addClass("errorFld");
						$("#lightbox .popup").css("height","auto"); 
						err=true;
					}
					else
					{
					  $('#test1').hide(); 
					  $('#SenderName').removeClass("errorFld"); 
					}
				} 
				else
				{
					$('#test1').hide();
					$('#urname').show();
					$('#SenderName').addClass("errorFld");
					$("#lightbox .popup").css("height","auto");
	    			err=true;
				}
			}
			else
					{
					  $('#test1').hide(); 
					  $('#SenderName').removeClass("errorFld"); 
					}
			
		 }  
   if(yourEmail  == "" || yourEmail == null )
	{
		$('#test1').hide();
		$('#uremail').show();
		$('#yourEmail').addClass("errorFld");
		$("#lightbox .popup").css("height","auto");
		err=true;
	}
	else
	{ 
		if(yourEmail != null)
		{
		   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/ ; 
		   var address = yourEmail;
		 
		   if(reg.test(address) == false) 
		   {
		     $('#test1').hide();
			 $('#invaliduremailerror').show();
			 $('#yourEmail').addClass("errorFld");
			 $("#lightbox .popup").css("height","auto"); 
			 err=true;
		   } 
		   if(reg.test(address) == true) 
		   { 
			 $('#test1').hide();
			 $('#yourEmail').removeClass("errorFld");  
		   } 
		} 
		
	}
	
	if (personalMessage !=null)
		{ 
				var len = personalMessage.length; 
				if (len>250)
				{
					 $('#test1').hide();
					 $('#invalidPersonalMessage').show();
					 $('#personalMessage').addClass("errorFld");
					 $("#lightbox .popup").css("height","auto"); 
					 err=true;
				}
					if (len>250)
				{
					 $('#test1').hide(); 
					 $('#personalMessage').removeClass("errorFld"); 
				}
		}
		  
	
	var text =document.emailFriendFrm.SenderName.value +' '+'has sent you product information from theBrick.com' ; 
	document.getElementById("msgSubject").value =text;
	
	if(err == true)
	{
	  $('#err').show();
	  if( $("#recipientName").is(".errorFld") )
	   {
		  $('#recipientName').focus();
		 }
		 else if($('#recipientEmail').is(".errorFld"))
		 {
			$('#recipientEmail').focus();
		 }
     else if($('#SenderName').is(".errorFld"))
		 {
			$('#SenderName').focus();
		 }
		else if($('#yourEmail').is(".errorFld"))
		 {
			$('#yourEmail').focus();
		 }
	  return false;
	}
	else
	{
	   $('#test1').show();
       
	   
	   return true;
	}
 }
 
 
function trim(s) {
	return s.replace(/^\s+|\s+$/g,"");
}
