﻿/**
 * by leili
 */
Object.extend(Prototype, {
  Author:'lihongci',
  Tel: '13816047885',
  Email: 'fox2bar@gmail.com',
  Msn: 'fox2bar@hotmail.com',
  emptyListener: function(event){},
  listeners: ['pe','data','onblur','onresize','onfocus','index','markTrs','clickElementLast',
              'onmouseover','onmouseout','onmousedown','onmouseup','onmousemove',
              'ondblclick','onclick','onselectstart','oncontextmenu',
			  'onkeydown','onkeypress','onkeyup','onresize','onchange','onreset',
			  'onerror','onload','onunload','onselect','onscroll','onsubmit',
			  'oncontextmenu','oncontrolselect','ondrag','ondragend','ondragenter',
			  'ondragleave','ondragover','ondragstart','ondrop'],
  ElFragment: '(?:#[\{])((\n|\r|.)*?)(?:[\}])',
  XMPFragment: '(?:<xmp.*?>)((\n|\r|.)*?)(?:<\/xmp>)',
  LINKFragment: '<link.*?(>|/>)',
  BodyChildNodesFragment: '(?:<body.*?>)((\n|\r|.)*?)(?:<\/body>)'			  
});

var BaseEvent = Class.create();
BaseEvent.prototype = {
  initialize: function(target, when) {
    this.target = target;//the target component.
	this.when = when;//the time stamp.
	this.initID();
  },
  initID: function(){
    this.id = Prototype.Author + this.when.getFullYear() + 
	this.when.getMonth() + this.when.getDay() + 
	this.when.getHours() + this.when.getMinutes() +
	this.when.getSeconds() + this.when.getMilliseconds();
  }
};



Object.extend(PeriodicalExecuter.prototype,{
  initialize: function(callback, frequency,asynchronous) {
	this.asynchronous = asynchronous||false;
	this.callbacks = new Array();
	this.listeners = new Array();
	if(typeof callback == 'function'){
	  this.callbacks.push(callback);
	}else if(callback instanceof Array){
	  callback.each((function(element){
		if(typeof element == 'function')
		  this.callbacks.push(element);
		else
		  this.listeners.push(element);
	  }).bind(this));
	}else{
	  this.listeners.push(callback);
	}
	
    this.frequency = frequency;
    this.currentlyExecuting = false;
	this.status = 1;//1 run,-1 pause,0 stop
    this.registerCallback();
  },
  pause: function(){
    this.status = -1;
  },
  activate: function(){
    this.status = 1;
  },
  registerCallback: function() {
    this.interval = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },
  stop: function(){
	this.status = 0;  
  },
  onTimerEvent: function() {
	
	var executeTask = (function(){
	  if (!this.currentlyExecuting) {
		try {
			
			this.currentlyExecuting = true;
			
			this.callbacks.each((function(fun){
			  if(this.asynchronous) setTimeout(fun,10);
			  else fun();
			}).bind(this));//callback functions
			
			this.listeners.each((function(listener){
										  
			  var fireEvents = (function(){
			    (listener.actionPerformed||Prototype.emptyFunction)(new BaseEvent(this,new Date()));//fireEvents
			  }).bind(this);
			  
			  if(this.asynchronous) setTimeout(fireEvents,10);
			  else fireEvents();
			  
			}).bind(this));
			
		} finally {
			this.currentlyExecuting = false;
		}
      }	  
	}).bind(this);
	switch(this.status){
	  case 1:
        executeTask();
		break;
	  case -1:
	    Prototype.emptyFunction();
		break;
	  default:
	    window.clearInterval(this.interval);
	}
  },
  toString: function(){
    return '[PeriodicalExecuter]';
  }

});


Object.extend(String.prototype, {
  byteLength: function(){
    return this.replace(/[^\x00-\xff]/g,"**").length;
  },			  
  stripEls: function(){
    return this.replace(new RegExp(Prototype.ElFragment, 'img'), '');
  },
  stripXmps: function() {
    return this.replace(new RegExp(Prototype.XMPFragment, 'img'), '');
  },
  stripLinks: function() {
    return this.replace(new RegExp(Prototype.LINKFragment, 'img'), '');
  },  
  extractBodies: function() {
    var matchAll = new RegExp(Prototype.BodyChildNodesFragment, 'img');
    var matchOne = new RegExp(Prototype.BodyChildNodesFragment, 'im');
    return (this.match(matchAll) || []).map(function(bodyTag) {
      return (bodyTag.match(matchOne) || ['', ''])[1];
    });
  },
  extractEls: function() {
    var matchAll = new RegExp(Prototype.ElFragment, 'img');
    var matchOne = new RegExp(Prototype.ElFragment, 'im');
    return (this.match(matchAll) || []).map(function(elTag) {
      return (elTag.match(matchOne) || ['', ''])[1];
    }); 
  },
  extractXmps: function() {
    var matchAll = new RegExp(Prototype.XMPFragment, 'img');
    var matchOne = new RegExp(Prototype.XMPFragment, 'im');
    return (this.match(matchAll) || []).map(function(xmpTag) {
      return (xmpTag.match(matchOne) || ['', ''])[1];
    });
  },
  extractLinks: function() {
    var matchAll = new RegExp(Prototype.LINKFragment, 'img');
    var matchOne = new RegExp(Prototype.LINKFragment, 'im');
    return (this.match(matchAll) || []).map(function(xmpTag) {
      return (xmpTag.match(matchOne) || ['', ''])[1];
    });
  },  
  fetchXmps: function() {
    var matchAll = new RegExp(Prototype.XMPFragment, 'img');
    var matchOne = new RegExp(Prototype.XMPFragment, 'im');
    return (this.match(matchAll) || []).map(function(xmpTag) {
      return (xmpTag.match(matchOne) || ['', ''])[0];
    });
  },
  fetchLinks: function() {
    var matchAll = new RegExp(Prototype.LINKFragment, 'img');
    var matchOne = new RegExp(Prototype.LINKFragment, 'im');
    return (this.match(matchAll) || []).map(function(xmpTag) {
      return (xmpTag.match(matchOne) || ['', ''])[0];
    });
  },  
  hasEl: function(){
    return new RegExp(Prototype.ElFragment, 'img').test(this);
  },
  evalScripts: function() {
    return this.extractScripts().map(function(script){
	  //var tempScript = '(function(){\n' + script + '\n}).apply(window)';
	  var dynamic = new Function(script);
	  dynamic.apply(window);
	  //eval(tempScript);
	});
  },  
  evalEls: function(){
    var item = arguments[0];
    var page = arguments[1];
	var index = arguments[2];
	var matchOne = new RegExp(Prototype.ElFragment, 'im');
    var thisStr = this;
    var temp = thisStr.match(matchOne);
    if(temp){
      thisStr = thisStr.replace(temp[0],eval(temp[1])).evalEls(item,index,page);
    }
    return thisStr;
  },
  toResourceParams: function() {
//    var pairs = this.split(/[\n|\r]+/);
//    return pairs.inject({}, function(params, pairString) {
//      var pair = pairString.split(/[ ]*=[ ]*/);
//      params[pair[0]] = pair[1];
//      return params;
//    });
      return (new Function('return '+this)).call();
  },
  parseResourceFile: function() {
    return this.split(/[ ]*\,[ ]*/);
  },
  parseTag:function() {
    var tagText = this;
	var targetNode = {};
	
	(function parseTagName() {
		//var rightOfLeftTag = tagText.indexOf(">");
		var rightOfLeftTag = tagText.search(/>|\/>/);
		var endpoint = rightOfLeftTag;
		var leftmostBlankOfLeftTag = tagText.substring(0, rightOfLeftTag).indexOf(" ");
		if (leftmostBlankOfLeftTag > -1) {
			endpoint = leftmostBlankOfLeftTag;
		}
		targetNode.tagName = tagText.substring(1, endpoint);
	}).call(this);
	
	(function parseTagAttributes() {
		var blankCount = 0;
		var tempName = "";
		var tempValue = "";
		var flag = -1;
		var fetchValueFlag = 0;
		for (var i = 1; i < (tagText.indexOf(">", 1)); i++) {
			if (tagText.charAt(i) == " ") {
				blankCount++;
				if (blankCount == 1) {
					flag = 0;
				}
			//continue;
			} else {
				if (tagText.charAt(i) == "=") {
					flag = 1;
				} else {
					if (tagText.charAt(i) == "'" || tagText.charAt(i) == "\"") {
						++fetchValueFlag;
						if (fetchValueFlag == 2) {
							fetchValueFlag = 0;
							flag = 0;
							targetNode[tempName] = tempValue;
							tempName = "";
							tempValue = "";
						}
					} else {
						if (flag == 1) {
							tempValue = tempValue + tagText.charAt(i);
						} else {
							if (flag == 0) {
								tempName = tempName + tagText.charAt(i);
							}
						}
					}
				}
			}
		}
	}).call(this);
	
	(function parseBody() {
		var tagN = "</" + targetNode.tagName + ">";
		var pos = tagText.lastIndexOf(tagN);
		if (pos>0 || (pos - (tagN.length - 1) > 0)) {
			targetNode.body = tagText.substring(tagText.indexOf(">", 1)+1, pos);
		}
	}).call(this);
	return targetNode;
  },
  parseXmps:function() {
    var xmpTags = this.fetchXmps();
    return xmpTags.map(function(xmpTag){
      return xmpTag.parseTag();
    });
  },
  parseLinks:function() {
    var linkTags = this.fetchLinks();
    return linkTags.map(function(linkTag){
      return linkTag.parseTag();
    });
  },
  byteLength: function(){
    return this.replace(/[^\x00-\xff]/g,"**").length;
  },			  
  trim: function() {
	  var tempStr=this;
	  while(tempStr.substring(0,1)==" ") tempStr = tempStr.substring(1,tempStr.length);
	  while(tempStr.substring(tempStr.length-1)==" ") tempStr = tempStr.substring(0,tempStr.length-1);
	  return tempStr;
  }
});




var Validator = Class.create();

Validator.REGEXP_NUMBER = /^[-\+]?\d+(\.\d+)?$/;

Validator.REGEXP_EMAIL = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/;
Validator.REGEXP_PHONE = /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/;
Validator.REGEXP_MOBILE = /^((\(\d{2,3}\))|(\d{3}\-))?(13|15)\d{9}$/;
Validator.REGEXP_IDCARD = /(^\d{15}$)|(^\d{17}[0-9Xx]$)/;
Validator.REGEXP_MONEY = /^\d+(\.\d+)?$/;
Validator.REGEXP_ZIP = /^[1-9]\d{5}$/;
Validator.REGEXP_QQ = /^[1-9]\d{4,10}$/;
Validator.REGEXP_INT = /^[-\+]?\d+$/;
//Validator.REGEXP_URL = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
Validator.REGEXP_DATE = /^\d{4}-\d{1,2}-\d{1,2}$/;
Validator.REGEXP_TIME = /^\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}$/;


Validator.prototype = {
  initialize: function() {
     //debug('A Validator instance be created!');
  },
  isEn: function(str){
      str = new String(str);
	  for   (var   x=0;x<str.length;x++)   {   
	    if(str.charCodeAt(x)<1 || str.charCodeAt(x)>255)   {   
	       return false;
	    }
	  }   
	  return true;     
  },
  isZh: function(str){
      return !this.isEn();
  },
  isEmail: function(email){
      return Validator.REGEXP_EMAIL.test(email);
  },
  isNullOrBlank: function(str){
      if(str == null) return true;
	  
      if(str.trim().length<1) return true;
	  
      return false; 
  },
  isPassword : function(password){
	  if(this.isNullOrBlank(password) || password.length<6 || password.length>26){
		  return false;
	  }
	  
	  return this.isEn(password);

  },
  isInt : function(str){
	  return Validator.REGEXP_INT.test(str);
  },
  
  isPhone : function(str){
	  return Validator.REGEXP_PHONE.test(str);
  }
};

var validator = new Validator();







var Web = {
getCookiePartValue: function(offset){
    var commaPosition = document.cookie.indexOf (";", offset);
    if (commaPosition == -1) commaPosition = document.cookie.length;
    return unescape(document.cookie.substring(offset, commaPosition)||'');
},
setCookie: function(cookieName, cookieValue){
	var expdate = new Date();
	var argumentLength = arguments.length;
	var expires = (argumentLength > 2) ? arguments[2] : null;
	var path = (argumentLength > 3) ? arguments[3] : null;
	var domain = (argumentLength > 4) ? arguments[4] : null;
	var secure = (argumentLength > 5) ? arguments[5] : false;
    if(expires!=null) expdate.setTime(expdate.getTime() + ( expires * 1000 ));
	var cookie = cookieName + "=" + escape (cookieValue) +((expires == null) ? "" : ("; expires="+ expdate.toGMTString()))+((path == null) ? "" : ("; path=" + path))+((domain == null) ? "" : ("; domain=" + domain))+((secure == true) ? "; secure" : "");
    //alert("cookie===========>" + cookie);
	document.cookie = cookie;
	
},
deleteCookie: function(cookieName){
	var exp = new Date();
	exp.setTime (exp.getTime() - 1000);
	
	
	var argumentLength = arguments.length;
	var path = (argumentLength > 1) ? arguments[1] : null;
	var domain = (argumentLength > 2) ? arguments[2] : null;
	var secure = (argumentLength > 3) ? arguments[3] : false;	
	var cval = this.getCookie(cookieName,path,domain,secure);
	
	document.cookie = cookieName + "=" + cval + "; expires="+ exp.toGMTString()+((path == null) ? "" : ("; path=" + path))+((domain == null) ? "" : ("; domain=" + domain))+((secure == true) ? "; secure" : "");
},
getCookie: function(cookieName){
	var arg = cookieName + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
    while (i < clen){
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) return document.getCookiePartValue (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
	if(document.cookie.indexOf(cookieName)>=0) return '';
    return null;
}
};
Object.extend(document, Web);//向现有代码兼容.


var Effect = {NONE:0X000,SHADOW:0x001};//效果常量
//Object.extend(Object.prototype, Effect);
var theme = {effect:Web.getCookie("effect")||Effect.NONE};

var Css = {
  DEFAULT_CSS_FILE_SUFFIX: '.css',
  loadAll: function(html){
	var links = html.parseLinks();
	//alert(links.length);
	links.each((function(link){
	  this.loadFile(link);
	}).bind(this));
  },
  loadFile: function(cssObject){
	  var link = document.createElement("link");
	  var heads = document.getElementsByTagName("head");
	  
	  var language = Web.getCookie("language");
	  var href = cssObject.href;
	  var pos = href.lastIndexOf('.');
	  if(language)
	    //if(pos >0)
		  cssObject.href = href.substring(0,pos) + "_" + language + href.substring(pos);
		//else 
		  //cssObject.href = href + '_' + language + this[DEFAULT_CSS_FILE_SUFFIX];
	  //else
	    //if(pos<0)
		  //cssObject.href = href + this[DEFAULT_CSS_FILE_SUFFIX];
	  
	  
	   $A(heads).each(function(hd){
		 function copyCssAttributes(target,src){
		   var att;
		   for(att in src){
		     if(att!='tagName'){
			   target[att] = src[att];
			 }
		   }
		   return target
		 }
	     hd.appendChild(copyCssAttributes(link,cssObject));
		 
	   }); 
  }
};


var ResourceUtils = {
  loadAll: function(html){
	var xmps = html.parseXmps();
	var currentObject = this;
	xmps.each(function(xmp){
	  var bundles = xmp.body.parseResourceFile();
	  bundles.each(function(bundleFile){
	    currentObject.loadFile(bundleFile,xmp.name);
	  });
	});
	
  },
  loadFile: function(bundleFile,bundleName){
    if(!bundleName) bundleName = Resource.DEFAULT_BUNDEL_NAME;
    var resource = new Resource(bundleFile);
    if(!window[bundleName]){
      window[bundleName] = resource;
    }else{
      Object.extend(resource,window[bundleName]);
      window[bundleName] = resource;
	}    
  }

};

var Resource = Class.create();
Resource.DEFAULT_BUNDEL_NAME = "res";
//Resource.DEFAULT_FILE_NAME_SUFFIX = ".oplink";
Resource.prototype = {
  initialize: function(bundleFile) {
    this.bundleFile = bundleFile;
	this.load();
  },
  load: function() {
    var language = Web.getCookie('language');
	var realFilePath = this.bundleFile;
	//if(!language){
	  //realFilePath = realFilePath + Resource.DEFAULT_FILE_NAME_SUFFIX;
	  //realFilePath = '/system/' + realFilePath;
	///}else{
	  //realFilePath = realFilePath + '_' + language + Resource.DEFAULT_FILE_NAME_SUFFIX;
	//}
	//alert("realFilePath------>" + realFilePath);
    var myAjax = new Ajax.Request(realFilePath,{method:"get",asynchronous:false,onException:function(obj,ex){alert(ex.message);}});
	var originalRequest = myAjax.transport;
	//alert("responseText---->" + originalRequest.responseText);
    Object.extend(this,originalRequest.responseText.toResourceParams());
  }
};


Object.extend(Ajax.Updater.prototype,{
  initialize: function(container, url, options) {
    this.containers = {
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      onComplete(transport, object);
    }).bind(this);

    this.request(url);
	if(!this.options.asynchronous) this.updateContent();
  },  
  updateContent: function() {
    var receiver = this.responseIsSuccess() ?
      this.containers.success : this.containers.failure;
    var response = this.transport.responseText;

    if (!this.options.evalScripts)
      response = response.stripScripts();

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        Element.update(receiver, response,this.options.asynchronous);
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Object.extend(Element.Methods, {
  shadow: function(element,mode,endpoint,step,interval,callback){
	  element = $(element);
	  endpoint = endpoint!=null?(endpoint<0?0:(endpoint>100?100:endpoint)):(mode?100:0);
	  //endpoint = (endpoint==null?endpoint:)||(mode?100:0);
	  step = step||20;
	  interval = interval||5;
	  var n = Element.getOpacity(element);
	  //if(n==null) n = 100;
	  //if(mode) n =0;
	  
	  var intervalId;
	  function asc(){
		 if(n>endpoint){
		   if(intervalId) clearInterval(intervalId);
		   if(callback) callback(element);
		   return;
		 }else{
		   n = n+step;
		 }
	  } 
	  function desc(){
		 if(n<endpoint){
		  if(intervalId) clearInterval(intervalId);
		  if(callback) callback(element);
		  return;
		 }else{
		   n = n-step;
		 }
	  }
	  
	  function temp(){
		Element.setOpacity(element,n);
		if(mode)
		  asc();
		else
		  desc();
	  }
	  
	  intervalId = setInterval(temp,interval);
  },
  toCenter:function(element,width,height){
	element = $(element);
	var parent = element.getOffsetParent();
	//alert(parent.offsetWidth);
	var width = width || this.getDimensions(element).width || 400;
	var height = height || this.getDimensions(element).height || 300;
    if(width<parent.clientWidth)
       element.style.left = (parent.clientWidth/2 - width/2) + "px";//element.offsetWidth/2;
    else
	   element.style.left = 0 + "px";
    //alert(parent.cumulativeScrollOffset());
    
    if(height<(parent.clientHeight-parent.cumulativeScrollOffset()[1]))
      element.style.top = ((parent.clientHeight-parent.cumulativeScrollOffset()[1])/2 - height/2) + "px";//element.offsetHeight/2;
    else 
      element.style.top = 0 + "px";
  },

  update: function(element, html,asynchronous) {
	element = $(element);
	var onlyHtml = html.stripScripts();
	Css.loadAll(onlyHtml);
	ResourceUtils.loadAll(onlyHtml);
	var withoutXmps = onlyHtml.stripXmps();
	var bodyChilds = withoutXmps.extractBodies();
	//alert("======11=======>   " + bodyChilds);
	this.removeChilds(element);
	element.innerHTML = bodyChilds && bodyChilds.length>0?bodyChilds[0].evalEls():withoutXmps.evalEls();
    //$(element).innerHTML = html.stripScripts();
    if(asynchronous)
	  setTimeout(function() {html.evalScripts()}, 10);
	else
	  html.evalScripts();
  },
  findFormElements: function(regionElement){
	var result = new Array();
	var selectNodes=$A(regionElement.getElementsByTagName("select"));
	var buttonNodes=$A(regionElement.getElementsByTagName("button"));
	result = result.concat(selectNodes,buttonNodes);
	return result;
  },
  disableFormElements: function(regionElement){
	$A(this.findFormElements(regionElement)).each(function(value){
	   value.disabled = true;
	});
  },
  enableFormElements: function(regionElement){
	$A(this.findFormElements(regionElement)).each(function(value){
	   value.disabled = false;
	});
  }
});

Object.extend(Event.Methods,{
	upFind : function(event,target){
		var parent = $(event).element();
		while(parent!=null){
			if(parent==$(target))
				return true
			parent = parent.parentNode;
		}
		return false;
	}
});

delete Event.extend;
Event.extend = (function() {
	  var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
	    m[name] = Event.Methods[name].methodize();
	    return m;
	  });
	
	  if (Prototype.Browser.IE) {
	    Object.extend(methods, {
	      stopPropagation: function() { this.cancelBubble = true },
	      preventDefault:  function() { this.returnValue = false },
	      inspect: function() { return "[object Event]" }
	    });
	
	    return function(event) {
	      if (!event) return false;
	      if (event._extendedByPrototype) return event;
	
	      event._extendedByPrototype = Prototype.emptyFunction;
	      var pointer = Event.pointer(event);
	      Object.extend(event, {
	        target: event.srcElement,
	        relatedTarget: Event.relatedTarget(event),
	        pageX:  pointer.x,
	        pageY:  pointer.y
	      });
	      return Object.extend(event, methods);
	    };
	
	  } else {
	    Event.prototype = Event.prototype || document.createEvent("HTMLEvents")['__proto__'];
	    Object.extend(Event.prototype, methods);
	    return Prototype.K;
	  }
})();

var UI = {
  Abstract: { },
  Ajax: { }
};