﻿/*
 * Glacier Ltd. javascript 库 1.0.0
 * Copyright(c) 2006-2007, Glacier Ltd.
 * 
 * http://www.glacierbiz.com
 */

glacier = {};

// 用于旧版本的浏览器
window["undefined"] = window["undefined"];

/**
	* 复制一个对象的所有属性到另一个对象中。
	* @param {Object} obj: 接受复制属性值的对象
	* @param {Object} cfg: 包含源属性的对象。
	* @param {Object} def: 一个不同的对象，将被应用为默认值。
	* @return {Object} : 复制属性值后返回传入的obj
	*/
glacier.apply = function(obj, cfg, def){
    if(def){
        // 在对象作用域之外不能使用'this'对象时调用。
        glacier.apply(obj, def);
    }
    if(obj && cfg && typeof cfg == 'object'){
        for(var p in cfg){
            obj[p] = cfg[p];
        }
    }
    return obj;
};

glacier.$ = function(element){
  if (arguments.length > 1) {
    for (var i=0, elements=[], length=arguments.length; i<length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof(element)=='string')
    element = document.getElementById(element);
  return element;
};

/**
	* 浏览器的属性对象
	* 属性值包括： isStrict, isSecure, version, isOpera, isSafari, isIE, isIE7, isMozilla, isGecko, isFirefox, isBorderBox, isWindows, isMac
	*/
glacier.Browser={};

(function(){
	var _idSeed = 0;
	var ua = navigator.userAgent.toLowerCase();
	var _isStrict = document.compatMode == "CSS1Compat",
		_isSecure = (window.location.href.toLowerCase().indexOf("https")==0),
		_version = (ua.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ )||[])[1],
		_isOpera = /opera/.test(ua),
		_isSafari = (/webkit|khtml/).test(ua),
		_isIE = /msie/.test(ua) && !/opera/.test(ua),
		_isIE7 = _isIE && ua.indexOf("msie 7") > -1,
		_isMozilla = /mozilla/.test(ua) && !/(compatible|webkit)/.test(ua),
		_isGecko = !_isSafari && ua.indexOf("gecko") > -1,
		_isFirefox = _isMozilla && _isGecko && /firefox/.test(ua),
		_isBorderBox = _isIE && !_isStrict,
		_isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
		_isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
		_isUnix = (navigator.platform=='X11' && !IsWin && !IsMac);
		      
	// remove css image flicker
	if(_isIE && !_isIE7){
		try{
			document.execCommand("BackgroundImageCache", false, true);
		}catch(e){}
	};

	glacier.apply(glacier.Browser, {
		/**
			* 指示当前浏览器的Html验证模式是不是strict模式
			*/
		isStrict : _isStrict,
		/**
			* 指示页面是否运行在SSL模式下
			*/
		isSecure : _isSecure,
		version : _version,
		isOpera : _isOpera,
		isSafari : _isSafari,
		isIE : _isIE,
		isIE7 : _isIE7,
		isMozilla : _isMozilla,
		isGecko : _isGecko,
		isFirefox : _isFirefox,
		isBorderBox : _isBorderBox,
		isWindows : _isWindows,
		isMac : _isMac,
		isUnix : _isUnix,
		isDom: (document.getElementById)
	});
	
	glacier.apply(glacier, {
		/**
			* 指示当前的文档对象document是否已完全初始化并未响应事件做好准备。
			*/
		isReady : false,
		/**
			* 从对象cfg中复制在obj对象中不存在的属性obj对象中。
			*/
		applyIf : function(obj, cfg){
			if(obj && cfg){
					for(var p in cfg){
							if(typeof obj[p] == "undefined"){ obj[p] = cfg[p]; }
					}
			}
			return obj;
		},
		
		// 判断是否是undefined
		undefine : function(val){
			return (!val || typeof(val)=='undefined');
		},
		
		getAttribute: function(c, attr){
			var ctlAttr;
			if(glacier.Browser.isDom) {
				ctlAttr = c.getAttribute(attr);
			}
			else if(document.all) {
				var id = c.id||c.name;
				ctlAttr = eval('document.all["' + id + '"].' + attr);
			}
			if(typeof(ctlAttr) == "string")
				return ctlAttr;
			return "";
		},
		
		setText: function(c, text){
			if(glacier.Browser.isIE || c.innerText)
				c.innerText = text;
			else
				c.textContent = text;
		},

		addEventHandler: function(target, en, fn) {
			if(target.addEventListener) {
				target.addEventListener(en, fn, false);
			}
			else if(target.attachEvent) {
				target.attachEvent("on" + en, fn);
			}
			else {
				target["on" + en] = fn;
			}
		},
	  
		removeEventHandler: function(target, en, fn) {
			if(target.removeEventListener) {
				target.removeEventListener(en, fn, false);
			}
			else if(target.attachEvent) {
				target.detachEvent("on" + en, fn);
			}
			else {
				target["on" + en] = null;
			}
		},
	  
		formatEvent: function(ent) {
			if(glacier.Browser.isIE && glacier.Browser.isWindows) {
				ent.charCode = (ent.type=='keypress')?ent.keyCode:0;
				ent.eventPhase = 2;
				ent.isChar = (ent.charCode > 0);
				ent.pageX = ent.clientX + document.body.scrollLeft;
				ent.pageY = ent.clientY + document.body.scrollTop;
				ent.preventDefault = function() {
					this.returnValue = false;
				};
	      
				if(ent.type == 'mouseout') {
					ent.relatedTarget = ent.toElement;
				}
				else if(ent.type == 'mouseover') {
					ent.relatedTarget = ent.fromElement;
				}
	      
				ent.stopPropagation = function() {
					this.cancelBubble = true;
				};
	      
				ent.target = ent.srcElement;
				ent.time = (new Date()).getTime();
			}
			return ent;
		},
	  
		getEvent: function() {
			if(window.event) {
				return this.formatEvent(window.event);
			}
			else {
				return this.getEvent.caller.arguments[0];
			}
		},
		
		getTarget: function(e){
			var target;
			e=e||this.getEvent();
			if (e.target) target = e.target;
			else if (e.srcElement) target = e.srcElement;
			return target;
		}
	})
})();


glacier.applyIf(String, {
	// 替换字符串中的' 和 \
	escape : function(string) {
		return string.replace(/('|\\)/g, "\\$1");
	},
	
	// 压缩text中包含的空格
	trim : function(string) {
		return string.replace(/(^\s*)|(\s*$)/g,"");
	},
	
	// 在val的左边串上size长度的ch
	leftPad : function (val, size, ch) {
		var result = new String(val);
		if (ch == null) {
			ch = " ";
		}
		while (result.length < size) {
			result = ch + result;
		}
		return result;
	},
	
	format : function(format){
		var args = Array.prototype.slice.call(arguments, 1);
		return format.replace(/\{(\d+)\}/g, function(m, i){
			return args[i];
		});
	}
});

glacier.applyIf(Number.prototype, {
    constrain : function(min, max){
        return Math.min(Math.max(this, min), max);
    }
});

glacier.applyIf(Array.prototype, {
	indexOf : function(o){
		for (var i = 0, len = this.length; i < len; i++){
			if(this[i] == o) return i;
		}
		return -1;
	},

	remove : function(o){
		var index = this.indexOf(o);
		if(index != -1){
			this.splice(index, 1);
		}
	}
});

/************* StringBuilder 类 ************************/
function StringBuilder(initialText) {
	this._parts = (typeof(initialText) !== 'undefined' && initialText !== null && initialText !== '') ? [initialText.toString()] : [];
  this._validateString = function(p){
		if(typeof(p) !== 'string')
			throw 'Invalid arguments, Must be a string!';
  };
};

StringBuilder.prototype={
	append : function(str) {
		this._validateString(str);
		this._parts[this._parts.length] = str;
	},
	appendLine : function(str) {
		this._validateString(str);
		this._parts[this._parts.length] = ((typeof(str) === 'undefined') || (str === null) || (str === '')) ? '\r\n' : str + '\r\n';
	},
	clear : function() {
		this._parts = [];
	},
	toString : function() {
		return this._parts.join("");
	}
};

/************* StringBuilder 类 ************************/

