/**
 *
 */
var ndNewsUtils = {};

/**
 * 
 */
ndNewsUtils.prototype = {};

/**
 * delete white spaces at begining and end of the given string
 * @param string myString
 * @return string
 */
ndNewsUtils.trim = function(myString)
{
	return (myString.replace(/^\s+/g,'').replace(/\s+$/g,''));
};

/**
 * get translation of key from server
 * @param string key
 * @return XMLDocument
 */
ndNewsUtils.translate = function(key)
{
	var xhr = this.getXHR();
	if (xhr == null)
		return (null);
	var url = "index.php?controller=I18n&key="+encodeURIComponent(key);
	xhr.open("GET", url, false);
	xhr.send(null);
	if (xhr.readyState == 4)
	{
		return (xhr.responseXML);
	}
	return (null);
};

/**
 * open alert popup with the translation of key as content
 * @param string key
 * @return bool
 */
ndNewsUtils.alertTranslation = function(key, id)
{
	var xmlDocument = this.translate(key);
	if (!xmlDocument)
	{
		alert("an error occured");
		return (false);
	}
	var translation = $(xmlDocument.getElementsByTagName("translation")[0]).text();
	if (translation)
	{
		ndNewsUtils.alert(translation, id);
	}
	//for debugging
	else
		alert("problem with translation");
	return (true);
};

/**
 * open alert popup which disappear automaticaly
 * @param string content
 * @return bool
 */
ndNewsUtils.alert = function(content, id)
{
		var dialogDiv = document.createElement("div");
		var popupid = "alert";
		if (id != null && id.length > 0)
			popupid = id;
		dialogDiv.id = popupid;
		$(dialogDiv).attr("title", "Megalopolis");
		dialogDiv.innerHTML = content;
		$(dialogDiv).dialog({
			height: 50,
			resizable: false, draggable:false
			});
		window.setTimeout("$('#" + popupid + "').dialog('close');$('#" + popupid + "').remove();", 2000);
};

/**
 * return translation string  of key from server
 * @param string key
 * @return
 */
ndNewsUtils.getTranslation = function(key)
{
	var xmlDocument = this.translate(key);
	if (!xmlDocument)
		return (false);
	var translation = ndNewsUtils.trim($(xmlDocument).find("translation").text());
	if (translation)
		return (translation);
	//for debugging
	return (null);
};

ndNewsUtils.confirm = function(content, callback)
{
	var dialogDiv = document.createElement("div");
	dialogDiv.innerHTML = content;
	dialogDiv.setAttribute("title", "Megalopolis");
	var buttons = {};
	buttons[ndNewsUtils.getTranslation("Yes")] = function() { $(this).dialog('close'); if (callback) callback(); return (true); };
	buttons[ndNewsUtils.getTranslation("Cancel")] = function() { $(this).dialog('close'); return (false); };
		$(dialogDiv).dialog({
			resizable: false,
			modal: true,
			buttons: buttons
		});
};

/**
 * return a new XMLHttpRequest object
 * @return XMLHttpRequest
 */
ndNewsUtils.getXHR = function()
{
var xhr = null;
	
	if (window.XMLHttpRequest || window.ActiveXObject) 
	{
		if (window.ActiveXObject) 
		{
			try 
			{
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			} 
			catch(e) 
			{
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		else 
		{
			xhr = new XMLHttpRequest(); 
		}
	}
	else 
	{
		alert("AJAX failed");
		return (null);
	}
	return (xhr);
};

/**
 * return the text value of given node if any
 * @param DOMNode node
 * @return string
 */
ndNewsUtils.getTextValue = function(node)
{
	if (node.text)
		return (node.text);
	if (node.textContent)
		return (node.textContent);
	return (node.firstChild.nodeValue);
};

/**
 * add slashed before sepcial char
 * @param string str
 * @return string
 */
ndNewsUtils.addslashes = function(str) 
{
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return (str);
};

/**
 * check ajax request status
 * @param XMLHttpRequest xhr
 * @return XMLHttpRequest
 */
/*ndNewsUtils.processXHR = function(xhr)
{
	if (!xhr)
		return (null);
	if (xhr.status == 401 || xhr.status == 0)
	{
		//if there is no timeout popup already open
		if ($("#sessiontimeout").length == 0)
		{
			var dialogDiv = document.createElement("div");
			dialogDiv.id = "sessiontimeout";
			dialogDiv.innerHTML = ndNewsUtils.getTranslation("You have been inactive for too long, you have to log in again. You will be redirected to login page after ") + '<span id="count"> 5 </span>' + ndNewsUtils.getTranslation(" seconds.");
			$(dialogDiv).dialog({
				height: 50,
				width: "auto",
				resizable: false, 
				draggable:false,
				modal:true
				});
			var countInterval = window.setInterval(function()
				{
					if (Number($("#sessiontimeout #count").text()) > 0) 
						$("#sessiontimeout #count").text(" " + (Number($("#sessiontimeout #count").text()) - 1) + " ");
				}, 1000);
			window.setTimeout(function()
				{
					$('#sessiontimeout').dialog('close');
					$('#sessiontimeout').remove();
					window.clearInterval(countInterval);
					window.location.reload();
				}, 5000);
		}
	}
	else 
		ndNewsUtils.alertTranslation("getArticleViewerContent : An unknown error occured");
	return (true);
};*/


/**
 * update resPerPage value in query string of the current url
 * @param int resPerPage
 * @return bool
 */
ndNewsUtils.changeResPerPage = function(resPerPage)
{
	var newLocationSearch = window.location.search;
	var page = window.location.search.match(/page=(\d+)/);
	if(page) {
		var firstEltIndex = page[1]*this.getResPerPageCookie();
		var newPage = Math.floor(firstEltIndex / resPerPage);
		newLocationSearch = newLocationSearch.replace(/page=\d+/, 'page='+newPage);
	}
	this.setResPerPageCookie(resPerPage);
	if (newLocationSearch.match(/resPerPage=./))
		window.location.search = newLocationSearch.replace(/resPerPage=\d*/, "resPerPage="+resPerPage);
	else
		window.location.search = newLocationSearch + ((newLocationSearch.length > 0) ? '&' : '?') + "resPerPage="+resPerPage;
	return (true);
};

/**
 * get number of result per page cookie
 * @return integer
 */
ndNewsUtils.getResPerPageCookie = function()
{
	var content = ndNewsUtils.getCookie("resperpage");
	var propertyname = "resPerPageForType-" + 
			($("#searchBarType .selected input").get(0) ?
			 $("#searchBarType .selected input").get(0).id.split("-")[1] : "");
	var regExp = new RegExp(propertyname + "=([0-9]+)");
	var r = content.match(regExp);
	if(r) {
		return r[1];
	} else {
		return 5;//TODO : return the default value
	}
};

/**
 * set cookie to keep track of user preferences about article displayed number at a time 
 * @param int resPerPage
 * @return bool
 */
ndNewsUtils.setResPerPageCookie = function(resPerPage)
{
	var content = ndNewsUtils.getCookie("resperpage");
	var qs = new Querystring();
	var propertyname = "resPerPageForType-" + 
			($("#searchBarType .selected input").get(0) ?
			 $("#searchBarType .selected input").get(0).id.split("-")[1] : qs.get("type", ""));
	var regExp = new RegExp(propertyname + "=[0-9]+");
	if (content.match(regExp))
		content = content.replace(regExp, propertyname + "=" +resPerPage);
	else
		content = content + ((content.length > 0) ? '&' : '') + propertyname + "=" +resPerPage;
	ndNewsUtils.setCookieWithLifetime("resperpage", content, 366);
	return (true);
};

/**
 * remove elment text value
 * @param HTMLElement element
 * @return bool
 */
ndNewsUtils.resetTextField = function(element)
{
	if (element == null || $(element).val() == null )
		return (false);
	var defaultVal =  $(element).get(0)._defaultTextBoxValue ? $(element).get(0)._defaultTextBoxValue :  "";
	$(element).val(defaultVal);
	return (true);
};

/**
 * switch to class1 or class2 according to the current class
 * @param HTMLElement element
 * @param string class1
 * @param string class2
 * @return bool
 */
ndNewsUtils.switchClass = function(element, class1, class2)
{
	if (element == null)
		return (false);
	if (element.className.indexOf(" "+class1) != -1)
	{
		element.className = element.className.replace(new RegExp("( "+class1+")", "g"), " "+class2);
		return (true);
	}
	if (element.className.indexOf(" "+class2) != -1)
	{
		element.className = element.className.replace(new RegExp("( "+class2+")", "g"), " "+class1);
		return (true);
	}
	return (false);
};

/**
 * get the target of the given event
 * @param DOMEvent e
 * @return HTMLElement
 */
ndNewsUtils.getEventTarget = function(e)
{
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return (targ);
};

/**
 * return window size{width:w,height:h}
 * @return Object
 */
ndNewsUtils.windowSize = function()
{
	var w = 0;
	var h = 0;
	var pageh = 0;
	
	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return ({width:w,height:h});
};

/**
 * set a cookie giving its name and value
 * @param name
 * @param content
 * @return bool
 */
ndNewsUtils.setCookie = function(name, content) 
{
	document.cookie = name + "=" + escape(content);
	return (true);
};

/**
 * set a cookie giving its name and value and duration in days
 * @param name
 * @param content
 * @param dayDuration
 * @return bool
 */
ndNewsUtils.setCookieWithLifetime = function(name, content, dayDuration) 
{
  var ttl = new Date();
  ttl.setTime(ttl.getTime() + dayDuration*24*3600*1000);
  document.cookie = name + "=" + escape(content)
     + ";expires=" + ttl.toGMTString();
  return (true);
};

/**
 * get cookie value giving its name
 * @param name
 * @return string
 */
ndNewsUtils.getCookie = function(name) 
{
  var start, end;
  start = document.cookie.indexOf(name + "=");
  if (start >= 0) {
	  start += name.length + 1;
	  end = document.cookie.indexOf(";", start);
     if (end < 0) fin = document.cookie.length;
     return unescape(document.cookie.substring(start, end));
     }
  return "";
};

/**
 * delete cookie value giving its name
 * @param name
 * @return bool
 */
ndNewsUtils.unsetCookie = function(name)
{ 
	this.setCookieWithLifetime(name, "", -1);
	return (true);
};

ndNewsUtils.openDialog = function(title, content)
{
	var dialogDiv = document.createElement("div");
	$(dialogDiv).html(content);
	$(dialogDiv).attr("title", title);
	$("html").css("overflow", "hidden");
	$(dialogDiv).dialog({
		height:	400,
		width:	800,
		draggable: false,
		resizable: false,
		modal: true,
		close: function(event, ui)
		{
			this.parentNode.removeChild(this);
			$("html").css("overflow", "auto");
		}});
};

ndNewsUtils.sendBetaBugReport = function()
{
	var xhr = ndNewsUtils.getXHR();
	if (xhr == null)
		return (null);
	var url = "index.php?action=getBetaBugForm&controller=News";
	xhr.open("GET", url, false);
	xhr.send(null);
	if (xhr.readyState == 4)
	{
		if (xhr.responseText.length < 1)
		{
			var message = $(xhr.responseXML.getElementsByTagName("message")[0]).text();
			ndNewsUtils.openDialog(	"Megalopolis :" + commonLocale.error,
					commonLocale.bug_report_get_form_error);
			return (false);
		}
		//init dialog content
		var dialogDiv = document.createElement("div");
		var title = "Megalopolis :" + commonLocale.report_bug;
		dialogDiv.setAttribute("title", title);
		//add received content to ul tag
		$(dialogDiv).html(xhr.responseText);
		var form = $(dialogDiv).children("form").get(0);
		var bugreporturl = $(form).children("#bugreporturl").get(0);
		$(bugreporturl).attr("value", window.location.href);
		var buttons = {};
		buttons[commonLocale.send]= function()
		{
			$.post("index.php?action=sendBetaBug", $(form).serialize(),
			function(){ndNewsUtils.alert(commonLocale.bug_reported);});
			$(dialogDiv).dialog('close');
		};
		buttons[commonLocale.cancel]= function()
			{$(dialogDiv).dialog('close');};
		//show dialog
		$(dialogDiv).dialog(
				{
					height:	400,
					width:	800,
					draggable: false,
					resizable: false,
					modal: true,
					buttons: buttons,
					close: function(event, ui)
					{this.parentNode.removeChild(this);}
				});
		return (true);
	}
	ndNewsUtils.openDialog(	"Megalopolis :" + commonLocale.error,
							commonLocale.bug_report_get_form_error);
	return (false);
};

