
var index = 0;
var level = 0;

function isDateFormat(value) {
  var pattern = /^\d{4}\/\d{1,2}\/\d{1,2}$/;
  return pattern.test(value);
}

function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}


function isNum(value) {
  var result = true;
  var pattern = /^\d*(\.\d*)?$/;
  if (!pattern.test(value)) result = false;
  var num = parseFloat(value);
  if (isNaN(num)) result = false;
  return result;
}
function isPositive(value) {
  var result = true;
  result = isNum(value);
  if (result) {
    var num = parseFloat(value);
    if (num < 0) result = false;
  }
  return result;
}

function isBlank(value) {
	if(value && value.length > 0){
		  for(var i=0; i<value.length; i++) {
		    var c = value.charAt(i);
		    if ((c!=' ')&&(c!='\n')&&(c!='\t')) return false;
		  }
		  return true;
	  }else{
	  	return true;
	  }
}

function checkEmpty(field, msg)
{
  var fieldvalue = new String(field.value);
  if (isBlank(fieldvalue)) {
    alert(msg);
    field.focus();
    return false;
  }
  return true;
}
function isDate(value) {
  var result = isDateFormat(value);
  if (result) {
    var elems = value.split("/");
    var year = parseInt(elems[0]);
    var month = parseInt(elems[1]);
    var day = parseInt(elems[2]);
    if (month > 12) result = false;
    if (month==4||month==6||month==9||month==11) {
      if (day > 30) result = false;
    } else if (month==2) {
      if (year%4==0) {
        if (day > 29) result = false;
      } else {
        if (day > 28) result = false;
      }
    } else {
      if (day > 31) result = false;
    }
  }
  return result;
}
function isValidSupplierNumber(value) {
  var pattern = /^\d{8}document.getElementById/;
  return pattern.test(value);
}
function getDate(dateStr) {
  var s = dateStr.split('/');
  var d = new Date(eval(s[0]), eval(s[1]-1), eval(s[2]), 0, 0, 0, 0);
  return d;
  }

function replace(s, t, u) {
  /*
  **  Replace a token in a string
  **    s  string to be processed
  **    t  token to be found and removed
  **    u  token to be inserted
  **  returns new String
  */
  i = s.indexOf(t);
  r = "";
  if (i == -1) return s;
  r += s.substring(0,i) + u;
  if ( i + t.length < s.length)
  r += replace(s.substring(i + t.length, s.length), t, u);
  return r;
}
function openPicker(url, fieldName, submitFieldName, labelName, params) {
	  url = url + "?" + "selectedID=\'" + document.getElementById(fieldName).value + "\'&fieldName=\'" + fieldName + "\'&labelName=\'" + labelName  + "\'&submitFieldName=\'" + submitFieldName + "\'";
	  if (params != null && params.length > 0) {
	  	url = url + "&" + params;
	  }
	  var vWinUsers = window.open(url, 'SelectorPopup', 'status=no,resizable=yes,top=100,left=200,width=600,height=285,scrollbars=yes,resizable');
	  vWinUsers.opener = self;
	  vWinUsers.focus();
}

 var myEffects = {
  fade: function(elid) {
	var opacs = ["0",".1",".2",".3",".4",".5",".6",".7",".8",".9","1"];
	if (document.getElementById(elid).style.display == 'none'){
		document.getElementById(elid).style.opacity = '0';
		document.getElementById(elid).style.display = 'block';
		for (var i = 0; i < 11; i++){
		setTimeout('document.getElementById(\''+elid+'\').style.opacity = "'+opacs[i]+'";', i * 4);
		}
	}else{
	opacs.reverse();
	for (var i = 0; i < 11; i++) {
	    setTimeout('document.getElementById(\''+elid+'\').style.opacity = "'+opacs[i]+'";', i * 4);
	}
	setTimeout('document.getElementById(\''+elid+'\').style.display = "none";', i * 4);
	}
    }
}

function showDropDownMenu(id, list){
	begin="<div class='drop_down_menu'>";
	end='</div>';
	content ='';
	for(var i=0; i<list.length;i++){
		data = list[i];
		content+='<span class="menu" onclick="hideDropDownMenu(\''+id+'\');'+data.ref+'">'+data.value+"</span><br/>";
	}
	document.getElementById(id+"List").innerHTML=begin+content+end;
	if(document.getElementById(id+"List").style.display =='none' ||document.getElementById(id+"List").style.display ==''){
		document.getElementById(id+"List").style.display ='block';
	}else{
		document.getElementById(id+"List").style.display ='none';
	}
}

function hideDropDownMenu(id){
	setTimeout('document.getElementById(\''+id+'List\').style.display="none";',10);
}

function selectCode(name, div_id){
	DWRUtil.setValue(div_id,name);
}


function OMOver(OMO){OMO.style.backgroundColor='orange';}
function OMOut(OMO){OMO.style.backgroundColor='';}

function forward(eleid,url, isFrame) {	
  WebUtil.getInclude(url, function(data) {
    dwr.util.setValue(eleid, data, { escapeHtml:false });
  });
}
function goToTab(eleid,panelId, url) {
	if(eleid != null && eleid != ''){
		var ele = document.getElementById(eleid).parentNode;
		for(var i=0; i< ele.childNodes.length; i++){
			var obj = ele.childNodes[i];
			obj.className="unselected";		
		}
		document.getElementById(eleid).className="selected";	
	}
	forward(panelId,url);
}

function loadParentMenus(){
	DWREngine.setAsync(false);
	index = 0;
    DWRUtil.removeAllOptions("menu");
	document.getElementById('menu').options[index++]=new Option("請選擇","");
	var rootId = document.getElementById('rootMenu').value;
	if(rootId == null || rootId == ''){
		return;
	}
	MenuUtil.getParentMenusByRootId(rootId,
		function (list){
			if(list != null){
	            for(var i=0; i < list.length; i++) {
					level = 0;
	                var _menu = list[i];                                     
						document.getElementById('menu').options[index++]=new Option(_menu.menuName,_menu.menuid);
	        			getSubMenus( _menu);
	            }
	        }
	});	

}

function getSubMenus(menu){
	level++;
	var suffix="";
	for(var b=0; b<level;b++){
		suffix = suffix+"----";
	}		
	var subMenus = menu.subMenu;
        for(var j=0; j < subMenus.length; j++) {
            var _submenu = subMenus[j];
            if(_submenu.menuid != document.getElementById('rootMenu').value){
            	document.getElementById('menu').options[index++]=new Option(suffix+" "+_submenu.menuName,_submenu.menuid);
            }
            getSubMenus(_submenu, index, level);
            
        }
}

  
function loadCatalogs(){
	DWRUtil.removeAllOptions("catalog");
	CatalogUtil.getCatalogs(null, function(list){
	document.getElementById('catalog').options[0]=new Option("請選擇","");
		for(var i=0; i<list.length;i++){
			var catalog = list[i];
			document.getElementById('catalog').options[i+1]=new Option(catalog.catalogName,catalog.catalogid);
	    }
	});
}

function loadCategories(){
 DWREngine.setAsync(false);	
	locale = 'zh_TW';
	index = 0;
    DWRUtil.removeAllOptions("category");
	document.getElementById('category').options[index++]=new Option("請選擇類別","");
	CatalogUtil.getParentCategoriesByCatalogId(document.getElementById('catalog').value,locale,
	function (list){
		if(list != null){
                for(var i=0; i < list.length; i++) {
					level = 0;
                    var _category = list[i];                                     
						document.getElementById('category').options[index++]=new Option(_category.categoryName,_category.categoryid);
            		getSubCategory( _category, locale);
                }
            }
	});	
}

function getSubCategory(category, locale){
	
 DWREngine.setAsync(false);	
	level++;
	var suffix="";
	for(var b=0; b<level;b++){
		suffix = suffix+"----";
	}		
	var subCategories = category.subCategories;
        for(var j=0; j < subCategories.length; j++) {
            var _subCategory = subCategories[j];
            	document.getElementById('category').options[index++]=new Option(suffix+" "+_subCategory.categoryName,_subCategory.categoryid);
            getSubCategory(_subCategory, locale, index, level);
            
        }
}

function changeState(_obj){
	var state = document.deleteForm.all.checked;
	var _ids = document.deleteForm.ids;
	if(_obj){
		_ids = _obj;
	}
	
	if(_ids[0]){
		for(var i = 0; i < _ids.length; i++){
			_id = _ids[i];
			_id.checked = state;
		}
	}else{
		_ids.checked = state;
	}
}

function isBoxChecked(_ids){
	var isChecked = false;
	if(_ids){
		if(_ids[0]){
			for(var i=0; i<_ids.length;i++){
				if(_ids[i].checked == true){
					isChecked =true;
					break;
				}
			}
		}else{
			if(_ids.checked == true){
					isChecked =true;
				}
		}
	}
		return isChecked;
}

function getCheckedValue(_ids){
	var values = new Array();
	if(_ids){
		if(_ids[0]){
			for(var i=0; i<_ids.length;i++){
				if(_ids[i].checked == true){
					values.push(_ids[i].value);
				}
			}
		}else{
			if(_ids.checked == true){
					values.push(_ids.value);
				}
		}
	}
		return values;
}
function getCheckedRadioValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}


function resize(){
	var rightDiv = document.getElementById('rightDiv');
	if(rightDiv != null){
		if(rightDiv.style.display == "" || rightDiv.style.display == "block")
			rightDiv.style.display = "none";
		else
			rightDiv.style.display = "block";
	}
}
function resizeById(divId){
	var rightDiv = document.getElementById(divId);
	if(rightDiv != null){
		if(rightDiv.style.display == "" || rightDiv.style.display == "block")
			rightDiv.style.display = "none";
		else
			rightDiv.style.display = "block";
	}
}

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object
   for (var i in obj) {
      // if a parent (2nd parameter) was passed in, then use that to
      // build the message. Message includes i (the object's property name)
      // then the object's property value on a new line
      if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
      // Display the message. If the user clicks "OK", then continue. If they
      // click "CANCEL" then quit this level of recursion
      if (!confirm(msg)) { return; }
      // If this property (i) is an object, then recursively process the object
      if (typeof obj[i] == "object") {
         if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
      }
	}
}	