/* *******************************************************
J  a  v  a  c  a  t  z
Filename:   common.js
Purpose:    This file is created to hold common functions
            that are useful to other projects.
            Please do not put other codes in this file.
Created by: KY 2007.09.13
Modified by: KY 2009.05.29
******************************************************* */


/* kyMenu */
var kyMenu = {
	init: function(action) {
		if(action) action = action.toLowerCase();
		$$('.kyMenu ul ul').each( function(node) {
			$(node).hide();
		} );
		$$('.kyMenu ul').each( function(node) {
			$(node).hide();
		} );
		$$('.kyMenu li').each( function(node) {
			var kyMenuUL = $(node).up('.kyMenu');
			if($(kyMenuUL).hasClassName('fade') || $(kyMenuUL).hasClassName('appear')) action = 'fade';
			else if($(kyMenuUL).hasClassName('blind')) action = 'blind';
			$(node).observe('mouseenter', function(e) {
				$(node).addClassName('active');
				if($(node).down('ul')) {
					if(!action || action == 'fade' || action == 'appear') {
						new Effect.Appear($(node).down('ul'), { duration: 0.3 });
					} else if(action == 'blind') {
						new Effect.BlindDown($(node).down('ul'), { duration: 0.3, afterFinish: function() { $(node).down('ul').setStyle({'height':'auto'}); } });
					}
				}
			} );
			$(node).observe('mouseleave', function(e) {
				$(node).removeClassName('active');
				if($(node).down('ul')) {
					if(!action || action == 'fade' || action == 'appear') {
						new Effect.Fade($(node).down('ul'), { duration: 0.3 });
					} else if(action == 'blind') {
						new Effect.BlindUp($(node).down('ul'), { duration: 0.3, afterFinish: function() { $(node).down('ul').setStyle({'height':'auto'}); } });
					}
				}
			} );
		} );
	}
};



/* Get URL Parameter */
function getParameter(name) {		// get value of an ? parameter in url
	var url = window.location.href;
	var paramsStart = url.indexOf("?");
	if(paramsStart != -1) {
		var paramString = url.substr(paramsStart + 1);
		var tokenStart = paramString.indexOf(name);
		if(tokenStart != -1) {
			paramToEnd = paramString.substr(tokenStart + name.length + 1);
			var delimiterPos = paramToEnd.indexOf("&");
			if(delimiterPos == -1) {
				return paramToEnd;
			} else {
				return paramToEnd.substr(0, delimiterPos);
			}
		} else {
			return "";
		}
	}
}


/* Browser Detection */
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();


/* Set, Retrieve, Delete Cookies */
function setCookie(name, value, expires) { 
	var expDate = new Date(expires);
	document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expDate.toGMTString());
}
function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
	}
	return null;
}
function delCookie(name) {
	document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
}

/* Print Page */
function printPage() {
	var this_url = document.location.href;
	if(this_url.lastIndexOf('?') == -1) {	// there is no ? parameters
		this_url = this_url + "?screenmode=print";
	} else {
		this_url = this_url + "&screenmode=print";
	}
	var day = new Date();
	var id = day.getTime();
	eval("page" + id + " = window.open(this_url, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=640,height=480'); page" + id + ".focus();");
}
function printPageWithURL(ExtraURL) {
	var day = new Date();
	var id = day.getTime();
	eval("page" + id + " = window.open(ExtraURL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=640,height=480'); page" + id + ".focus();");
}
function printPage2(){
	print();
}


/* Fix PNG in MSIE, used in bodyOnLoad in needed */
function fixPNG() {
	// var arVersion = navigator.appVersion.split("MSIE");
	// var version = parseFloat(arVersion[1]);

	// if ((version >= 5.5) && (version < 7)) {
	if( BrowserDetect.browser == "Explorer" && BrowserDetect.version >= 5.5 && BrowserDetect.version < 7 && BrowserDetect.OS == "Windows" ) {
	   for(var i=0; i<document.images.length; i++) {
		  var img = document.images[i];
		  var imgName = img.src.toUpperCase();
		  if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
			 var imgID = (img.id) ? "id='" + img.id + "' " : "";
			 var imgClass = (img.className) ? "class='" + img.className + " fixPNG' " : "class='fixPNG'";
			 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
			 var imgStyle = "display:inline-block;" + img.style.cssText ;
			 if (img.align == "left") imgStyle = "float:left;" + imgStyle;
			 if (img.align == "right") imgStyle = "float:right;" + imgStyle;
			 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
			 var strNewHTML = "<span " + imgID + imgClass + imgTitle
			 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle // + ";"
			 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			 + "(src=\'" + img.src + "\', sizingMethod='scale');\">"
			 + "<span class='unfixPNG' style='display: none;'>" + img.src + ":::" + img.style.cssText + "</span>"	// moded by KY
			 + "</span>";
			 img.outerHTML = strNewHTML;
			 i = i-1;
		  }
	   }
	}
}
function unfixPNG() {	// undo fixPNG -- added by KY, not 100% foolproof yet.
	var itemFixPNG = $$('.fixPNG');
	var itemFixPNG_span = $$('.fixPNG .unfixPNG');
	var counter = 0;
	if(itemFixPNG.length > 0) {
		itemFixPNG.each( function(node) {
			var tmpText = itemFixPNG_span[counter].innerHTML.split(":::");
			var imgSrc = tmpText[0];
			var imgID = ($(node).id) ? "id='" + $(node).id + "' " : "";
			var imgClass = ($(node).className) ? "class='" + $(node).className + "' " : "";
			imgClass = imgClass.replace("fixPNG", "");
			var imgTitle = ($(node).title) ? "title='" + $(node).title + "' " : "";
			var imgStyle = (tmpText[1]!="") ? "style='" + tmpText[1] + "' " : "";
			$(node).outerHTML = "<img src='" + imgSrc + "' alt='beforePrintPNG' " + imgID + imgClass + imgTitle + imgStyle + " />";
			counter++;
		} );
	}
}


/* Smooth Anchor Scrolling
var ss = {
	fixAllLinks: function() {
		// Get a list of all links in the page
		var allLinks = document.getElementsByTagName('a');
		// Walk through the list
		for (var i=0;i<allLinks.length;i++) {
			var lnk = allLinks[i];
			if ((lnk.href && lnk.href.indexOf('#') != -1) && ( (lnk.pathname == location.pathname) ||
			('/'+lnk.pathname == location.pathname) ) && (lnk.search == location.search)) {
				// If the link is internal to the page (begins in #)
				// then attach the smoothScroll function as an onclick
				// event handler
				ss.addEvent(lnk,'click',ss.smoothScroll);
			}
		}
	},

	smoothScroll: function(e) {
		// This is an event handler; get the clicked on element,
		// in a cross-browser fashion
		if (window.event) {
		  target = window.event.srcElement;
		} else if (e) {
		  target = e.target;
		} else return;
		
		// Make sure that the target is an element, not a text node
		// within an element
		if (target.nodeName.toLowerCase() != 'a') {
			target = target.parentNode;
		}
		
		// Paranoia; check this is an A tag
		if (target.nodeName.toLowerCase() != 'a') return;
		
		// Find the <a name> tag corresponding to this href
		// First strip off the hash (first character)
		anchor = target.hash.substr(1);
		// Now loop all A tags until we find one with that name
		var allLinks = document.getElementsByTagName('a');
		var destinationLink = null;
		for (var i=0;i<allLinks.length;i++) {
			var lnk = allLinks[i];
			if (lnk.name && (lnk.name == anchor)) {
				destinationLink = lnk;
				break;
			}
		}
		
		// If we didn't find a destination, give up and let the browser do
		// its thing
		if (!destinationLink) return true;
		
		// Find the destination's position
		var destx = destinationLink.offsetLeft; 
		var desty = destinationLink.offsetTop;
		var thisNode = destinationLink;
		while (thisNode.offsetParent && (thisNode.offsetParent != document.body)) {
			thisNode = thisNode.offsetParent;
			destx += thisNode.offsetLeft;
			desty += thisNode.offsetTop;
		}
		
		// Stop any current scrolling
		clearInterval(ss.INTERVAL);
		
		cypos = ss.getCurrentYPos();
		
		ss_stepsize = parseInt((desty-cypos)/ss.STEPS);
		ss.INTERVAL =
		setInterval('ss.scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);
		
		// And stop the actual click happening
		if (window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		if (e && e.preventDefault && e.stopPropagation) {
			e.preventDefault();
			e.stopPropagation();
		}
	},
	
	scrollWindow: function(scramount,dest,anchor) {
		wascypos = ss.getCurrentYPos();
		isAbove = (wascypos < dest);
		window.scrollTo(0,wascypos + scramount);
		iscypos = ss.getCurrentYPos();
		isAboveNow = (iscypos < dest);
		if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
			// if we've just scrolled past the destination, or
			// we haven't moved from the last scroll (i.e., we're at the
			// bottom of the page) then scroll exactly to the link
			window.scrollTo(0,dest);
			// cancel the repeating timer
			clearInterval(ss.INTERVAL);
			// and jump to the link directly so the URL's right
			location.hash = anchor;
		}
	},
	
	getCurrentYPos: function() {
		if (document.body && document.body.scrollTop)
			return document.body.scrollTop;
		if (document.documentElement && document.documentElement.scrollTop)
			return document.documentElement.scrollTop;
		if (window.pageYOffset)
			return window.pageYOffset;
		return 0;
	},
	
	addEvent: function(elm, evType, fn, useCapture) {
		// addEvent and removeEvent
		// cross-browser event handling for IE5+,  NS6 and Mozilla
		// By Scott Andrew
		if (elm.addEventListener){
			elm.addEventListener(evType, fn, useCapture);
			return true;
		} else if (elm.attachEvent){
			var r = elm.attachEvent("on"+evType, fn);
			return r;
		} else {
			alert("Handler could not be removed");
		}
	} 
}

ss.STEPS = 40;

ss.addEvent(window,"load",ss.fixAllLinks);
/* end of Smooth Anchor Scrolling */


/* *** IE Update for ActiveX click to activate *** */
function ieupdate() {
	objects = document.getElementsByTagName("object");
	for (var i = 0; i < objects.length; i++)
	{
		objects[i].outerHTML = objects[i].outerHTML;
	}
}


var lang_months = new Array(12);
lang_months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var lang_weekdays = new Array(7);
lang_weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

/* formatTime 2008.04.28 */
var formatTimeString = new Array();
formatTimeString[0] = 'W + ", " + MM + " " + d + ", " + Y';
formatTimeString[1] = 'h + ":" + ii + ":" + ss + " " + A';
formatTimeString[1] = 'W + ", " + MM + " " + d + ", " + Y + " &nbsp;" + hh + ":" + ii + a';
function formatTime(objDateTime,formatIndex) {
	/*
	getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM
	getSeconds() - Number of seconds (0-59)
	getMinutes() - Number of minutes (0-59)
	getHours() - Number of hours (0-23)
	getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday
	getDate() - Day of the month (0-31)
	getMonth() - Number of month (0-11)
	getFullYear() - The four digit year (1970-9999)
	*/
	
	this.to2digits = function(n) {
		return (n < 10)?("0"+n.toString()):(n.toString());
	}
	
	var s = objDateTime.getSeconds();
	var i = objDateTime.getMinutes();
	var H = objDateTime.getHours();
	var W = lang_weekdays[objDateTime.getDay()];
	var d = objDateTime.getDate();
	var m = objDateTime.getMonth()+1;
	var Y = objDateTime.getFullYear();
	
	var A = (H < 12)?"AM":"PM";
	var a = A.toLowerCase();
	var h = (H < 12)?H:(H-12); h = (h==0)?h+12:h;
	var HH = to2digits(H);
	var hh = to2digits(h);
	var ii = to2digits(i);
	var ss = to2digits(s);
	
	var w = W.substring(0,3);
	var MM = lang_months[m-1];
	var M = MM.substring(0,3);
	var y = Y.toString().substring(2,4);
	
	if(formatIndex==null) formatIndex = 0;
	return eval(formatTimeString[formatIndex]);
}
