/**
 * objet that hold a news media and its informations, initialize itemId field
 * @param itemId
 * @return
 */
function ArticleItem( itemId )
{
	this._itemId = itemId;
	this._source = null;
	this._title = null;
	this._description = null;
	this._content = null;
	this._media = null;
	this._fontSize = null;
	
	this.NO_CONTENT = 0;
	this.CONTENT_OK = 1;
	this.NO_ITEM = 2;
}
	/**
	 *  initialize item informations
	 *  @params	string source
	 *  @params string title
	 *  @params string content
	 *  @params string description
	 *  @params string date
	 *  @return void
	 */
	ArticleItem.prototype.setItemValues = function (source, title, content, description, date)
	{
		this._source = source;
		this._content = content;
		this._title = title;
		this._description = description;
		this._date = date;
	};
	
	/**
	 * get font size pass in parameter in constructor
	 * @return	int
	 */
	ArticleItem.prototype.getFontSize = function()
	{
		this._fontSize = Number(ndNewsUtils.getCookie("articleViewerFontSize"));
		return (this._fontSize);
	};
	
	/**
	 * return id
	 * @return int
	 */
	ArticleItem.prototype.getId = function()
	{
		return (this._itemId);
	};
	
	/**
	 * return date
	 * @return string
	 */
	ArticleItem.prototype.getDate = function()
	{
		return (this._date);
	};
	
	/**
	 * return content
	 * @return string
	 */
	ArticleItem.prototype.getContent = function()
	{
		return (this._content);
	};
	
	/**
	 * return title
	 * @return string
	 */
	ArticleItem.prototype.getTitle = function()
	{
		return (this._title);
	};
	
	/**
	 * return description
	 * @return string
	 */
	ArticleItem.prototype.getDescription = function()
	{
		return (this._description);
	};
	
	/**
	 * interface function to get an item
	 * initialize class name to use and container where to put the loaded item
	 * @param int fontSize
	 * @return bool
	 */
	ArticleItem.prototype.getItem = function(fontSize)
	{
		if (this.getId() == -1)
			return (false);
		var articleViewer = this.helperArticleElement();
		return (true);
	};
	
	/**
	 * return html article viewer node
	 * @return HTMLDiv
	 */
	ArticleItem.prototype.helperArticleElement = function()
	{
		//main container
		var viewerDiv = document.createElement("div");
		$(viewerDiv).attr("id", "ndNewsArticleViewer-" + this.getId());
		$(viewerDiv).attr("class", "ndNewsArticleViewer");
		$(viewerDiv).height(ndNewsUtils.windowSize().height + "px");
		//article content container
		var articleSection = document.createElement("div");
		$(articleSection).attr("id", "ndNewsArticleSections");
		//articleSection.style.height = ndNewsUtils.windowSize().height + "px";
		var articleLoading = document.createElement("div");
		$(articleLoading).attr("id", "viewerBackground");
		$(articleSection).append(articleLoading);
		ArticleItem.switchToFullscreen(viewerDiv);
		//viewer menu container
		var closeButton = document.createElement("button");
		$(closeButton).attr("id", "articleViewerCloseBtn");
		$(closeButton).attr("class", "closeButton");
		$(closeButton).click(function() {
			ArticleItem.removeFullscreenContainer();
			location.hash = '#';	// setting to '' would reload the page
		});
		$(viewerDiv).append(closeButton);
		var menuDiv = document.createElement("div");
		$(menuDiv).attr("id", "ndNewsArticleMenu");
		$(menuDiv).height((ndNewsUtils.windowSize().height - $(closeButton).height() - 20) + "px");
		//append sub containers to main container
		$(viewerDiv).append(articleSection);
		$(viewerDiv).append(menuDiv);
		//clear div
		var clear = document.createElement("div");
		clear.className = "clear";
		$(viewerDiv).append(clear);
		this.getArticleViewerContent(viewerDiv);
		this.getMenuContent(viewerDiv);
		//viewerDiv.style.height = ndNewsUtils.windowSize().height + "px";
		$(window).resize(ArticleItem.resize);
		//viewerDiv.style.height = document.getElementsByTagName("html")[0].clientHeight + "px";
		/*
		var height = ndNewsUtils.windowSize().height;
		var totalrules=document.styleSheets[0].cssRules? document.styleSheets[0].cssRules.length : document.styleSheets[0].rules.length;
		if (document.styleSheets[0].insertRule)
			document.styleSheets[0].insertRule("#ndNewsArticleViewer{height:"+height+"px;width:"+document.getElementById("container").clientWidth+";}", totalrules -1); //add new rule to start of stylesheet
		else
			document.styleSheets[0].addRule("#ndNewsArticleViewer", "height:"+height+"px;width:"+document.getElementById("container").clientWidth+";");
		*/
		return (viewerDiv);
	};
	
	/**
	 * open article viewer container if it isn't
	 * @return Boolean
	 */
	ArticleItem.prototype.createViewerContainer = function()
	{
		if ($('#ndNewsArticleViewer-' + this.getId()).length > 0)
		{
			$("#ndNewsArticleSections").get(0).style.backgroundImage = "";
			$("#ndNewsArticleMenu").get(0).style.backgroundImage = "";
			return (null);
		}
		//create the article container
		var viewerDiv = document.createElement("div");
		viewerDiv.setAttribute("id", "ndNewsArticleViewer-" + this.getId());
		return ($('#ndNewsArticleViewer-' + this.getId()).get(0));
	};
	
	/**
	 * return content of article, format in div section : information, category, title, summary and content
	 * @return HTMLDiv
	 */
	ArticleItem.prototype.helperArticleSection = function(container, articleFromServer)
	{
		//reader is open?
		if (!ArticleItem.textViewerIsOpen())
			return (false);
		//article section container
		var articleSection = $("#ndNewsArticleSections").get(0);
		$(articleSection).html(articleFromServer);
		
		if (this.getFontSize())
			ArticleItem.setTextSize(this.getFontSize(), 12);
		//container compute height
		var paddingTopString = $("#ndNewsArticle").css("paddingTop");
		var paddingTop = Number(paddingTopString.substr(0, (paddingTopString.length - 2)));
		$("#ndNewsArticle").css("height", (ndNewsUtils.windowSize().height - paddingTop - 10) + "px");
		$("#textContent").css("padding-bottom", (Math.floor(ndNewsUtils.windowSize().height / 2)) + "px");
		//change window title
		document.title = ndNewsUtils.trim($("#articleTitle").text())+ ' - ' + document.title;
		window.setTimeout("if (MediaItem.ImageCanBeDisplay($('.articleViewerPicture').get(0), 500, 190))"
		+"{"
		+"	$('#mediaDiv').css('min-height','190px');"
		/*+"	$('#mediaDiv').height(190);"*/
		+"	$('#mediaDiv').css('float', 'left');"
		+"	$('#mediaDiv').css('background-image', 'none');"
		+"  $('.articleViewerPicture').resizeImages({width: 500, height: 0, clickable: false, callback: function(){$('.articleViewerPicture').fadeIn('slow');}});"
		+"}", 1000);
		if ($(articleSection).find("#articleMustBeBought").length == 0)
			window.setTimeout("ndNews.logView(" + this.getId() + " );", 3000);
		//compute image size, firefox take some time to display the picture so we add a time out
		//return container
		ArticleItem.focus();
		
		return (articleSection );
	};
	
	/**
	 * get article viewer article section content from the server and return an HTML string
	 * @return string
	 */
	ArticleItem.prototype.getArticleViewerContent = function(container)
	{
		//$('#ndNewsArticleViewer').css('z-index','10');
		var qs = new Querystring();
		var url = "index.php?controller=News&action=getArticle&itemId=" + this.getId() + "&pipeline=" + encodeURIComponent(qs.get("pipeline"));
		var item = this;
		jQuery.ajax({
			url		:	url,
			dataType : "html",
			success	:	function(data)
			{
				item.helperArticleSection(container, data);
				return (true);
			},
			error	:	function(xhr)
			{
				ndNewsUtils.processXHR(xhr);
				return (true);
			}
		});
		return (true);
	};

	/**
	 * return html article viewer menu node
	 * @return HTMLDiv
	 */
	ArticleItem.prototype.helperMenuSection = function(container, menuFromServer)
	{
		if (!ArticleItem.textViewerIsOpen())
			return (false);
		//create the media container for easier style
		var menuDiv = $("#ndNewsArticleMenu").get(0);
		menuDiv.style.backgroundImage = "none";
		
		//menu content
		var content = null;
		//does menu content div already exists
		if ($("#menuContent").length > 0)
			content = $("#menuContent").get(0);
		else
		{
			content = document.createElement("ul");
			$(content).attr('id',"menuContent");
		}
		menuDiv.appendChild(content);
		$(content).append(menuFromServer);
		//menu button - close, decrease text size, increase text size, slider change text size
		$("#articleViewerDecreaseFontSizeBtn").click(function() {
			ArticleItem.decreaseTextSize();
		});
		$("#articleViewerIncreaseFontSizeBtn").click(function() {
			ArticleItem.increaseTextSize();
		});
		//we have to check if content has already be loadded beacuse, when loadded content will automaticaly update
		//slider value. if menu load first, we use default value and content will update, else get prefered value from
		//cookie for silder position corresponds to content font size
		var sliderValue = $("#ndNewsArticleSections").children().length < 1 ? 12 : this.getFontSize();
		$("#slider").slider({
			value: sliderValue,
			min: 12,
			max: 22,
			step: 1,
			slide: function(event, ui) {
					ArticleItem.setTextSize(ui.value);
					}
		});
		//short cut for article on the same page
		$(content).append(this.helperMenuArticleNotRead());
		//print link
		if (!window.print)
			document.getElementById("articlePrint").style.display = "none";
		return (menuDiv);
	};
	
	/**
	 * get article viewer menu content from the server and return an HTML string
	 * @return string
	 */
	ArticleItem.prototype.getMenuContent = function(container)
	{
		var url = "index.php?controller=News&action=getMenuContent&itemId="+this.getId();
		var item = this;
		jQuery.ajax({
			url		:	url,
			success	:	function(data)
			{
				item.helperMenuSection(container, data);
				return (true);
			},
			error	:	function(xhr)
			{
				ndNewsUtils.processXHR(xhr);
				return (true);
			}
		});
		return (true);
	};
	
	/**
	 * set list of article on the same page
	 * @return HTMLDiv
	 */
	ArticleItem.prototype.helperMenuArticleNotRead = function(listlength)
	{
		var url = window.location.href;
		if (url.indexOf("#", 0) != -1)
			url = url.substr(0, url.indexOf("#", 0));
		if (url.indexOf("?", 0) == -1)
			url += "?";
		var reg = new  RegExp("(action=[a-zA-Z]+)", "g");
		if (url.match(reg))
			url = url.replace(reg, 'action=getSameCategoryArticles'); // getNotReadArticles
		else
			url += "&action=getSameCategoryArticles";
		url += "&itemId="+this.getId();
		jQuery.ajax({
			url : url,
			dataType : "html",
			success : function(data)
			{
				if (data.length == 0)
					return (false);
				$(data).insertAfter("#shareLinks");
				return (true);
			},
			error : ndNewsUtils.processXHR
		});
		/*var articlelist = $('.articlePreviewRow:not(.read)');
		var searchedId = window.location.hash.substr(1, window.location.hash.length);
		if (articlelist.length < 1)
			return (null);
		if (listlength == null)
			listlength = 5;
		var menuitem = document.createElement("li");
		var menuitemtitle = document.createElement("span");
		var menuitemcontent = document.createElement("ul");
		$(menuitemtitle).attr("class", "menuItemTitle");
		//set menu item title
		var qs = new Querystring();
		if (qs.get("controller", "News") == "NewsAlert")
		{
			var qs = new Querystring();
			var alertId = qs.get("alertId", null);
			tempArticlelist = $("#alert-" + alertId + " .alertItems").children('.articlePreviewRow:not(.read)');
			if (tempArticlelist.length != 0)
			{
				$(menuitemtitle).text(ndNewsUtils.getTranslation("Other articles about:") + " " + $("#navgationTitle" + alertId + " a").text().split(':')[0]);
				articlelist = tempArticlelist;
			}
			else
				$(menuitemtitle).text(ndNewsUtils.getTranslation("Other articles about other alerts:") + " ");
		}
		else if(qs.get("search", null) != null)
			$(menuitemtitle).text(ndNewsUtils.getTranslation("Other articles about:") + " “" + qs.get("search", "") + "”");
		else if(qs.get("controller", null) == "NewsPaper" && window.location.hash.length > 1)
		{
			tempArticlelist = $("#article-" + this.getId()).parent().children('.articlePreviewRow:not(.read)');
			if (tempArticlelist.length != 0)
			{
				$(menuitemtitle).text(ndNewsUtils.getTranslation("Other articles in:") + " " + $("#viewerArticleCategory span").text());
				articlelist = tempArticlelist;
			}
			else
				$(menuitemtitle).text(ndNewsUtils.getTranslation("Other articles in your newspaper:") + $("#userNewsPaperName").text());
		}
		else
		{
			var selectedPipelineId = $("#pipelineContainer .pipeline.selected").get(0);
			$(menuitemtitle).text(ndNewsUtils.getTranslation("Other articles in:") + " “" + $("#" + $(selectedPipelineId).attr("id") + " .pipelineElement").text() + "”");
		}
		$(menuitem).attr("class", "articleMenuItem");
		$(menuitem).append(menuitemtitle);
		$(menuitemcontent).attr("id", "onSamePage");
		$(menuitem).append(menuitemcontent);
		var i = 0;
		while(i < listlength && i < articlelist.length)
		{
			if (articlelist.get(i).id.split('-')[1] == this.getId())
			{
				i++;
				continue;
			}
			var liitem = document.createElement("li");
			var linkitem = document.createElement("a");
			$(linkitem).attr("href", "#"+articlelist.get(i).id);
			$(linkitem).text($("#"+articlelist.get(i).id+" .articleCropTitle").text());
			$(linkitem).click(function()
					{
						var articleid = $(this).attr("href").substr(1, $(this).attr("href").length);
					});
			$(liitem).append(linkitem);
			$(menuitemcontent).append(liitem);
			i++;
		}
		return (menuitem);
		*/
	};
	
	/**
	 * return index in the given list of the searched article
	 * @param searchedId
	 * @param articlelist
	 * @return int
	 */
	ArticleItem.prototype.helperMenuArticleGetIndex = function(searchedId, articlelist)
	{
		if ( searchedId == null)
			return (-1);
		var i = 0;
		while(i < articlelist.length)
		{
			var articleId = articlelist.get(i).id;
			if (searchedId == articleId)
			{
				return (i);
			}
			i++;
		}
		return (-1);
	};
	
	/**
	 * return a html div containing buttons to change article text size
	 * @return HTMLDiv
	 */
	ArticleItem.prototype.helperTextSizeBtn = function()
	{
		var btnContainer =  document.createElement("div");
		btnContainer.id="viewerCommand";
		//btnContainer.appendChild(ndNewsUI.helperBtn(null, "+ d'infos"));
		btnContainer.appendChild(ndNewsUI.helperBtn(ArticleItem.increaseTextSize, "+"));
		btnContainer.appendChild(ndNewsUI.helperBtn(ArticleItem.decreaseTextSize, "-"));
		var closeBtn = document.createElement("button");
		closeBtn.id = "articleViewerCloseBtn";
		closeBtn.onclick = function() {
			ArticleItem.removeFullscreenContainer();
			location.hash = '#';	// setting to '' would reload the page
		};
		btnContainer.appendChild(closeBtn);
		return (btnContainer);
	};
	
	/**
	 * return a html div containing a button
	 * @return HTMLDiv
	 */
	ArticleItem.prototype.helperEndBtn = function()
	{
		var btnContainer =  document.createElement("div");
		btnContainer.id="endBtn";
		btnContainer.appendChild(ndNewsUI.helperBtn(null, "s'abonner"));
		return (btnContainer);
	};
	
	
/**
 * compute image final size to fit fullscreen container
 * the height is fixed by parameter size (to be sure that media will not be heigher than available screen)
 * and the width is compute according to the image ratio
 * @param HTMLElement imageElement
 * @return bool
 */
ArticleItem.computeFullScreenImageOptimalSize = function (imageElement)
{
	var container = document.getElementById("container");
	return (ndNewsUI.computeOptimalListImageSize(imageElement, 0, document.body.clientHeight));
};

/**
 * get the medie element element from its container and put it in the fullscreen container,
 * save its state and change its attributes and size
 * @param HTMLElement objectElement
 * @return bool
 */
ArticleItem.switchToFullscreen = function(objectElement)
{
	if (objectElement == null)
		return;
	
	//close previous opened article if any
	ArticleItem.removeFullscreenContainer();
	
	//////////////////////////
	//move media object to foreground
	var container = document.getElementsByTagName("body")[0];
	var playerDiv = document.createElement("div");
	var backgroundDiv = document.createElement("div");
	var parentContainer = objectElement.parentNode;
	//nom et style des div
	$(playerDiv).attr("id", "ndNewsTextViewer");
	$(playerDiv).attr("class", "fullscreenContainer");
	$(backgroundDiv).attr("id", "ndNewsTextViewerBackground");
	$(backgroundDiv).attr("class", "fullscreenContainerBackground");
	$(backgroundDiv).click(function(){ArticleItem.removeFullscreenContainer(); location.hash = '#';});
	
	//////////////////////////
	// Compute image size for fullscreen
	playerDiv.appendChild(backgroundDiv);
	playerDiv.appendChild(objectElement);
	container.appendChild(playerDiv);
	
	//playerDiv.style.position = "fixed";
	//backgroundDiv.style.width = ndNewsUtils.windowSize().width + "px";
	if (ndNewsUtils.windowSize().height <  $("body").height())
		backgroundDiv.style.height = $("body").height() + "px";
	else 
		backgroundDiv.style.height = ndNewsUtils.windowSize().height + "px";
	$("html").css("overflow", "hidden");
	return (true);
};
	
/**
 * delete fullscreen container from the document
 * @return bool
 */
ArticleItem.removeFullscreenContainer = function()
{
	if (document.getElementById("ndNewsTextViewer") != null)
	{
		$(window).unbind('resize', ArticleItem.resize);
		document.getElementsByTagName("body")[0].removeChild(document.getElementById("ndNewsTextViewer"));
	}
    var compt=1;
    while(document.title.split("-")[compt])
    {
        compt = parseInt(compt) + 1;
    }
    compt=parseInt(compt) - 1;
    
    if(document.title.split("-")[compt])
        document.title = ndNewsUtils.trim(document.title.split("-")[compt]);
	$("html").css("overflow", "auto");
	return (true);
};

ArticleItem.textViewerIsOpen = function()
{
	if (document.getElementById("container") != null && document.getElementById("ndNewsTextViewer") != null)
		return (true);
	return (false);
};

/**
 * increase article viewer content text size changing its style font-size property
 * @return bool
 */
ArticleItem.increaseTextSize = function()
{
	if (($("#slider").slider('value') + 1) > $("#slider").slider( "option", "max" ))
		return (false);
	ArticleItem.setTextSize($("#slider").slider('value') + 1);
	return (true);
};

/**
 * decrease article viewer content text size changing its style font-size property
 * @return bool
 */
ArticleItem.decreaseTextSize = function()
{
	if (($("#slider").slider('value') - 1) < $("#slider").slider( "option", "min" ))
		return (false);
	ArticleItem.setTextSize($("#slider").slider('value') - 1);
	return (true);
};

/**
 * set article viewer content text size changing its style font-size property
 * @return bool
 */
ArticleItem.setTextSize = function(size)
{
	var textContainer = document.getElementById("ndNewsArticle");
	if ( textContainer == null )
		return (false);
	
	//the first time we expect that a reference size to be passed, the following slider value will be the de reference value
	var refValue = 12;
	var ratio = size / 12;
	$(textContainer).children(":not(#viewerInformation)").each(function() {
		//reset inline style
		$(this).css("fontSize", "");
		$(this).css("lineHeight", "");
		//get external css style
		var textSize = $(this).css("fontSize").substr(0, $(this).css("fontSize").length - 2);
		var lineHeight = $(this).css("lineHeight").substr(0, $(this).css("lineHeight").length - 2);
		//compute new inline style
		$(this).css("fontSize", (Number(textSize) * ratio) + "px");
		$(this).css("lineHeight", (Number(lineHeight) * ratio) + "px");
		});
	if ($("#slider").length > 0 && $("#slider").slider('value') != size)
		$("#slider").slider('value', size);
	ndNewsUtils.setCookieWithLifetime("articleViewerFontSize", size, 366);
	return (true);
};

/**
 * open all article viewer section
 * @return bool
 */
ArticleItem.expandAll = function(container)
{
	for (var i = 0; i < container.childNodes.length; i++)
	{
		if (container.childNodes[i].style)
			container.childNodes[i].style.display = "block";
	}
	ArticleItem.getExpandAllBtn().style.display = "none";
	return (true);
};

/**
 * close an article section specifying the container and the button
 * @return bool
 */
ArticleItem.closeSection = function(container, expandButton)
{
	container.style.display = "none";
	if (expandButton.style.display != "block")
		expandButton.style.display = "block";
};

/**
 * return the button whitch expans all article viewer sections
 * @return HTMLButtonElement
 */
ArticleItem.getExpandAllBtn = function()
{
	return (document.getElementById("expandBtn"));
};

ArticleItem.resize = function()
{
	if ($("#ndNewsTextViewer").length < 1)
		return (false);
	$("#ndNewsTextViewer").get(0).style.height = ndNewsUtils.windowSize().height + "px";
	//$("#ndNewsArticleSections").get(0).style.height = ndNewsUtils.windowSize().height + "px";
	if ($("#ndNewsArticle").length < 1)
		return (false);
	var paddingTopString = $("#ndNewsArticle").css("paddingTop");
	var paddingTop = Number(paddingTopString.substr(0, (paddingTopString.length - 2)));
	var closeButtonHeight = $("#articleViewerCloseBtn").height();
	//alert(ndNewsUtils.windowSize().height - paddingTop - 10);
	$("#ndNewsArticle").get(0).style.height = (ndNewsUtils.windowSize().height - paddingTop - 10) + "px";
	$("#ndNewsArticleMenu").get(0).style.height = (ndNewsUtils.windowSize().height - closeButtonHeight - 20) + "px";
	$("[id|=ndNewsArticleViewer]").get(0).style.height = ndNewsUtils.windowSize().height + "px";
	$("#ndNewsTextViewerBackground").get(0).style.height = ndNewsUtils.windowSize().height + "px";
	//$("#ndNewsTextViewerBackground").get(0).style.width = ndNewsUtils.windowSize().width + "px";
};

ArticleItem.focus = function()
{
	$("#ndNewsArticle").focus();
};

