/*
* Displays an error message according to a string the server sends.
* The strings syntax is as follows: 'infoMsg~3022,errMsg~4000,...,msgType~msgId'
* Where each message is separated by a , (comma)
* The first element is the message type and the second one seperated by the ~ (tilda) sign is the message ID
* no , (comma) should follow the last message since that creates an empty
* array cell when the function splits the string.
*/
var errorMessage = new Object();

errorMessage = function(contentPath,serverMessageString,serverVariables,withoutTranslation,container,lang,sid){
	// by default the message is translated by the client side and therefore the default value of withoutTranslation variable is false
	if (withoutTranslation == null || withoutTranslation == undefined || withoutTranslation == '') {
		withoutTranslation = false;
	}

	//in case the message's container is not specified
	if(frames != null && frames.length > 0)
		serverMsgCell = frames[0].serverMsgCell;
	var serverMsgCell = (serverMsgCell != undefined || serverMsgCell != null) ? serverMsgCell : '#messageCell';
	if (container && container != '') {
		serverMsgCell = '#'+container;
	}
	//check that the server specified an error message
	if(serverMessageString != ''){
		if (withoutTranslation) {
			var singleMessage = serverMessageString.split("~");
			var msgType = singleMessage[0];
			var messageStr = singleMessage[1];

			//locates the message's container and appends a rendered table that includes the messages content
			$("iframe").contents().find(serverMsgCell).append(errorMessage.tableRender(msgType,messageStr))
				.children("table")
			.css("font-weight","bold");
			//in case the function is being called from a window with no iframe
			$(serverMsgCell).append(errorMessage.tableRender(msgType,messageStr))
				.children("table")
			.css("font-weight","bold");
		} else {
			var allMessages = serverMessageString.split(",");
			var replaceVariables = serverVariables.split(",")
			var singleVar = '';
			//loop the amount of times there are messages from the server
			for(msgs in allMessages){
				//if the server sends variables with the messages then create an array for them
				// this is done in getMessage() function

				singleMessage = allMessages[msgs].split("~");
				var msgType = singleMessage[0];
				var msgId = singleMessage[1];
				var messageStr = getMessage(contentPath,msgId,replaceVariables[msgs],lang,sid);
				//locates the message's container and appends a rendered table that includes the messages content
				$("iframe").contents().find(serverMsgCell).append(errorMessage.tableRender(msgType,messageStr))
					.children("table")
				.css("font-weight","bold");
				  //in case the function is being called from a window with no iframe
				$(serverMsgCell).append(errorMessage.tableRender(msgType,messageStr))
					.children("table")
				.css("font-weight","bold");
			}
		}
	}
}

getMessage = function(contentPath,msgId,replaceVariables,lang,sid){

	var $str;
	if (contentPath == 1) { // the default translations that are situated in translations.js
		// search for the translations array in the  (main.html)
		if (tPT) {
			$str = tPT[msgId];
			// if the translations are found but the specific msgId is not defined,
			// then use a standart message which sould be in msgId = 0 in the same array
			if ($str == null || $str == undefined) {
				$str = tPT[0];
				replaceVariables = '' + msgId;
			}
		// otherwise search for the translations in self
		} else if (tPT) {
			$str = tPT[msgId];
		}
		if ($str == null || $str == undefined) {
			$str = 'N/A';
		}

		// try to replace the paramers in the correct order in the message placeholders
		if(replaceVariables != null && replaceVariables != ''){
			var vArray = replaceVariables.split("~");
			for (singleVar in vArray) {
				$str = $str.replace(/\[\]/,vArray[singleVar]);
			}
		}
		return $str;
	} else if (contentPath == 2) { // client error messages translations (like in alerts) that are situated in clientErrors.js
		// search for the translations array in the  (main.html)
		if(tCE){
			if (tCE.length == 0) {
				tCE = loadClientText(contentPath,lang,sid);
			}
			$str = tCE[msgId];
			// if the translations are found but the specific msgId is not defined,
			// then use a standart message which sould be in msgId = 0 in the same array
			if ($str == null || $str == undefined) {
				$str = tCE[0];
				replaceVariables = '' + msgId;
			}
		// otherwise search for the translations in self
		} else if (tCE) {
			$str = tCE[msgId];
		}
		if ($str == null || $str == undefined) {
			$str = 'N/A';
		}

		// try to replace the paramers in the correct order in the message placeholders
		if(replaceVariables != null && replaceVariables != ''){
			var vArray = replaceVariables.split("~");
			for (singleVar in vArray) {
				$str = $str.replace(/\[\]/,vArray[singleVar]);
			}
		}
		return $str;
	} else if (contentPath == 3) { // server side error messages translations (like in message boxes) that are situated in errors.js
		// search for the translations array in the  (main.html)
		if(tSE){
			if (tSE.length == 0) {
				tSE = loadClientText(contentPath,lang,sid);
			}
			$str = tSE[msgId];
			// if the translations are found but the specific msgId is not defined,
			// then use a standart message which sould be in msgId = 0 in the same array
			if ($str == null || $str == undefined) {
				$str = tSE[0];
				replaceVariables = '' + msgId;
			}
		// otherwise search for the translations in self
		} else if (tSE) {
			$str = tSE[msgId];
		}
		if ($str == null || $str == undefined) {
			$str = 'N/A';
		}

		// try to replace the paramers in the correct order in the message placeholders
		if(replaceVariables != null && replaceVariables != ''){
			var vArray = replaceVariables.split("~");
			for (singleVar in vArray) {
				$str = $str.replace(/\[\]/,vArray[singleVar]);
			}
		}
		return $str;
	}

	var $str = '';
	$.ajax({
	  async: false,
	  url: contentPath,
	  cache: true,
	  dataType: "text",
	  processData: false,
	  contentType:"text/plain",
	  success: function(returnedData){
			//finds a div with the specified message id
			resultData = $(returnedData).filter("div[id='"+msgId+"']");
			//if(resultData.find("div")){
			//	;
			//}
				if($(resultData).is("div")){
					resultData = $(resultData).html();
				}
				else{
					resultData = $(returnedData).filter("div[id='0']").html();
					replaceVariables = msgId;
				}
			

			//if the server sends variables with the messages then create an array for them
			if(replaceVariables != ''){
				var vArray = replaceVariables.split("~");
				for (singleVar in vArray) {
					resultData = resultData.replace(/\[\]/,vArray[singleVar]);
				}
			}
			resultData.replace(/\[\]/g,'');
			$str = resultData;
		}
	});
	return $str;
}

//Builds a table according to tableType and inserts msgData into the content td
errorMessage.tableRender = function(tableType,msgData){
  var tableRequest = '';
  	if(tableType == 'clean'){
		tableRequest = msgData;
	}
	else if(tableType == 'infoMsg'){
		tableRequest = '\
    <table class="message infoMsg">\
       <tr>\
          <td width="7"><\/td>\
          <td class="icon info"><\/td>\
          <td>'+msgData+'<\/td>\
       <\/tr>\
     <\/table>';
	}
	else if(tableType == 'errorMsg'){
		tableRequest = '\
			<table class="message errorMsg">\
				<tr>\
          <td width="7"><\/td>\
          <td class="icon decline"><\/td>\
          <td>'+msgData+'<\/td>\
				<\/tr>\
      <\/table>';
	}
	else if(tableType == 'successMsg'){
		tableRequest = '\
     <table class="message successMsg">\
        <tr>\
          <td width="7"><\/td>\
          <td class="icon accept"><\/td>\
          <td>'+msgData+'<\/td>\
				<\/tr>\
      <\/table>';
	}
	return tableRequest;
}

var disableMultiSend = function(){
	//$("iframe").contents().find("form").bind("submit",function(event){
	var iFrameWIN = document.getElementById('contentiframe').contentWindow.document;
	$(iFrameWIN).find("form").bind("submit",function(event){
		event.preventDefault();
	});

	function releaseSubmit(){
		return true;
		//find the submit button and change it to the loading image
		$("iframe").contents().find("[name='submit']").replaceWith('<img id="preloadImg" src="'+preloadWorkingGif.src+'" width="56" height="21" alt="">');
		//disables the button if the form is valid
		$(this).attr("disabled","disabled");
		//unbinds the prohibiting function and submits the form
		$("iframe").contents().find("form").unbind("submit").submit();
	}

	//binds a click event to every "submit" button
	$("iframe").contents().find(".submit").click(function(){
		if($.isFunction(frames[0].validateForm)){
			if(frames[0].validateForm())
				releaseSubmit();
		}
		//else
		//	releaseSubmit();
	});
}

function submitFormWithEnter(myfield,e)   
{   
   var keycode;   
   if (window.event)   
   {   
      keycode = window.event.keyCode;   
   }   
   else if (e)   
   {   
      keycode = e.which;   
   }   
   else  
   {   
      return true;   
   }   
  
   if (keycode == 13)   
   {   
      $("input[type='button']").click();
      return false;   
   }   
   else  
   {   
      return true;   
   }   
}   

function submitJxData(formEL){
				
				var getStr = "";
				formEL.find("input,select,textarea").each(function(i){
					if ($(this).attr("name") && $(this).attr("name") != "" && !$(this).attr("disabled")){
						if (($(this).attr("type")=="radio" && !$(this).attr("checked"))) return;
						if (($(this).attr("type")=="checkbox" && !$(this).attr("checked"))) return;
						var thisStr = $(this).val();
						//thisStr = thisStr.replace(/&/g,"&#38;");
						getStr += $(this).attr("name") + "=" + encodeURIComponent(thisStr) + "&";
					}
					
				});
				getStr += "_=" + getUnixTime();	
				return getStr;
			}
			
			function getUnixTime()
			{
				var foo = new Date; // Generic JS date object
				var unixtime_ms = foo.getTime(); // Returns milliseconds since the epoch
				var unixtime = parseInt(unixtime_ms / 1000);	
				return unixtime;
			}
