/* Version 2 @ 23 Feb 2011 */
/*
Validation :
- require : textbox, textarea, checkbox, radio, select
- numeric : textbox
- alphabet : textbox
- email : textbox

Example:
<input type="txt" name="test" class="require alphabet" />
*/

var Config = new Array;	
function initForm(objForm, formConfig){
	

	formName = objForm.attr("name");
	
	//alert(objForm.find("input:text:eq(0)").offset().left);
	
	Config[formName] = new Array;
	//Config[formName]["arrowLeftPos"] = objForm.offset().left + formConfig["arrowLeft"];
	//Config[formName]["arrowLeftPos"] = objForm.find("input:text:eq(0)").offset().left + formConfig["arrowLeft"]; //** หาค่าของ textbox อันแรก
	//Config[formName]["arrowTopPos"] =formConfig["arrowTop"];

	(formConfig["showBalloon"] ? objForm.data("showBalloon",true) : objForm.data("showBalloon",false));
	objForm.data("styleName", formConfig["styleName"]);
//	objForm.data("", formConfig["styleName"]);
	objForm.data("module", formConfig["module"]);
	
	if (formConfig["languageType"] == "php") {
		objForm.data("alertMessage", AlertMessage(objForm) );	/* PHP */
	} else {
		objForm.data("alertMessage", formConfig["alertMsg"]);     /* ASP.NET */
	}
	//objForm.find("select")
	
	// Active Style Input Object
	objForm.find("input, textarea").not(".active").focus(function(){
		$(this).addClass("active");									
	}).blur(function(){
		$(this).removeClass("active");									
	});
	
	// Initial Balloon Alert DIV
	initAlert(objForm);
	objForm.find("input:text, textarea").keyup(function(){
		Caller = $(this);
		
		if (Caller.hasClass("alert") && (!IsEmpty(Caller.val()))) {
			//alert(Caller.filter(":textarea").parent().attr("id"));
			if (objForm.data("showBalloon")) {	
				$("div.err"+Caller.attr("name")).filter(":visible").fadeOut('fast');					
			}
			
			Caller.removeClass("alert").removeClass(Caller.data("styleAlert"));
			//alert(Caller.filter(":textarea").parent().attr("id"));
			Caller.filter("input:text, textarea").parent().removeClass(Caller.data("styleAlert"));
			Caller.parent().removeClass("bgAlert");
		}
		
	});
	
	objForm.find("input:checkbox, input:radio").click(function(){
		
		objName = $(this).attr("name");
		Caller = objForm.find("input[name='"+objName+"']");
		if (Caller.hasClass("alert")) {
			if (objForm.data("showBalloon")) {		
				$("div.err"+Caller.attr("name")).filter(":visible").fadeOut('fast');					
			}
			Caller.removeClass("alert");
			Caller.parent().removeClass("bgAlert");
			
			/* Find Oprion group */
			objForm.find("input[name='"+objName+"']").next().removeClass("ui-radio-state-alert").removeClass("ui-checkbox-state-alert");
			
			
		}
	});
	
	objForm.find("select").change(function(){
		Caller = $(this);
		//alert(Caller.attr("id"));
		if (Caller.hasClass("alert") && (Caller.val()!="NULL")) {
			if (objForm.data("showBalloon")) {		
				$("div.err"+Caller.attr("name")).filter(":visible").fadeOut('fast');					
			}
			
			Caller.removeClass("alert");
			Caller.parent().removeClass("bgAlert");
		}
		
	});
	
	
	
	

}
	
	
	
function ValidateForm(objForm){
	var valid = true;
	var started = +new Date;

	objForm.find("input:text").filter(".require").each(function () {
	    Input = $(this);

	    if (IsEmpty(Input.val())) {
	        valid = false;
	        //Input.parent().addClass(Input.data("styleAlert"));
	        showAlert(Input);
	    }

	});
	
	objForm.find("input:text").filter(".numeric").each(function(){
		
		Input = $(this);
		if (!IsEmpty(Input.val()) && !IsNum(Input.val())) {
			
			valid = false;				
			//Input.parent().addClass(Input.data("styleAlert"));
			showAlert(Input);
		}
			
	});
	

	objForm.find("input:text").filter(".email").each(function(){
		
		Input = $(this);
		if (!IsEmpty(Input.val()) && !IsEmail(Input.val())) {
			valid = false;				
			//Input.parent().addClass(Input.data("styleAlert"));
			showAlert(Input);
		}
			
	});
	
	objForm.find("input:text").filter(".alphabet").each(function(){
		
		Input = $(this);
		if (!IsEmpty(Input.val()) && !IsAlphabet(Input.val())) {
			valid = false;
			//Input.parent().addClass(Input.data("styleAlert"));
			showAlert(Input);
		}
			
	});
	
	objForm.find("textarea").filter(".require").each(function(){	
		Input = $(this);
		if (IsEmpty(Input.val())) {
			valid = false;		
			//Input.parent().addClass(Input.data("styleAlert"));
			showAlert(Input);
		}
	});
	


	//objForm.find("input:checkbox:eq(0), input:radio:eq(0)").filter(".require").each(function(){
	objForm.find("input:checkbox, input:radio").filter(".require").each(function () {


	    obj = $(this);
	    InputName = $(this).attr("name");
	    if (objForm.find("input[name='" + InputName + "']").index(obj) == 0) {  /* validate once per name */
	        Input = objForm.find("input[name='" + InputName + "']");
	        if (!IsOption(Input)) {
	            valid = false;
	            Input.filter(":radio").next().addClass("ui-radio-state-alert");
	            Input.filter(":checkbox").next().addClass("ui-checkbox-state-alert");
	            showAlert(Input);
	        }
	    }

	});
	
	objForm.find("select.require").each(function(){	
		Input = $(this);

		if (!IsSelected(Input)) {
			valid = false;
			showAlert(Input);
		}
	});
	
	return valid;
}
	



function initAlert(objForm){
	
	objForm.find("input:text,input:password,textarea,select").filter(".require").each(function(){
		objInputName = $(this).attr("name");
		$("body").append(AlertHTML(objInputName, objForm.data("alertMessage")));															   
	});
	
	objForm.find("input:checkbox.require:eq(0), input:radio.require:eq(0)").each(function(){
		objInputName = $(this).attr("name");
		$("body").append(AlertHTML(objInputName, objForm.data("alertMessage")));															   
	});
	
}


function showAlert(objInput){
	
	objForm =  objInput.parents("form");
	objForm.find("input:submit, input:image").focus();
	var formName = objForm.attr("name");
//	alert(objForm);	
	if (objForm.data("showBalloon")) {
		objInputName = objInput.attr("name");
		
		
		
		if (!$("div.err"+objInputName).hasClass("err"+objInputName)) {
			//alert("appernd");
			$("body").append(AlertHTML(objInputName, objForm.data("alertMessage")));	
			
			
		}
		 errDiv = $("div.err"+objInputName);
		
//		 if (errDiv.is(":hidden")) {
//			
//			errDiv.css("left",Config[formName]["arrowLeftPos"]);
//			var offsetTop = objInput.offset().top;
//
//			if (objInput.find(":eq(0)").length > 0) {
//				//alert(objInput.attr("id")+"="+offsetTop + "," +objInput.find(":eq(0)").length );
//				offsetTop = $("#"+objInput.attr("id")+"_title").offset().top;
//				
//			}
//			alert(Config[formName]["arrowTopPos"]);			
////			errDiv.css("top",offsetTop+Config[formName]["arrowTopPos"]);	
//
//			//errDiv.css("top",objInput.offset().top+Config[formName]["arrowTopPos"]);
//		
//			//errDiv.fadeIn("slow");
////			errDiv.show().animate({"left": "+=20px" }, "fast");
//
//		 }
	}
	//$("#sel1_title").addClass(objInput.data("styleAlert"));
	//alert(objInput.data("styleAlert"));
	$("#"+objInput.attr("name")+"_title").not(".alert").addClass(objInput.data("styleAlert")); // ## For Select Menu
	
//	Input.parent().addClass(Input.data("styleAlert"));
	
//	objInput.filter("input:text").not(".alert").addClass("alert").addClass(objInput.data("styleAlert")).filter(":checkbox,:radio").parent().addClass("bgAlert");
	objInput.filter("input:text, textarea").not(".alert").addClass("alert").addClass(objInput.data("styleAlert")).parent().addClass(objInput.data("styleAlert"));
	//objInput.filter("input:checkbox,input:radio").parent().addClass("bgAlert");
//	alert();

	objInput.filter("textarea").addClass("alert");
	//objInput.filter(":textarea").not(".alert").addClass("alert").addClass(objInput.data("styleAlert")).filter(":checkbox,:radio").parent().addClass("bgAlert");
	
}

function showAlert_Balloon(objInput){
	
	objForm =  objInput.parents("form");
	objForm.find("input:submit").focus();
	var formName = objForm.attr("name");
//	alert(objForm);	
	if (objForm.data("showBalloon")) {
		objInputName = objInput.attr("name");
		
		
		
		if (!$("div.err"+objInputName).hasClass("err"+objInputName)) {
			//alert("appernd");
			$("body").append(AlertHTML(objInputName, objForm.data("alertMessage")));	
			
			
		}
		 errDiv = $("div.err"+objInputName);
		
		 if (errDiv.is(":hidden")) {
			
			errDiv.css("left",Config[formName]["arrowLeftPos"]);
			errDiv.css("top",objInput.offset().top+Config[formName]["arrowTopPos"]);	
			//errDiv.fadeIn("slow");
			errDiv.show().animate({"left": "-=50px", "opacity":"0.9" }, "fast");
		 }
	}
	$("#sel1_title").addClass(objInput.data("styleAlert"));
	//alert(objInput.data("styleAlert"));
	$("#"+objInput.attr("name")+"_title").addClass(objInput.data("styleAlert"));
	objInput.not(".alert").addClass("alert").addClass(objInput.data("styleAlert")).filter(":checkbox,:radio").parent().addClass("bgAlert");
	
}


function AlertHTML(objInputName, alertMessage){
	
	var htm = '<div class="divError err'+objInputName+'">\n';
	htm +=	'<div class="alertMarkFocus">\n';
	htm +=	'</div>\n';
	htm +=	'</div>\n';
	
	return htm;
	
	
	
}

function AlertHTML_Balloon(objInputName, alertMessage){
/*	var htm = '<div class="formError">\n';
		htm +=	'<div class="formErrorArrow">\n';
		htm +=	'		<div class="line10"></div>\n';
		htm +=	'		<div class="line9"></div>\n';
		htm +=	'		<div class="line8"></div>\n';
		htm +=	'		<div class="line7"></div>\n';
		htm +=	'		<div class="line6"></div>\n';
		htm +=	'		<div class="line5"></div>\n';
		htm +=	'		<div class="line4"></div>\n';
		htm +=	'		<div class="line3"></div>\n';
		htm +=	'		<div class="line2"></div>\n';
		htm +=	'		<div class="line1"></div>\n';
		htm +=	'	</div>\n';
		htm +=	'	<div class="formErrorContent">test</div>\n';
		htm +=	'</div>';
	return htm;*/
	
	var htm = '<div class="divError err'+objInputName+'">\n';
	htm +=	'<div class="formErrorArrow">\n';
	htm +=	'<div class="line10"></div>\n';
	htm +=	'<div class="line9"></div>\n';
	htm +=	'<div class="line8"></div>\n';
	htm +=	'<div class="line7"></div>\n';
	htm +=	'<div class="line6"></div>\n';
	htm +=	'<div class="line5"></div>\n';
	htm +=	'<div class="line4"></div>\n';
	htm +=	'<div class="line3"></div>\n';
	htm +=	'<div class="line2"></div>\n';
	htm +=	'<div class="line1"></div>\n';
	htm +=	'</div>\n';
	htm +=	'<div class="formError">\n';

	htm +=	'<div class="formErrorContent">'+alertMessage+'</div>\n';
	htm +=	'</div>\n';
	htm +=	'</div>\n';
	
	return htm;
	
	
	
}


function AlertMessage(objForm){
		module = objForm.data("module");
		var Alert = $.ajax({
		   type: "GET",
		   url: "inc/ajaxAlertMessage.php",
		   data: "module="+module,
		   async: false, 
		   complete: function(msg){
				//alert(msg.responseText);
				//return msg.responseText;
				return msg;
			}
		});
		var sAlert = (Alert.status == '200' ? Alert.responseText : strAlert );
		
		return sAlert;
}

/*======= Alert Tooltip =========*/
	 // Define corners and opposites arrays
	var corners = [
	   'bottomLeft', 'bottomRight', 'bottomMiddle',
	   'topRight', 'topLeft', 'topMiddle',
	   'leftMiddle', 'leftTop', 'leftBottom',
	   'rightMiddle', 'rightBottom', 'rightTop'
	];
	var opposites = [
	   'topRight', 'topLeft', 'topMiddle',
	   'bottomLeft', 'bottomRight', 'bottomMiddle',
	   'rightMiddle', 'rightBottom', 'rightTop',
	   'leftMiddle', 'leftTop', 'leftBottom'
	];
	var i = 0;
	
	
function AlertToolTip(objSubmit, msg) {
	// If counter reaches maximum, reset
		 //if(i === corners.length) i = 0;
		 i = 2; //## Set Corner to bottomMiddle
        if ($.browser.msie && ($.browser.version == 6))	{rad=0;} else {rad=10;}
		
		
         // Destroy currrent tooltip if present
         if(objSubmit.data("qtip")) objSubmit.qtip("destroy");
        //alert(objSubmit.attr("id"));
         //objSubmit.html(opposites[i]) // Set the links HTML to the current opposite corner
            objSubmit.qtip({
               content: msg, // Set the tooltip content to the current corner
               position: {
                  corner: {
                     tooltip: corners[i], // Use the corner...
                     target: opposites[i] // ...and opposite corner
                  }
               },
               show: {
                  when: false, // Don't specify a show event
                  ready: true // Show the tooltip when ready
               },
               hide: 'unfocus', // Don't specify a hide event
               style: {
                  border: {
                     width: 5,
                     radius: rad
                  },
                  padding: 10, 
                  textAlign: 'center',
                  tip: true, // Give it a speech bubble tip with automatic corner detection
                  name: 'red' // Style it according to the preset 'cream' style
               }
            });
			
			// alert(objSubmit);	  
         
        // i++; // Increase the counter
	 }

/* Alert Panel */
function AlertPanel(msg){
	
	if ($("#divWarning").length == 0 ) { 
		var html = '<div id="divWarning" > \n';
			html += '<div id="warningmsg"><div id="msg" class="imgPNG" /><div style="clear:both" /></div> \n';
			html += '<div id="warningBottom"> \n';
			html += '<div id="bottomLeft"><img src="img/warning_bl.png" alt="" width="20" height="20"/></div> \n';
			html += '<div id="bottomCenter">&nbsp;</div> \n';
			html += '<div id="bottomRight"><img src="img/warning_br.png" alt="" width="20" height="20"/></div> \n';
			html += '</div> \n';
			html += '<div style="clear:both" />    \n';
			html += '</div>';
		
		$("body").append(html);
		if ($.browser.msie && ($.browser.version.substr(0,1)>6)) {
			$("div#divWarning").css("filter","Alpha(Opacity=90)");
		}
	}
	$("div#divWarning #msg").html(msg).parent().css("z-index",maxZindex());
	//$("div#divWarning").css("min-height", "120px" );
	//alert($("div#divWarning #msg").offsetHeight );
	$("div#divWarning").slideDown({ duration: 500, easing: "easeOutBounce", complete: function(){
		$("body").click(function(){
			/*$("div#divWarning").slideUp({ duration: 300, easing: "easeOutExpo", complete: function(){
																						
			} });*/			
			if ($.browser.msie) {
			  // search for selectors you want to add hover behavior to
				$("div#divWarning").fadeOut("fast");
				
				if ($.browser.version.substr(0,1)>6) {	
				//	alert($.browser.version.substr(0,1));
					$("div#divWarning").css("filter","Alpha(Opacity=90)");
				}
			
			} else {
				$("div#divWarning").slideUp({ duration: 300, easing: "easeOutExpo" });
			}


			
			//$("div#divWarning").hide();
		});																						
																						
	}});
	
	//$("div#divWarning").show();
	
	
}

function maxZindex(){
	var maxZ = Math.max.apply(null,$.map($('body > *'), function(e,n){
	if($(e).css('position')=='absolute')
		return parseInt($(e).css('z-index'))||1 ;
	})
	);
	return (maxZ);
}
//===== Validate Function ===========//

	function IsOption(object){
	
		return object.filter(":checked").length > 0;
	}
	
	function IsSelected(object){
		
		return object.val() != "NULL";
	}
	
	function IsEmail(email) {
			var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
					if (regex.test(email)){
						return true;
					}else {
						return false;
					}
}

	function IsNum(form_value)
		{
			if (form_value.match(/^\d+$/) == null)
				return false;
			else
				return true;
		}
		
		
		
function Trim(s)
{
	return($.trim(s));
}

function IsEmpty(value)
{
	return $.trim(value).length == 0;
}


function IsAlphabet(value) {
		var regex = /([a-zA-Z0-9])+$/;
					if (regex.test(value)){
						return true;
					}else {
						return false;
					}
		
}

function IsDecimal(s){
	tmp = true;
	s.value = Trim(s.value);
	firstChar = s.substring(0, 1);
	if (firstChar < "0" || "9" < firstChar )  {
		return false;	
	}
	
	for (var i = 0; i < s.length; i++) {
		var ch = s.substring(i, i + 1);
		 if ((ch < "0" || "9" < ch ) && (ch != ".") && (ch != ",")) {
			tmp = false;
			break;
		 }
		 if (tmp == false) {
			break;
		 }
	}
	return(tmp);
}


function IsSpace(s){
	var temp = " ";
	var i = 0;
	space	= false;
	s = Trim(s);
	while (i <= s.length) {
		temp = s.charAt(i);
		if (temp == " " ) {
			if ( i < s.length - 1 ) {
				space = true
			}
		}
		i++;
	}
	return (space);
}

function IsFileEmpty(objField) {
	var WSPACE=' \t\n\r';
	var v = objField.value;
	if ((v == null) || (!v.length)) return true;
	for (var i = 0; i < v.length; i++) {
		if (WSPACE.indexOf(v.charAt(i)) == -1) return false;
	}
	return true;
}

function IsPassword(s) {
	var regex = /([a-zA-Z0-9_\-])+$/;
	if (regex.test(value)){
		return true;
	}else {
		return false;
	}
		
 }


function Warning(obj, msg) {
	alert(msg);
	obj.focus();
}

function NoPermission()
{
	alert("You don\' t have permission please contact administrator.");
}

function WarningAndSelect(obj, msg) {
	alert(msg);
	obj.select();
}


function fn_delete_confirm(n, url, msg) {
	var answer = confirm (msg);
	if (answer) {
		window.location = url;
	} else {
		return (false);
	}
}


// === Put DIV over SELECT===
function divOverSelect(divID){
	objDiv = document.getElementById(divID);
	strIframe = "<iframe src=\"javascript:;\" scrolling=\"no\" frameborder=\"0\" style=\"position:absolute;width:"+objDiv.offsetWidth+"px;height:"+objDiv.offsetHeight+"px; top:-1px;border:none;display:block;z-index:0\"></iframe>";
	objDiv.innerHTML = strIframe + objDiv.innerHTML ;
}

//});


//## For Select Menu Hide Alert ##
function checkSelectAlert(objSelect) {
	var Input = $("#"+objSelect.id); // ## For Select Menu
	var InputTitle = $("#"+objSelect.id+"_title"); // ## For Select Menu
	var objForm =  Input.parents("form");
//	alert("test");
	if (InputTitle.hasClass(Input.data("styleAlert"))) { InputTitle.removeClass(Input.data("styleAlert")) }
	if (objForm.data("showBalloon")) {	
				$("div.err"+Input.attr("name")).filter(":visible").fadeOut('fast');					
	}
//	alert(Input.data("styleAlert"));
		
}

function removeAlertCalendar(datetext, instance){
	$obj = $("input#"+instance.id);	
	$obj.removeClass("alert").removeClass($obj.data("styleAlert")); 
	$obj.parent().removeClass($obj.data("styleAlert"));
}
