var _oper_site = $('html').attr('tag-site');
$(document).ready(function(){
	var url = (window.location.hash).replace('#',_oper_site);
	if(url){
		load_page(url);
	}
	button_init();
	form_init();
});
//ajax 載入頁面
function load_page(url, datas)
{
	saveSearch(url);
	tinymce.remove();
	tinymce.triggerSave();
	$.ajax({
		url:url,
		type:"POST",
		data: datas,
		cache:false,
		error:function(data){
			alert('網路連線過慢,網頁請重新整理');
			//window.location.href = 'main.php';
		},
		success:function(data){
			$("#page_content").html(data);
			button_init();
			form_init();
			//更新側欄數據
			$.ajax({
				url:Project_Country+'oper/ajax/ajax_get_order_cal-p.php',
				cache:false,
				success:function(d){
					var obj = JSON.parse(d);
					for(var key in obj){
						$("#Update_"+key).html(obj[key]);
					}
				}
			});
		} 
	});
}
function go_page(url){
	window.location.hash = url.replace(_oper_site,'');
}
function button_init(){
	//換頁
	$(".GO_PAGE_BT").on('click',function(){
		var url = $(this).attr('send').replace(_oper_site,'');
		//到列表、匯出頁的時候自動帶入搜尋條件
		if(url.indexOf('_Oper') != -1 || url.indexOf('_Rep') != -1)
		{
			const arr = url.split('?');
			const path = arr['0'].replace('#','').replace(_oper_site,'');
			const p1 = path.indexOf('_Oper');
			const p2 = path.indexOf('_Rep');
			const key = path.substr(0,Math.max(p1,p2));
			const data = sessionStorage.getItem(key);
			if(data && !arr['1'])
			{
				url = path+data;
			}
		}
		window.location.hash = url;
	});
	//全選
	$(".SELECT_ALL_BT").on("click", function(){
		$(".List_Checkbox").prop('checked', true);	
		$(".List_Checkbox").parents('tr').attr("style", "background-color:#CFE9FE");	
		
		return false;
	});
	//取消全選
	$(".UNSELECT_ALL_BT").on("click", function(){
		$(".List_Checkbox").prop('checked', false);
		$(".List_Checkbox").parents('tr').attr("style", "");	
		
		return false;
	});
	//核選
	$(".List_Checkbox").on("click", function(){
		if(this.checked == true){
			$(this).parents('tr').attr("style", "background-color:#CFE9FE");	
		}
		else{
			$(this).parents('tr').attr("style", "");	
		}
	});
	//勾選送出
	$(".CHECK_SEND_BT").on("click", function(){
		$this = $(this);									 
		var tmp = [];
		$(".List_Checkbox:checked").each(function(){
			tmp.push($(this).val());										  
		});
		if(!tmp[0]){
			bootbox.alert(_jsLang.沒有勾選任何項目);
			return false;
		}
		bootbox.confirm($(this).attr('msg'),function(e){
			if(e){
				var send = $this.attr('send') + "&ID=" + tmp.join(",");
				ajaxRequest($this.attr('url'), send, function(j){
					show_stack(j.type,j.text);
					if(j.fun)eval(j.fun);
				}, 'json');				
			}
		});									 
	});
	//單鍵背景處理
	$(".ONE_CLICK_BT").on("click", function(){
		var msg = $(this).attr("msg");	
		var send = $(this).attr("send");
		var url  = $(this).attr("url");
		bootbox.confirm(msg,function(e){
			if(e){
				ajaxRequest(url, send, function(j){
					show_stack(j.type,j.text);
					if(j.fun)eval(j.fun);
				}, 'json');	
			}
		});
		return false;
	});
	
	//展開收合搜尋
	$(".OPEN_SEARCH_BT").on("click", function(){
		ajaxRequest($(this).attr('url'), $(this).attr('send'), function(html){
			$("#main_searchbox").toggle();	
		}, 'html');	
		
		return false;
	});
	
	//排列序號Blur
	$(".PORDER_NO_TEXT").on("blur",function(){
		var error = false;
		$(".PORDER_NO_TEXT").attr("style", "");	
		$(".PORDER_NO_TEXT").each(function(){
			if(isNaN(this.value) || this.value == ""){
				$(this).attr("style", "background-color:#CFE9FE");	
				error = true;
			}
		});
		if(error){
			this.value = 1;
			bootbox.alert(_jsLang.排列序號只能填入數字或不可空白);
		}
		
		return false;
	});
	
	//排列序號Blur
	$(".ORDER_NO_TEXT").on("blur",function(){
		var error = false;
		$(".ORDER_NO_TEXT").attr("style", "");	
		$(".ORDER_NO_TEXT").each(function(){
			if(isNaN(this.value) || this.value == ""){
				$(this).attr("style", "background-color:#CFE9FE");	
				error = true;
			}
		});
		if(error){
			this.value = 1;
			bootbox.alert(_jsLang.排列序號只能填入數字或不可空白);
		}
		
		return false;
	});
	
	//更改排列序號
	$(".SET_PORDER_NO_BT").on("click",function(){
		var tmp = [];
		var msg = $(this).attr("msg");	
		var send = $(this).attr("send");
		var url  = $(this).attr("url");
		//重置排列序號的時候要加上當前的條件
		const arr = url.split('?');
		const path = arr['0'].replace('#','').replace(_oper_site,'');
		const p1 = path.indexOf('_Oper');
		const p2 = path.indexOf('_Rep');
		const key = path.substr(0,Math.max(p1,p2));
		const data = sessionStorage.getItem(key);
		if(data)
		{
			send = (data+send).replace('?','&');
		}
		$(".PORDER_NO_TEXT").each(function(){
			var id = $(this).attr('id').replace(/Parent_Order_No/, "");	
			tmp.push(id + "||" + $(this).val());
		});
		send += "&ID=" + tmp.join(",");
		bootbox.confirm(msg,function(e){
			if(e){
				ajaxRequest(url, send, function(j){
					show_stack(j.type,j.text);
					if(j.fun)eval(j.fun);
				}, 'json');	
			}
		});
		
		return false;
	});
	
	//更改排列序號
	$(".SET_ORDER_NO_BT").on("click",function(){
		var tmp = [];
		var msg = $(this).attr("msg");	
		var send = $(this).attr("send");
		var url  = $(this).attr("url");
		//重置排列序號的時候要加上當前的條件
		const arr = url.split('?');
		const path = arr['0'].replace('#','').replace(_oper_site,'');
		const p1 = path.indexOf('_Oper');
		const p2 = path.indexOf('_Rep');
		const key = path.substr(0,Math.max(p1,p2));
		const data = sessionStorage.getItem(key);
		if(data)
		{
			send = (data+send).replace('?','&');
		}
		
		$(".ORDER_NO_TEXT").each(function(){
			var id = $(this).attr('id').replace(/Order_No/, "");	
			tmp.push(id + "_" + $(this).val());
		});
		send += "&ID=" + tmp.join(",");
		bootbox.confirm(msg,function(e){
			if(e){
				ajaxRequest(url, send, function(j){
					show_stack(j.type,j.text);
					if(j.fun)eval(j.fun);
				}, 'json');	
			}
		});
		
		return false;
	});
	
	//送出搜尋
	$(".SEARCH_FORM").on("submit", function()
	{
		var send = {};
		if($(this).find("#search_type").val()){	
			$("#" + $(this).attr('id') + " :input:not(:button,:submit,:reset)").each(function(){
				if(this.type=='select-one'){
					send[this.id] = this.value;
				}
				else if(this.type=='text' || this.type=='number'){
					send[this.id] = this.value;
				}
				else if(this.type == 'select-multiple'){
					var i = 0;	
					var tmpArr = [];
					$(this).children("option").each(function(){
						if(this.selected == true){
							if(this.value){
								tmpArr[i] = this.value;	
								i++;
							}
						}
					});
					send[this.id] = tmpArr.join(",");
				}
			});
			send = 'osearch='+JSON.stringify(send)+'&page=1';
		}
		else
		{
			send = '';
		}
		var hash = window.location.hash;
		if(hash.match('osearch='))
		{
			const p1 = hash.indexOf('osearch=')-1;
			const p2 = hash.indexOf('page=')-1;
			hash = hash.substr(0,Math.min(p1,p2));
		}
		const connect = (hash.indexOf('?') == -1)?'?':'&';
		//切換網址
        window.location.hash = hash+connect+send;
		return false;
	});
	
	//查詢
	$(".SEARCH_BT").on("click", function(){
		$(".SEARCH_FORM").submit();
	});
	
	//重置查詢
	$(".RESET_SEARCH_BT").on("click", function(){
		$(this).parents(".SEARCH_FORM").find("#search_type").val("");
		var url = (window.location.hash).replace('#',_oper_site);
		if(url.match('osearch='))
		{
			const p1 = window.location.hash.indexOf('osearch=')-1;
			const p2 = window.location.hash.indexOf('page=')-1;
			const hash = window.location.hash.substr(0,Math.min(p1,p2));
			window.location.hash = hash;
			return false;
		}
		hashchange();
	});
	
}
//只有搜尋、從menu點擊、重整時儲存
function saveSearch(path)
{
	const arr = path.split('?');
	const key = arr['0'].replace('#','').replace(_oper_site,'').replace('_Oper.php','');
	
	if(arr['1'])
	{
		sessionStorage.setItem(key,'?'+arr['1']);
	}
	else
	{
		sessionStorage.removeItem(key);
	}
}
function form_init(){
	
	//日期選擇器
	$(".DATE").datetimepicker({			
		format:'YYYY-MM-DD'
	});
	
	//時間選擇器
	$(".TIME").datetimepicker({			
		format:'HH:mm:ss'
	});
	
	//日期+時間選擇器
	$(".DATETIME").datetimepicker({		
		format:'YYYY-MM-DD HH:mm',
		sideBySide:true,
	});
	//日期+時間選擇器 10 min
	$(".DATETIME_10M").datetimepicker({		
		format:'YYYY-MM-DD HH:mm',
		sideBySide:true,
		stepping:10,
	});
	
	if($(".iCheck").size() > 0){
		$(".iCheck").iCheck({
			checkboxClass: 'icheckbox_square-blue',
			radioClass: 'iradio_square-blue'
		});
	}
	//日期+時間選擇器
	$(".DATETIME_S").datetimepicker({		
		format:'YYYY-MM-DD HH:mm:ss',
		sideBySide:true,
	});
	
	//國別+縣市
	$(".COUNTRY_BT").load(Project_Country+'oper/ajax/ajax_country.php',{type:'country'},function(){
		var $Country = $(this);
		var sub_id = $(this).attr('sub_id');
		$Country.bind('change',function(){
			$("#" + sub_id + "[group='"+$Country.attr('group')+"']").load(Project_Country+'oper/ajax/ajax_country.php',{type:'city',id:$Country.val()},function(){
				var city    = $("#" + sub_id).attr('city');
				if(city>0){
					$("#" + sub_id).children().each(function(){
						if($(this).val()==city){
							$(this).attr('selected',true);
						}
					});
				}		
			});
		});
		
		var country = $Country.attr('country');	
		if(country>0){
			$Country.children().each(function(){
				if($(this).val()==country){
					$(this).attr('selected',true);
				}
			});
			$Country.change();
		}
	});
	
	//提示方塊
	$(".Popover_Hover").popover();	
}
function hashchange(){
	var url = (window.location.hash).replace('#',_oper_site);
	if(url){
		load_page(url);
	}else{
		window.location.href = 'main.php';
	}
}
function show_stack($type,$text) {
	var modal_overlay;
	info_box = new PNotify({
        title: "",
        text: $text,
        type: $type,
        delay: 1000,
        history: {
            history: false
        },
        stack: false,
        before_open: function(PNotify) {
            // Position this notice in the center of the screen.
            PNotify.get().css({
                "top": ($(window).height() / 2) - (PNotify.get().height() / 2),
                "left": ($(window).width() / 2) - (PNotify.get().width() / 2)
            });
        },
    });
}
function tinyMce(selector, width, height){
  tinymce.init({
    cache_suffix: '?v=0720',
    language: 'zh_TW',
    width: width,
    height: height,
    selector:selector,
    resize: true,
    convert_urls:false,
    mode :'textareas',
    valid_children: "+body[style|link|script]",
		valid_elements : "*[*]",
    skin_url: Project_Country+"plugin/tinymce/skins/lightgray",
    plugins: [
      "advlist autolink lists link charmap print preview anchor",
      "searchreplace visualblocks code fullscreen",
      "insertdatetime media table contextmenu paste textcolor,image filetool",
      "emoticons"
    ],
    toolbar: "insertfile undo redo | styleselect fontselect fontsizeselect forecolor backcolor | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | file emoticons"
  });
}