/*
*	LET THE JAVASCRIPT NOOBNESS BEGIN!
*	Everything (c) LifeLogger.com
*
*	Todo
*	===========================
*	1) Learn Javascript
*/


/*
*	SHARED VARS
*/
var LI = document.getElementsByTagName('li');
var DIV = document.getElementsByTagName('div');
var SPAN = document.getElementsByTagName('span');
var process = true;
var blurTabs = true;
var targetElement;
var targ;
var okdtarg;
var tabclicked;
var pg = 1;

/*
*	ON PAGE LOAD
*/
function onPageLoad() {
	// detect if any onclick happened
	document.onclick = onClick;
	document.onsubmit = onSubmit;

	// load default ajax sections on pageload
	loadDefaultAjax();
	loadSearchForm();

	// grab default stuff
	ajax('get_messages', 'getPMCount', '', '');
	ajax('get_friendrequests', 'getFriendRequests', '', '');

	// preload loading.gif
	loadImage = new Image();
	loadImage.src = 'http://blog.my.com.my/common/images/loading.gif';

}

function onSubmit() {
	if(document.getElementById('spinner')) {
		toggleMsg('spinner', '<div class="loader"><img src="http://blog.my.com.my/common/images/loading.gif" alt="" class="loading" /></div>');
	}
	return true;
}

/*
*	SEARCH FORM
*
*/
function loadSearchForm() {
	// set search form's channel value
	if(document.getElementById('sechannel')) {
		targ = 'sechannel';
		onClick();
	}
}

/*
*	CHAR COUNT
*/
function charcount(maxchar, formname, fieldname) {
	if(document.forms[formname].elements[fieldname].value.length > maxchar) {
		document.forms[formname].elements[fieldname].value = document.forms[formname].elements[fieldname].value.substring(0,maxchar);
	}
	textlength = document.forms[formname].elements[fieldname].value.length;
	textremain = maxchar - textlength;
	document.getElementById('charcount').innerHTML = textremain;
}

/*
*	DEFAULT AJAX LOADS
*/
function loadDefaultAjax() {
	// loop through each one to find the ajax loaders
	for (var i = 0; i < LI.length; ++i) {
		if(process == true) {
			// check if the tab is default
			splat = LI[i].id.split('_');

			// if default is true, then load ajax for this tab
			if(splat[4] == 'd') {
				// get proper vars from the ID
				if(splat[2]) var3 = splat[2];

				// since this is the initial load, only do ajax when the div is empty
				if(document.getElementById(var3).innerHTML == '') {
					// set process to false so that it waits until
					// ... the previous function is finished (which will then set it to true)
					process = false;
					// set the target ID
					targ = LI[i].id;
					// simulate onClick
					onClick();
				}
			}
		}
	}
}

/*
*	SET NOFOCUS TO TABS (only if blurTabs flag value is true)
*/
function setNoFocus() {
	var browser = navigator.appName;

	// to hell with IE
	if(browser != 'Microsoft Internet Explorer') {
		if(blurTabs == true) {
			for (var i = 0; i < LI.length; ++i) {
				splat = LI[i].id.split('_');

				// set nofocus
				if(splat[0] == 'tab') if(LI[i].childNodes[0]) LI[i].childNodes[0].onfocus = blurLink;
				if(splat[0] == 'nav') if(LI[i].childNodes[1]) LI[i].childNodes[1].onfocus = blurLink;
			}
			for (var i = 0; i < SPAN.length; ++i) {
				splater = SPAN[i].id.split('_');

				// set nofocus
				if(splater[0] == 'link') if(SPAN[i].childNodes[0]) SPAN[i].childNodes[0].onfocus = blurLink;
			}
		}
	}
}
// Utility to help setNoFocus()
function blurLink() {
	if(this.blur) this.blur();
}

/*
*	ONCLICK EVENTS MANAGER (will be triggered whenever clicking happens)
*/
function onClick(e) {
	// get the ID of affected element
	if(!targ) {
		if (!e) var e = window.event;
		if (e.target) targ = e.target.parentNode.id;
		else if (e.srcElement) targ = e.srcElement.parentNode.id;
		if(targ) if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode.id;
		tabclicked = true;
	}
	else tabclicked = false;

	// get the element of targeted ID
	if(targ) targetElement = document.getElementById(targ);

	// check if element exists (hence valid request)
	if(targetElement != '') {

		// implode the ID to get some values
		splat = targ.split('_');

		// get proper vars from the ID
		if(splat[0]) var var1 = splat[0];
		if(splat[1]) var var2 = splat[1];
		if(splat[2]) var var3 = splat[2];
		if(splat[3]) var var4 = splat[3];
		if(splat[4]) var var5 = splat[4];
		if(splat[5]) var var6 = splat[5];

		// set page value if available
		if(var5 == 'page') var page = var6;

		// action = var3 + var4
		if(var3 && var4) var action = var3 + '_' + var4;

		// unset targ (not being used after this line), targ is only useful for initial ajax loads
		if(targ) targ = '';

		// check if it's an ajax request, run ajax if true
		if(var2 == 'ajax') {
			// check if page value available, and pass as condition
			if(page) {
				cond = '&page=' + page;
				ajax(var3, action, cond);
			}
			else ajax(var3, action);
		}

		if(var2 == 'tips') {
			if(var3 == 'next') request = pg + 1;
			if(var3 == 'prev') request = pg - 1;
			
			// check if request is valid
			requestid = 'pg_' + request;
			if(!document.getElementById(requestid)) {
				return false;
			}
			else {
				pg = request;
			}
			
			// close other tips
			for (var i = 0; i < DIV.length; ++i) {
				// check if the tab is default
				splat = DIV[i].id.split('_');
				if(splat[0] == 'pg') DIV[i].style.display = 'none';
			}
			
			// show current tip
			current = 'pg_' + pg;
			if(document.getElementById(current)) Effect.Appear(current);
			
			// determine whether there's a next tip
			nexttip = 'pg_' + (pg+1);
			if(document.getElementById(nexttip)) document.getElementById('link_tips_next').innerHTML = '<a href="#" class="right" onfocus="this.blur()">more &raquo;</a></span>';
			else  document.getElementById('link_tips_next').innerHTML = '<span class="blur right">more &raquo;</span>';
			
			// determine whether there's a prev tip
			prevtip = 'pg_' + (pg-1);
			if(document.getElementById(prevtip)) document.getElementById('link_tips_prev').innerHTML = '<a href="#" class="left" onfocus="this.blur()">&laquo; back</a></span>';
			else  document.getElementById('link_tips_prev').innerHTML = '<span class="blur left">&laquo; back</span>';
		}

		// toggle objects
		if(var2 == 'toggle') {
			if(document.getElementById(var4)) proToggler(var4, var3);
		}

		// toggle objects
		if(var2 == 'stoggle') {
			if(document.getElementById(var4)) proStoggler(var4, var3);
		}

		// unset vars and return false
		if(var1) {
			// unset them!
			var1 = '';
			var2 = '';
			var3 = '';
			var4 = '';
			var5 = '';
			var6 = '';
			action = '';
			targetElement = '';

			return false;
		}

		targetElement = '';
	}
}

/*
*	HIDE/SHOW LAYERS
*/
function proToggler(id, defaultClassName) {
	obj = document.getElementById(id);

	// if layer is hidden, open it
	if(obj.className != defaultClassName) {

		// close all other layers in the same var3
		for (var i = 0; i < LI.length; ++i) {
			splat = LI[i].id.split('_');
			if(splat[2] == defaultClassName) {
				objabc = document.getElementById(splat[3]);
				if(objabc) objabc.className = 'hidden';
			}
		}
		for (var i = 0; i < DIV.length; ++i) {
			splat = DIV[i].id.split('_');
			if(splat[2] == defaultClassName) {
				objdef = document.getElementById(splat[3]);
				if(objdef) objdef.className = 'hidden';
			}
		}
		for (var i = 0; i < SPAN.length; ++i) {
			splat = SPAN[i].id.split('_');
			if(splat[2] == defaultClassName) {
				objghi = document.getElementById(splat[3]);
				if(objghi) objghi.className = 'hidden';
			}
		}

		// open the current requested layer
		obj.className = defaultClassName;
	}
	// if layer is open, set hide
	else obj.className = 'hidden';
}

/*
*	HIDE/SHOW LAYERS SPECIAL
*/
function proStoggler(id, defaultClassName) {
	obj = document.getElementById(id);

	// if layer is hidden, open it
	if(obj.className != defaultClassName) {

		// close all other layers in the same var3
		for (var i = 0; i < LI.length; ++i) {
			splat = LI[i].id.split('_');
			if(splat[2] == defaultClassName) {
				objabc = document.getElementById(splat[3]);
				if(objabc) {
					objabc.style.display = 'none';
					objabc.className = 'dummy';
				}
			}
		}
		for (var i = 0; i < DIV.length; ++i) {
			splat = DIV[i].id.split('_');
			if(splat[2] == defaultClassName) {
				objdef = document.getElementById(splat[3]);
				if(objdef) {
					objdef.style.display = 'none';
					objdef.className = 'dummy';
				}
			}
		}
		for (var i = 0; i < SPAN.length; ++i) {
			splat = SPAN[i].id.split('_');
			if(splat[2] == defaultClassName) {
				objghi = document.getElementById(splat[3]);
				if(objghi) {
					objghi.style.display = 'none';
					objghi.className = 'dummy';
				}
			}
		}

		// open the current requested layer
		obj.className = defaultClassName;
		Effect.Appear(id, {duration: 1});
	}
	// if layer is open, set hide
	else {
		obj.style.display = 'none';
		obj.className = 'dummy';
	}
}
function hide(id) {
	obj = document.getElementById(id);
	obj.style.display = "none";
}
function show(id) {
	obj = document.getElementById(id);
	obj.style.display = "";
}


/*
*	AJAX LOADER (loads all ajax functions)
*/
function ajax(div, func, cond, toggle) {
	// check if any empty parameter
	if(div != '' && func != '') {
		// set params (if condition is passed, then add it)
		if(cond) params = 'var1=ajax&var2=' + func + cond + '&phpself=' + self;
		else params = 'var1=ajax&var2=' + func + '&phpself=' + self;

		if(self != '/') actionURL = self + '/';
		else actionURL = self;

		// grab element of the display div, to show content in this layer
		//if(document.getElementById(div)) displayBlock = document.getElementById(div);

		// show loading sign
		if(toggle == 'load') {
			toggleMsg(div, '<div class="loader"><img src="http://blog.my.com.my/common/images/loading.gif" alt="" class="loading" /></div>');
		}
		else if(toggle) {
			msg = toggle;
			toggleMsg(div, msg);
		}
		
		// do the ajax thing		
		new Ajax.Updater(div, actionURL, {
			asynchronous:true,
			method:'post',
			parameters: params,
			onSuccess: function(t) {
				// if there's response, insert into display block					
				//if(t.responseText != '') displayBlock.innerHTML = t.responseText;

				// if default load, process will be false. if so, set it back to true and run default ajax stuff again				
				if(process == false) {
					process = true;
					loadDefaultAjax();
				}
			}
		})
	}
	return false;
}

function copyUsername() {
	if(document.forms['signup']) {
		if(document.forms['signup'].elements['username'].value)
		document.getElementById('usernamecheck').innerHTML = document.forms['signup'].elements['username'].value;
	}
}

function checkUsernameAvailability() {
	username = document.forms['createblog'].elements['create_blog_username'].value;
	ischinese = false;
	
	for(i=0; i<username.length; i++)
	{		
		if(username.charCodeAt(i)>127)
		{			
			ischinese = true;			
		}		
	}

	if(ischinese){
		document.getElementById('useravail').innerHTML = "<span class=\"bad\">(E305) Sorry, the username '" + username + "' is not valid.</span>"
	}else{
		username = replacestring(username, '%', '%25');
		username = replacestring(username, '&', '%26');
		username = replacestring(username, '?', '%3F');	
		username = replacestring(username, '+', '%2B');	
		username = replacestring(username, '#', '%23');	
		
		cond = '&username=' + username + '&email=' + document.forms['createblog'].elements['email'].value + '&astroid=' + document.forms['createblog'].elements['astroid'].value;
		
		ajax('useravail', 'check_username', cond, '<div class="loader"><img src="http://blog.my.com.my/common/images/loading.gif" alt="" class="loading" /> Checking username...</div>');
	}
}

function checkPassword() {
	p1 = document.forms['signup'].elements['password'].value;
	p2 = document.forms['signup'].elements['password2'].value;

	// passwords match?
	if(p1 === p2) {
		if(p1.length < 6 || p1.length > 20)
		document.getElementById('checkpassword').innerHTML = '<span class="bad">Your password must contain between 6-20 characters.</span>';
		else
		document.getElementById('checkpassword').innerHTML = '<span class="good">Great! Passwords match, please go on.</span>';
	}
	else {
		document.getElementById('checkpassword').innerHTML = '<span class="bad">Sorry, your passwords don\'t match. Please try again.</span>';
	}
}

function checkEmail() {
	email = document.forms['signup'].elements['eadd'].value;
	if(email != '') document.getElementById('checkemail').innerHTML = '';
	else document.getElementById('checkemail').innerHTML = '<span class="bad">Email address is a compulsory field.</span>';
}

function checkTerms() {
	if(document.forms['signup'].elements['terms'].checked == 1) document.getElementById('checkterms').innerHTML = '';
	else document.getElementById('checkterms').innerHTML = '<span class="bad">Kindly confirm whether you agree with the Terms and Conditions.</span>';
}

/*
*	FUNCTION TO REPLACE STRING
*/
function replacestring(inputString, badString, goodString, caseSensitive) {
	fixedReplace = "";
	UI = inputString;
	UB = badString;
	if ((caseSensitive != 1) && (caseSensitive != true)) {
		UI = inputString.toUpperCase();
		UB = badString.toUpperCase();
	}
	badEnd = -1;
	badLoc = UI.indexOf(UB);
	if (badLoc != -1) {
		for (x=1; (badLoc != -1); x++) {
			fixedReplace = fixedReplace +
			inputString.substring((badEnd +
			1), badLoc) + goodString
			badEnd = badLoc + UB.length - 1;
			badLoc = UI.indexOf(UB, (badLoc + 1)); }
			fixedReplace = fixedReplace +
			inputString.substring((badEnd + 1),
			inputString.length); }
			else { fixedReplace = inputString;    }
			return fixedReplace;
};

/*
*	SHOW/HIDE LOADING MSG
*/
function toggleMsg(block, msg) {
	// the needed vars
	if(document.getElementById(block))
	var block = document.getElementById(block);

	// show loading sign
	if(msg) block.innerHTML = msg;
	// unset the loading msg
	else block.innerHTML = '';
}

/*
*	SELECT ALL
*/
function selectAll(theField) {
	sup = "document."+theField
	if(eval(sup)) {
		var tempval=eval(sup);
		tempval.focus();
		tempval.select();
	}
}

/*
*	WINDOWS ONLOAD
*/
window.onload = function() {
	if(window.fillup) fillup(); // tickerbar
	if(window.onPageLoad) onPageLoad();
	if(window.setNoFocus) setNoFocus();
	var myinterval = window.setInterval('copyUsername()',50); // check msg every x seconds
}

