//FIXME Most of these functions could be simplified by using JQuery.

/**
 * Counts the characters of a given element, if the limit is reached deletes the last character
 * @param element the element
 * @param limit the limit
 * @return
 */
function countchars(element,limit) {
	//alert (element+limit);
	if (element.value.length <= limit) {
		//document.getElementById("charcountdown").innerHTML = 500-document.getElementById(id).value.length;
	}
	else {
		//alert (limit+" characters limit reached!");
		element.value = element.value.substring(0, limit);
	}
}


//var HTML, picwin = null;
//var picURL = '../images/icons/clip.png';

/**
 * Validates a new project form and shows errors
 */
function validateNewProject() {
	var flag1 = true;
	var flag2 = true;
	var flag3 = true;
	var flag4 = true;
	var flag5 = true;
	
	var error = " <img src='../images/icons/error.gif'/>";
	if (document.newproject.projectname.value=="") {
		document.getElementById("projectname").innerHTML = error+" ";
		flag1 = false;
	}
	else {
		document.getElementById("projectname").innerHTML = " ";
	}
	if (document.newproject.description.value=="")  {
		document.getElementById("description").innerHTML = error+" ";
		flag2 = false;
	}
	else {
		document.getElementById("description").innerHTML = " ";
	}

	if (document.newproject.sp!=undefined) {
		if (document.newproject.sp.value=="")  {
			document.getElementById("sp").innerHTML = error+" ";
			flag4 = false;
		}
		else {
			document.getElementById("sp").innerHTML = " ";
		}
	}
	else {
		document.getElementById("sp").innerHTML = error+" ";
		flag4 = false;
	}
	
	 flag = flag1&&flag2&&flag3&&flag4&&flag5;

	if (flag==false) {
		show("error");	
	}
	
	return flag;
}

/**
 * Selects people and 
 * @param id
 * @param user
 * @return
 */
function selectPeople(id,user) {
	var image;
	image = (document.getElementById("addicon"+id).src).indexOf("add");
	if (image==-1) {
		document.getElementById("addicon"+id).src="../images/icons/add.gif"; 
		document.getElementById("add"+id).style.backgroundColor='#ffffff';
		document.getElementById("avatar"+id).style.backgroundColor='#ffffff'; 
		document.getElementById("name"+id).style.backgroundColor='#ffffff'; 
		document.getElementById("check"+id).checked=false; 
	}
	else {
	document.getElementById("addicon"+id).src="../images/icons/undo.gif"; 
	document.getElementById("addicon"+id).title="undo";
	document.getElementById("add"+id).style.backgroundColor='#c5ee9b';
	document.getElementById("avatar"+id).style.backgroundColor='#c5ee9b'; 
	document.getElementById("name"+id).style.backgroundColor='#c5ee9b'; 
	document.getElementById("check"+id).checked=true; 
	}
}

/**
 * Show a certain the div
 * @param div the div id
 * @return
 */
function show(div) {
	document.getElementById(div).style.display = '';
}

/**
 * Hides a certain div
 * @param div the div id
 * @return
 */
function hide(div) {
	if (document.getElementById(div)!=null) {
		document.getElementById(div).style.display = 'none';
	}
}

/**
 * Shows a div on click and hides in on the next click
 * @param div
 * @return
 */
function showhide(div) {
	if (document.getElementById(div).style.display == '') {
	document.getElementById(div).style.display = 'none';}
	else {
		document.getElementById(div).style.display = '';
	}
}

/**
 * Creates an Ajax request
 * @return the xmlHttp object
 */
function createAjaxRequest() {
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e){
		// Internet Explorer
		try{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e){
			try{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	return xmlHttp;
}

/**
 * Ajax call to reply.php to show the reply form
 * @param id the id for the Ajax response
 * @param type the type of reply
 * @return
 */
function reply(id,type) {
	//alert(id);
	var xmlHttp = createAjaxRequest();
	
	var url = "reply.php";
	var params = "id="+id+"&type="+type;
	xmlHttp.open("POST", url, true);

	//Send the proper header information along with the request
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("charset","iso-8859-1");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");

	xmlHttp.onreadystatechange = function() {//Call a function when the state changes.
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			//alert (xmlHttp.responseText);
			document.getElementById(id).innerHTML=xmlHttp.responseText;
		}
	}
	xmlHttp.send(params);
}

/**
 * Ajax call to addreply.php, adds a reply and shows it
 * @param id the id for the Ajax response
 * @return
 */
function addReply(id) {
	var eventtext = document.getElementById("reply"+id).eventtext.value;
	
	var xmlHttp = createAjaxRequest();
	
	var url = "addreply.php";
	var params = "id="+id+"&eventtext="+encode(eventtext);
	xmlHttp.open("POST", url, true);

	//Send the proper header information along with the request
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("charset","iso-8859-1");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");

	xmlHttp.onreadystatechange = function() {//Call a function when the state changes.
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			//alert (xmlHttp.responseText);
			document.getElementById(id).innerHTML=xmlHttp.responseText;
		}
	}
	xmlHttp.send(params);
}

/**
 * Encodes the reply to avoid problems with foreign characters
 * @param v the string to encode
 * @return the encoded string
 */
function encode(v) {
return escape(v).replace(/\+/ig, "%2B").replace(/\//ig, "%2F");
}

/**
 * Shows a message in a confirm alert box
 * @param message the message to show
 * @return true/false
 */
function confirmMessage(message) {
	if (confirm(message.replace("<br/>","\n"))) {
		return true;
	}
	else {
		return false;
	}
}

/**
 * Checks if a comment if empty
 * @param id the if of the element where the comment is
 * @return true/false
 */
function validateComment(id) {
	if (document.getElementById("reply"+id).eventtext.value!="") {
		addReply(id);
		return false;
	}
	else {
		return false;
	}
}

/**
 * Validates the fields of the usercofiguration.php page form and shows the errors
 * @return a flag (true/false)
 */
function validateUserConfiguration() {
	var error = " <img src='../images/icons/error.gif'/>";
	var flag=false;
	var flag1=true;
	var flag2=true;
	var flag3=true;
	var flag4=true;
	if (document.userconfiguration.newpassword.value!='') {
		if (document.userconfiguration.newpassword.value.length>=6) {
			document.getElementById("newpassword").innerHTML = " ";
			hide("error"+"newpassword");
		}
		if (document.userconfiguration.newpassword.value.length<6) {
			document.getElementById("newpassword").innerHTML = error+" ";
			show("error"+"newpassword");
			flag1=false;
		}
		else {
			if (document.userconfiguration.newpassword.value!=document.userconfiguration.newpassword2.value) {
				document.getElementById("newpassword").innerHTML = error+" ";
				document.getElementById("newpassword2").innerHTML = error+" ";
				show("error"+"newpassword2");
				flag2=false;
			}
			else {
				document.getElementById("newpassword").innerHTML = " ";
				document.getElementById("newpassword2").innerHTML = " ";
				hide("error"+"newpassword2");
			}
		}
	}
	if (document.userconfiguration.name.value.length<2) {
		document.getElementById("name").innerHTML = error+" ";
		show("error"+"name");
		flag3=false;
	}
	else {
		document.getElementById("name").innerHTML = " ";
		hide("error"+"name");
	}
	if (document.userconfiguration.surnames.value.length<2) {
		document.getElementById("surnames").innerHTML = error+" ";
		show("error"+"surnames");
		flag4=false;
	}
	else {
		document.getElementById("surnames").innerHTML = " ";
		hide("error"+"surnames");
	}
	flag = flag1&&flag2&&flag3&&flag4;
	//alert (flag);
	return flag;
}

/**
 * Validates the new client form and shows error
 * @return true/false
 */
function validateNewClient() {
	var flag1 = true;
	var flag2 = true;
	var flag3 = true;
	var flag4 = true;
	var flag5 = true;
	var flag6 = true;
	
	var error = " <img src='../images/icons/error.gif'/>";
	if (document.newclientclass.clientname.value=="") {
		document.getElementById("clientname").innerHTML = error+" ";
		flag1 = false;
	}
	else {
		document.getElementById("clientname").innerHTML = " ";
	}
	if (document.newclientclass.clientcode.value=="")  {
		document.getElementById("clientcode").innerHTML = error+" ";
		flag2 = false;
	}
	else {
		document.getElementById("clientcode").innerHTML = " ";
	}
	if (document.newclientclass.clientpass.value=="")  {
		document.getElementById("clientpass").innerHTML = error+" ";
		flag3 = false;
	}
	else {
		document.getElementById("clientpass").innerHTML = " ";
	}
	if ((document.newclientclass.day.value=="")||(document.newclientclass.month.value=="")||(document.newclientclass.year.value==""))  {
		document.getElementById("expirdate").innerHTML = error+" ";
		flag4=false;
	}
	else {
		document.getElementById("expirdate").innerHTML = " ";
	}
	if ((document.newclientclass.maxusers.value!=""&&(!isNumber(document.newclientclass.maxusers.value)))||
			(document.newclientclass.maxusers.value!=""&&(parseInt(document.newclientclass.maxusers.value)<parseInt(document.newclientclass.currentusers.value))))  {
		document.getElementById("maxusers").innerHTML = error+" ";
		flag4=false;
	}
	else {
		document.getElementById("maxusers").innerHTML = " ";
	}
	if (document.newclientclass.co.value=="")  {
		document.getElementById("co").innerHTML = error+" ";
		flag6 = false;
	}
	else {
		document.getElementById("co").innerHTML = " ";
	}
	flag = flag1&&flag2&&flag3&&flag4&&flag5&&flag6;
	if (flag==false) {
		show("error");
	}
	return flag;
}

/**
 * Checks if a value is a number of not
 * @param n the number
 * @return true/false
 */
function isNumber(n) {
	  return !isNaN(parseFloat(n)) && isFinite(n);
	}

/**
 * Validates a document and shows error (if any)
 * @return true/false
 */
function validateDocument() {
	var flag = true;
	
	if(document.newdocument.document.value=="") {
		alert ("No file attached!");
		flag = false;
	}
	else if(document.newdocument.doctype.value=="") {
		alert ("No document type selected!");
		flag = false;
	}
	else if (document.getElementById("exists").innerHTML!="") {
		if (confirm(document.getElementById("exists").innerHTML)) {
			document.newdocument.replace.value = "1";
			flag = true;
		}
		else {
			flag= false;
		}
	}
	return flag;
}

/**
 * Ajax call to validatedocument.php
 * @return
 */
function checkDocument() {
	var xmlHttp = createAjaxRequest();

	var url = "validatedocument.php";
	var params = "document="+document.newdocument.document.value;
	xmlHttp.open("POST", url, true);

	//Send the proper header information along with the request
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("charset","iso-8859-1");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");

	xmlHttp.onreadystatechange = function() {//Call a function when the state changes.
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			document.getElementById("exists").innerHTML = xmlHttp.responseText;
		}
	}
	xmlHttp.send(params);
}

/**
 * Jquery function that controls the Kion Online submenu
 */
$(document).ready(function(){
	var previousactive 
	//$("ul.subnav").parent().append("<span id='spanonline'></span>"); //Only shows drop down trigger when js is enabled - Adds empty span tag after ul.subnav
	
	$("#subonline").click(function() { //When trigger is clicked...
		$("#subonline").addClass("online");
		$("#spanonline").addClass("online");
		previousactive = $("ul.topnav").find(".active").attr("id");
		$("ul.topnav").find(".active").removeClass("active");
		
		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click

		$(this).parent().hover(function() {
		}, function(){	
			//$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
			//$("#online").removeClass("online");
			//$("#spanonline").removeClass("online");
		});
		
		$("body").click(function(){
			$(this).parent().parent().find("ul.subnav").slideUp('slow');
			$("#subonline").removeClass("online");
			$("#spanonline").removeClass("online");
			$("ul.topnav").find("#"+previousactive).addClass("active");
			},function(){});
		
		//Following events are applied to the trigger (Hover events for the trigger)
		return false;
		}).hover(function() { 
			$(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});

});

/**
 * Jquery function to validate the registration form (it uses jquery.validate.js plugin)
 */
$(document).ready(function() {
	// validate signup form on keyup and submit
	$("#registerForm").validate({
		rules: {
			mail: {
				required: true,
				email: true
			},
			password: {
				required: true,
				minlength: 6
			},
			conpassword: {
				required: true,
				minlength: 6,
				equalTo: "#password"
			},
			name: {
				required: true,
				minlength: 2,
				maxlength: 30
			},
			surnames: {
				required: true,
				minlength: 2,
				maxlength: 50
			},
			company: {
				required: true,
				minlength: 3,
				maxlength: 50
			},
			accept: "required"
		}
	});
	
});

/**
 * Jquery function to validate the modifyuser form (it uses jquery.validate.js plugin)
 */
$(document).ready(function() {
	// validate signup form on keyup and submit
	$("#modifyuser").validate({
		rules: {
			oldpassword: {
				minlength: 6
			},
			newpassword: {
				required: "#oldpassword:filled",
				minlength: 6
			},
			newpassword2: {
				required: "#oldpassword:filled",
				minlength: 6,
				equalTo: "#newpassword"
			},
			name: {
				required: true,
				minlength: 2,
				maxlength: 30
			},
			surnames: {
				required: true,
				minlength: 2,
				maxlength: 50
			}
		}
	});
	
});

/**
 * Jquery function to validate the loginregister.php form (it uses jquery.validate.js plugin)
 */
$(document).ready(function() {
	// validate signup form on keyup and submit
	$("#loginRegisterForm").validate({
		rules: {
			mail: {
				required: true,
				email: true
			},
			password: {
				required: true,
				minlength: 6
			},
			conpassword: {
				required: true,
				minlength: 6,
				equalTo: "#password"
			},
			name: {
				required: true,
				minlength: 2,
				maxlength: 30
			},
			surnames: {
				required: true,
				minlength: 2,
				maxlength: 50
			},
			company: {
				required: true,
				minlength: 3,
				maxlength: 50
			},
			country: "required",
			address: "required",
			zip: "required",
			city: "required",
			state: "required",
			telephone: "required",
			accept: "required"
		}
	});
	
});

/**
 * Jquery function that makes an Ajax call to selectsate.php depending on the country selected
 */
$(document).ready(function() {
	$("#country_code").change(function(){
		var countrycode = $("#country_code").attr('value');
			//$("#state1").show();
			//$("#state2").show();
	        $.ajax({
                url: 'selectstate.php',
                cache: false,
                data: 'countrycode='+countrycode,
                success: function(result) {
        			$("#state2").html(result);
	        	}
	        });
	});
});
