// 分類：data、form、cookies、misc

//data
var show_data_not_ok_error = false;
var show_email_error = false;
var show_password_error = false;
var show_password_match_error = false;
var show_captcha_error = false;
var show_duplicate_error = false;
var show_no_event = false;

function is_form_data_ok(){
	var user_data_valid=true;

	// ↓資料檢查區
	//如果have_captcha為true，才會檢查認証碼是否正確
	if ( typeof(have_captcha) != "undefined" ) { 
		if ( have_captcha && !captcha_check("#input_captcha",captcha_code) ) {
			user_data_valid=false;
			show_captcha_error = true;
		}
	}
	
	//regular expression - patterns
	var email_rx=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$/;
	var password_rx = /^[a-zA-Z0-9]{6,12}$/;
	
	//必填text欄位的檢查是否有輸入內容
	jQuery(":text[req='req']").each(function(){
		if ( jQuery(this).val().length < 1 ){
			user_data_valid=false;
			show_data_not_ok_error = true;
		}
	});

	//password欄位檢查是否有輸入
	jQuery(":password[req='req']").each(function(){
		if ( jQuery(this).val().length < 1 ){
			user_data_valid=false;
			show_data_not_ok_error = true;
		}
	});

	//必填的 radio 是否有點選
	var radios = get_radio_names();
	if ( radios.length >= 1 ){
		for ( var i=0 ; i<=radios.length ; i++ ){
			if ( jQuery(":radio[name='"+radios[i]+"']").attr("req")=="req" &&  jQuery(":radio[name='"+radios[i]+"']:checked").length<1 ) {
				user_data_valid=false;
				show_data_not_ok_error = true;
			}
		}
	}
	
	//必填的 checkbox 是否有勾選
	var checks = get_checkbox_names();
	if ( checks.length>=1 ) {
	    for ( var i=0 ; i<=checks.length ; i++ ){
		    if ( jQuery(":checkbox[name='"+checks[i]+"']").attr("req")=="req" &&  jQuery(":checkbox[name='"+checks[i]+"']:checked").length<1 ){
				user_data_valid=false;
				show_data_not_ok_error = true;
			}
		}
	}
	
	//如果有 user_mail 欄位，再檢查格式是否正確
	if ( jQuery("input[name='user_email']").length>=1 )  {
		if ( jQuery("input[name='user_email']").val().length>=1 && !email_rx.test(jQuery("input[name='user_email']").val()) ){
			user_data_valid=false;
			show_email_error = true;
		}
	}
	
	//如果有 user_password 欄位，再檢查格式是否符合規定
	if ( jQuery("input[name='user_password']").length>=1 )  {
		if ( jQuery("input[name='user_password']").val().length>=1 && !password_rx.test(jQuery("input[name='user_password']").val()) ){
			user_data_valid=false;
			show_password_error = true;
		}
	}
	
	//如果有 is_event ，再檢查 event_id 是否有設好
	if ( typeof(is_event) == "undefined" ) {
		//	
	}
	else if ( typeof(is_event) != "undefined" && (is_event == false) ) {
		//	
	}
	else {
		if ( jQuery("#event_id").length<1 ){
			user_data_valid=false;
			show_no_event = true;
		}
	}
	
	//密碼、確認密碼的檢查
	if ( jQuery("input[name='confirm_password']").length >0 ) {
		var password1 = jQuery("input[name='user_password']").val();
		var password2 = jQuery("input[name='confirm_password']").val();
		if ( password1 == password2 )  {
			//
		}
		else {
			user_data_valid=false;
			show_password_match_error = true;
		}
	}
		
	// ↑資料檢查區
	if ( user_data_valid ){
		return true;
	}
	else {
		return false;
	}

}

function check_duplicate(field_name, show_alert){
	var email_rx=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$/;
	var field_value = jQuery(":input[name='"+field_name+"']").val();
	if ( field_value.length >=1 && email_rx.test(field_value) ) {
		jQuery(".checking").show();
		jQuery("#check_usable").hide();
		
		var filename="http://" + window.location.host + "/_event-includes/_pchomekids_check_duplicate.php";
		jQuery.post(filename,
			{"duplicate_field_name":field_name,"duplicate_field_value":field_value},
			function(responseMessage){
				if ( responseMessage=="found_duplicate" ){
					if ( show_alert ) {
						window.alert("您所檢查的資料已經有人使用了喔！請換一個吧！");
						jQuery(":input[name='"+field_name+"']").val("");
					}
					else {
						return true;
					}
				}
				else if ( responseMessage=="bad" ){
					if ( show_alert ) {
						window.alert("很抱歉! \可能因為上線人數過多，您的資料未能正確儲存，請稍後再試試!");
					}
					else {
						return true;
					}
				}
				else if ( responseMessage=="no_duplicate" ) {
					if ( show_alert ) {
						window.alert("你所輸入的資料可以使用。");
					}
					else {
						return false;
					}
				}
				else {
					alert(responseMessage);
				}
				jQuery("#check_usable").show();
				jQuery(".checking").hide();
			});
	}
	else {
		alert("沒有資料或資料格式有問題，不進行檢查！");
	}
}

function save_data(action_filename) {
	var m0="";
	var m1="";
	var m2="";
	var m3="";
	var m4="";
	var m5="";
	if ( !is_form_data_ok() ){
		if ( typeof(data_not_ok_message) != "undefined" ) {
			var m0 = (show_data_not_ok_error)?data_not_ok_message:"";
		}
		if ( typeof(email_error_message) != "undefined" ) {
			var m1 = (show_email_error)?email_error_message:"";
		}
		if ( typeof(password_error_message) != "undefined" ) {
			var m2 = (show_password_error)?password_error_message:"";
		}
		if ( typeof(password_match_error_message) != "undefined" ) {
			var m3 = (show_password_match_error)?password_match_error_message:"";
		}
		if ( typeof(captcha_error_message) != "undefined" ) {
			var m4 = (show_captcha_error)?captcha_error_message:"";
		}
		if ( typeof(no_event_message) != "undefined" ) {
			var m5 = (show_no_event)?no_event_message:"";
		}
		
		alert(form_error_message_prefix + m0 + m1 + m2 + m3 + m4 + m5);
		
		show_data_not_ok_error = false;
		show_email_error = false;
		show_password_error = false;
		show_password_match_error = false;
		show_captcha_error = false;
		show_duplicate_error = false;
		show_no_event = false;
	}
	else {
		jQuery("#waiting").show();
		
		//收集資料
        var a = get_element_names_values();	
		a[0][a[0].length]="post_date";
		a[1][a[1].length]=getDateTime();
		var data_type=jQuery(":input[name='data_type']").val();
		var data_action=jQuery(":input[name='data_action']").val();
		var duplicate_field_name = jQuery(":input[duplicate='no']").attr("name");
		var duplicate_field_value = jQuery(":input[name='"+duplicate_field_name+"']").val();
		var old_password = jQuery(":input[name='old_password']").val();
		var uid = jQuery(":input[name='uid']").val();
		//var filename="http://" + window.location.host + "/event/_event-includes/_tbevent_save_data.php";
		jQuery.post(action_filename,
			//傳送那些資料
			{"fields[]":a[0],"values[]":a[1],"data_type":data_type,"duplicate_field_name":duplicate_field_name,"duplicate_field_value":duplicate_field_value,"data_action":data_action,"old_password":old_password,"uid":uid},
			function(responseMessage){
				if ( responseMessage=="good" ){
					window.alert("您的資料已正確儲存了，感謝您的參與！");
					form_clear();
				}
				else if ( responseMessage.search("newpost_success") >= 0 ){
					var aa = responseMessage.split(",");
					window.alert("您的投稿資料已正確儲存了，感謝您的參與！");
					form_clear();
					window.location.href = "indoor_photo.php?p=" + aa[1];
				}
				else if ( responseMessage=="bad" ){
					window.alert("很抱歉! \可能因為上線人數過多，您的資料未能正確儲存，請稍後再試試!");
				}
				else if ( responseMessage.search("vote_success") >= 0 ){
					window.alert("投票成功！感謝您的參與！");
					jQuery("#send_button").show();
					window.location.reload();
					//form_clear();
				}
				else if ( responseMessage.search("too_many_votes") >= 0 ){
					window.alert("一張照片一天只能投一票喔！");
					form_clear();
				}
				else if ( responseMessage.search("vote_stop") >= 0 ){
					window.alert("投票活動已經截止了喔！");
					form_clear();
				}
				else {
					alert(responseMessage);
				}
				jQuery("#waiting").hide();
		});
	}
}

function admin_login() {
	var user_name=jQuery(":input[name='user_name']").val();
	var user_password=jQuery(":input[name='user_password']").val();
	var filename="login1.php";
	jQuery.post(filename,
		{"user_name":user_name,"user_password":user_password},
		function(responseMessage){
			if ( responseMessage=="login_success" ){
				form_clear();
				window.alert("您所提供的帳號、密碼是正確的，自動將網頁轉向目標頁面。");
				location.href = "get-photos.php";
			}
			else if ( responseMessage=="login_fail" ) {
				window.alert("登入失敗。可能是您所提供的帳號或密碼有問題，也有可能是系統目前有些問題。");
				form_clear();
			}
			else {
				alert(responseMessage);
			}
	});
}

//form

function get_element_names(){  //return Array
	var a=new Array();
	jQuery(":text,:radio,:checkbox,select,textarea,:password,input:hidden").each(function(){
		nowName=jQuery(this).attr("name");
		var isUnique=true;
		for ( var i=0 ; i<a.length ; i++ ){
			if ( nowName == a[i] ){
				isUnique=false;
			}
		}
		if ( isUnique ){
		    a[a.length]=nowName;  //讓資料加入陣列，成為最後一個元素
    }
    });
	return a;
}

function get_element_names_values() { //return array, [1]:names, [2]:values
	var user_data_name = new Array();
	var user_data_value = new Array();
	//除了可複選的 checkbox 以外的元素
	jQuery(":text,:radio:checked,select,textarea,:password,:input[type='hidden']").each(function(){
		user_data_value[user_data_name.length] = jQuery(this).val();
		user_data_name[user_data_name.length] = jQuery(this).attr("name");
	});
	var b = "";
	var bNames = get_checkbox_names();
	for ( var i = 0 ; i < bNames.length ; i++ ){
		user_data_name[user_data_name.length] = bNames[i];
		jQuery(":checkbox[name="+bNames[i]+"]:checked").each(function(){
			b = b+","+jQuery(this).val();
		});
		user_data_value[user_data_value.length] = b.substring(1);
		b="";
	}
	var result = [user_data_name,user_data_value];
	return result;
}

function get_checkbox_names(){  //收集checkbox的name，不重複
	var a = new Array();
	jQuery(":checkbox").each(function(){
		nowName = jQuery(this).attr("name");
		var isUnique=true;
		for ( var i = 0 ; i < a.length ; i++ ){
			if ( nowName == a[i] ){
				isUnique = false;
			}
		}
		if ( isUnique ){
		    a[a.length]=nowName;  //讓資料加入陣列，成為最後一個元素
    }
    });
	return a;
}

function get_radio_names(){  //收集radio的name，不重複
	var a=new Array();
	jQuery(":radio").each(function(){
		nowName=jQuery(this).attr("name");
		var isUnique=true;
		for ( var i=0 ; i<a.length ; i++ ){
			if ( nowName == a[i] ){
				isUnique=false;
			}
		}
		if ( isUnique ){
		    a[a.length]=nowName;  //讓資料加入陣列，成為最後一個元素
    }
    });
	return a;
}

function yyyyMmDdList(argYearSelect,argMonthSelect,argDaySelect){  //年、月、日的下拉式選單

	var dateTimeObj=new Date();
	var yyyy=dateTimeObj.getFullYear(); //firefox不能使用getYear()
	
	jQuery("select[name='"+argYearSelect+"'],select[name='"+argMonthSelect+"'],select[name='"+argDaySelect+"']").append("<option value=\"\"></option>").css("width","50px");

	for ( i=1901 ; i<=parseInt(yyyy) ; i++ ){
		jQuery("select[name='"+argYearSelect+"']").append("<option value=\""+i+"\">"+i+"</option>");
	}
	
	for ( i=1 ; i<=12 ; i++ ){
		if ( i<10 ){
			i="0"+i;
		}
	    jQuery("select[name='"+argMonthSelect+"']").append("<option value=\""+i+"\">"+i+"</option>");
	}
	
	for ( i=1 ; i<=31 ; i++ ){
		if ( i<10 ){
			i="0"+i;
		}
		jQuery("select[name='"+argDaySelect+"']").append("<option value=\""+i+"\">"+i+"</option>");
	}
}

function numberList(argSelectName,argStart,argEnd){  //數字下拉式選單

	jQuery("select[name='"+argSelectName+"']").append("<option value=\"\"></option>").css("width","50px");

	for ( i=argStart ; i<=argEnd ; i++ ){
		jQuery("select[name='"+argSelectName+"']").append("<option value=\""+i+"\">"+i+"</option>");
	}
}

function fieldLenForDbCollect(){  //利用get_element_names()產生相對應的欄位在資料表中所需的大小
	var fieldLens=new Array();
	var a=get_element_names();
	jQuery.each(a,function(i,v){
		fieldLens[fieldLens.length]=jQuery("input[name='"+v+"']").attr("field_len") || jQuery("select[name='"+v+"']").attr("field_len") || jQuery("textarea[name='"+v+"']").attr("field_len") || "";
	});
	
	return fieldLens;
}

function formElementTypeCollect(){  ////利用get_element_names()產生element的type
	var types=new Array();
	var a=get_element_names();
	jQuery.each(a,function(i,v){
		types[types.length]=jQuery("input[name='"+v+"']").attr("type") || jQuery("select[name='"+v+"']").attr("type") || jQuery("textarea[name='"+v+"']").attr("type");
	});
	
	return types;
}

function htmlForm2CreateTableSql(){
	var a=get_element_names();
	var b=formElementTypeCollect()
	var c=fieldLenForDbCollect();
	var tableName="d200904_advcode";
	
	var part1="CREATE TABLE `"+tableName+"` ( `id` int(11) unsigned NOT NULL auto_increment COMMENT 'id',";
	var part2="";
	for ( var i=0 ; i<a.length ; i++ ){
		if (c[i]=="" ){
			c[i]="1";
		}
		if ( b[i]=="text" || b[i]=="radio" || b[i]=="checkbox" || b[i]=="select-one" || b[i]=="password" || b[i]=="hidden"){
			/*part2=part2+"`"+a[i]+"` varchar("+c[i]+") collate utf8_unicode_ci NOT NULL COMMENT '"+a[i]+"',";*/
			part2=part2+"`"+a[i]+"` text collate utf8_unicode_ci NOT NULL COMMENT '"+a[i]+"',";
		}
		else if (  b[i]=="textarea" ) {
			part2=part2+"`"+a[i]+"` text collate utf8_unicode_ci NOT NULL COMMENT '"+a[i]+"',";
		}
}
  
var part3="`postdate` datetime NOT NULL COMMENT '資料儲存日期',<br />PRIMARY KEY  (`id`))ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;";

document.write("<span style=\"background-color:#ffffff\">"+part1+part2+part3+"</span>");
}

//cookies

function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name){
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
		{ 
		c_start=c_start + c_name.length+1; 
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		} 
	  }
	return "";
}

function example_cookie() { //用cookie來鎖定目前是第幾頁（第幾個流程）
	if ( getCookie("pointer").length<1 ){
		setCookie("pointer",0);  //第幾個流程，例如目卷的第幾題
		setCookie("answers","");  //其他要儲存的資料，例如累加使用者所選的答案
		var pointer=0;
	}
	else {
		var pointer=getCookie("pointer");
	}
}

//misc

function mapTest(){
	var myFamily={son:"ryder" };
	myFamily.father="eric";
	myFamily.mother="carrie";
	alert(myFamily.father);
}

function processingShow(){
	var a=getPageSize();
	jQuery("#processing").css("left",0);
	jQuery("#processing").css("top",0);
	jQuery("#processing").css("width",a[0]);
	jQuery("#processing").css("height",a[1]);
	jQuery("#processing1").css("left",(a[0]-100)/2);
	jQuery("#processing1").css("top",(a[1]-66)/2);
	jQuery("#processing").show();
}

function getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function getDateTime(){  //產生 yyyy-mm-dd hh:mm:ss
	//format: yyyy-mm-dd hh:mm:ss
	var dateTimeObj=new Date();
	var yyyy=dateTimeObj.getFullYear(); //firefox不能使用getYear()
	var mm=dateTimeObj.getMonth()+1;
	var dd=dateTimeObj.getDate();
	var hh=dateTimeObj.getHours();
	var mi=dateTimeObj.getMinutes();
	var ss=dateTimeObj.getSeconds();
	if ( mm<10 ){
		mm="0"+mm;
	}
	if ( dd<10 ){
		d="0"+dd;
	}
	if ( hh<10 ){
		hh="0"+hh;
	}
	if ( mi<10 ){
		mi="0"+mi;
	}
	if ( ss<10 ){
		ss="0"+ss;
	}
	fullDateTime=yyyy+"-"+mm+"-"+dd+" "+hh+":"+mi+":"+ss;
	return fullDateTime;
}

function putProcessing(){
	jQuery("body").append("<div id=\"processing\"><div id=\"processing1\"><img src=\"_processing.gif\" /></div></div>");
}

function form_clear(){
	jQuery(":text,select,textarea,:password").each(function(){
	   jQuery(this).val("");
	});
	jQuery(":radio,:checkbox").attr("checked","");
}

function check_box_max(source,max_num){
    var chk=source.name;
    if ( $(":checkbox[name='"+chk+"']:checked").length>=max_num ){
	   //alert("最多選三項！");
	   $(":checkbox[name='"+chk+"']:not(:checked)").attr("disabled",true);
	}
	else {
	    $(":checkbox[name='"+chk+"']").attr("disabled",false);
	}
}

function randomnumber(min_num,max_num) {
	var a=Math.floor(Math.random()*(max_num - min_num)) + min_num;
	return a.toString();
}

function captcha_check(captcha_field_id,right_captcha){ //(使用者輸入的認証碼欄位id,正確的認証碼)
	input = jQuery(captcha_field_id).val();
	if ( right_captcha == input ){
		return true;
	}
	else {
		return false;
	}
}

function captcha_regenerate(img_id, captcha_home){ //(img的id)
	captcha_code = randomnumber(111111,999999);
	jQuery(img_id).attr("src", captcha_home + "_captcha/captcha.php?n="+captcha_code);
}

/***********不再用的****************/

