var isUtil = {
	Browser: {
		IE6: navigator.userAgent.indexOf('MSIE 6') > -1,
		IE7: navigator.userAgent.indexOf('MSIE 7') > -1,
		FF: navigator.userAgent.indexOf('Firefox') > -1
	},

	makeUrl: function(url, args, isQueryString) {
		var link = url;
		if (isQueryString) {
			link += ((String(url).indexOf('?') > -1) ? '&' : '?')+Object.toQueryString(args);
		}
		else {
			$H(args).each(function (pair) {
				if (pair.value != '') {
					// replace special character
					if (typeof pair.value == 'string')
						pair.value = pair.value.replace(/\%/g, '%25').replace(/\$/g, '%24').replace(/\\/g, '+s|||').replace(/\//g, '+s|2F|').replace(/\ /g, '+s|+|').replace(/\./g, '+s|.|').replace(/\?/g, '%3F').replace(/\&/g, '%26').replace(/\#/g, '%23');
					link += '/'+pair.key+'/'+pair.value;
				}
			});
		}
		return link;
	},
	movePage: function(url, args, isQueryString) {
		window.location = isUtil.makeUrl(url, args, isQueryString);
	},
	newPage: function(url, args, isQueryString, name) {
		window.open(isUtil.makeUrl(url, args, isQueryString), name);
	},

	autoBlur: function(parentId) {
		var str = 'a';
		if (typeof parentId != 'undefined')
			str = '#'+parentId+' a';
		$$(str).each( function (el, index) {
			el.onfocus = function () { el.blur(); };
		});
	},

	CheckNotAllowedChar: function(NotAllowChars, el, ErrMsg) {
		if (!el.value)
			return true;

		var val = el.value;
		NotAllowChars = NotAllowChars.split(',');
		var chk = $A(NotAllowChars).detect( function( chr, index ) {
			return (((chr != '') && (val.indexOf(chr) != -1)) || (val.indexOf('\\') != -1));
		});
		if (chk) {
			if (ErrMsg != '')
				alert(ErrMsg);
			el.focus();
			return false;
		}
		else
			return true;
	},

	RegisterCheckAll: function(formId, allCheck, eachCheck) {
		var form = $(formId);
		var all = form.getInputs('checkbox', allCheck)[0];
		var boxes = form.getInputs('checkbox', eachCheck);
		var drag = false;
		if (boxes && (boxes.length > 0)) {
			Event.observe(all, 'click', function() {				
				var isAllChecked;
				if (all.checked)
					isAllChecked = true;
				else
					isAllChecked = false;
				boxes.each(function (box) {
					if (box.disabled == false)
						box.checked = isAllChecked;
				});			
			});
			
			var curChkCounter = 0;
			boxes.each(function (box) {
				Event.observe(box, 'click', function() {
					var chkCounter = 0;
					boxes.each(function (box2) {
						if (box2.checked || box2.disabled)
							chkCounter++;
					});
					if (chkCounter == boxes.length)
						all.checked = true;
					else
						all.checked = false;
				});
				if (box.checked || box.disabled)
					curChkCounter++;
			});
			if (curChkCounter == boxes.length)
				all.checked = true;
			else
				all.checked = false;
		}
	},

	clearSelection: function() {
		try {
			if (document.selection && document.selection.empty){
				document.selection.empty() ;
			} else if (window.getSelection) {
				var sel=window.getSelection();
				if (sel && sel.removeAllRanges)
					sel.removeAllRanges() ;
			}
		} catch (e) {}
	},

	viewport: function() {
		var bW, bH;
		if (self.innerHeight) // all except Explorer
		{
			bW = document.documentElement.clientWidth;
			bH = self.innerHeight;
		}
		else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
		{
			bW = document.documentElement.clientWidth;
			bH = document.documentElement.clientHeight;
		}
		else if (document.body) // other Explorers
		{
			bW = document.body.clientWidth;
			bH = document.body.clientHeight;
		}
		return {'width':bW, 'height':bH};
	},

	sendOption: {},
	send: function(url, args, responser) {
		// initialize sendOption
		isUtil.sendOption = {
			useLoading: true,
			successLink: '',
			success: function(re) {
				if (isUtil.sendOption.useLoading)
					isDialogUtil.showLoading();
				if (isUtil.sendOption.successLink == '')
					self.location.reload();
				else
					isUtil.movePage(isUtil.sendOption.successLink);
			},
			fail: function(re) {}
		};

		var resultFunc;
		var responserType = typeof responser;
		if (responserType == 'function') {
			resultFunc = responser;
			isUtil.sendOption.successLink = '';
		}
		else if (responserType == 'string') {
			resultFunc = isUtil.viewResult;
			isUtil.sendOption.successLink = responser;
		}
		else if (responserType == 'object') {
			resultFunc = isUtil.viewResult;
			Object.extend(isUtil.sendOption, responser || {});
		}
		else {
			resultFunc = isUtil.viewResult;
			isUtil.sendOption.successLink = '';
		}
		if (url == null)
			url = self.location.href;

		if (isUtil.sendOption.useLoading)
			isDialogUtil.showLoading();

		new Ajax.Request(url, {
			method : 'post',
			parameters : args,
			onComplete : resultFunc
		});
	},

	viewResult: function(re) {
		if (isUtil.sendOption.useLoading)
			isDialogUtil.hideLoading();

		var Result = re.responseText.evalJSON();

		if ((typeof Result.msg != "undefined") && (Result.msg != ""))
			alert(Result.msg);

		if (Result.result)
			isUtil.sendOption.success(re);
		else
			isUtil.sendOption.fail(re);
	},

	loadingTag: function(commonImgPath) {
		return '<div class="small_loading_icon"><img src="'+commonImgPath+'/loading_s.gif" /></div>';
	},

	popup: function(url, name, width, height) {
		window.open(url, name, 'width='+width+',height='+height+',menubar=no,status=no,toolbar=no');
	},

	textareaMaxLength: function(el) {
		el = $(el);
		if ((el.type == 'textarea') || (el.type == 'text')) {
			var maxlength = el.readAttribute('max_length') || el.readAttribute('maxlength');
			if (!el.disabled && maxlength && String(maxlength).isNumber() && (parseInt(maxlength) > 0)) {
				var maxLengthEvent = false;
				var maxFunc = function(evt) {
					if (!maxLengthEvent && (el.value.length > maxlength)) {
						maxLengthEvent = true;
						var msg = el.readAttribute('maxlength_msg');
						if (msg)
							alert(msg);
						el.value = el.value.substring(0, maxlength);
						maxLengthEvent = false;
					}
				};
				Event.observe(el, 'keyup', maxFunc);
				Event.observe(el, 'mouseup', maxFunc);
			}
		}
	}
};

Event.observe(window, 'load', function() {
	try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}
	isUtil.autoBlur();
});


var sortUtil = {
	init: function(tbl, baseUrl, nowKey, nowType, QueryString, moveFunc) {
		$(tbl).select('th').each( function(el) {
			var key = el.getAttribute('isSort');
			if (key) {
				el.setStyle({'cursor':'pointer'});
				var nextType = 'asc';
				if (key == nowKey) {
					var nowTypeStr;
					if (nowType == 'asc') {
						nextType = 'desc';
						nowTypeStr = ' ▲';
					}
					else {
						nowTypeStr = ' ▼';
					}
					el.insert({'bottom':nowTypeStr});
				}

				Event.observe(el, 'click', function() {
					if (typeof moveFunc == 'undefined')
						isUtil.movePage(baseUrl.unescapeTag(), {'OrderField':key, 'OrderType':nextType}, QueryString);
					else
						moveFunc(baseUrl.unescapeTag(), {'OrderField':key, 'OrderType':nextType});
				});
			}
		});
	}
};