/*==========================================================

 KEY.LIBRARY(JS) 0.03
 under the New BSD License license:
 http://www.opensource.org/licenses/bsd-license.php

==========================================================*/

/* Namespace
----------------------------------------------------------*/

var KEY = {};

KEY.version = 0.03;



/*==========================================================

 @HTML

==========================================================*/

KEY.HTML = {};



/* Get Element
----------------------------------------------------------*/
KEY.HTML.GetElement = function() {
	
	this.$ = function(selector) {
		var result = {};
		if(selector.charAt(0).match(/\#/)) {
			var selector = selector.substring(1);
			var element = document.getElementById(selector);
			if(element) {
				result = element;
				result._w = element.offsetWidth;
				result._h = element.offsetHeight;
				result._x = element.offsetLeft;
				result._y = element.offsetTop;
				while(element.offsetParent) {
					element = element.offsetParent;
					result._x += element.offsetLeft;
					result._y += element.offsetTop;
				}
				return result;
			} else {
				return false;
			}
		} else {
			result = [];
			var element = selector.split(".")[0] || "*";
			var classname = selector.split(".")[1];
			var html = document.getElementsByTagName(element);
			var Index = html.length;
			for(var i=0; i<Index; i++) {
				if(html[i].className.match(classname)) result.push(html[i]);
			}
			if(!result.length) result = false;
			return result;
		}
	}

};



/* Get FormElement
----------------------------------------------------------*/
KEY.HTML.GetFormElement = function() {
	
	this.$I = function(selector) {
		var result = [];
		var form = document.forms;
		var query = (selector.charAt(0).match(/\#/)) ? "id" : "className";
		var selector = selector.substr(1);
		for(var i=0; i<form.length; i++){
			if(form[i][query].match(selector)) {
				var item = form[i].elements;
				var Index = item.length;
				for(var j=0; j<Index; j++){
					if(item[j].type.match(/text/)) result.push(item[j]);
					if(item[j].type.match(/pass/)) result.push(item[j]);
					if(item[j].type.match(/file/)) result.push(item[j]);
				}
			}
		}
		if(!result.length) result = false;
		return result;
	}

};



/* Event
----------------------------------------------------------*/
KEY.HTML.Event = function() {
	
	this.append = function(element, evtType, func, useCapture) {
		if(evtType=="mousewheel") {
			if(navigator.userAgent.toUpperCase().match("FIREFOX")) evtType = "DOMMouseScroll";
		}
		if(element.addEventListener) {
			if(!useCapture) useCapture = false;
			element.addEventListener(evtType, func, useCapture);
		} else if(element.attachEvent) {
			element.attachEvent("on"+evtType, func);
		} else {
			var evtStorage = element["on"+evtType];
			element["on"+evtType] = evtStorage ? function() {func(); evtStorage()} : func;
		}
	};
	
	this.remove = function(element, evtType, func, useCapture) {
		if(evtType=="mousewheel") {
			if(navigator.userAgent.toUpperCase().match("FIREFOX")) evtType = "DOMMouseScroll";
		}
		if(element.removeEventListener) {
			if(!useCapture) useCapture = false;
			element.removeEventListener(evtType, func, useCapture);
		} else if(element.detachEvent) {
			element.detachEvent("on"+evtType, func);
		} else {
			return false;
		}
	}
	
};

/* Get Require
----------------------------------------------------------*/
KEY.HTML.Require = function() {
	
	this.require = function(postFile, replaceFile, postElement) {
		if(!postElement) postElement = 'script';
		var path;
		var element = document.getElementsByTagName(postElement);
		var Index = element.length;
			for(var i=0,j=0; i<Index; i++) {
				if(element[i].src.indexOf(postFile)>=0) {
					path = element[i].src.replace(postFile,replaceFile);
				}
			}
		return String(path);
	}

};



/*==========================================================

 @User

==========================================================*/

KEY.User = {};



/* User Environment
----------------------------------------------------------*/
KEY.User.Environment = function() {

	var agent = navigator.userAgent.toUpperCase();
	
	this.os = function() {
		if(agent.match(/WIN(DOWS)?/)) return "windows";
		else if(agent.match(/MAC/)) return "mac";
		else if(agent.match(/X11/)) return "unix";
		else if(agent.match(/LINUX/)) return "linux";
	};
	
	this.ua = function() {
		if(agent.match(/MSIE/)) return "msie";
		else if(agent.match(/CHROME/)) return "chrome";
		else if(agent.match(/SAFARI/)) return "safari";
		else if(agent.match(/FIREFOX/)) return "firefox";
		else if(agent.match(/NETSCAPE/)) return "netscape";
		else if(agent.match(/OPERA/)) return "opera";
	};
	
	this.engine = function() {
		if(this.os()=="mac"&&agent.match(/MSIE/)) return "macie";
		else if(agent.match(/MSIE 8.0/)) return "ie8";
		else if(agent.match(/MSIE 7.0/)) return "ie7";
		else if(agent.match(/MSIE 6.0/)) return "ie6";
		else if(agent.match(/MSIE/)) return "ie";
		else if(agent.match(/WEBKIT/)) return "webkit";
		else if(agent.match(/GECKO/)) return "gecko";
		else if(agent.match(/OPERA/)) return "opera";
	};
	
	this.mode = function() {
		if(document.compatMode=='BackCompat') return 'quirk';
		if(document.compatMode=='CSS1Compat') return 'standard';
	};
	
	this.flash = function() {
		var version;
		var shockwave = navigator.mimeTypes["application/x-shockwave-flash"];
		var plugin = (navigator.mimeTypes && shockwave) ? shockwave.enabledPlugin : 0;
		if(plugin) {
			var player = navigator.plugins["Shockwave Flash"].description.split(" ");
			var index = player.length;
			for(var i=0; i<index; i++) {
				if(isNaN(parseInt(player[i]))) continue;
					version = parseInt(player[i],10);
			}
		} else if(agent.match(/MSIE/) && agent.match(/WINDOWS/)) {
			version = new ActiveXObject("ShockwaveFlash.ShockwaveFlash").FlashVersion();
			version = Math.floor(version/0x10000);
		}
		return version;
	}

};

/* Window and Document Size
----------------------------------------------------------*/
KEY.User.Size = function() {

	this.windowW = function() {
		if(self.innerWidth) {
			return self.innerWidth;
		} else if(document.documentElement && document.documentElement.clientWidth) {
			return document.documentElement.clientWidth;
		} else if(document.body) {
			return document.body.clientWidth;
		}
	};
	
	this.windowH = function() {
		if(self.innerHeight) {
			return self.innerHeight;
		} else if(document.documentElement && document.documentElement.clientHeight) {
			return document.documentElement.clientHeight;
		} else if(document.body) {
			return document.body.clientHeight;
		}
	};

	this.windowX = function() {
		return window.screenX || window.screenLeft;
	};
	
	this.windowY = function() {
		return window.screenY || window.screenTop;
	};
	
	this.documentW = function() {
		if(window.innerWidth && window.scrollMaxX) {
			return window.innerWidth + window.scrollMaxX;
		} else if(document.body.scrollWidth > document.body.offsetWidth) {
			return document.body.scrollWidth;
		} else {
			return document.body.offsetWidth;
		}
	};
	
	this.documentH = function() {
		if(window.innerHeight && window.scrollMaxY) {
			return window.innerHeight + window.scrollMaxY;
		} else if(document.body.scrollHeight > document.body.offsetHeight) {
			return document.body.scrollHeight;
		} else {
			return document.body.offsetHeight;
		}
	};
	
	this.documentX = function() {
		if(document.documentElement.scrollLeft) {
			return document.body.scrollLeft || document.documentElement.scrollLeft;
		} else {
			return document.body.scrollLeft;
		}
	};
	
	this.documentY = function() {
		if(document.documentElement.scrollTop) {
			return document.body.scrollTop || document.documentElement.scrollTop;
		} else {
			return document.body.scrollTop;
		}
	}
	
};



/*==========================================================

 @Data

==========================================================*/

KEY.Data = {};



/* Cookie
----------------------------------------------------------*/
KEY.Data.Cookie = function() {

	this.get = function(key) {
		var key = key+"=";
		if(document.cookie.match(key)){
			var cookies = document.cookie.split(";");
			var Index = cookies.length;
			for(var i=0; i<Index; i++) {
				var cooky = cookies[i];
				var total = cooky.length;
				if(cooky.charAt(0)==" ") cooky = cooky.substring(1,total);
				if(cooky.indexOf(key)==0) return unescape(cooky.substring(key.length,total));
			}
			return null;
		}
	};
	
	this.set = function(key, value, expires, path, domain, secure) {
		var now = new Date().getTime();
		if(expires) expires = expires*1000*60*60*24;
		var expireDate = new Date(now+(expires)).toGMTString();
		var cookieData = key+"="+escape(value)
			+((expires) ? ";expires="+expireDate : "")
			+((path) ? ";path="+path : "")
			+((domain) ? ";domain="+domain : "")
			+((secure) ? ";secure" : "");
		document.cookie = cookieData;
	};
	
	this.clear = function(key, path, domain) {
		if(this.get(key)) {
			var cookieData = key+"= ;expires=Fri, 31-Dec-1999 23:59:59 GMT"
				+((path) ? ";path="+path : "")
				+((domain) ? ";domain="+domain : "");
			document.cookie = cookieData;
		}
	}
	
};

/* Parser
----------------------------------------------------------*/
KEY.Data.Parser = function() {

	this.query = function(urlVars) {
		var params = {};
		if(!urlVars) return params;
		if(urlVars.match(/[\?]/)) {
			var query = urlVars.split("?")[1].split("&");
		} else {
			var query = urlVars.split("&");
		}
		for(var i=0; i<query.length; i++) {
			var key = unescape(query[i].split("=")[0]);
			var val = unescape(query[i].split("=")[1]);
			params[key] = val;
		}
		return params;
	};
	
	this.string = function(string, key) {
		var param = {};
		for(var i=0; i<key.length; i++) {
			var ptn = new RegExp("\\b"+ key[i] +"[0-9]+");
			var reg = string.match(ptn);
			param[key[i]] = reg ? reg[0].substring(1) : false;
		}
		return param;
	}
	
};

/* XHRequest
----------------------------------------------------------*/
KEY.Data.XHRequest = function(openMethod, openAsynchro) {
	
	var openMethod = openMethod ? openMethod.toUpperCase() : "GET";
	var openAsynchro = openAsynchro || true;
	var XHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP');
	
	this.onLoading = {};
	this.onLoadError = {};
	this.onComplete = {};
	
	this.load = function(url) {
		var url = url+"?cache="+new Date().getTime();
		var onLoading = this.onLoading;
		var onLoadError = this.onLoadError;
		var onComplete = this.onComplete;
		var onReadyState = function() {
			if(XHR.readyState==1) {
				(typeof onLoading=="function") ? onLoading() : null;
			} else if(XHR.readyState==4) {
				if(XHR.status==401 || XHR.status==403 || XHR.status==404) {
					(typeof onLoadError=="function") ? onLoadError() : null;
				} else if(XHR.status==200) {
					(typeof onComplete=="function") ? onComplete(XHR.responseXML) : null;
				}
			}
		};
		
		if(XHR) {
			XHR.onreadystatechange = onReadyState;
			XHR.open(openMethod, url, openAsynchro);
			XHR.send(null);
		}
	}
	
};



/*==========================================================

 @KEY.LIBRARY(JS)
 @Useful Module

==========================================================*/

/* Namespace
----------------------------------------------------------*/

if(!KEY.Module) KEY.Module = {};



/* User
----------------------------------------------------------*/
KEY.Module.User = function() {
	
	KEY.User.Environment.call(this);
	KEY.User.Size.call(this);
	
};


KEY.Module.User.prototype = {
	
	setcode : function(e) {
		var userunv = this.os() +" "+ this.ua() +" "+ this.engine();
		if(userunv!="") {
			var targetName = e.toLowerCase(e);
			var element = document.getElementsByTagName(targetName)[0];
			var exist = element.className;
			element.className = exist ? exist+" "+userunv : userunv;
		}
	}
	
};



/* Rollover
----------------------------------------------------------*/
KEY.Module.Rollover = function(rollout, rollover) {
	
	KEY.HTML.GetElement.call(this);
	if(!document.presetImage) document.presetImage = [];
	
	rollout = rollout+".";
	rollover = rollover+".";
	
	var set = function(image) {
		var preset = document.presetImage;
		var Index = image.length;
			for(var i=0; i<Index; i++) {
				var swap = image[i];
				swap.out = swap.src;
				swap.ov = swap.src.replace(rollout, rollover);
				swap.onmouseover = function() {this.src = this.ov};
				swap.onmouseout = function() {this.src = this.out};
				var presetImage = new Image();
				presetImage.src = swap.ov;
				preset.push(presetImage);
			}
	};
	
	this.init = function(selector) {
		var image = this.$(selector);
		if(!image) return false;
		var Index = image.length;
		for(var i=0; i<Index; i++) {
			if(image[i].nodeName.toLowerCase()=="img") {
				set([image[i]]);
			} else {
				var images = image[i].getElementsByTagName("img");
				set(images);
			}
		}
	}
	
};



/* Flash
----------------------------------------------------------*/
KEY.Module.Flash = function(require) {
	
	this.version = require;
	var user = new KEY.User.Environment();
	this.player = user.flash();
	this.src = String();
	this.id = String();
	this.vars = String();
	this.exist = String();
	this.scale = "noscale";
	this.menu = "false";
	this.wmode = "transparent";
	this.bgcolor = "#ffffff";
	
};

KEY.Module.Flash.prototype = {
	
	init : function(swfContainer, swfWidth, swfHeight) {
		this.swfContainer = document.getElementById(swfContainer);
		this.exist = this.swfContainer.innerHTML;
		this.swfContainer.innerHTML = "";
		this.swfWidth = swfWidth;
		this.swfHeight = swfHeight;
	},
	
	frame : function(minWidth, minHeight) {
		var size = new KEY.User.Size();
		var event = new KEY.HTML.Event();
		var swfContainer = this.swfContainer.style;
		swfContainer.width = "100%";
		swfContainer.height = "100%";
		function frameResize() {
			var w = size.windowW();
			var h = size.windowH();
			if(w<=minWidth) swfContainer.width = minWidth +"px";
			else swfContainer.width = "100%";
			if(h<=minHeight) swfContainer.height = minHeight +"px";
			else swfContainer.height = "100%";
		}
		frameResize();
		event.append(window, "resize", frameResize);
	},
	
	embed : function() {
		var embed = document.createElement("embed");
		embed.setAttribute("type", "application/x-shockwave-flash");
		embed.setAttribute("width", this.swfWidth);
		embed.setAttribute("height", this.swfHeight);
		embed.setAttribute("quality", "high");
		embed.setAttribute("scale", this.scale);
		embed.setAttribute("menu", this.menu);
		embed.setAttribute("wmode", this.wmode);
		embed.setAttribute("bgcolor", this.bgcolor);
		return embed;
	},
	
	load : function(src) {
		if(this.player >= this.version) {
			var swf = this.embed();
			swf.setAttribute("src", src);
			if(this.id) swf.setAttribute("id", this.id);
			if(this.vars) swf.setAttribute("flashvars", this.vars);
			this.swfContainer.appendChild(swf);
		} else {
			this.swfContainer.innerHTML = this.exist;
		}
	}
	
};



/* WINDOW
----------------------------------------------------------*/
KEY.Module.Window = function() {

	KEY.User.Environment.call(this);
	KEY.HTML.GetElement.call(this);
	KEY.Data.Parser.call(this);

	this.classkey = ["w","h"];

};


KEY.Module.Window.prototype = {

	init : function(selector) {
		var self = this;
		var a = this.$(selector, "a");
		if(!a) return false;
		var Index = a.length;
		for(var i=0; i<Index; i++) {

		a[i].onclick = function() {
				var classname = this.className;
				if(classname.match(/\b[w|h][0-9]+/ig)) {
					var size = self.string(this.className, self.classkey);
					var param = "width="+ size[self.classkey[0]]
					+", height="+ size[self.classkey[1]]
					+", toolbar = no"
					+", menubar = yes"
					+", location = no"
					+", scrollbars = yes"
					+", directories = no"
					+", status = yes"
					+", resizable = yes";
				} else {
					var param = "width="+ screen.availWidth
					+", height="+ screen.availHeight
					+", left = 0"
					+", top = 0"
					+", toolbar = no"
					+", menubar = no"
					+", location = no"
					+", scrollbars = no"
					+", directories = no"
					+", status = no"
					+", resizable = no";
				}
					
				var subWindow = window.open(this.href, this.title, param);
				subWindow.focus();
				
				return false;
			}
		}
	},

	open : function(a, Width, Height) {
		var param;
		var url = a.href;
		var Name = a.title || "subWindow";
		if(Width) {
			if(this.engine()=="ie7") Height = Height + 28;
				param = "width="+ Width;
				param += ", height="+ Height;
				param += ", toolbar = no";
				param += ", menubar = yes";
				param += ", location = no";
				param += ", scrollbars = yes";
				param += ", directories = no";
				param += ", status = yes";
				param += ", resizable = yes";
			} else {
				Width = screen.availWidth;
				Height = screen.availHeight;

				if(this.engine()=='ie6') {
				Width = Width-10;
				Height = Height-30;
			}
			param = "width="+ Width;
			param += ", height="+ Height;
			param += ", left = 0";
			param += ", top = 0";
			param += ", toolbar = no";
			param += ", menubar = no";
			param += ", location = no";
			param += ", scrollbars = no";
			param += ", directories = no";
			param += ", status = no";
			param += ", resizable = no";
		}

		var subWindow = window.open(url, Name, param);
		subWindow.focus();
	}
	
};



/* Smart Scroll
----------------------------------------------------------*/
KEY.Module.SmartScroll = function(step, delay, key) {
	
	KEY.HTML.GetElement.call(this);
	this.user = new KEY.User.Size();
	this.event = new KEY.HTML.Event();
	this.cookie = new KEY.Data.Cookie();
	this.cookie.set("check", true);
	
	this.step = step || 20;
	this.delay = delay || 500;
	this.timer = null;
	this.hashs = null;
	this.key = key || "dest";
	this.exclude = null;
	
};

KEY.Module.SmartScroll.prototype = {
	
	init : function() {
		var self = this;
		var base = location.href;
		var element = document.getElementsByTagName('a');
		var Index = element.length;
		var destination = this.cookie.get(this.key);

		var exPattern = new RegExp(self.exclude);
		var current = base.substring(0, base.lastIndexOf("."));
		current = decodeURIComponent(current);
		var check = this.cookie.get("check");
		
		if(destination!=undefined) {
			this.cookie.clear(this.key);
			setTimeout(function() {
				self.run("#"+destination);
			}, this.delay);
		}
		
		for(var i=0; i<Index; i++) {
			var a = element[i];
			if(a.target || a.className.match(exPattern)) continue;
			
			var id = a.href.split("#")[1];
			var destinat = a.href.substring(0, a.href.lastIndexOf("."));
			destinat = decodeURIComponent(destinat);

			if(current==destinat) {
				if(document.getElementById(id)) {
					a.onclick = function() {
						self.run(this.hash);
						return false;
					}
				}
			} else {
				if(check && a.href.split("#")[1]) {
					a.onclick = function() {
						self.cookie.set("dest", this.href.split("#")[1]);
						location.href = this.href.split('#')[0];
						return false;
					}
				}
			}
		}
	},
	
	run : function(hashs) {
		var self = this;
		self.hashs = hashs;
		clearInterval(self.timer);
		self.event.append(document, 'mousewheel', function() {clearInterval(self.timer)});
		
		var y  = this.$(hashs)._y;
		var ph = this.user.documentH();
		var wh = this.user.windowH();
		var dx = 0;
		var dy = (ph-y<=wh) ? ph-wh : y;
		self.timer = setInterval(function() {
			var mv = 0;
			var py = self.user.documentY();
			if(dy<=0) dy = 0;
			if(dy==py) {
				scrollTo(dx,dy);
				clearInterval(self.timer);
				self.timer = null;
				if(self.hashs) document.location.hash = self.hashs;
			} else {
				mv = ((dy-py)>0) ? Math.ceil((dy-py)*self.step/100) : Math.floor((dy-py)*self.step/100);
				mv = py+mv;
				scrollTo(dx,mv);
			}
		}, 25);
	}
	
};



/* Form Control
----------------------------------------------------------*/
KEY.Module.FormControl = function() {
	
	KEY.HTML.GetFormElement.call(this);
	
	this.clearInput = function(targetForm) {
		var item = this.$I(targetForm);
		for(var i=0; i<item.length; i++) {
			item[i].onfocus = function() {if(this.value == this.defaultValue) this.value = ""};
			item[i].onblur  = function() {if(!this.value) this.value = this.defaultValue};
		}
	}

};


/* Stripe TableRow
----------------------------------------------------------*/
KEY.Module.StripeRow = function(setClassName) {
	
	KEY.HTML.GetElement.call(this);
	this.setClassName = setClassName;
	this.either = "odd";
	
};

KEY.Module.StripeRow.prototype = {
	
	init : function(selector) {
		var turns = 0;
		var either = this.either.toLowerCase();	
		if(either=='odd') turns = 0;
		if(either=='even') turns = 1;
		var targetElement = this.$(selector);
		if(!targetElement) return;
		targetElement = (targetElement.length) ? targetElement : [targetElement];
		for(var i=0; i<targetElement.length; i++) {
			var tr = targetElement[i].getElementsByTagName('tr');
			var Index = tr.length;
			for(var j=0; j<Index; j++) {
				if(j%2==turns) {
					var exist = tr[j].className;
					tr[j].className = exist ? exist+' '+this.setClassName : this.setClassName;
				}
			}
		}
	}
	
};
