// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

document.observe("dom:loaded", function() {
	/*
	$$('ul.top .elt .elt div.body').each(function(item) {
		setupMore(item);
	});
	*/
});

function setupElt(elt) {
	setupMore(elt.down('.body'));
	setKnobs(elt);
}

function setupMore(item) {
	if (item != null) {
		if (item.childElements().length > 10
				&& item.down('.attachments') != null) {
			// 7 is the exact number of items required to hide after 4, but we use more
			// to have some leeway
			item.addClassName('initial');

			item.childElements()[3].nextSiblings().each(function(elt) {
				if (!elt.match('span')) {
					elt.addClassName('more');
				}
			});

			//alert(item+": "+item.childElements());
			item.down('.attachments').insert(
				{ 'before':
				'<a class="readMore" href="#" onclick="return showMore(this)">Read more / Lire plus</a>' }
			);
		}

		setSize(item.down('img.avatar'));
		setSize(item.down('.images img'));
	}
}

function showMore(elt) {
	elt.parentNode.removeClassName('initial');
	return false;
}

/* Called for each element to set its knobs */
function setKnobs(elt) {
	// To not filter out the top element
	if ($(elt.parentNode).hasClassName('top')) return;

	var knobOpened = new Element('a');
	knobOpened.href = "#";
	knobOpened.update('V');
	knobOpened.addClassName("knobOpened");
	knobOpened.onclick = function() { return closeElt(elt); }
	elt.insert({ 'top': knobOpened });

	var knobClosed = new Element('a');
	knobClosed.href = "#";
	knobClosed.update('>');
	knobClosed.addClassName("knobClosed");
	knobClosed.onclick = function() { return openElt(elt); }
	elt.insert({ 'top': knobClosed });
}

/*
 * Called for each element as it is displayed, to set its status according to
 * the filter
 */
function setKnob(elt, result) {
	// To not filter out the top element
	if ($(elt.parentNode).hasClassName('top')) return;

	var f = $("filterForm").filter;
	var filter = parseInt(f.options[f.selectedIndex].value);

	if (filter == 'null' || result >= filter) {
		elt.removeClassName('closed');
	} else if (result < filter) {
		elt.addClassName('closed');
	}
}

function closeElt(elt) {
	elt.shrink({ queue: 'knob', direction: 'top-left' });
	elt.morph("closed", { queue: 'knob' });

	return false;
}

function openElt(elt) {
	elt.removeClassName("closed");
	elt.grow(elt, { direction: 'top-left' });

	return false;
}


function getCookie(name) {
	var start = document.cookie.indexOf(name+"=");
	var len = start+name.length+1;
	if ((!start) && (name != document.cookie.substring(0, name.length))) return null;
	if (start == -1) return null;
	var end = document.cookie.indexOf(";",len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
}

function setCookie(name, value) {
	var expires_date = new Date( new Date().getTime() + (3000 * 1000 * 60 * 60 * 24) );
	document.cookie = name + "=" +escape( value ) +
		(";expires=" + expires_date.toGMTString());
	/*+ 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );*/
}


/*
 * The parameter 'filter' is not the value itself, but an index!
 */
function setFilter(filter, elt) {
	setCookie('filter', $("filterForm").filter.selectedIndex);

	new Ajax.Updater('listByVote', '/elt/listByVote/'+elt, { asynchronous:true, evalScripts:true });
	new Ajax.Updater('listByDate', '/elt/listByDate/'+elt, { asynchronous:true, evalScripts:true });

	$$('.result').each(function(result) {
		//alert(parseInt(result.innerHTML)+', '+filter);
		if (filter == 'null' || parseInt(result.innerHTML) >= parseInt(filter)) {
			Element.removeClassName(result.parentNode.parentNode.parentNode, 'closed');
		} else if (parseInt(result.innerHTML) < parseInt(filter)) {
			Element.addClassName(result.parentNode.parentNode.parentNode, 'closed');
		}
	});
}

function setFilterFromCookie() {
	if (getCookie('filter') != null) {
		$("filterForm").filter.selectedIndex = getCookie('filter');
	} else {
		$("filterForm").filter.selectedIndex = 2;
	}
	$("filterForm").filter.onchange();
}

function decrementFilter() {
	$("filterForm").filter.selectedIndex--;
	$("filterForm").filter.onchange();
	return false;
}

function incrementFilter() {
	$("filterForm").filter.selectedIndex++;
	$("filterForm").filter.onchange();
	return false;
}

/*
 * Set all choices to nothing.
 * Mostly used for login/logout
 */
function resetChoices() {
	document.body.select('selected').each( function(choice) {
		Element.removeClassName(choice, 'selected');
	});
}

/*
 * Set all choices to user's values
 * Mostly used for login/logout
 */
function updateChoices(choices) {
	$$('.con').each( function(choice) {
		if (choices[choice.parentNode.parentNode.parentNode.parentNode.id] == "-1") {
			Element.addClassName(choice, 'selected');
		}
	});
	$$('.result').each( function(choice) {
		if (choices[choice.parentNode.parentNode.parentNode.id] == "-1"
			|| choices[choice.parentNode.parentNode.parentNode.id] == "1") {
			Element.addClassName(choice, 'selected');
		}
	});
	$$('.pro').each( function(choice) {
		if (choices[choice.parentNode.parentNode.parentNode.parentNode.id] == "1") {
			Element.addClassName(choice, 'selected');
		}
	});
}

function setSize(img) {
	//var divHeight = findPosY($(img.parentNode.parentNode).down('.eltSub')) - findPosY(img);
	/*
	var divHeight = $(img.parentNode).getHeight();

	if (false && img.offsetWidth > 1) {
		var debug = document.createElement("span");
		debug.appendChild(document.createTextNode(
					"getHeight: "+$(img.parentNode).getHeight()
					+"; divHeight: "+divHeight
					+"; img.offsetHeight:"+img.offsetHeight
					+"; img.offsetParent.offsetWidth: "+img.offsetParent.offsetWidth
					+"; img.offsetWidth:"+img.offsetWidth
					+"; Element.viewportOffset: "+$(img.parentNode).down('.choice')
					+"; findPosY(img):"+findPosY(img)
					+"; findPosY($(img.parentNode).select('choice')[0]):"
					+findPosY($(img.parentNode).select('choice')[0])));
		if (img.parentNode.parentNode) img.parentNode.parentNode.insertBefore(debug, img.parentNode);
	}
	*/

	if ($(img)) {
		var divHeight = $(img.parentNode).getHeight() - 12;
		//alert(img.parentNode.parentNode.id+": "+divHeight);

		if (divHeight <	0) {
			// This is specific to other inline images
			divHeight = $(img.parentNode.parentNode).getHeight() - 24;
		}

		if (divHeight > 0) {
			$(img).setStyle({ maxHeight: divHeight+'px' });
			//if (divHeight > 0 && $(img).getHeight() > divHeight) $(img).setStyle({ height: divHeight+'px' });
		}
	}
}

function findPosY(obj) {
	if (!obj) return 0;
	var curtop = 0;
	if (obj.offsetParent)
		while (1) {
			curtop += obj.offsetTop;
			if (!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

// Widen the elt until it is moved below or it is wider than its parent elt
function widen(elt) {
	if (elt.widened) return;
	elt.widened = true;

	var initialPosition = findPosY(elt);
	var initialParentWidth = elt.parentNode.offsetWidth;
	while (initialPosition == findPosY(elt) && elt.offsetWidth < initialParentWidth) {
		elt.cols = elt.cols + 1;
	}
	elt.cols = elt.cols - 1;
	//alert(elt.cols);
}

// Resize text area accordingly to its content
function resize(elt) {
	//alert(elt.parentNode.offsetWidth);
	//elt.style.width = elt.parentNode.offsetWidth+"px";
	widen(elt);
	var lines = elt.value.split('\n');
	var newRows = lines.length + 1;
	var oldRows = elt.rows;

	for (var i = 0; i < lines.length; i++) {
		var line = lines[i];
		if (line.length >= elt.cols) newRows += Math.floor(line.length / elt.cols);
	}
	//alert(newRows);

	if (newRows > elt.rows) elt.rows = newRows;
	if (newRows < elt.rows) elt.rows = Math.max(5, newRows);
}
