// JavaScript Document
//$j = jQuery.noConflict();
$j = jQuery;

$j.fn.delay = function( time, name ) {
    return this.queue( ( name || "fx" ), function() {
        var delayself = this;
        setTimeout(function() { $j.dequeue(delayself); } , time );
    });
};

//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;
}

Array.prototype.indexOf = function(val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == val) {
			return i;
		}
	}
	return false; 
}

//loop function
Array.prototype.loop = function(iterator) {
    for (var i = 0, length = this.length; i < length; i++){
      iterator(this[i]);
  	}
}

jQuery.fn.removex = function(options) {
	var anim = options && options.anim ? options.anim : 250;
	var color = options && options.color ? options.color : '#ffff66';
	var delay = options && options.delay ? options.delay : 10;
	$j(this).css('background',color).animate(
		{opacity:1},
		delay,
		function() {
			$j(this).animate(
				{opacity:0},
				anim,
				function() {
					$j(this).remove();
				}
			);
		});
};
jQuery.fn.emptyx = function(options) {
	$j(this).children().removex(options);
};

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 
var ie = isInternetExplorer;
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){

	/* This is the pattern from Regular Expression Tester, FF AddOn. */
	var pattern = /^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/;
	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,
	f: '',
	err:false,
	callback: '',
	defaultmsg: 'Invalid input. Please check your input.',
	dialog: false,
	
	show: function(f){

		
		if(!IsEmpty(this.msg)) {
			
			if(this.dialog){
				Dialog(this.msg);
			} else {
				$j('#'+this.name+"_error").css({display:"block", visibility:"visible"});
				$j('#'+this.name+"_error").html('<span class="errorBText">'+this.msg+'</span>');
				$j("input[name='"+this.name+"']").focus();
				$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);
				return;
			}
		} 

	},
	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"});
		VForm.msg = [];
		
		
	},
	
	validate: function(f, callback){
		this.f = f;
		this.clearAll(f);
		var arr = $j.makeArray(f);
		this.err = false;

		for(var i=0;i < arr.length; i++){
			if($j(arr[i]).hasClass("Required")) {
				VForm.err = VForm.check($j(arr[i]));
				if(VForm.err) break;
			} else if($j(arr[i]).hasClass("EmailRequired")) {
				VForm.err = VForm.checkEmail($j(arr[i]));
				if(VForm.err) break;
			}
		}
		//console.log(this.err);
		if(!this.err) {
			if(callback) {
				callback(this.f);
			} else this.f.submit();
		} else{
			this.show(f);	
		}
	},
	
	check:function(obj){
		//obj = jquery object
		var val = false;
		switch(obj.attr("type")){
			case 'text' :
			case 'textarea' :
			case 'file' :
			if(IsEmpty(obj.val()))	val = true; 
			break;
			
			case 'checkbox' :
			case 'radio' :
			if(!obj.attr("checked")) val = true;
			break;
			
		}
		
		
		if(val){
			VForm.err = true;
			this.name = obj.attr("name");
			VForm.msg = obj.attr("alt") == '' ? VForm.defaultmsg : obj.attr("alt");
		} 
		
		return val;
	},
	
	checkEmail:function(obj){
		var val = false;
		if(IsEmpty(obj.val()) || !EmailValidate(obj.val())){
			VForm.err = true;
			VForm.msg = obj.attr("alt") == '' ? VForm.defaultmsg : obj.attr("alt");
			val = true;
			VForm.name = obj.attr("name");
		}
		
		return val;
	}
	
};


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/' + TEMPLATE_NAME + '/img/msgbox.ok.gif) no-repeat 0 0',
	height: '100px',
	
	Init:function() {

		this.div = '<div id="'+this.id+'"></div>';
		this.defaulttime = 4000;
		this.delaytime = 800;
		this.callback = '';
		$j("body").prepend(this.div);
		$j('#'+this.id).css({
			position:'absolute',
			top:this.GetTop() + "px",
			//bottom:'0px',
			left:'0px',
			width:'450px',
			zIndex:'9999',
			textAlign: 'left',
			fontWeight: 'bold',
			fontFamily: 'Tahoma',
			fontSize: '1.5em',
			display:'none',
			//filter: 'alpha(opacity=90)',
			//opacity: '.9'
			float: 'left'
		});
	},
	
	ShowText:function(msg, callback){
		//Original implementation	
		//this.ShowContent('text', msg, callback);
		Dialog(msg);
	},
	
	ShowHtml:function(msg, callback){
		//Original implementation	
		//this.ShowContent('html', msg, callback);
		Dialog(msg);
	},
	
	ShowContent: function(type, msg, callback){
		
		this.callback = callback || this.callback;
		this.time = this.defaulttime;
	
		//if(this.div == '')
			this.Init();
		
		if(msg != '' || msg.length > 0)	{
			if(type == 'text')
				this.DisplayText(msg);
			else if(type == 'html')
				this.DisplayHtml(msg);
			else
				this.DisplayText(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()\","+this.defaulttime+"); });", this.delaytime);	
		/*
		var self = this;
		$j('#'+self.id).delay(self.delaytime).slideDown('fast', function() {
			$j('#'+self.id).delay(self.time).slideUp('fast',function() {
				if(self.callback) eval(self.callback);
			});
		});
		*/
		
	},

	Remove:function(){
		//$j(this.div).slideUp("fast", function(){ this.div.remove(); });
		$j('#'+this.id).slideUp("fast").empty().remove();
		eval(this.cfunc);
	},
	
	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] : '';
		
	}
	
	
};

/* Render the rows with class "rowclass", of tables with class "tblclass" as odd and evn */
/*
function RenderRows(tblclass,rowclass,odd,evn) {
	
	var rc = rowclass || ".listrow";
	var tc = tblclass || ".list";
	var odd = odd || 'odd';
	var evn = evn || 'evn';
	
	$j(tc+' '+rc+':odd').each(function(i) {
		$j(this).addClass(odd);
	});
	$j(tc+' '+rc+':even').each(function(i) {
		$j(this).addClass(evn);
	});
	
}
*/
// checkbox select all function
// obj - the selectall checkbox
// selector - jquery selector for list checkboxes
function SelectAll(obj,selector) {
	if($j(obj).attr('checked'))
		$j(selector).attr('checked','checked');
	else
		$j(selector).removeAttr('checked');
}

function AddUploadRow(container,fieldname) {
	$j(container).append("<div class='addfile'><input type='file' name='"+fieldname+"[]' /></div>");
}


function AjaxLoad(container,url,params) {
	$j(container).load(url,params);
}

function jd(data) {
	return eval('('+data+')');
}

/* PHCMS Shadowbox 
Shortcut to open Shadowbox by javascript.
Call Shadowbox manually using script rather than a tag
Version 1.0
By K.Wong (Mediasphere 2009)

*/
var PHCMS_ShadowBox = {

	//manual option
	option 	: {
		option : { modal:false, animate:true, displayNav: true} , 
		settings : { player:'img', title:'Not Found', content: '', height:screen.availHeight, width:screen.availWidth} 
	},
	
	SetOptions : function(arg) {
	
		if(arg.length == 0) {
			return false;
		} else {
			for(var x in arg) {
				if(typeof(this.option['settings'][x]) != 'undefined') {
					this.option['settings'][x] = arg[x];
				}
			}
		}
	},
	
	Init: function(arg) {
	
		this.SetOptions(arg);
		this.Open();	
	
	},

	Open : function() {

		Shadowbox.open(this.option['settings'], this.option['option']);
		
	},
	
	Close: function() {
		
		Shadowbox.close();
		
	}
	
};

function SBOpen(stitle, url, h, w) {

	if(h == '') h = (screen.availHeight-100);
	if(w == '') w = (screen.availWidth-100);

	//alert(PHCMS_ShadowBox.option['option'].animate);
	PHCMS_ShadowBox.Init({
		player:'iframe', 
		title:stitle,
		content:url,
		height:h +"px",
		width:w +"px"
	});

}

function SBClose(){
	PHCMS_ShadowBox.Close();	
}


function SBLoad(){
	
	Shadowbox.loadSkin('classic', '/jscript/shadowbox/src/skin');
	Shadowbox.loadLanguage('en', '/jscript/shadowbox/src/lang');
	Shadowbox.loadPlayer(['flv', 'html', 'iframe', 'img', 'qt', 'swf', 'wmp'], '/jscript/shadowbox/src/player');
	
	window.onload = function(){
		Shadowbox.init();
	};

}

/* End of PHCMS Shadowbox */

function MatchHeights(master,inherit) {
	if($j(master).length && $j(inherit).length) {
		var p = /px|em|%/;
		var h = parseInt($j(master).height()) - (parseInt($j(master).css('padding-top').replace(p,'')) + parseInt($j(master).css('padding-bottom').replace(p,'')));
		//if(!ie) console.log(h);
		$j(inherit).each(function() {
			var pt = $j(this).css('padding-top').replace(p,'');
			var pb = $j(this).css('padding-bottom').replace(p,'');
			var nh = parseInt(h)-(parseInt(pt)+parseInt(pb));
			$j(this).height(nh + 'px');
			//$j(this).height(h + 15 + 'px');
		});
	}
}


