

var isIE = navigator.userAgent.toLowerCase().indexOf('ie');

function getbyid(id) {
	if (document.getElementById) {
		return document.getElementById(id);
	} else if (document.all) {
		return document.all[id];
	} else if (document.layers) {
		return document.layers[id];
	} else {
		return null;
	}
}

//添加Select選項
function addoption(obj) {
	if (obj.value=='addoption') {
		var newOption=prompt('請輸入:','');
		if (newOption!=null && newOption!='') {
			var newOptionTag=document.createElement('option');
			newOptionTag.text=newOption;
			newOptionTag.value=newOption;
			try {
				obj.add(newOptionTag, obj.options[0]); // doesn't work in IE
			}
			catch(ex) {
				obj.add(newOptionTag, obj.selecedIndex); // IE only
			}
			obj.value=newOption;
		} else {
			obj.value=obj.options[0].value;
		}
	}
}

//顯示/隱藏內容
function showContent(contentid,ctrlid,opentext,closetext) {
	var content=document.getElementById(contentid);
	if (ctrlid!='') {var ctrl=document.getElementById(ctrlid);}
	if (content.style.display=='') {
		content.style.display='none';
		if (ctrlid!='') {ctrl.innerHTML=opentext;}
		CreatCookie('ss_openmenu', '0');
	} else {
		content.style.display='';
		if (ctrlid!='') {ctrl.innerHTML=closetext;}
		CreatCookie('ss_openmenu', '1');
	}
}

//getElementsByTagNameS
function getElementsByTagNames(list,obj) {
	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function addMouseEvent() {
	//為輸入框添加焦點效果
	var inputs=getElementsByTagNames('input,textarea');
	for (i=0;i<inputs.length;i++) {
		var inputtype = inputs[i].type.toLowerCase();
		if(inputtype == 'checkbox' || inputtype == 'radio') continue;
		inputs[i].onfocus=function() {
			this.className='focus';
			var temptips=document.getElementById(this.id+'tips');
			if (temptips) {
				temptips.style.display='block';
				//temptips.style.width=this.offsetWidth-10+'px';
				temptips.style.top=findPosY(this)-temptips.offsetHeight-3+'px';
				temptips.style.left=findPosX(this)+3+'px';
				//alert(findPosY(this));
			}
		}
		inputs[i].onblur=function() {
			this.className='';
			var temptips=document.getElementById(this.id+'tips');
			if (temptips) {
				myTimeout = window.setTimeout(function() {temptips.style.display='none';}, 200); 
				//temptips.style.display='none';
			}
		}
	}
	//為信息列表添加選中效果
	var articleList=document.getElementById('articlelist');
	if (articleList) {
		var articleRows=articleList.getElementsByTagName('tr');
		for(i=0;i<articleRows.length;i++){
			articleRows[i].onclick=function() {
				var tempCheckbox=this.getElementsByTagName('input')[0];
				if (tempCheckbox) {
					if(this.className==''){
						this.className='selected';
						tempCheckbox.checked=true;
					} else {
						this.className='';
						tempCheckbox.checked=false;
					}
				}
			}
		}
	}
	//為IE下的Checkbox和Radio去處背景色
	if (isIE>-1) {
		minputs=document.getElementsByTagName('input');
		for(i=0;i<minputs.length;i++){
			if(minputs[i].type!='text'&&minputs[i].type!='file'){
				minputs[i].style.backgroundColor='transparent';
				minputs[i].style.backgroundImage='none';
				minputs[i].style.border='none';
			}
		}
	}
}

function addTag(tag, id) {
	var tagInput=document.getElementById(id);	
	if (tagInput) {
		tagInput.value+=tag+' ';
	}
}


function checkall(form, prefix, checkall) {
	var checkall = checkall ? checkall : 'chkall';
	for(var i = 0; i < form.elements.length; i++) {
		var e = form.elements[i];
		if(e.name != checkall && (!prefix || (prefix && e.name.match(prefix)))) {
			e.checked = form.elements[checkall].checked;
		}
	}
}

function divshow(show, hide) {
	for(i=0;i<show.length;i++){
		document.getElementById(show[i]).style.display = '';
	}
	for(i=0;i<hide.length;i++){
		document.getElementById(hide[i]).style.display = 'none';
	}
}

function unbutton(btn) {
	for(i=0;i<btn.length;i++){
		document.getElementById(btn[i]).disabled=true;
	}
}

function ischeck(id, prefix) {
	form = document.getElementById(id);
	for(var i = 0; i < form.elements.length; i++) {
		var e = form.elements[i];
		if(e.name.match(prefix) && e.checked) {
			return true;
		}
	}
	alert('請選擇要操作的對象');
	return false;
}


function checkall(form, prefix, checkall) {
	var checkall = checkall ? checkall : 'chkall';
	for(var i = 0; i < form.elements.length; i++) {
		var e = form.elements[i];
		if(e.name != checkall && (!prefix || (prefix && e.name.match(prefix)))) {
			e.checked = form.elements[checkall].checked;
		}
	}
}


function getid(id) {
	return document.getElementById(id);
}

function uploadFile(mode) {
	var theform = document.getElementById("theform");
	var msg = document.getElementById("divshowuploadmsg");
	var msgok = document.getElementById("divshowuploadmsgok");
	var oldAction = theform.action;
	var oldonSubmit = theform.onSubmit;
	msgok.style.display = 'none';
	msg.style.display = '';
	msg.innerHTML = "正在上傳中，請您稍等......";
	theform.action = siteUrl + "/batch.upload.php?mode=" + mode;
	theform.onSubmit = "";
	theform.target = "phpframe";
	theform.submit();
	theform.action = oldAction;
	theform.onSubmit = oldonSubmit;
	theform.target = "";
	if(mode ==2) {
		delpic();
	}
	return false;
}

function attacheditsubmit(aid) {
	var theform = document.getElementById("theform");
	var oldAction = theform.action;
	var oldonSubmit = theform.onSubmit;
	theform.action = siteUrl + "/batch.upload.php?editaid=" + aid;
	theform.onSubmit = "";
	theform.target = "phpframe";
	theform.submit();
	theform.action = oldAction;
	theform.onSubmit = oldonSubmit;
	theform.target = "";
	return false;
}

/**
 * 隱藏並顯示上傳DIV中的指定標籤
 * @param string id: 待顯示的標籤ID
 */
function hideshowtags(upid,id) {
	//獲取上傳DIV對像
	var uploadobj = getbyid(upid).getElementsByTagName('div');
	for(var i=0; i< uploadobj.length; i++) {
		if(uploadobj[i].id.indexOf('upload') != -1) {
			uploadobj[i].style.display = "none";
		}
	}
	var showtagobj = getbyid(id);
	showtagobj.style.display = "block";
	
	var tags = getbyid(upid).getElementsByTagName('div')[0].getElementsByTagName('a');
	for(var i=0; i< tags.length; i++) {
		tags[i].className = "";
	}
	if (getbyid(id+'tab')) { getbyid(id+'tab').className = "current"; }
}
/**
 * 計算字符串長度
 * @param str checkStr:要計算的字符串長度
 */
function chklength(checkStr) {
	var n = 0;
	for (i = 0; i<checkStr.length; i++) {
		chcode = checkStr.charCodeAt(i);
		if (chcode>=0 && chcode<=255) {
			n++;
		} else {
			n += 2;
		}
	}
	return n;
}
/***************批量上傳調用開始***********************/
/**
 * 插入一個預覽圖片
 * @param object obj: 上傳文本框對像
 */
function insertimg(obj) {
	var childnum = getbyid("batchdisplay").getElementsByTagName("input");	//獲取上傳控制個數
	var upallowmax = getbyid("uploadallowmax").value;
	//判斷是否超過限制
	if(upallowmax < childnum.length ) {
		alert("一次允許最多上傳"+ upallowmax +"個");
		return false;
	}
	//獲取最高ID
	var id =getmaxid();
	//添加默認的DIV
	var pichtml = '';
	var src = obj.value;
	
	//判斷文件類型
	var patn = /\.jpg$|\.jpeg$|\.gif$|\.png$|\.bmp$/i;
	var filetype = 'file';
	if(patn.test(src)){
		filetype = 'image';
		
	}
	
	var temp_title = src.substr(src.lastIndexOf('\\')+1);
	if(src.lastIndexOf('.') != -1){
		temp_title = temp_title.substr(0,(src.substr(src.lastIndexOf('\\')+1)).lastIndexOf('.'));
	}
	pichtml += '<div class="picspace" id="pic_space_' + id + '" onmouseover="mouseoverpic(' + id + ', 0)" onmouseout="mouseoutpic(' + id + ', 0)">';
	pichtml += '<a href="javascript:;" onclick="delpic('+id+');" style="float: right; margin: 10px 5px 0 0;">刪除</a>';
	if (navigator.userAgent.toLowerCase().indexOf('ie') < 0 || filetype != 'image') {
		pichtml += '<img src="admin/images/upload_file.gif" alt="upload file" class="nopreview" align="absmiddle" />';
	} else {
		pichtml += '<img src="' + src + '" id="pic_item_id_' + id + '" align="absmiddle" />';
	}
	pichtml += '<span class="pictext" id="pic_text_' + id + '">';
	pichtml += '<label id="label_pic_' + id + '" title="'+getStrbylen(temp_title,40)+'"><span id="pic_' + id + '">'+getStrbylen(temp_title,16)+'</span><input  id="pic_input_' + id + '" type="text" name="picname[]" value="'+temp_title+'" style="display: none;" /></label>';
	pichtml += '</span><div style="display:none;"><input type="text" name="title[]" value="'+ temp_title +'" id="pic_title_' + id + '" /><input type="text" name="thumb[]" value="'+ (getbyid('uploadthumb2') == null?"":getbyid('uploadthumb2').value) +'"/></div>';
	pichtml += '</div>';

	// 把圖片框加到pic_space_main中去
	var picmain = getbyid("batchpreview");
	picmain.innerHTML = picmain.innerHTML + pichtml;
	obj.style.display = 'none';	//隱藏當前的上傳對像
	var newid = id+1;	//獲取下一個最大的上傳ID並創建新的上傳控件
	addupload(newid);	//創建一個新的上傳控制
}
/**
 * 添加一個新的上傳對像控件
 * @param int newid: 新的上傳控件ID後綴
 */
function addupload(newid) {
	//兩種生成方式，解決瀏覽器之間的兼容性問題
	try{
		//IE模式下的創建方式,解決常規setAttribute設置屬性帶來的一些未知的錯誤
		var uploadHTML = document.createElement("<input type=\"file\" id=\"batch_" + newid + "\" name=\"batchfile[]\" onchange=\"insertimg(this)\" class=\"fileinput\">");
		getbyid("batchdisplay").appendChild(uploadHTML);
	}catch(e) {
		//非IE模式則須要用下列的常規setAttribute設置屬性，否則生成的結果不能正常初始化
		var uploadobj = document.createElement("input");
		uploadobj.setAttribute("name", "batchfile[]");
		uploadobj.setAttribute("onchange", "insertimg(this)");
		uploadobj.setAttribute("type", "file");
		uploadobj.setAttribute("id", "batch_" + newid);
		uploadobj.setAttribute("class", "fileinput");
		getbyid("batchdisplay").appendChild(uploadobj);
	}
}
/**
 * 得到頁面中可用的最大ID號
 * 寫這個函數主要是因為不能通過圖片的個數來計算可用的最大ID號.
 * 圖片是可以取消的,如果取消,則通過圖片個數算出的最大ID號會與已有圖片的ID號重疊.
 */
function getmaxid() {
	var items = getbyid("batchdisplay").getElementsByTagName("input");
	var count = items.length;
	var id = 0;
	for (var i=0; i<count; i++) {
		if(items[i].id.substr(0, 6) == "batch_") {
			tmp_id = new Number(items[i].id.substr(6));
			if(id < tmp_id) {
				id = tmp_id;
			}
		}
	}
	if(id == 0) {
		return 1;
	}
	id = new Number(id);
	return id;
}
/**
 * 截取指定字符串長度
 * @param string str: 要截取的字符串
 * @param int len: 要截取的長度
 * @return 
 */
function getStrbylen(str, len) {
	var num = 0;
	var strlen = 0;
	var newstr = "";
	var laststrlen = 1;
	var obj_value_arr = str.split("");
	for(var i = 0; i < obj_value_arr.length; i ++) {
		if(i < len && num + byteLength(obj_value_arr[i]) <= len) {
			num += byteLength(obj_value_arr[i]);
			strlen = i + 1;
		}
	}
	if(str.length > strlen) {
		if(byteLength(str.charAt(strlen-1)) == 1){
			laststrlen = 2;
		}
		newstr = str.substr(0, strlen-laststrlen) + '…';
	} else {
		newstr = str;
	}
	return newstr;
}
/**
 * 判斷中英問混排時候的長度
 * @param string sStr: 混排的字符串
 */
function byteLength (sStr) {
	aMatch = sStr.match(/[^\x00-\x80]/g);
	return (sStr.length + (! aMatch ? 0 : aMatch.length));
}
/**
 * 鼠標移到預覽圖事件
 * @param int id: 操作對像ID反綴
 * @param int optype: 操作類型
 */
function mouseoverpic(id,optype) {
	if(optype == 1) {
		var delpicbutton = getbyid("del_pic_button" + id);
		if(delpicbutton.style.display != "inline") {
			delpicbutton.style.display="inline";
		}
	} else if(optype == 0) {
		getbyid("pic_" + id).style.display = "none";
		getbyid("pic_input_" + id).style.display = "inline";
	}
}
/**
 * 鼠標移出預覽圖事件
 * @param int id: 操作對像ID反綴
 * @param int optype: 操作類型
 */
function mouseoutpic(id, optype) {
	if(optype == 1) {
		var delpicbutton = getbyid("del_pic_button" + id);
		delpicbutton.style.display="none";
	} else if(optype == 0) {
		var picobj = getbyid("pic_" + id);
		var inputobj = getbyid("pic_input_" + id);
		var labelobj = getbyid("label_pic_" + id);
		picobj.style.display = "inline";
		inputobj.style.display = "none";
		//判斷是否為空，如果為空則取默認的文件名稱
		var re = /\s/ig;
   		var result = inputobj.value.replace(re, "");
		if(result == "") {
			inputobj.value = getbyid("pic_title_" + id).value;
		}
		picobj.innerText = inputobj.value;
		labelobj.title = inputobj.value;
	}
}
/**
 * 刪除全部預覽圖或其中的某一張
 * @param int pid: 要刪除的預覽圖ID後綴，如沒有填寫則刪除全部的預覽圖
 */
function delpic(pid) {
	//判斷是否有傳刪除的圖片ID，如果沒有則刪除全部的圖片
	if(typeof pid != "undefined") {
		getbyid("batchpreview").removeChild(getbyid("pic_space_"+pid));
		//刪除相對應的上傳控件
		getbyid("batchdisplay").removeChild(getbyid("batch_" + pid));
	} else {
		//獲取全部圖片對像
		var previewobj = getbyid("batchpreview");
		var allobj = previewobj.getElementsByTagName("div");
		for(var i = allobj.length - 1; 0<=i; i--) {
			if(allobj[i].id.indexOf("pic_space_") != -1) {
				previewobj.removeChild(allobj[i]);
			}
		}
		var bdisplay = getbyid("batchdisplay");
		var allupobj = bdisplay.getElementsByTagName("input");
		for(var i = allupobj.length - 1; 0<=i; i--) {
			bdisplay.removeChild(allupobj[i]);
		}
		addupload(1);
	}
	return false;
}
/***************批量上傳調用結束***********************/
