	$(document).ready(function(e) {
        $('button.reset_button').click(function(e) {
			$('div.form-group.has-error .error_alert').html('');
			$('div.form-group').removeClass('has-error');
        });
    });
	
	/**************************************************************************************************************************/
						//'txt','number','phone','Phone No.'
	function validate(input_type, sub_type, tag_id, tag_title,min_len, max_len, data_type)
	{
		var val 	= $.trim($('#'+tag_id).val());
		var msg		= '';
		//console.log(data_type);
		if(input_type == 'dd')
		{
			if(val == '')
			{
				msg	= 'Please select '+tag_title;
			}
		}
		else if(input_type == 'cb')
		{
			if(val == '')
			{
				msg	= 'Please select '+tag_title;
			}
		}
		else
		{
			if(val == '')
			{
				if(tag_id == 'cpassword')
				{
					msg	= 'Please '+tag_title;
				}
				else
				{
					msg	= 'Please enter '+tag_title;
				}
				
			}
			else if(sub_type == 'email' && !(validateEmail(val)))
			{
				msg	= 'Please enter a valid '+tag_title;
			}
			else if(sub_type == 'number' && !(validateEmail(val)))
			{
				msg	= 'Please enter a valid '+tag_title;
			}
			else if(val.length > max_len && max_len != '')
			{
				msg	= 'Only '+max_len+' characters are allowed for '+tag_title;
			}
			else if(val.length < min_len && min_len != '')
			{
				msg	= tag_title+' must be at least '+min_len+' characters in length';
			}
			else if(data_type == 'alpha' && !(isAlpha(val)))
			{
				msg	= 'Only alphabets are allowed in '+tag_title;
			}
			else if(data_type == 'alphanumeric' && !(isAlphaNumeric(val)))
			{
				msg	= 'Only alphabets & numbers are allowed in '+tag_title;
			}
			else if(data_type == 'notonlyspecialchar' && !(isOnlySpecialCharacters(val)))		
			{
				msg	= 'Only special characters are not allowed in '+tag_title;
			}
			else if(data_type == 'domain' && !(isValidDomain(val)))		
			{
				msg	= 'Invalid domain format (e.g. mydomain.com)';
			}
			else if(data_type == 'isNumber' && !(allowNumericOnly(val)))		
			{
				msg	= 'Only numbers are allowed in '+tag_title;
			}
		}
		
		if(msg != '')
		{
			$('#'+tag_id).parent('div.form-group').addClass('has-error');
			$('#'+tag_id+'_info').html(msg+'.').css('display','inline-block');
			//setTimeout(function(){ $('#'+tag_id).parent('div.form-group').removeClass('has-error'); }, 5000);
		}
		else
		{
			$('#'+tag_id+'_info').html('').css('display','none');
			$('#'+tag_id).parent('div.form-group').removeClass('has-error');
		}
	}
	
	/**************************************************************************************************************************/
	function validateEmail(x) 
	{
		var atpos = x.indexOf("@");
		var dotpos = x.lastIndexOf(".");
		if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= x.length) 
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	/**************************************************************************************************************************/
	function isNumber(evt) 
	{
		evt = (evt) ? evt : window.event;
		var charCode = (evt.which) ? evt.which : evt.keyCode;
		//console.log(charCode);
		if (charCode > 31 && (charCode < 48 || charCode > 57)) 
		{
			return false;
		}
		return true;
	}
	
	/**************************************************************************************************************************/
	function isAlphaNumeric(val) 
	{
    	var regex = new RegExp("^[a-zA-Z0-9 -_]+$");
		if (regex.test(val)) 
		{
			return true;
		}
		return false;
	}
	
	/**************************************************************************************************************************/
	function isAlpha(val) 
	{
    	var regex = new RegExp("^[a-zA-Z ]+$");
		if (regex.test(val)) 
		{
			return true;
		}
		return false;
	}
	
	/**************************************************************************************************************************/
	function isValidDomain(val) 
	{
    	var regex = new RegExp("^(?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}$");
		//'^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$');
		if (/^(?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}$/g.test(val)) 
		{
			return true;
		}
		return false;
	}
	/**************************************************************************************************************************/
	function isOnlySpecialCharacters(val) 
	{
    	//var regex = new RegExp("^[a-zA-Z ]+$");
		if (/[a-z 0-9]/.test(val.toLowerCase())) 
		{
			return true;
		}
		return false;
	}
	
	/**************************************************************************************************************************/
	function searchusers()
	{
		var val = $.trim($('#search_user').val());
		if(val == '')return false;
		window.location = site_url+'userlisting/'+val;
	}
	
	function search_users(event)
	{
		if(event.keyCode == 13)
		{
			searchusers();
		}
	}
	/**************************************************************************************************************************/
	// create password live validation
	var hasAlpha 		= false;
	var hasNumber		= false;
	var hasCapital		= false;
	var hasValidLength 	= false;
	var pswdbtn			= false;
	function validatePasswords(form_id, password_field)
	{
		$(form_id+' '+password_field).keyup(function() {
			var pswd 			= $(this).val();
			//validate letter
			//console.log(pswd);
			if (pswd.match(/[A-z]/) ) 
			{
				$(form_id+' #letter').removeClass('invalid').addClass('valid');
				hasAlpha 		= true;
			} 
			else 
			{
				$(form_id+' #letter').removeClass('valid').addClass('invalid');
				hasAlpha 		= false;
			}
			//validate capital letter
			
			if ( pswd.match(/[A-Z]/) ) 
			{
				hasCapital		= true;
				$(form_id+' #capital').removeClass('invalid').addClass('valid');
			} 
			else 
			{
				hasCapital		= false;
				$(form_id+' #capital').removeClass('valid').addClass('invalid');
			}
			
			//validate number
			if ( pswd.match(/\d/) ) 
			{
				hasNumber		= true;
				$(form_id+' #number').removeClass('invalid').addClass('valid');
			} 
			else 
			{
				hasNumber		= false;
				$(form_id+' #number').removeClass('valid').addClass('invalid');
			}
			//validate the length
			if(pswd.length < 8 ) 
			{
				hasValidLength = false;
				$(form_id+' #length').removeClass('valid').addClass('invalid');
			} 
			else 
			{
				hasValidLength = true;
				$(form_id+' #length').removeClass('invalid').addClass('valid');
			}		
		
			if(hasValidLength == true && hasAlpha == true && hasNumber == true && hasCapital == true)
			{
				$(form_id+' #pswdbtn').attr('disabled',false);
				pswdbtn = true;
			}
			else
			{
				$(form_id+' #pswdbtn').attr('disabled',true);
				pswdbtn	= false;
			}			   
		});
		
		$(form_id+' '+password_field).focus(function(){
			$(form_id+' .pass_hint').css('display','');		 
		});
		
		$(form_id+' '+password_field).blur(function() {
			if(hasValidLength == true && hasAlpha == true && hasNumber == true && hasCapital == true)
			{
				$(form_id+' .pass_hint').css('display','none');
			}		   
		});
	}
	
	function validate_passwords(form_id, password_field)
	{
		var pswd 			= $('#'+password_field).val();
		//validate letter
		//console.log(pswd);
		if (pswd.match(/[A-z]/) ) 
		{
			hasAlpha 		= true;
		} 
		else 
		{
			hasAlpha 		= false;
		}
		//validate capital letter
		
		if ( pswd.match(/[A-Z]/) ) 
		{
			hasCapital		= true;
		} 
		else 
		{
			hasCapital		= false;
		}
		
		//validate number
		if ( pswd.match(/\d/) ) 
		{
			hasNumber		= true;
		} 
		else 
		{
			hasNumber		= false;
		}
		//validate the length
		if(pswd.length < 8 ) 
		{
			hasValidLength = false;
		} 
		else 
		{
			hasValidLength = true;
		}		
	
		if(hasValidLength == true && hasAlpha == true && hasNumber == true && hasCapital == true)
		{
			return true;
		}
		else
		{
			return false;
		}			   
	
	}
	
	function allowAlphaNumericOnly(e) 
	{
		var regex 	= new RegExp("^[a-zA-Z0-9 ]+$");
		if(e.charCode == 0)
		{
			var key = 0;
		}
		else
		{
			var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
		}
		//console.log(key);
		if (!regex.test(key)) {
		   e.preventDefault();
		   return false;
		}
	}
	
	/*********************************************************************************************************************/
	
	function allowNumericOnly(val) 
	{
		var regex = new RegExp("^[0-9]+$");
		if (regex.test(val)) 
		{
			return true;
		}
		//console.log(key);
	}
	
	/*********************************************************************************************************************/
	
	function ReturnCount()
	{
		$.ajax({
			url: site_url+"load/load_count/",
			dataType:"json",
			success: function(result){
				//console.log(result.rows);
				$('#draft_count').text((result.rows[0][0].Draft_messages != 0) ? '('+result.rows[0][0].Draft_messages+')' : '');
				$('#inbox_unread').text((result.rows[1][0].Unread_messages != 0) ? '('+result.rows[1][0].Unread_messages+')' : '');
				$('#starred_count').text((result.rows[3][0].StarredMessages != 0) ? '('+result.rows[3][0].StarredMessages+')' : '');
				if(result.rows[2])
				{
					if(result.rows[2].length != 0)
					{
						for(var i = 0; i < result.rows[2].length; i++)
						{
							var _count	= result.rows[2][i].MessagesinTag;
							$('#'+result.rows[2][i].tag_id+'_tag').text((_count != 0) ? '('+_count+')' : '');
						}
						//console.log(result.rows[2][i]);
					}
				}
				//tags_dd
				//console.log(result.rows[4]);
				if(result.rows[4])
				{
					if(result.rows[4].length != 0)
					{
						for(var i = 0; i < result.rows[4].length; i++)
						{
							var _count	= result.rows[4][i].MessagesinTag;
							$('#'+result.rows[4][i].folder_id+'_folder').text((_count != 0) ? '('+_count+')' : '');
							//console.log(result.rows[4][i]);	
						}
					}
				}
			}
		});
	}
	
	
	/******************* Mark Starred Starts **********/
	var xhr = null;
	function mark_as_starred(thread_id, val,MessageType,op)
	{
		var STP_Data					= null;
			STP_Data					= {};
			// SP parametes required
			STP_Data.thread_ids 		= '';
			STP_Data.message_ids		= '';
			STP_Data.threadORMsgs		= op;
			STP_Data.MessageType		= MessageType;
			STP_Data.OperationType		= 'Starred';
			STP_Data.SetValue			= val;
			STP_Data.User_id			= '';
			threads						= {};
		
		//console.log(op);
		//console.log(STP_Data.SetValue);
		if(op == 'Thread')
		{
			threads.data			= [];
			threads.data[0]			= {};
			threads.data[0].val		= thread_id;
			STP_Data.thread_ids		= threads;
		}
		else
		{
			threads.sub_data		= [];
			threads.sub_data[0]		= {};
			threads.sub_data[0].val	= thread_id;
			STP_Data.message_ids	= threads;
		}
		
		if($.trim(val) == 1)
		{
			if(op == 'Thread')
			{
				$('#starred_div_'+thread_id).removeClass('star_icon_checked').addClass('star_icon_checked_active');			
				$('.starred_sub_'+thread_id).removeClass('star_icon_checked').addClass('star_icon_checked_active');			
				$('#starred_div_'+thread_id).parent('a').attr('onclick',"mark_as_starred('"+thread_id+"',0,'"+MessageType+"','"+op+"');");
				
				$('.thread_pane_'+thread_id).removeClass('star_icon_checked').addClass('star_icon_checked_active');
				var on_click_attr 	= $('.thread_pane_'+thread_id).attr('onclick');
					on_click_attr 	= on_click_attr.replace("'1'","'0'");
				$('.thread_pane_'+thread_id).attr('onclick',on_click_attr);	
				//console.log(on_click_attr);				
			}
			else
			{
				$('.starred_view_pane_'+thread_id).removeClass('star_icon_checked').addClass('star_icon_checked_active');
				$('.starred_view_pane_'+thread_id).attr('onclick',"mark_as_starred('"+thread_id+"',0,'"+MessageType+"','"+op+"')");
				$('#starred_sub_'+thread_id).removeClass('star_icon_checked').addClass('star_icon_checked_active');
				$('#starred_sub_'+thread_id).parent('a').attr('onclick',"mark_as_starred('"+thread_id+"',0,'"+MessageType+"','"+op+"')");
			}
		}
		else
		{
			if(op == 'Thread')
			{
				$('#starred_div_'+thread_id).removeClass('star_icon_checked_active').addClass('star_icon_checked');
				$('.starred_sub_'+thread_id).removeClass('star_icon_checked_active').addClass('star_icon_checked');
				$('#starred_div_'+thread_id).parent('a').attr('onclick',"mark_as_starred('"+thread_id+"',1,'"+MessageType+"','"+op+"')");
				
				$('.thread_pane_'+thread_id).removeClass('star_icon_checked_active').addClass('star_icon_checked');
				var on_click_attr 	= $('.thread_pane_'+thread_id).attr('onclick');
					on_click_attr 	= on_click_attr.replace("'0'","'1'");
				$('.thread_pane_'+thread_id).attr('onclick',on_click_attr);		
				//console.log(on_click_attr);	
			}
			else
			{
				$('.starred_view_pane_'+thread_id).removeClass('star_icon_checked_active').addClass('star_icon_checked');
				$('.starred_view_pane_'+thread_id).attr('onclick',"mark_as_starred('"+thread_id+"',1,'"+MessageType+"','"+op+"')");
				$('#starred_sub_'+thread_id).removeClass('star_icon_checked_active').addClass('star_icon_checked');
				$('#starred_sub_'+thread_id).parent('a').attr('onclick',"mark_as_starred('"+thread_id+"',1,'"+MessageType+"','"+op+"')");
			}
		}
		
		if (xhr != null) 
		{
			return false;
		}
		//return false;
		xhr	= $.ajax({
				url: 		conversation_url+'update_op/',
				dataType:	"json",
				type:		'POST',
				data: 		STP_Data,  // pass in data as strings
				success: function(result){
					//console.log(result);
					xhr = null;
					if (!result.success) 
					{
						if(result.login_url)
						{
							window.location = result.login_url;
						}
						
						//$scope.ShowNotification('Error Occured.','error');
						$('#alert_msg').html('<div class="alert alert-danger">Error Occured.</div>').fadeIn(150).delay(2000).fadeOut(150);
					} 
					else 
					{
						ReturnCount();
						var _msg	= 'Marked as Starred Successfully.';
						if(val == 0)
						{
							_msg	= 'Removed from Starred Successfully.';
						}
								
						//$scope.ShowNotification(_msg,'success');
						$('#alert_msg').html('<div class="alert alert-success">'+_msg+'</div>').fadeIn(150).delay(2000).fadeOut(150);
					}
				}
			});			
	};	
	/******************* Mark Starred Ends ************/
	
	function resetform(form_id)
	{
		document.getElementById(form_id).reset();
	}
	
	function submitForm_to(post_to,locate_to,form_id)
	{
		$('#msgs_'+form_id).html('<span class="alert alert-success">Processing information...</span>').fadeIn(150);
		$('#'+form_id).ajaxForm({
			type: "POST",   
			url: post_to,
			dataType: 'json',
			success: function(data)
			{
				if(data.success) 
				{
					if(data.message)
					{
						$('#msgs_'+form_id).html('<span class="alert alert-success">'+data.message +'</span>').fadeIn(150);						
					}
					if(locate_to != '')
					{
						window.location = locate_to;
					}
					else
					{
						$('.close').click();
						document.getElementById(form_id).reset();
					}
				}
				else
				{
					$('#msgs_'+form_id).html('<span class="error">Error, Please provide all required fields.</span>');
					//console.log(data.errors.length);
					for(var i = 0; i < data.errors.length; i++)
					{
						if(data.errors[i].field)
						{
							if(data.errors[i].error)
							{
								if($.trim(data.errors[i].error) == 'The Confirm Password field does not match the New Password field.')
								{
									data.errors[i].error	= 'Confirm Password doesn\'t match.';		
								}
								$('#'+data.errors[i].field).addClass('has-error');
								$('#'+data.errors[i].field+'_info').addClass('error_alert').html(data.errors[i].error).fadeIn(150);
							}
						}
						else
						{
							$('#msgs_'+form_id).html('<span class="error">'+data.errors[i].error+'</span>').fadeIn(150);
						}
					}
					setTimeout(function(){ $('#msgs_'+form_id).html(''); }, 5000);
				} 
			}
		}).submit();
		return false;
	}
		