/* 
 * Object: common javascript
 * Author: Jena.w
 * Site: Ishere.cn
 * LastUpdate: 2010年8月6日16时25分06秒
 */
 
/* common
--------------------------------------------------*/
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
var is_safari = (userAgent.indexOf('webkit') != -1 || userAgent.indexOf('safari') != -1);

function isUndefined(variable) {
	return typeof variable == 'undefined' ? true : false;
}

function in_array(needle, haystack) {
	if(typeof needle == 'string' || typeof needle == 'number') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
					return true;
			}
		}
	}
	return false;
}

function strlen(str) {
	return (is_ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}

function getExt(path) {
	return path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
}
function checkFocus(target) {
	var obj = $(target);
	if(!obj.hasfocus) {
		obj.focus();
	}
}
function insertContent(target, text) {
	var obj = $(target);
	selection = document.selection;
	checkFocus(target);
	if(!isUndefined(obj.selectionStart)) {
		var opn = obj.selectionStart + 0;
		obj.value = obj.value.substr(0, obj.selectionStart) + text + obj.value.substr(obj.selectionEnd);
	} else if(selection && selection.createRange) {
		var sel = selection.createRange();
		sel.text = text;
		sel.moveStart('character', -strlen(text));
	} else {
		obj.value += text;
	}
}

function eEnd(event) {
	e = event ? event : window.event;
	if(is_ie) {
		e.returnValue = false;
		e.cancelBubble = true;
	} else if(e) {
		e.stopPropagation();
		e.preventDefault();
	}
}
/*
-------------------------------------------------------------*/
getCheckCode = function() {
  $('img-checkcode').removeClassName('hidden').src = '/checkcode.gif';
};
submitSimpleForm = function(obj, wrap) {
	var frm;
	if(typeof obj == 'object')
		frm = $(obj).up('form');
	else
		frm = obj;
  if (!checkForm(frm)) return false;
  if($(wrap)) $(wrap).removeClassName('hide').removeClassName('hiden').removeClassName('hiding');
  return true;
};
/**
	 * check form
	 * field attribute request="t"
	 * field attribute sameas="field id"
	 * field attribute url="t"
	 * field attribute email="t"
	 * field attribute group="gname"
	 *
	 * @param string frm
	 * @return true/false
	 */
checkForm = function(frm) {
  var pass = true;
  var _group = Array();
  var fields = $(frm).getElements();
  $A(fields).each(function(fld) {
    if ($(fld).readAttribute('request') != 't') return;
    var disable = $(fld).hasAttribute('disabled');
    if (disable) return;
    var isurl = $(fld).readAttribute('url') == 't' ? true: false;
    var defval = $(fld).readAttribute('default');
		var wrap = $(fld).getAttribute('wrap');
    if ($(fld).hasAttribute('group')) {
      var _gname = $(fld).readAttribute('group');
     	var _type = $(fld).readAttribute('type');
      if (_group.toString().indexOf(_gname) == -1) {
        _group.push(_gname);
        _group[_gname] = Array();
      }
      if ((_type == 'text' && $F(fld) && defval != $F(fld)) || ((_type == 'radio' || _type == 'checkbox') && $(fld).checked)) {
        _group[_gname].push('checked');
      }
      return;
    }
    if (!$F(fld) || (isurl && $F(fld) == 'http://') || (defval == $F(fld))) {
      Field.focus(fld);
      new Effect.Highlight(wrap?wrap:$(fld).parentNode, {
        startcolor: '#ff0000'
      });
      pass = false;
      throw $break;
    }
    if ($(fld).hasAttribute('email')) {
      var patn = /^[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]*)*@[a-zA-Z0-9\-]+([\.][a-zA-Z0-9\-]+)+$/;
      if (!patn.test($F(fld).strip())) {
        Field.focus(fld);
        new Effect.Highlight(wrap?wrap:$(fld).parentNode, {
          startcolor: '#ff0000'
        });
        pass = false;
        throw $break;
      }
    }
    if ($(fld).hasAttribute('sameas')) {
      sameas = $(fld).readAttribute('sameas');
      if ($F(fld) != $F(sameas)) {
        Field.focus(fld);
        new Effect.Highlight(wrap?wrap:$(fld).parentNode, {
          startcolor: '#ff0000'
        });
        pass = false;
        throw $break;
      }
    }
  });
  $A(_group).each(function(group) {
    if (_group[group].length < 1) {
			var first = $$('input[group="' + group + '"]')[0];
			var wrap = $(first).readAttribute('wrap');
      new Effect.Highlight(wrap?wrap:$(first).parentNode, {
        startcolor: '#ff0000'
      });
      pass = false;
      throw $break;
    }
  });
  return pass;
};
FormatNumber = function(srcStr, nAfterDot) {
  var srcStr, nAfterDot;
  var resultStr, nTen;
  srcStr = "" + srcStr + "";
  strLen = srcStr.length;
  dotPos = srcStr.indexOf(".", 0);
  if (dotPos == -1) {
    resultStr = srcStr + ".";
    for (i = 0; i < nAfterDot; i++) {
      resultStr = resultStr + "0";
    }
    return resultStr;
  } else {
    if ((strLen - dotPos - 1) >= nAfterDot) {
      nAfter = dotPos + nAfterDot + 1;
      nTen = 1;
      for (j = 0; j < nAfterDot; j++) {
        nTen = nTen * 10;
      }
      resultStr = Math.round(parseFloat(srcStr) * nTen) / nTen;
      return resultStr;
    } else {
      resultStr = srcStr;
      for (i = 0; i < (nAfterDot - strLen + dotPos + 1); i++) {
        resultStr = resultStr + "0";
      }
      return resultStr;
    }
  }
};
/* msg window
------------------------------------------------------------------*/
msgwin = function(s, t) {
  var msgWinObj = $('msgwin');
  if (!msgWinObj) {
    var msgWinObj = document.createElement("div");
    msgWinObj.id = 'msgwin';
    msgWinObj.style.display = 'none';
    msgWinObj.style.position = 'absolute';
    msgWinObj.style.zIndex = '100000';
    $$('body')[0].appendChild(msgWinObj);
  }
  msgWinObj.innerHTML = s;
  msgWinObj.style.display = '';
  msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)';
  msgWinObj.style.opacity = 0;
  var sTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop: document.body.scrollTop;
  pbegin = sTop + (document.documentElement.clientHeight / 2);
  pend = sTop + (document.documentElement.clientHeight / 5);
  setTimeout(function() {
    showmsgwin(pbegin, pend, 0, t)
  },
  10);
  msgWinObj.style.left = ((document.documentElement.clientWidth - msgWinObj.clientWidth) / 2) + 'px';
  msgWinObj.style.top = pbegin + 'px';
};

showmsgwin = function(b, e, a, t) {
  step = (b - e) / 10;
  var msgWinObj = $('msgwin');
  newp = (parseInt(msgWinObj.style.top) - step);
  if (newp > e) {
    msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + a + ')';
    msgWinObj.style.opacity = a / 100;
    msgWinObj.style.top = newp + 'px';
    setTimeout(function() {
      showmsgwin(b, e, a += 10, t)
    },
    10);
  } else {
    msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)';
    msgWinObj.style.opacity = 1;
    setTimeout('displayOpacity(\'msgwin\', 100)', t);
  }
};

displayOpacity = function(id, n) {
  if (!$(id)) {
    return;
  }
  if (n >= 0) {
    n -= 10;
    $(id).style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + n + ')';
    $(id).style.opacity = n / 100;
    setTimeout('displayOpacity(\'' + id + '\',' + n + ')', 50);
  } else {
    $(id).style.display = 'none';
    $(id).style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)';
    $(id).style.opacity = 1;
  }
};
/* image auto size
--------------------------------------------------*/
_img = function(ImgD, _w, _h){   
	var areaWidth = _w;  
	var areaHeight = _h;
	var image=new Image();   
	image.src=ImgD.src;   
	if(image.width>0 && image.height>0){   
		 if(image.width/image.height>= areaWidth/areaHeight){   
				 if(image.width>areaWidth){   
						 ImgD.width=areaWidth;   
						 ImgD.height=(image.height*areaWidth)/image.width;   
				 }else{   
						 ImgD.width=image.width;   
						 ImgD.height=image.height;   
				 }   
		 }else{   
				 if(image.height>areaHeight){   
						 ImgD.height=areaHeight;   
						 ImgD.width=(image.width*areaHeight)/image.height;   
				 }else{   
						 ImgD.width=image.width;   
						 ImgD.height=image.height;   
				 }   
		 }   
	}
};
/* checkbox
----------------------------------------------*/
checkAll = function(lab, callback){
	var ipts = $$('input[name="'+lab+'"]');
	$A(ipts).each(
		function(ipt){
			if($(ipt).disabled) return;
			$(ipt).checked = true;
		}
	);
	if(typeof callback == 'function')
		callback();
};
checkNone = function(lab, callback){
	var ipts = $$('input[name="'+lab+'"]');
	$A(ipts).each(
		function(ipt){
			$(ipt).checked = false;
		}
	);
	if(typeof callback == 'function')
		callback();
};
checkReverse = function(lab, callback){
	var ipts = $$('input[name="'+lab+'"]');
	$A(ipts).each(
		function(ipt){
			if($(ipt).disabled) return;
			if($(ipt).checked){
				$(ipt).checked = false;
			}else{
				$(ipt).checked = true;
			}
		}
	);
	if(typeof callback == 'function')
		callback();
};
checkNum = function(lab){
	var ipts = $$('input[name="'+lab+'"]'), num = 0;
	$A(ipts).each(
		function(ipt){
			if($(ipt).checked)
				num++;
		}
	);
	return num;
};
/* process items
---------------------------------------------------*/
processItem = function(action, id, label, postto, conmsg){
	if(!id){
		ids = $$('input[name="'+label+'"]');
		var _ids = new Array();
		$A(ids).each(function(_id){if($(_id).checked)_ids.push($F(_id))});
		if(!_ids.length){
			alert('请先选择');
			return;
		}
		id = _ids.join(',');
	}
	if( typeof conmsg != 'boolean' && conmsg != false){
		if(!confirm(conmsg?conmsg:'确定要继续吗？')) return;
	}
	var _action = postto?postto:'';
	
	$$('body')[0].appendChild(
		Builder.node('form',{method:'post',id:'frm-process', action:_action, target:'_self'},[
			Builder.node('input',{type:'hidden',name:'id',value:id}),
			Builder.node('input',{type:'hidden',name:'action',value:action})
		])
	);
	$('frm-process').submit();
};
/* popup window
--------------------------------------------------------*/
popWindow = function(id, cnt, offset){
	hideWindow();
	if(!$('popwindow-'+id)){
		$$('body')[0].appendChild(
			Builder.node('div',{id:'popwindow-'+id, 'class':'hiding lft absolute',style:'z-index:9999999'},[
				Builder.node('div',{'class':'gr_r_t'},[
					Builder.node('div',{'class':'gr_l_t'},[
						Builder.node('div',{'class':'gr_r_b'},[
							Builder.node('div',{'class':'gr_l_b'},[
								Builder.node('div',{id:'popwincnt-'+id})
							])
						])
					])
				])
			])
		);
	}
	$('popwincnt-'+id).update(cnt);
	$('popwindow-'+id).show();
	
	setWindowPosition(id, offset);
	dragWindow(id);
};
setWindowPosition = function(showid, offset) {
	var showobj = $(showid);
	var menuobj = $('popwindow-'+showid);
	if(isUndefined(offset)) offset = 0;
	if(showobj) {
		showobj.pos = fetchOffset(showobj);
		showobj.X = showobj.pos['left'];
		showobj.Y = showobj.pos['top'];
		showobj.w = showobj.offsetWidth;
		showobj.h = showobj.offsetHeight;
	}
	menuobj.w = menuobj.offsetWidth;		
	menuobj.h = menuobj.offsetHeight;
	var sTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
	if(showobj && offset != -1) {
		menuobj.style.left = (showobj.X + menuobj.w > document.body.clientWidth) && (showobj.X + showobj.w - menuobj.w >= 0) ? showobj.X + showobj.w - menuobj.w + 'px' : showobj.X + 'px';
		menuobj.style.top = offset == 1 ? showobj.Y + 'px' : (offset == 2 || ((showobj.Y + showobj.h + menuobj.h > sTop + document.documentElement.clientHeight) && (showobj.Y - menuobj.h >= 0)) ? (showobj.Y - menuobj.h) + 'px' : showobj.Y + showobj.h + 'px');
	} else if(offset == -1) {
		menuobj.style.left = (document.body.clientWidth-menuobj.w)/2 + 'px';
		var divtop = sTop + (document.documentElement.clientHeight-menuobj.h)/2;
		if(divtop > 100) divtop = divtop - 100;
		menuobj.style.top = divtop + 'px';
	}
	if(menuobj.style.clip && !is_opera) {
		menuobj.style.clip = 'rect(auto, auto, auto, auto)';
	}
};
hideWindow = function() {
	var wins = $$('div[id^="popwindow-"]');
	$A(wins).each(
		function(win){
			$(win).hide();
		}
	);
};
fetchOffset = function(obj) {
	var left_offset = obj.offsetLeft;
	var top_offset = obj.offsetTop;
	while((obj = obj.offsetParent) != null) {
		left_offset += obj.offsetLeft;
		top_offset += obj.offsetTop;
	}
	return { 'left' : left_offset, 'top' : top_offset };
};
dragWindow = function(id){
	var draghandle = $('popwindow-'+id).down('div.cur_move');
	if(draghandle){
		new Draggable($('popwindow-'+id),{
			revert:false, 
			handle:draghandle, 
			onStart:(
				function(){}
			).bind(this), 
			onEnd:(
				function(){}
			).bind(this)
		});
	}
};
/* ajax pop window
---------------------------------------------------------------*/
var isProcess = false;
ajaxPopWin = function(evt, obj, offset, width){
	eEnd(evt);
	if(isProcess) return;
	isProcess = true;
	if(isUndefined(offset)) offset = -1;
	
	var targetid = $(obj).readAttribute('id');
	var targeturl = $(obj).readAttribute('href');
	
	var cnt = '';
	cnt_a = '<div style="background-color:#fafafa; width:'+(width?width:'')+'px" class="pad_all_10"><div id="popwin-'+targetid+'" class="lft100"><div class=" loading"></div></div>';
	cnt_b = '<div class="clearfloat"></div></div>';
	cnt = cnt_a + cnt_b;
	
	popWindow(targetid, cnt, offset);
	getAjaxPanel(targetid, targeturl, offset);
};
getAjaxPanel = function(targetid, targeturl, offset){
	new Ajax.Updater('popwin-'+targetid, targeturl,{
		parameters:{targetid:targetid},
		onComplete:function(){
			dragWindow(targetid);
			setWindowPosition(targetid, offset);
			isProcess = false;
		},
		evalScripts:true
	});
};
doContinue = function(evt, targetid, targeturl, offset){
	eEnd(evt);
	getAjaxPanel(targetid, targeturl, offset);
};
doAjax = function(id){
	$('p-'+id).addClassName('submitting');
	$('msg-'+id).update('').addClassName('hiding');
	
	if(!checkForm('frm-'+id)){
		$('p-'+id).removeClassName('submitting');
		return false;
	}
	
	new Ajax.Request('/ajax.dll',{
		parameters:$('frm-'+id).serialize(true),
		onSuccess:function(t){
			var j=t.responseJSON;
			if(j.ok){
				eval(j.command);
			}else{
				var msg = j.msg?j.msg:'处理失败！';
				$('msg-'+id).update(msg).removeClassName('hiding');
				$('p-'+id).removeClassName('submitting');
			}
		}
	});
};
/* cookie
--------------------------------------------------*/
var _cookie = {
	
	add : function(name, value, days){
		var Days = days || 365;
		var exp  = new Date();    //new Date("December 31, 9998");
			exp.setTime(exp.getTime() + Days*24*60*60*1000);
			document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString() + ";path=/";
	},
	
	del : function(name){
		var exp = new Date();
			exp.setTime(exp.getTime() - 1);
		var cval=widgets_Cookie.get(name);
			if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString() + ";path=/";
	},
	
	get : function(name){
		var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
			if(arr=document.cookie.match(reg)) return unescape(arr[2]);
			else return null;
	}
};
/* page masker
------------------------------------------------------*/
masker = function(wrapid, opacity){
	var wrap = null;
	if($(wrapid))
		wrap = $(wrapid);
	else
		wrap = $$('body')[0];
	
	var opa_ = opacity?opacity:0.5;
	Element.addClassName(wrap, 'masked');	
	zindx = parseInt(Element.getStyle(wrap, 'z-index')) || 200000;
	$(wrap).appendChild(
		Builder.node('div', {id:'pagemasker', 'class':'mask', style:'filter:alpha(opacity='+(opa_*100)+');-moz-opacity:'+opa_+';opacity:'+opa_+';z-index:'+(zindx+1)})
	);
};
hideMasker = function(){
	if($('pagemasker')) Element.remove('pagemasker');
	$A($$('.masked')).each(function(el){$(el).removeClassName('masked');});
};
/*
 *click
 */
if (!Prototype.Browser.IE) {
  HTMLElement.prototype.click = function() {
    var evt = this.ownerDocument.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
    this.dispatchEvent(evt);
  }
}
