var regExp1 = new RegExp("[^A-Za-z0-9_]");  //เฉพาะภาษาอังกฤษและตัวเลข
var regExp2 = new RegExp("[!$<>`/'\"?.&=%@#*(),:;~^0-9]");  //ห้ามใช้สัญลักษณ์พิเศษและตัวเลข
var regExp3 = new RegExp("[!$<>`/'\"?.&=%@#*(),:;~]");  //ห้ามใช้สัญลักษณ์พิเศษ
var regExp4 = new RegExp("[^0-9]");  //เฉพาะตัวเลข
var regExp5 = new RegExp("[^0-9.,]");  //เฉพาะตัวเลขมีจุดได้
var regExp6= /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  //ตรวจสอบอีเมล์
var regExp7 = new RegExp("[!$<>`/'\"?.&=%@#*():;~]");  //ห้ามใช้สัญลักษณ์พิเศษ ยกเว้น , ใช้กับ tag
var regExp8 = new RegExp("['\"]");  //ห้ามใช้ ' " ใช้กับ title
var regExp9 = new RegExp("[&`:<>'\"+#%@/;?|~]");  //ห้ามใช้ & ` : < > ' " + # % @ / ; ? \ | ~ , ใช้กับ Alias URL (Mod Rewrite)
var regExp10 = new RegExp("[^@A-Za-z0-9_]");  //เฉพาะ@,ภาษาอังกฤษและตัวเลข
var regExp11 = /(http|https|ftp):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2,3}/;  //ตรวจสอบ url
var tip_list = new Array();
var validate = new Array();
var url_before = "";
var progress_time;
var tab_num = new Array();
var tab_selected = new Array();

/* Init */

function init()
{
	$(".disabled,.disabled2").focus(function(){this.blur();});
	$(".numbers").keyup(function(){numbers_digit();});
	numbers_digit();
	checkbox_init();
	link_blank_init();
	search_box_init()
	/*menubar_init();*/
	preload(url_script+"jquery/images/loading.gif,"+url_script+"jquery/images/ico_check.gif,"+url_script+"jquery/images/btn_normal_over.gif,"+url_script+"jquery/images/btn_submit_over.gif,"+pre_dir+"images/starbig_yellow.gif");
}	

/* Preload Images */

function preload(images) {
	var imageArray = new Array();
	imageArray = images.split(',');
	var imageObj = new Image();
	for(i=0; i<=imageArray.length-1; i++) {
		//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
		imageObj.src=images[i];
	}
}

/* QTip */

function tip(id,type,text)
{
	if(type=="tip")
	{
		$(id).qtip(
		{
			content: text,
			position: {
				my: "left center",
				at: "right center"
			},
			style: {
				tip: {
					 corner: true
				},
				classes: "ui-tooltip-green"
			},
			show: {
				event: "mouseenter"
			},
			hide: {
				event: "mouseleave"
			}
		});
	}
	if(type=="input_error")
	{
		$(id).qtip(
		{
			content: text,
			position: {
				my: "left center",
				at: "right center"
			},
			style: {
				tip: {
					 corner: true
				},
				classes: "ui-tooltip-red"
			},
			show: {
				event: "focus"
			},
			hide: {
				event: "blur"
			}
		});
	}else
	if(type=="area_error")
	{
		$(id).qtip(
		{
			content: text,
			position: {
				container: $(id),
				my: "left center",
				at: "right center"
			},
			style: {
				tip: {
					 corner: true
				},
				classes: "ui-tooltip-red"
			},
			show: {
				event: "mouseenter"
			},
			hide: {
				event: "mouseleave"
			}
		});
	}
}

/* Load Page */

function load_page(url,div_id,progress_id,scrollto,complete_func)
{
	progress(progress_id);
	$.get(encodeURI(url),{},
	function(data)
	{
		if(data != "session_timeout")
		{
			progress(progress_id,"");
			$("#"+div_id).html(data);
			if(complete_func != "")
			{
				eval(complete_func+"();");
			}
			if(scrollto)
			{
				divOffset = $("#"+div_id).offset().top;
				$("html,body").animate({scrollTop: divOffset-10 }, 400);
			}
			init();
		}else
		{
			window.location.assign(pre_dir+"login.php");
		}
	});
}

function load_form(data)
{
	if(data == null)
	{
		$("#content_body").show();
		$("#content_form").hide();
	}else
	{
		$("#content_body").hide();
		$("#content_form").show();
		$("#content_form").html(data);
	}
	return true;
}

/* progress */

function progress(id,text)
{
	if(text == null)
		$(id).html("<div style=\"text-align:center\"><img src=\"" + url_script +"jquery/images/loading.gif\" alt=\"\" /></div>");
	else
		$(id).html(text);
	clearTimeout(progress_time);
}

/* Tab Switch */

function tabSwitch(tab_id,tab_body)
{
	var id;
	$("#"+tab_id+" a").removeClass("selected");
	$("#"+tab_id+" a[href=#"+tab_body+"]").addClass("selected");
	$("#"+tab_id+" a").each(function()
	{
		id = this.toString().split("#");
		id = id[1];
		$("#"+id).hide();
		if(tab_body == id)
		{
			$("#"+tab_body).show();
		}
	});
}

function tabAutoSwitch(tab_id,time)
{
	var tab_switch_index,tab_switch_id;

	if(tab_selected[tab_id] == undefined && tab_num[tab_id] == undefined) //decare var
	{
		tab_selected[tab_id] = null;
		tab_num[tab_id] = null;
	}
	if(tab_selected[tab_id] == null && tab_num[tab_id] == null)
	{
		tab_selected[tab_id] = $("#"+tab_id+" a:.selected").index();
		tab_num[tab_id] = $("#"+tab_id+" a").length;
		$("#"+tab_id+" a").click(function()
		{
			tab_selected[tab_id] = "-1";
		});
	}
	setTimeout(function(){
		if(tab_selected[tab_id] != "-1")
		{
			if(tab_selected[tab_id]+1 < tab_num[tab_id])
				tab_switch_index = tab_selected[tab_id]+1;
			else
				tab_switch_index = 0;
			tab_selected[tab_id] = tab_switch_index;
			tab_switch_id = $("#"+tab_id+" a").eq(tab_switch_index).attr("href").split("#");
			tabSwitch(tab_id,tab_switch_id[1]);
			tabAutoSwitch(tab_id,time);
		}
	},time);
}

/* Modal */

function modal_open(url,f_id,w)
{
	$.get(url, {id : f_id },
	function(data)
	{
		if(data != "session_timeout")
		{
			$(data).modal({maxWidth:w, onClose:modal_close});
			init();
		}else
		{
			window.location.assign(pre_dir+"login.php");
		}
	});
}

function modal_close()
{
	$.modal.close();
}

/* Tool */

function checkbox_init()
{
	$(".check_all").click(
	function()
	{
		if($(".check_all").attr("checked"))
			$(".check").attr("checked","checked");
		else
			$(".check").removeAttr("checked");
	});
	
	$(".check").click(
	function()
	{
		var r=true;
		$(this).each(function(){
			if($(this).attr("checked") == false)
				r = false;
		});
		if(r == false)
			$(".check_all").removeAttr("checked");
		else
		if($(".check:checked").length == $(".check").length)
		{
			$(".check_all").attr("checked","checked");
		}
	});
}

function tool_checkbox(url,url_b,text,progress_id,complete_func)
{
	if($(".check:checked").length == 0)
	{
		clearTimeout(progress_time);
		progress_time = setTimeout("progress('"+progress_id+"','')",5000);
		progress(progress_id,"กรุณาเลือกข้อมูลที่ต้องการ");
	}else
	{
		$(".check:checked").each(function(index)
		{
			if(index != 0)
				url += ",";
			url += $(this).val();
		});
		tool_confirm(url,url_b,text,progress_id,complete_func)
	}
}

function tool_confirm(url,url_b,text,progress_id,complete_func)
{
	if(confirm(text))
	{
		if(url_b != "")
			url_before = url_b;
		progress(progress_id);
		$(".check,.check_all").attr("disabled","disabled");
		$.get(encodeURI(url), {},
		function(data)
		{
			if(data == "success")
			{
				progress(progress_id,"");
				if(complete_func != "")
				{
					eval(complete_func+"();");
				}
			}else
			if(data == "session_timeout")
			{
				window.location.assign(pre_dir+"login.php");
			}else
			{
				progress(progress_id,data);
			}
			$(".check,.check_all").removeAttr("disabled");
		});
	}
}

/* Number Comma */

function numbers_digit()
{
	var num,fnum;
	$(".numbers").each(function(e){
		if($(this)[0].tagName == "INPUT")
		{
			$(this).val($(this).val().replace(/,/g,"").replace(/[^0-9\.]/g,""));
			if($(this).val() != "")
			{
				num = $(this).val().split(".");
				if(num.length > 1)
				{
					fnum = num[0]*1+"";
					fnum = fnum.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
					$(this).val(fnum+"."+num[1].replace(/,/g,"").substring(0,2));
				}else
				{
					$(this).val($(this).val()*1);
					$(this).val($(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
				}
			}
		}else
		{
			if($(this).text().replace(/,/g,"")<0)
			{
				$(this).addClass("numbers_error");
				$(this).text($(this).text().replace(/,/g,"").replace(/[^0-9\.-]/g,"").replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
			}else
			{
				$(this).removeClass("numbers_error");
				$(this).text($(this).text().replace(/,/g,"").replace(/[^0-9\.-]/g,"").replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
			}
			if($(this).text() != "")
				$(this).text(number_curency($(this).text()));
		}
	});
	$(".curency").each(function(){
		if($(this)[0].tagName == "INPUT")
		{
			$(this).val($(this).val().replace(/,/g,"").replace(/[^0-9\.]/g,""));
			if($(this).val() == "")
				$(this).val($(this).val()*1);
		}
	});
}

function number_curency(str) {
   // if (/^\$?[1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{0,2})?$/.test(str) ) {
        if (/\.[0-9]$/.test(str) ) {
            str += "0";
        }
        else if (/\.$/.test(str)) {
            str += "00";
        }
        else if (!/\.[0-9]{2}$/.test(str) ) {
            str += ".00";
        }
        return str;
  /*  }
    else {
        return "Invalid";
    }*/
}

/* Text Editor Init */
function textEditor_init(id,h)
{ 
	var config = {
		toolbar : 
		[
			{ name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-' ] },
			{ name: 'styles',      items : [ 'TextColor','BGColor','-','RemoveFormat','-' ] },
			{ name: 'clipboard',   items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo','-' ] },
			{ name: 'editing',     items : [ 'Find','Replace','SelectAll','-' ] },
			{ name: 'document',    items : [ 'Preview','Templates','Maximize', 'ShowBlocks' ] },
			'/',
			{ name : 'fontsize', items : ['FontSize','-'] },
			{ name: 'paragraph',   items : [ 'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','NumberedList','BulletedList','Outdent','Indent','Blockquote','-' ] },
			{ name: 'links',       items : [ 'Link','Unlink','Anchor','-' ] },
			{ name: 'insert',      items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','-' ] },
			{ name: 'tools',       items : [ 'Source','-','About' ] }
		],
		skin : 'silverclear',
		height : h,
		extraPlugins : 'tableresize'
	};
	$(id).ckeditor(config);
	//CKEDITOR.replace(id,config);
}

function textEditorMember_init(id,h)
{
	var config = {
		toolbar : 
		[
			{ name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','-' ] },
			{ name: 'styles',      items : [ 'TextColor','BGColor','-','RemoveFormat','-' ] },
			{ name: 'clipboard',   items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo','-' ] },
			{ name: 'editing',     items : [ 'SelectAll','-' ] },
			{ name: 'document',    items : [ 'Preview','Maximize', ] },
			'/',
			{ name : 'fontsize', items : ['FontSize','-'] },
			{ name: 'paragraph',   items : [ 'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','NumberedList','BulletedList','Outdent','Indent','-' ] },
			{ name: 'links',       items : [ 'Link','Unlink','-' ] },
			{ name: 'insert',      items : [ 'Image','Table','HorizontalRule','Smiley','-' ] },
			{ name: 'tools',       items : [ 'About' ] }
		],
		skin : 'silverclear',
		height : h,
		extraPlugins : 'tableresize'
	};
	$(id).ckeditor(config);
	//CKEDITOR.replace(id,config);
}

function textEditor_data(mode,id,text)
{
	if(mode == "get")
	{
		return CKEDITOR.instances[id].getData();
	}else
	if(mode == "add")
	{
		CKEDITOR.instances[id].setData(CKEDITOR.instances[id].getData()+text);
	}else
	if(mode == "insert")
	{
		CKEDITOR.instances[id].insertHtml(text);
	}else
	if(mode == "set")
	{
		CKEDITOR.instances[id].setData(text);
	}
}

function textEditor_destroy(id)
{
	$(id).ckeditor(function(){
			this.destroy();
	});
	//CKEDITOR.instances[id].destroy();
}

/* Init Link Blank Open in New Window */

function link_blank_init()
{
	$("._blank").attr("target","_blank");
}

/* Open Window */

function open_window(goto_url,width,height)
{
	x=screen.width/2-width/2;
	y=screen.height/2-height/2;
	ipwindow=open("","","fullscreen=no,resizable=yes,scrollbars=no,toolbar=no,menubar=no,width="+width+",height="+height+",left="+x+",top="+y);
	ipwindow.location.assign(goto_url);
}

/* Textarea Maxlength */

function textarea_maxlength(object, mlength)
{
	if (object.getAttribute && object.value.length>mlength)
		object.value=object.value.substring(0,mlength);
}

/* Search Box */

function search_box_init()
{
	search_box();
	$("#search_box").submit(
	function()
	{
		if($("#search_box input[name=q]").val() == "ใส่คำค้นหาที่นี่")
			$("#search_box input[name=q]").val("");
		return true;
	});
	$("#search_box input[name=q]").removeAttr("onfocus");
	
	$("#search_box input[name=q]").focus(
	function()
	{
		search_box();
	});
	
	$("#search_box input[name=q]").blur(
	function()
	{
		search_box();
	});
}

function search_box()
{
	if($("#search_box input[name=q]").val() == "")
	{
		$("#search_box input[name=q]").css("color","#999").val("ใส่คำค้นหาที่นี่");
	}else
	if($("#search_box input[name=q]").val() == "ใส่คำค้นหาที่นี่")
	{
		$("#search_box input[name=q]").css("color","#000").val("");
		$("#search_option,#search_q_title").fadeIn();
	}else
	{
		$("#search_option,#search_q_title").fadeIn();
	}
}

function selectAllText(textbox)
{
    textbox.focus();
    textbox.select();
}
