﻿var isIE = document.all?true:false;
var isNS = document.layers?true:false;

function checkAll( formObj, fieldName ){
   for (var i = 0; i < formObj.length; i++) {
        if( !formObj[i].name )continue;
        if(formObj[i].name.indexOf(fieldName) > -1)
        formObj[i].checked=!formObj[i].checked;
   }
}

function checkForm( obj ){
   for( i=0; i<col.length; i++ ){
        if( obj[col[i]].value=="" ){
            alert("Please Entry" + col_name[i] + "！");
            obj[col[i]].focus();
            event.returnValue = false;
            return false;
        }
   }
}

//Enter鍵失效
function cancel_enter(e){
	var evt = e || window.event;
     if(evt.keyCode == 13){
		document.body.focus();
		return false;
	 }
     return true;
}

//ESC鍵失效
function cancelEsc(e){
	var evt = e || window.event;
     if(evt.keyCode == 29){
		document.body.focus();
		return false;
	 }
     return true;
}


function openDialog( url, set, obj ){
    //檢查是否支援 Show Dialog
    if ( typeof window != "undefined"
    && ((typeof window.showModalDialog)=='function' || (typeof window.showModalDialog)=='object' ) ) {
		if( !set )set = 'dialogHeight:450px;dialogWidth:600px;dialogTop:220px;dialogLeft:200px;';
		var tt = new Date(); //VOID CATCH
		window.showModalDialog( url+'&tt='+tt.getTime(), self, set );
	}else{
		if( set ){
			set = set.replace( /;/g, ',' );
			set = set.replace( /dialog/g, '' );
			set = set.replace( /:/g, '=' );
		}
		openWin( url, set );
	}
}


function openWin( url, set, name ){
	if( name==null )name = '_new';
	var winID = window.open( url, '_new', "top=10,width=780,height=650,left=10,scrollbars=1,resizable=yes," + set );
    if( winID.opener==null )winID.opener = window;
    winID.opener.name = 'opener';
}

//2009.6.4新增彈出列印用視窗
function printPDF( url, set, name ){
	if( name==null )name = '_new';
	var winID = window.open( "print_frame.php?url=" + escape(url), '_new', "top=10,width=780,height=650,left=10,scrollbars=1,resizable=yes," + set );
    if( winID.opener==null )winID.opener = window;
    winID.opener.name = 'opener';
}

function scrollPage( tid ){
    var obj = document.getElementById(tid);
    obj.scrollIntoView();
}

/* 設定TEXTAREA大小　　*/
function setTextareaRows( obj, is_min ){
   if( obj ){
       if( is_min ){
           if( obj.rows <= 1 ){
               return;
           }
           obj.rows -= 3;
       }else obj.rows += 3;
   }
}

/* 排序 */
function Sort(SortKey){
	var F = document.getElementById('QFORM');
	//更換
	if( F.order_by.value.indexOf(SortKey) == -1 ){
		F.order_by.value = SortKey;
		F.dec.value = 'ASC';
	}else if( F.dec.value.indexOf('DESC') == -1 ){
		F.order_by.value = SortKey;
		F.dec.value = 'DESC';
	}else{
		F.order_by.value = SortKey;
		F.dec.value = 'ASC';
	}
	F.submit();
}

function checkIsNum(s){
	var patrn=/^[-,+]{0,1}[0-9]{0,}$/;
	if (!patrn.exec(s))return false;
	return true;
}

function parseInt2(s){
	var num = (s+'').replace( ',', '' );
	var patrn=/^[-,+]{0,1}[0-9|\.]{0,}$/;
	if( !patrn.exec(num) )return 0;
	//去掉第一個零
	num = num.replace( /^0/, '' );
	if( num=='' )num = 0;
	return parseInt(num);
}

function parseFloat2(s, digit){
	if( s=='' )return 0;
	s = (s+'').replace( ',', '' );
	var patrn=/^[-,+]{0,1}[0-9.]{0,}$/;
	if (!patrn.exec(s))return 0;
	if( digit==2 )return Math.round(s*100)/100;
	return Math.round(s*10000)/10000;
}

function returnNull( obj ){
	if( parseFloat2(obj.value)==0 )obj.value = '';
}

function trim( str ){
	var re = /^[ ]+|[ ]+$/g;
	return str.replace(re,"");
}

function retrim2( str ){
	str = str.replace( /&#39;/g, "'" );
	str = str.replace( /&#34;/g, '"' );
	return str;
}

function showStatus(sMsg){
	window.status = sMsg ;
	return true ;
}

function addCommas( nStr ){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while( rgx.test(x1) ){
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//若物件中字串超過則自動截短
function auto_substr(obj, max,is_alarm){
	if( !obj )return;
	if( obj.value=='' )return;
	if( max==0 )return;
	var str = obj.value + '';
	if( str.length <= max )return;
	obj.value = str.substring(0,max);
	if( is_alarm==null || is_alarm==1 )alert( 'The column is ' + max + ' chars limit.' );
}

//每LEN個字便自動斷行 TEXTAREA用
function auto_wrap( str, len ){
	var count = 0;
	var c = 0;
	var new_str = '';

	var ary = str.split("\r\n");
	for( var I=0; I<ary.length; I++ ){
		count = 0;
		c = 0;
		ln = ary[I].length;
		for( i=0; i<ln; i++ ){
			var sc = ary[I].charCodeAt(i);
			if( sc < 31 ){
				c = 0;
			}else if( sc > 127 ){
				count += 2;
				c = 2;
			}else{
				count++;
				c = 1;
			}
			if( count >= len && i<ln ){
				new_str += "\r\n";
				count = c;
			}
			new_str += ary[I].substr( i, 1 );
		}
		if( I < ary.length-1 )new_str += "\r\n";
	}
	return new_str;
}

//只可輸入數字
function onlyDigits(e){
	var _ret = true;
	if (isIE) {
	    if (window.event.keyCode < 46 || window.event.keyCode > 57) {
	        window.event.keyCode = 0;
	        _ret = false;
	    }
	}
	if (isNS) {
	    if (e.which < 46 || e.which > 57) {
	        e.which = 0;
	        _ret = false;
	    }
	}
	if( !_ret ){}
	return (_ret); 
}


function hidden_tr( tr_id ){
	document.getElementById(tr_id).style.display = "none";
}

function display_tr( tr_id ){
	document.getElementById(tr_id).style.display = "";
}
//==============================================================================
//新增至我的購物車
function quick_add_to_cart( from_type, prod_id, sale_id, qty, from_ID ){
	var now = new Date();
	var tt = now.getTime();
	new Ajax.Request( '?prog=cart&item=add_to_cart&time=' + tt, { method:'get',
		parameters:{ 'from_type':from_type, 'prod_id':prod_id, 'sale_id':sale_id, 'qty':qty },
		onSuccess: function(transport){
			
			var rs = transport.responseText.evalJSON();
			if( rs.is_ok==0 ){
				alert( rs.msg );
				return false;
			}
			if( from_type==1 ){
			//產品清單
				alert( '商品已加入購物車' );
				var showObj = document.getElementById( from_ID );
				showObj.innerHTML = '<B>(' + rs.qty + '</B>)';
				
			}else{
			//產品資訊頁
				alert( '商品已加入購物車' );
				var showObj = document.getElementById( from_ID );
				showObj.innerHTML = '目前有 <B>' + rs.qty + '</B> 件在購物車中';
			}
			return true;
		}
	});
}

//------------------------------------------------------------------------------
/* 尋找物件位置 */
function findPos( obj ){
	var curleft = curtop = 0;
	if( obj.offsetParent ){
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while( obj = obj.offsetParent ){
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return new Array(curleft,curtop);
}

/* 取得滑鼠座標 */
function getMouseXY( e ){
	var IE = document.all ? true : false;
	// If NS -- that is, !IE -- then set up for mouse capture
	if( !IE )document.captureEvents(Event.MOUSEMOVE);
	// Temporary variables to hold mouse x-y pos.s
	var tempX = 0;
	var tempY = 0;
	if( IE ){ // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	}else{  // grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
	}
	// catch possible negative values in NS4
	if( tempX < 0 ){ tempX = 0; }
	if( tempY < 0 ){ tempY = 0; }
	return new Array( tempX, tempY );
}

//計算行數
function countLines( strtocount, cols ){
	var hard_lines = 1;
	var last = 0;
	while( true ){
		last = strtocount.indexOf("\n", last+1);
		hard_lines ++;
		if( last == -1 )break;
	}
	//var soft_lines = Math.round(strtocount.length / (cols-1));
	//var hard = eval("hard_lines  " + unescape("%3e") + "soft_lines;");
	return hard_lines;
}

//將TEXTAREA自動長大
function displayTextarea( obj, str, min_rows, is_auto_wrap, max_word, is_init ){
    //自動斷行
    if( is_auto_wrap ){
	    //str = auto_wrap( str, obj.cols );
		//obj.value = str;
	}
	if( max_word > 0 ){
		auto_substr( obj, max_word, 1 );
	}

	var line = 0;
	if( is_init )
		line = countLines( str, obj.cols )-1;    //此段行方式使用抓取斷行符號
	else{
		scrollHeight = obj.scrollHeight;
		line = Math.ceil( (scrollHeight-4)/16 );
	}
    if( min_rows==null )min_rows = 1;
    obj.rows = line < min_rows ? min_rows : line;
}

//展開單一項物件的TEXTAREA ( 載入時使用, 不限字數且不自動斷行 )
function auto_set_textarea( obj_id ){
    displayTextarea(document.getElementById(obj_id), document.getElementById(obj_id).value, document.getElementById(obj_id).rows, 0, 0 );
}
//展開指定FORM中所有的TEXTAREA
function auto_set_form_all_textarea( form_id ){
    var form_obj = document.getElementById( form_id );
	var count = form_obj.elements.length;
	for( i=0; i<count; i++ ){		
	     if( form_obj.elements[i].type=='textarea' ){
			 displayTextarea( form_obj.elements[i], form_obj.elements[i].value, form_obj.elements[i].rows, 0, 0, 0 );
		}
	}
}
//離開頁面前先提醒
function leave_page( url ){
    if( confirm('確定離開頁面？') )location.href=url
}
//------------------------------------------------------------------------------
function setCookie(name, value, expires, path, domain, secure){
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name){
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1){
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }else{
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1){
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain){
    if (getCookie(name)){
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/*****************************************************
  Mouse Drag & Drop
  Javascript元素拖曳操作Byshawl.qiu
  */
var is
function start_drag(){
}
function stop_drag(){
}

function fDragging(obj, e, limit){
	if(!e) e=window.event;
	var x=parseInt(obj.style.left);
	var y=parseInt(obj.style.top);

	var x_=e.clientX-x;
	var y_=e.clientY-y;

	if(document.addEventListener){ //W3C
		document.addEventListener('mousemove', inFmove, true);
		document.addEventListener('mouseup', inFup, true);
	} else if(document.attachEvent){ //IE
		document.attachEvent('onmousemove', inFmove);
		document.attachEvent('onmouseup', inFup);
	}

	inFstop(e);
	inFabort(e)

	function inFmove(e){
		var evt;
		if(!e)e=window.event;

		if(limit){
			var op=obj.parentNode;
			var opX=parseInt(op.style.left);
			var opY=parseInt(op.style.top);

			if((e.clientX-x_)<0) return false;
			else if((e.clientX-x_+obj.offsetWidth+opX)>(opX+op.offsetWidth)) return false;

			if(e.clientY-y_<0) return false;
			else if((e.clientY-y_+obj.offsetHeight+opY)>(opY+op.offsetHeight)) return false;
			//status=e.clientY-y_;
		}

		obj.style.left=e.clientX-x_+'px';
		obj.style.top=e.clientY-y_+'px';
		inFstop(e);
	} // shawl.qiu script

	function inFup(e){
		var evt;
		if(!e)e=window.event;

		if(document.removeEventListener){
			document.removeEventListener('mousemove', inFmove, true);
			document.removeEventListener('mouseup', inFup, true);
		} else if(document.detachEvent){
			document.detachEvent('onmousemove', inFmove);
			document.detachEvent('onmouseup', inFup);
		}

		inFstop(e);
	} // shawl.qiu script

	function inFstop(e){
		if(e.stopPropagation) return e.stopPropagation();
		else return e.cancelBubble=true;
	} // shawl.qiu script

	function inFabort(e){
		if(e.preventDefault) return e.preventDefault();
		else return e.returnValue=false;
	} // shawl.qiu script
}
//==============================================================================
//說明視窗DIALOG ( 將說明內容寫於頁面 )
function view_help( contentID, param ){
	openDialog( 'blank.htm' );
	event.returnValue = false;
	return false;	
}
//==============================================================================
//備註顯示
function show_list_comment( obj, seq ){
	var pos = findPos(obj);
	var commObj = document.getElementById('WINDOW_COMMENT_BLOCK');
	var comm_innerObj = document.getElementById('WINDOW_COMMENT_STR');
	commObj.style.display = 'block';
	comm_innerObj.innerHTML = obj.content;
	if( pos[0] > 600 )pos[0] -= 220;
	commObj.style.left = pos[0];
	commObj.style.top = pos[1];
}
//更換行色
function trans_row_color( rowObj, is_over ){
	if( is_over ){
		rowObj.actBgColor = rowObj.runtimeStyle.backgroundColor;
		rowObj.style.backgroundColor = '#FFEE99';
	}else{
		rowObj.style.backgroundColor = rowObj.actBgColor;
	}
}
//點選行變色
function click_row_color( rowObj ){
	if( rowObj.IS_CLICK ){
		rowObj.runtimeStyle.backgroundColor = '';
		rowObj.IS_CLOCK = 0;
	}else{ 
		rowObj.runtimeStyle.backgroundColor = '#FEDACD';
		rowObj.IS_CLICK = 1;
	}
}
