// awSpell common JS codes for all sub-sites
// icon things
var currentIcon = '';
var fadeEvent;
var setIconEvent;

function showIcon(layerName,location) {
	clearTimeout(fadeEvent);
	clearTimeout(setIconEvent);
	if (currentIcon!==layerName) {
		if (layerName=='icon01') {
			addT=-30; addL=-80; hideIt('icon02'); hideIt('icon03'); hideIt('icon04');
		} else if (layerName=='icon02') {
			addT=-30; addL=-63; hideIt('icon01'); hideIt('icon03'); hideIt('icon04');
		} else if (layerName=='icon03') {
			addT=-30; addL=-75; hideIt('icon01'); hideIt('icon02'); hideIt('icon04');
		} else if (layerName=='icon04') {
			addT=-30; addL=-75; hideIt('icon01'); hideIt('icon02'); hideIt('icon03');
		} else if (layerName=='icon05') {
			// no need to hide other icons
			addT=-37; addL=-180;
		};
		setPosition(location,layerName,addT,addL);
		new Effect.Appear(layerName,{duration:0.5});
	}
	fadeEvent = window.setTimeout('Effect.Fade(\''+layerName+'\', {duration:0.3})',6500);
	setIconEvent = window.setTimeout(setIcon,6500);
	currentIcon = layerName;
}
function setIcon() {
	currentIcon = '';
}

var currentPopup = '';
var currentBox = '';
var newX = 0;
var newY = 0;

function popUpBox(targetObj,targetPos,message,killTarget) {
	if (killTarget!=='') {
		new Effect.Fade(killTarget, {duration:0});
	};
	// if rollOver happens, clear any timeout action
	if (currentPopup!=='' && currentBox==targetObj) {
		clearTimeout(currentPopup);
		currentPopup = '';
	} else {
		currentBox = targetObj;
		$(targetObj).update('<div>'+message+'</div>');
		var coors = findPos(targetPos);
		var objectWidth = $(targetObj).getWidth()/2;
		var locationWidth = $(targetPos).getWidth()/2;
		newX = coors[0]+locationWidth-objectWidth;
		newY = coors[1]-90;
		setPosition(targetPos,targetObj,newY,newX);
		new Effect.Appear(targetObj, {duration:0.3});
		new Effect.Move(targetObj, {
			x:0, y:30, mode:'relative',
			transition: Effect.Transitions.spring
		});
	};
}
function popOutBox(targetObj) {
	currentPopup = window.setTimeout("fadePopup('"+targetObj+"')",3000);
}
function fadePopup(targetObj) {
	if ($(targetObj)) {
		if (currentPopup!=='' && $(targetObj).style.display!=='none') {
			currentPopup = '';
			new Effect.Fade(targetObj, {duration:0.5});
			new Effect.Move(targetObj, {x:0,y:-30,mode:'relative'});
		};
	};
}

// submenu things
function setPosition(targetPos,targetObj,addT,addL) {
	// add back the dollar sign
	var targetPosition = $(targetPos);
	var coors = findPos(targetPosition);
	var x = $(targetObj);
	x.style.top = (coors[1]+addT) + 'px';
	x.style.left = (coors[0]+addL) + 'px';
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}

function setWidth(target,pixel) {
	$(target).style.width = pixel+'px';
}
function setHeight(target,pixel) {
	$(target).style.height = pixel+'px';
}

// common DIV control
function hideIt(obj) {
	if ($(obj)) {
		$(obj).hide();
	}
}
function showIt(obj) {
	if ($(obj)) {
		$(obj).show();
	}
}
function fadeIn(obj) {
	if ($(obj).style.display=='none') {
		new Effect.Appear(obj);
	}
}
function switchContents(hideItem,showItem) {
	hideIt(hideItem);
	Effect.Appear(showItem,{duration:0.5});
}
function autoContents(boxContent) {
	if ($(boxContent).style.display=="none") {
		showIt(boxContent);
	} else {
		hideIt(boxContent);
	}
}
function autoFade(boxContent) {
	if ($(boxContent).style.display=="none") {
		new Effect.Appear(boxContent);
	} else {
		new Effect.Fade(boxContent,{duration:0.3});
	}
}
function autoSlide(boxContent) {
	if ($(boxContent).style.display=="none") {
		new Effect.SlideDown(boxContent);
	} else {
		new Effect.SlideUp(boxContent,{duration:0.3});
	}
}

// submenus and icons
// !!! must work with Lightbox Scripts
function openSubs(submenuName,location,setX,setY) {
	if (!setX) { setX=-40; };
	if (!setY) { setY=-20; };
	if ($(submenuName).style.display=='none') {
		setPosition(location,submenuName,setX,setY);
		new Effect.Appear(submenuName,{duration:0.3});
		// add overlay
		var objBody = document.getElementsByTagName("body").item(0);
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlayOnMenu');
		objOverlay.style.display = 'none';
		objOverlay.onclick = function() { hideIt('overlayOnMenu'); Effect.Fade(submenuName,{duration:0.2}); killOverlay(); return false; }
		objBody.appendChild(objOverlay);
		var arrayPageSize = getPageSize();
		$('overlayOnMenu').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
		new Effect.Appear('overlayOnMenu', { duration: 0.05, from: 0.0, to: 0.1 });
	} else {
		new Effect.Fade(submenuName,{duration:0.2});
		hideIt('overlayOnMenu');
		killOverlay();
	}
}
function killOverlay () {
	var thisObj = 	$("overlayOnMenu");
	thisObj.parentNode.removeChild(thisObj);
}

function itemOn(targetItem) {
	$(targetItem).style.borderTop = '1px solid #fff';
	$(targetItem).style.borderLeft = '7px solid #fff';
	$(targetItem).style.borderBottom = '1px solid #fff';
}
function itemOff(targetItem) {
	$(targetItem).style.borderTop = '1px solid #d1e0ec';
	$(targetItem).style.borderLeft = '7px solid #d1e0ec';
	$(targetItem).style.borderBottom = '1px solid #d1e0ec';
}
function selectItem(targetItem,targetCheckbox,checkBox) {
	if (checkBox) {
		if ($(targetCheckbox).checked==true) {
			itemOn(targetItem);
		} else {
		itemOff(targetItem);
		}
	} else {
		if ($(targetCheckbox).checked==false) {
			itemOn(targetItem);
			$(targetCheckbox).checked = true;
		} else {
			itemOff(targetItem);
			$(targetCheckbox).checked = false;
		}
	}
}
function closeItem(itemName) {
	if (itemName) {
		groupName = itemName+'_group';
		if ($(groupName)) {
			$(groupName).style.display = 'none';
		}
		groupName2 = 'd'+itemName+'_group';
		if ($(groupName2)) {
			$(groupName2).style.display = 'none';
		}
	}
}

function setFormValue(targetName,assignValue) {
	targetName.value = assignValue;
}

function fadeListItems(itemArray) {
	eachItem = itemArray.split(",");
	for (i=0;i<eachItem.length;i++) {
		var thisTime = 75*i+1;
		setTimeout('Effect.Appear(\''+eachItem[i]+'\',{duration:0.25})',thisTime);
	}
}

// jump
// remember this line in the end of the HTML
// <div><a name="end" id="end"></a></div>
var Mac = navigator.appVersion.indexOf('Mac',0) != -1;
var Win = navigator.appVersion.indexOf('Win',0) != -1;
var IE  = navigator.appName.indexOf("Microsoft Internet Explorer",0) != -1;
var NN  = navigator.appName.indexOf("Netscape",0) != -1;
var Moz = navigator.userAgent.indexOf("Gecko") != -1;
var Vmajor = parseInt(navigator.appVersion); // ex. 3
var Vminor = parseFloat(navigator.appVersion); // ex. 3.01
var WinIE = (Win && IE);
var MacIE5 = ((Mac && navigator.appVersion.indexOf('MSIE 5',0) != -1) || (Mac && IE && VER > 4));
var MacIE4 = ((Mac && navigator.appVersion.indexOf('MSIE 4.',0) != -1));
var MacIE3 = ((Mac && navigator.appVersion.indexOf('MSIE 3.',0) != -1));
var bAgent = navigator.userAgent;
var d = document;

function sniffer(){
	this.Win = bAgent.indexOf("Win",0) != -1 ? 1 :0;
	this.Mac = bAgent.indexOf("Mac",0) != -1 ? 1 :0;
	this.Moz = ((bAgent.indexOf("Gecko") != -1) && (bAgent.indexOf("Safari",0) == -1)) ? 1 :0;
	this.OPERA = bAgent.indexOf("Opera",0) != -1 ? 1 :0;
	this.SAFARI = bAgent.indexOf("Safari",0) != -1 ? 1 :0;
	this.checkObj = d.all?(d.getElementById?3:2):(d.getElementById?4:(d.layers?1:0));
	this.allObj = ((this.checkObj == 1) || (this.checkObj == 2) || (this.checkObj == 3) || (this.checkObj == 4));
	return this;
}
var usr = new sniffer;
function getWindowHeight(){
	if(usr.Mac && (usr.checkObj == 1 || usr.OPERA)){
		return window.innerHeight;
	}else if(usr.Win && usr.checkObj == 1){
		return window.innerHeight - 16;
	}else if(usr.checkObj == 4){
		return window.innerHeight - 15;
	}else if(usr.OPERA || usr.checkObj == 2 || usr.checkObj == 3){
		return d.body.clientHeight;
	}
}

function getWindowXOffset(){
	if(usr.checkObj == 2 || usr.checkObj == 3){
		return d.body.scrollLeft;
	}else if(usr.checkObj == 1 || usr.checkObj == 4){
		return window.pageXOffset;
	}
}
function getWindowYOffset(){
	if(usr.checkObj == 2 || usr.checkObj == 3){
		return d.body.scrollTop;
	}else if(usr.checkObj == 1 || usr.checkObj == 4){
		return window.pageYOffset;
	}
}

function getDocHeight(){
	if(usr.checkObj == 1){
		return getTagTop('end') + 1;
	}else if(usr.checkObj == 2 || usr.checkObj == 3 || usr.checkObj == 4){
		return getTagTop('end');
	}
}
function getDistanceMaxY(){
	if(usr.allObj){
		return (getDocHeight() - getWindowHeight());
	}
}
function setObj(idName){
	return d.all ? d.all(idName) : d.getElementById ? d.getElementById(idName) : d.layers[idName];
}
function getTagTop(idName) {
	var obj = setObj(idName);
	var tagCoords = new Object();
	if((usr.checkObj == 2) || (usr.checkObj == 3) || (usr.checkObj == 4)) {
		tagCoords.y = obj.offsetTop;
		while ((obj = obj.offsetParent) != null) {
			tagCoords.y += obj.offsetTop;
		}if(usr.Mac && usr.Moz){
			return tagCoords.y - 12;
		}else if((usr.Win && usr.Moz) || (usr.Mac && usr.SAFARI)){
			return tagCoords.y - 9;
		}else{
			return tagCoords.y;
		}
	} else if(usr.checkObj == 1) {
		tagCoords.y = d.anchors[idName].y;
		return tagCoords.y;
	}
	return idName;
}

/*PageScroller*/
var pageScrollTimer;
function pageScroll(toX,toY,frms,frX,frY) {
	if(pageScrollTimer) clearTimeout(pageScrollTimer);
	var spd = usr.Mac ? 14 :16;
	var actX = getWindowXOffset();
	var actY = getWindowYOffset();
	if(!toX || toX < 0) toX = 0;
	if(!toY || toY < 0) toY = 0;
	if(!frms) frms = usr.NN ? 10 :usr.Mac ? 4 :5;
	if(!frX) frX = 0 + actX;
	if(!frY) frY = 0 + actY;

	frX += (toX - actX) / frms;
	if (frX < 0) frX = 0;
	frY += (toY - actY) / frms;
	if (frY < 0) frY = 0;
	var posX = Math.ceil(frX);
	var posY = Math.ceil(frY);
	window.scrollTo(posX, posY);
	if((Math.floor(Math.abs(actX - toX)) < 1) && (Math.floor(Math.abs(actY - toY)) < 1)){
		clearTimeout(pageScrollTimer);
		window.scroll(toX,toY);
	}else if(posX != toX || posY != toY){
		pageScrollTimer = setTimeout("pageScroll("+toX+","+toY+","+frms+","+frX+","+frY+")",spd);
	}else{
		clearTimeout(pageScrollTimer);
	}
}

function jumpToAnchor(idName) {
	if(usr.allObj){
		if(!!idName){
			var anchorY = getTagTop(idName);
			var dMaxY = getDistanceMaxY();
			var setY = (anchorY<1)?0:(anchorY>dMaxY)?dMaxY:anchorY;
			if(anchorY>1){
				pageScroll(0,setY);
			}else if(anchorY<=1){
				pageScroll(0,0);
			}else{
				location.hash = idName;
			}
		}else{
			pageScroll(0,0);
		}
	}else{
		!!idName ? location.hash = idName : location.hash = "top";
	}
}
function jumpToPageTop() {
	if(usr.allObj){
		pageScroll(0,0);
	}else{
		!!idName ? location.hash = idName : location.hash = "top";
	}
}

function timeElapsed(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 365 )
		return;
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 13 && "1 week ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
		day_diff < 59 && "1 month ago";
}

// remove all special characters
function stripMessage(message) {
	message = encodeURIComponent(message);
	message = message.replace(/\+/ig, "%2b");
	message = message.replace(/\~/ig, "%7E");
	message = message.replace(/\!/ig, "%21");
	message = message.replace(/\(/ig, "%28");
	message = message.replace(/\)/ig, "%29");
	message = message.replace(/\'/ig, "%27");
	return message;
}

function isNumeric(strString) {
	var strValidChars = "0123456789.-";
	var strChar;
	var blnResult = true;
	if (strString.length == 0) return false;
	for (i = 0; i < strString.length && blnResult == true; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			blnResult = false;
		}
	}
	return blnResult;
}

function startWarning(text,fadeOut) {
	if ($('warningLine')) {
		$('warningLine').show();
		$('warningLine').childNodes[0].update(text);
		if (fadeOut=='true') {
			fadeOutWarning();
		};
	} else {
		alert(text);
	}
}
function fadeOutWarning() {
	if ($('warningLine')) {
		window.setTimeout("Effect.SlideUp('warningLine',{duration:0.5})",5000);
	};
}
function closeWarning() {
	new Effect.SlideUp('warningLine',{duration:0.5})
}

function checkLogin(state,inputField) {
	if (state=='focus') {
		if ($(inputField).value=='') {
			changeStyle(inputField+'Login','focus');
		} else {
			changeStyle(inputField+'Login','hasText');
		}
	} else if (state=='blur') {
		if ($(inputField).value=='') {
			changeStyle(inputField+'Login','');
		};
	};
}
function goLogin() {
	if (document.loginBox.username.value=='' || document.loginBox.password.value=='') {
		new Effect.Shake('sidePersonal',{distance:5});
		$("loginProcess").innerHTML = 'Missing fields detected. Please fill all in.';
	} else {
		new Ajax.Request(globalSiteURL+'/'+AJAXfile+'-ajax-login.php', {
			method: 'POST',
			parameters: {
				loginMethod:'ajax',
				username: document.loginBox.username.value,
				password: document.loginBox.password.value
			},
			onCreate: function() {
				$('loginProcess').update('. . . . . . .....');
			},
			onSuccess: function(transport) {
				if (transport.responseText=='success') {
					$("loginProcess").update('Processing...');
					window.location = $("loginLocation").value;
				} else {
					new Effect.Shake('sidePersonal',{distance:5});
					$("loginProcess").update('Login failed. Please try again.');
				}
			}
		});
	}
}

// get user info on the side bar
function getUserinfo(username,info) {
	new Ajax.Updater("userinfoArea", globalSiteURL+'/'+AJAXfile+'-ajax-getUserinfo.php', {
		method: 'GET',
		parameters: { username: username, info: info },
		onCreate: function() {
			hideIt("userinfoArea"); showIt("userinfoLoad");
		},
		onSuccess: function() {
			hideIt("userinfoLoad"); showIt("userinfoArea");
		}
     });
}

// get member listing
function getMemberList(memberToList,letter,page) {
	jumpToPageTop();
	new Ajax.Request(globalSiteURL+'/'+AJAXfile+'-ajax-getMemberList.php', {
		method: 'POST',
		parameters: { memberToList: memberToList, letter: letter, p: page },
		onCreate: function() {
			$("memberListBox").update('Refreshing list...');
		},
		onSuccess: function(transport) {
			$("memberListBox").update(transport.responseText);
			fadeListItems($("fadeItems").innerHTML);
		}
	});
}

// signup
function signup() {
	if ($('signupUsername').value=='' || $('signupName').value=='' || $('signupEmail').value=='' || $('signupPassword').value=='' || $('signupConfirm').value=='') {
		alert('Please fill in every field to continue.');
	} else if ($('signupPassword').value!==$('signupConfirm').value) {
		alert('Your passwords do not match. Please check again.');
	} else {
		showIt('infoBox');
		new Ajax.Request(globalSiteURL+'/'+AJAXfile+'-ajax-signup.php', {
			method: 'POST',
			parameters: {
				username: $("signupUsername").value,
				name: $("signupName").value,
				email: $("signupEmail").value,
				password: $("signupPassword").value
			},
			onCreate: function() {
				$("infoLine").innerHTML = 'Processing...';
			},
			onSuccess: function(transport) {
				$("infoLine").innerHTML = transport.responseText;
			}
		});
	}
}

function changeStyle(targetObj,targetStyle) {
	$(targetObj).className = targetStyle;
}

// add to bookmark - for members only
// but put here because some other pages have it
function addToBM(thisLink) {
	new Ajax.Request(globalSiteURL+'/'+AJAXfile+'-ajax-wingsBook.php', {
		method: 'POST',
		parameters: {
			addAction: 'quickadd',
			addLink: thisLink
		},
		onSuccess: function(transport) {
			if (transport.responseText=='done') {
				alert('Bookmark added.');
			} else {
				alert('Cannot add your bookmark, please try again.');
			};
		}
	});
}

function getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	return [pageWidth,pageHeight];
}