/**
 * 
 */
var ndNewsUI = 
{
		_closeMenuCallBack : null
};

/**
 * 
 */
ndNewsUI.prototype = {};

/**
 * open fullscreen dark popup and insert objectElement into it
 * @param HTMLElement objectElement
 * @param bool returnToInitial
 * @param bool back
 * @return bool
 */
ndNewsUI.toForeground = function(objectElement, returnToInitial, callback)
{
	if (document.getElementById("ndNewsPlayerFullscreenContainer") != null || objectElement == null)
		return;
	
	//////////////////////////
	//move media object to foreground
	var container = document.getElementsByTagName("body")[0];
	var playerDiv = document.createElement("div");
	var backgroundDiv = document.createElement("div");
	var closebutton = document.createElement("button");
	var parent = objectElement.parentNode;
	var nextSibling =  objectElement.nextSibling;
	////gestion du click sur la balise div en arriere plan
	if (objectElement.addEventListener == null)
	{
		if (callback)
			callback();
		backgroundDiv.attachEvent("onclick", ndNewsUI.removeFullscreenContainer);
	}
	else
	{
		backgroundDiv.addEventListener("click", ndNewsUI.removeFullscreenContainer, false);
	}
	//div name et style
	playerDiv.setAttribute("id", "ndNewsPlayerFullscreenContainer");
	playerDiv.setAttribute("class", "fullscreenContainer");
	backgroundDiv.setAttribute("id", "fullscreenContainerBackground");
	backgroundDiv.setAttribute("class", "fullscreenContainerBackground");
	$(closebutton).attr("class", "closeButton");
	$(closebutton).click(ndNewsUI.removeFullscreenContainer);
	$(playerDiv).css("overflow", "auto");
	backgroundDiv.style.position = "absolute";
	if (ndNewsUtils.windowSize().height <  $("body").height())
		backgroundDiv.style.height = $("body").height() + "px";
	else 
		backgroundDiv.style.height = ndNewsUtils.windowSize().height + "px";
	//insert div in the page
	$(backgroundDiv).append(closebutton);
	playerDiv.appendChild(backgroundDiv);
	playerDiv.appendChild(objectElement);
	container.appendChild(playerDiv);
	//playerDiv.style.position = "absolute";
	//objectElement.style.position = "relative";
	
	//document.getElementsByTagName('html')[0].style.overflow = "hidden";
	return (true);
};

/**
 * restore media state and put it back in its original container
 * @param HTMLElement objectElement
 * @param HTMLElement container
 * @param HTMLElement nextSibling
 * @return bool
 */
ndNewsUI.returnToInitialGround = function(objectElement, container, nextSibling)
{
	//objectElement.onclick = function(){ndNewsUI.toForeground(objectElement);};
	objectElement.style.position = "static";
	objectElement.style.top = "";
	objectElement.style.marginTop = "";
	if (nextSibling)
		container.insertBefore(objectElement, nextSibling);
	else
		container.appendChild(objectElement);
	window.setTimeout( ndNewsUI.removeFullscreenContainer, 200);
	//document.getElementsByTagName('html')[0].style.overflow = "auto";
	return (true);
};

/**
 * delete fullscreen container from the document
 * @return bool
 */
ndNewsUI.removeFullscreenContainer = function()
{
	if (document.getElementById("ndNewsPlayerFullscreenContainer") != null)
		document.getElementsByTagName("body")[0].removeChild(document.getElementById("ndNewsPlayerFullscreenContainer"));
	return (true);
};

/**
 * return a 3 parts button
 * @param function callback
 * @param string value
 * @return HTMLDivElement
 */
ndNewsUI.helperBtn = function(callback, value)
{
	var btnContainer = document.createElement("div");
	var leftPart = document.createElement("p");
	var rightPart = document.createElement("p");
	var centerPart = document.createElement("button");
	leftPart.className = "btLeftPart";
	rightPart.className = "btRightPart";
	btnContainer.className = "btBox";
	centerPart.className = "btCenterPart";
	centerPart.onclick = callback;
	centerPart.innerHTML = value;
	btnContainer.appendChild(leftPart);
	btnContainer.appendChild(centerPart);
	btnContainer.appendChild(rightPart);
	return (btnContainer);
};

/**
 * add jquery draggable property to an element
 * @param jqueryElement el
 * @return bool
 */
ndNewsUI.addDraggable = function(el)
{
	el.draggable({
		axis:"y", 
		ghosting:true, 
		opacity: 0.7,
		revert: true
		});
	el.disableSelection();

	el.addClass("drag");
	return (true);
};

/**
 * add jquery droppable property to an element
 * @param jqueryElement el
 * @return bool
 */
ndNewsUI.addDroppable = function(el)
{
	el.droppable(
	{
		//elle accept les élément ayant la class ‘drag’
		accept : '.drag',
		//ici cela affecte des classes css suivant que la zone est active ou hover. Pratique pour changer de style au survol.
		//activeclass: ‘activeEmplacement’,
		//activeClass: 'hoverEmplacement',
		hoverClass: 'hoverEmplacement',
		//plusieurs zone de tolerance existe. Allez faire un tour sur la doc.
		//Ici nous choisissons de pouvoir dropper un élément quand le pointeur de la souri est dans la zone.
		tolerance: 'pointer',
		//on définit ce qu’il va se passer lorsqu’on drop un élément dans la zone. On passe l’élément draggé en parametre.
		drop: function (drag, ui)
		{
			//what to do on drag event
			//call back to send new position to server
			if (ndNewsUI.moveElementTo(ui.draggable.get(0), this))
			{
				this.parentNode.insertBefore(ui.draggable.get(0), this);
				ui.draggable.get(0).style.top = "";
				ui.draggable.get(0).style.left = "";
			}
		},
		fit: true
	}
	);
};

/**
 * send move element in database request to server
 * @param jqueryElement drag
 * @param jqueryElement drop
 * @return bool
 */
ndNewsUI.moveElementTo = function(drag, drop)
{
	var xhr = ndNewsUtils.getXHR();
	if (xhr == null)
		return (false);
	var url = "index.php?controller=NewsPaper&action=moveElementTo&source=" + drag.id + "&destination=" + drop.id;
	xhr.open("GET", url, false);
	xhr.send("");
	if (ndNewsUtils.getTextValue(xhr.responseXML.getElementsByTagName("status")[0]) == "OK")
	{
		return (true);
	}
	ndNewsUI.translate("An error occurs when moving element");
	return (false);
};

//todo: replace the following 2 methods by jquery pluging method in jquery.ndnewsUI.js

/**
 * replace the calling Element by a text box and save a allback function which will be invoke when
 * switching to span
 * @param function callBack
 * @param bool nofocus
 * @param string defaultValue
 * @return bool
 */
ndNewsUI.switchToTextBox = function(callBack, nofocus, defaultValue)
{
	var textBox = document.createElement("input");
	var textvalue = ndNewsUtils.trim($(this).text().length != 0 ? $(this).text() : $(this).val());
	textBox.value = defaultValue ? defaultValue : textvalue;
	textBox._oldValue = ndNewsUtils.trim($(this).text());
	var typeAtt = document.createAttribute("type");
	typeAtt.value = "text";
	textBox.setAttributeNode(typeAtt);
	var classAtt = document.createAttribute("id");
	classAtt.value = this.getAttribute("id");
	textBox.setAttributeNode(classAtt);
	textBox._userNewsPaperId = this._userNewsPaperId;
	textBox._saveCallBack = callBack ? callBack : this._saveCallBack;
	textBox.onblur = ndNewsUI.switchToSpan;
	this.parentNode.replaceChild(textBox, this);
	if (!nofocus)
		textBox.focus();
	return (true);
};

/**
 * call the saved callback and replace the calling Element by a span
 * @return bool
 */
ndNewsUI.switchToSpan = function()
{
	if (this._saveCallBack == null)
		return (false);
	var span = document.createElement("span");
	var classAtt = document.createAttribute("id");
	classAtt.value = this.getAttribute("id");
	span.setAttributeNode(classAtt);
	span.innerHTML += ndNewsUtils.trim(this.value);
	span._saveCallBack = this._saveCallBack;
	span.switchToTextBox = ndNewsUI.switchToTextBox;
	span.onclick = function(){span.switchToTextBox();};
	if (this.value != this._oldValue)
	{
		if (!this._saveCallBack(this.value))
			span.value = this._oldValue;
	}
	span._userNewsPaperId = this._userNewsPaperId;
	this.parentNode.replaceChild(span, this);
	return (true);
};

/**
 * compute possible max size for the given picture
 * @param HTMLImageElement imageElement
 * @param int maxwidth
 * @param int maxheight
 * @return imageSize
 */
ndNewsUI.computeOptimalListImageSize = function(imageElement, maxwidth, maxheight)
{
	var imageSize = 
	{
			height: null,
			width: null
	};
	//alert('image size width : '+imageElement.clientWidth+' height : '+imageElement.clientHeight);
	if (imageElement._imageOriginalHeight == null && imageElement._imageOriginalWidth == null)
	{	
		imageElement._imageOriginalHeight = imageElement.height;
		imageElement._imageOriginalWidth = imageElement.width;
	}
	//alert('compute new size: image width: ' + imageElement.width + " height: " + imageElement.height + "  asked width: " + maxwidth + " height: " + maxheight);
	if(imageElement.height==0 || imageElement.width==0)
		return null;// erreur
	// original ratio of the image
	var img_ratio = imageElement.width / imageElement.height;
	if(maxwidth==0 && maxheight==0) {
		// no clue... returning original size
		imageSize.width = imageElement.width;
		imageSize.height = imageElement.height;
	} else if(maxwidth==0) {
		// free width : setting height to maxheight
		imageSize.width = Math.floor(maxheight * img_ratio);
		imageSize.height = maxheight;
	} else if(maxheight==0) {
		// free height : setting width to maxwidth
		imageSize.width = maxwidth;
		imageSize.height = Math.floor(maxwidth / img_ratio);
	} else {
		var tgt_ratio = maxwidth / maxheight;
		if(tgt_ratio >= img_ratio) {
			// zone destination plus étendue en largeur que l'image source
			imageSize.width = Math.floor(maxheight * img_ratio);
			imageSize.height = maxheight;
		} else {
			// zone destination plus étendue en hauteur que l'image source
			imageSize.width = maxwidth;
			imageSize.height = Math.floor(maxwidth / img_ratio);
		}
	}
	return (imageSize);
};

/**
 * display HTML div sourceMenu and sourceMenuHeader which are hidden by default
 * and save callback on the current object which will be call when closing menu
 * @param function callBack
 * @return bool
 */
ndNewsUI.openMenu = function (callBack)
{
	var header = document.getElementById("sourceMenuHeader");
	var body = document.getElementById("sourceMenu");
	if (header == null || body == null)
		return (false);
	this._closeMenuCallBack = (callBack != null) ? callBack : null;
	header.style.visibility = "visible";
	body.style.visibility = "visible";
	return (true);
};

/**
 * hide HTML div sourceMenu and sourceMenuHeader and invoke callback
 * @param callBack
 * @return bool
 */
ndNewsUI.closeMenu = function (callBack)
{
	var header = document.getElementById("sourceMenuHeader");
	var body = document.getElementById("sourceMenu");
	header.style.visibility = "hidden";
	body.style.visibility = "hidden";
	callBack = (callBack != null) ? callBack : this._closeMenuCallBack;
	if (callBack)
		callBack();
	return (true);
};

/**
 * uncheck all source check box
 * @return bool
 */
ndNewsUI.resetAllSources = function()
{
	var inputs = document.getElementById("sourceMenu").getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++)
	{
		if (inputs[i].type.toLowerCase() == "checkbox")
		{
			inputs[i].checked = false;
		}
	}
	ndNews.switchSourceBtns();
	document.getElementById("selectSources").removeAttribute("title");
	return (true);
};


/**
 * switch selected class between 2 buttons
 * @param HTMLElement|jQeryElement btn1
 * @param HTMLElement|jQeryElement btn2
 * @return bool
 */
ndNewsUI.switch2BtnOnOff = function(btn1, btn2)
{
	$(btn1).click(
			function()
			{
				$(btn1).addClass("selected");
				$(btn2).removeClass("selected");
			});
	$(btn2).click(
			function()
			{
				$(btn2).addClass("selected");
				$(btn1).removeClass("selected");
			});
};

/**
 * return the comma-separated id string and comma-separated title string of item checked in source menu
 * @return selectedSourceList
 */
ndNewsUI.addCheckedSources = function()
{
	var sources = document.getElementById("sourcelist").getElementsByTagName("li");
	if (sources.length < 1 || document.getElementById("sourcelist").getElementsByTagName('input').length < 1)
		return (null);
	var selectedSourceList = 
	{
			sourceIds : "",
			sourceTitles : ""
	};
	var title = "sources: ";
	var sourceIds = "";
	for (var i = 0; i < sources.length; i++)
	{
		var checkbox = sources[i].getElementsByTagName('input')[0];
		if (checkbox.checked)
		{
			title += sources[i].getElementsByTagName("img")[0].title + ", ";
			sourceIds += sources[i].id.split("-")[1] + ",";
		}
	}
	selectedSourceList.sourceTitles = title.substring(0, title.length - 2);
	selectedSourceList.sourceIds = sourceIds.substring(0, sourceIds.length - 1);
	return (selectedSourceList);
};
