// JavaScript Document

$j = jQuery.noConflict();

//in_array function
Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}

//loop function
Array.prototype.loop = function(iterator) {
    for (var i = 0, length = this.length; i < length; i++){
      iterator(this[i]);
  	}
}

function OnEnter(e)
{
	var keycode = '';
	
	//for IE
	if(isInternetExplorer)	{
		keycode = e.keyCode;
	} else {
		if(e.which){
			keycode = e.which;	
		}
	}
	
	//on Enter
	if(keycode == 13){
		return true;		
	} else {
		return false;	
	}
}

var isInternetExplorer = (navigator.appName.indexOf("Microsoft") != -1);
var isSafari = navigator.userAgent.indexOf("Safari") != -1 

function ShowBox(id){

	if($j(id).css("display") == "none"){
		$j(id).fadeIn("normal");
	} else {
		$j(id).fadeOut("fast");
	}

}

function SlideBox(id){

	if($j(id).css("display") == "none"){
		$j(id).slideDown("normal");
	} else {
		$j(id).slideUp("fast");
	}

}


//Show div only
function Show(id){
	if($j(id).css("display") == "none"){
		$j(id).fadeIn("normal");
	}
}

//Hide div only
function Hide(id){
	if($j(id).css("display") == "block"){
		$j(id).fadeOut("fast");

	}
}

//Check email function 
function EmailValidate(value){

	/* Not working for this format: someone@company.co.nz, the fix is below.
	var pattern = /^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,4})$/i;
	*/
	var pattern = /^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,4})(\.([a-z]{2,4}))*$/i;
	return (pattern.test(value)) ? true : false;

}

function IsEmpty(value){
	
	var pattern = /.+/;
	return (pattern.test(value)) ? false : true;
	
}

function IsNumeric(value){
	
	var pattern = /^\d+$/;
	return (pattern.test(value)) ? true : false;
	
}

function IsAlphabet(value){
	
	var pattern = /^[a-z]+$/i;
	return (pattern.test(value)) ? true : false;
	
}

function IsAlphaNumeric(value){
	
	var pattern = /^[a-zA-Z\d]+$/;
	return (pattern.test(value)) ? true : false;
	
}

function DateValidate(value, type){
	
	var pattern = '';
	
	if(type == "") type = "dd/mm/yyyy";
	
	if(type == "dd/mm/yyyy")
		pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
	
			
	return (pattern.test(value)) ? true : false;
	
}

//function to check if the input type radio or checkbox is checked
function IsChecked(input) {

	var checked = false;
	var len = input.length;
	if(len < 0) return false;
	if(typeof(len) == 'undefined'){
		if(input.checked)
			checked = true;
	} else {
		for(i=0;i<len;i++){
			if(input[i].checked){
				checked = true;
				break;
			}
		}
	}
	
	return checked;
	
}

//function to return value of the checked radio button or checkbox
function CheckedValue(input){

	var len = input.length;
	var val = [];
	if(typeof(len) == 'undefined'){
		if(input.checked)
		val.push(input.value);
	} else {
		for(i=0;i<len;i++){
			if(input[i].checked){
				val.push(input[i].value);
			}
		}	
	}
	return val;
	
}

//function to return value of the selected item in a select dropdown box
function SelectedValue(input){

	var len = input.length;
	var val = [];
	for(i=0;i<len;i++){
		if(input[i].selected){
			val.push(input[i].value);
		}
	}
	return val;
	
}


//Function to count line breaks and character
//Adapted from http://www.demodirectory.com/scripts/common.js

function countLineBreaks(obj){
	var iLength = obj.value.length;
	
	var strLineBreaks = obj.value.match(new RegExp("(\\n)", "g"));
	var countLineBreaks = strLineBreaks ? strLineBreaks.length : 0;
	return countLineBreaks;
}

// function to count total characters in text area
//Adapted from http://www.demodirectory.com/scripts/common.js

function textCounter(field, counter_field, maxlimit) {
	
	var lineBreaks = countLineBreaks(field);
	
	var adjust = (isInternetExplorer) ? 1 : 0;
	if (field.value.length - lineBreaks * adjust > maxlimit){
		field.value = field.value.substring(0, maxlimit + lineBreaks * adjust);
		field.focus();
	} else {
		counter_field.value = maxlimit - field.value.length + lineBreaks * adjust;
	}
}


/* Simple Form Validator Script 
** Author : K.Wong (Mediasphere June 2008)
*/

VForm = { 
	id:'VForm',
	msg: '', 
	name:'',
	t:0, 
	show: function(f){

		
		if(!IsEmpty(this.msg)) {
			
			$j('#'+this.name+"_error").css({display:"block"});
			$j('#'+this.name+"_error").html('<span class="errorBText">'+this.msg+'</span>');
			if(f.elements[this.name]){
				f.elements[this.name].focus();
				//f.elements[this.name].className = 'inputerror';
			}
			$j('#'+this.id+'_error').css({display:"block", visibility:"visible", color:"#FF0000"});
			$j('#'+this.id+'_error').html('<span class="errorBText">Input Error: '+this.msg+'</span>');
			this.t = setTimeout("$j('#"+this.id+"_error').slideUp()",10000);
			
		} 

	},
	clearAll: function(f) {
		
		clearTimeout(this.t);
		
		for(var i=0; i<f.elements.length;i++){
			
			//replace [] for multiple select
			elid = '#'+f.elements[i].name;
			
			el = elid.replace(/\[|\]/g, '');
			el += "_error";
			
			if($j(el) && !IsEmpty($j(el).html()))
				$j(el).css({display:"none"});
			/*
			if($j('#'+f.elements[i].name+"_error") && !IsEmpty($j('#'+f.elements[i].name+"_error").innerHTML))
				$j('#'+f.elements[i].name+"_error").css({display:"none"});
			*/	
			//if(f.elements[i].type == 'text' || f.elements[i].type == 'select-one') f.elements[i].className = '';	
			
		}
		$j('#'+this.id+'_error').html('');
		$j('#'+this.id+'_error').css({ display:"none"});
		
		
	}
};


function Validator() {
	
	var validator = $j.extend(true, {}, VForm);
	return validator;

}

//function to launch Popup
function launchObject(filename, path, name, height, width, fullscreen, resize) {
  
	var str = '';
	var source = path.replace(/\//gi,"|");
	
	if(fullscreen) {
		str += "fullscreen=yes, scrollbars=no, resizable=no";
	
	
	} else {
		str += "height=" + height + ",innerHeight=" + height;
		str += ",width=" + width + ",innerWidth=" + width;
		str += ", scrollbars=yes";
		if(resize) str += ", resizable=yes";
		else str+= ", resizable=no";
	}
	
	if (window.screen) {
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;
		
		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;
		
		str += ",left=" + xc + ",screenX=" + xc;
		str += ",top=" + yc + ",screenY=" + yc;
	}
	
	var url = "/launchObject.php?objectname="+filename+"&path="+source;
	if(fullscreen) url += "&fs=1";
	
	url += "&width="+width+"&height="+height;
	
	return window.open(url, name, str);

}


function launchPopup(url, name, height, width){

	var str = '';
	str += "height=" + height + ",innerHeight=" + height;
	str += ",width=" + width + ",innerWidth=" + width;
	str += ",scrollbars=yes,resizable=no";

	if (window.screen) {
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;
		
		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;
		
		str += ",left=" + xc + ",screenX=" + xc;
		str += ",top=" + yc + ",screenY=" + yc;
	}
	
	name = name.replace(/\s/gi, "_");
	
	return window.open(url, name, str);
	
	
}

function RequestPassword(f){
	
	if(!EmailValidate(f.elements["email"].value)){
		
		$j('#forgotPasswordDiv').html("Email is invalid");
		
	} else {
		
		f.submit();
	}
	
	
}

//Function to add Bookmark, only work for IE and FireFox, not working for Safari
function addBookmark(title,url) {
	
	if(navigator.userAgent.indexOf("Safari") != -1){
		void(prompt(title,url));
	} else if (window.sidebar) { 
		window.sidebar.addPanel(title, url,""); 
	} else if( document.all ) {
		window.external.AddFavorite( url, title);
	} else if( window.opera && window.print ) {
		//alert("safari")
		return true;
	}
}


//Message Box
//Version 0.1
//Author : K.wong (Mediasphere Pty Ltd)
//Need a lot of improvement, but works for now.
//Use: MsgBox.Show('message');
var MsgBox = {

	div: '',
	id: '_KalMsgBox_',
	bg: 'transparent url(/templates/default/img/infobg.jpg) repeat-x 0 0',
	height: '40px',
	
	Init:function() {

		this.div = '<div id="'+this.id+'"></div>';
		$j("body").prepend(this.div);
		$j('#'+this.id).css({
			position:'fixed',
			top:this.GetTop() + "px",
			//bottom:'0px',
			left:'0px',
			width:'100%',
			height:'auto',
			zIndex:'9999',
			textAlign: 'center',
			fontWeight: 'bold',
			fontFamily: 'Tahoma',
			fontSize: '1.5em',
			display:'none'
		});
	},
	
	ShowText:function(msg){
	
		if(this.div == '')
			this.Init();
		
		if(msg != '' || msg.length > 0)	{
			this.DisplayText(msg);
		}
	
	},
	
	ShowHtml:function(msg){
	
		if(this.div == '')
			this.Init();
		
		if(msg != '' || msg.length > 0)	{
			this.DisplayHtml(msg);
		}
	
	},
	
	DisplayText:function(txt){
		
		$j('#'+this.id).css({
			height:this.height,
			background: this.bg
		});
		
		$j('#'+this.id).html('<div style="padding:10px;">'+txt+'</div>');
		this.ShowMessage();
	
	},

	DisplayHtml:function(txt){
	
		//$j(this.div).html('<div style="padding:10px;">'+txt+'</div>');
		$j('#'+this.id).html(txt);
		this.ShowMessage();
	
	},

	ShowMessage:function(){
		this.SetTop();
		setTimeout("$j('#"+this.id+"').slideDown('fast', function(){ setTimeout(\"MsgBox.Remove()\",4000); });", 800);	
		
	},

	Remove:function(){
		//$j(this.div).slideUp("fast", function(){ this.div.remove(); });
		$j('#'+this.id).slideUp("fast");
	},
	
	GetTop:function(){
		//return isInternetExplorer ? document.documentElement.scrollTop : window.scrollY;	
		return 0;
	},
	
	SetTop:function(){
		//alert(this.GetTop());
		$j('#'+this.id).css({top: this.GetTop() + "px"});
	}

}


var Cookie = {
	
	cookies: [],
	
	Init: function(){
	
		this.readCookie();
	},
	
	readCookie: function(){
		
		var thiscookie = document.cookie;
		
		if(thiscookie != "") {
			
			var mycookies = thiscookie.split(";");
			for(var i = 0; i < mycookies.length; i++){
				var temp = mycookies[i].split("=");
				var name = temp[0];
				var val = temp[1];
				this.cookies[name] = val;
			}
		}
	},
	
	setCookie: function(obj){
		
		
		var on = new Date(); on.setDate(on.getDate()+30);
		var off = new Date(); off.setDate(off.getDate()-1);
		
		var add = "expires="+on.toGMTString()+";";
		var remove = "expires="+off.toGMTString()+";";
		
		var path = obj.path == '' ? "path=/;" : "path=" + obj.path + ";";
		path = path.replace("http://"+document.domain, '');
		
		if(obj.status == 1){
			//write the cookie
			document.cookie = obj.name+"="+obj.value+";" + add + path;		
		} else {
			//delete the cookie	
			document.cookie = obj.name+"="+obj.value+";" + remove + path ;			
		}
	},
	
	exists: function(cookiename){
		this.Init(); 
		return (typeof(this.cookies[cookiename]) != 'undefined') ? true : false;
	},
	
	value: function(cookiename){
	
		this.Init();
		return this.exists(cookiename) ? this.cookies[cookiename] : '';
		
	}
	
	
}

function jd(data){
	return eval('(' + data + ')');	
}
