/* *** CSS class manipulation *** */
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}
/* ****** */

/* *** CSS style manipulation *** */
function hasStyle(ele,stl,val) {
	var ret_val = false;
	if(val)
	{
		ret_val = eval("ele.style." + stl) == val;
	}
	else
	{
		ret_val = eval("ele.style." + stl) != null;
	}
	return ret_val;
}

function addStyle(ele,stl,val) 
{
	if (!this.hasStyle(ele,stl,val)) 
	{
		eval("ele.style." + stl + " = val");
	}
	
}

function removeStyle(ele,stl) {
	if (hasStyle(ele,stl)) 
	eval("ele.style." + stl + " = ''");
}
/* ****** */

/* *** event manipulator *** */
function AttachEvent(obj,evt,fnc,useCapture){
	if (!useCapture) useCapture=false;
	if (obj.addEventListener){
		obj.addEventListener(evt,fnc,useCapture);
		return true;
	} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
	else{
		BrowserAttachEvent(obj,evt,fnc);
		obj['on'+evt]=function(){ BrowserFireEvent(obj,evt) };
	}
} 

//The following are for browsers like NS4 or IE5Mac which don't support either
//attachEvent or addEventListener
function BrowserAttachEvent(obj,evt,fnc){
	if (!obj.myEvents) obj.myEvents={};
	if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
	var evts = obj.myEvents[evt];
	evts[evts.length]=fnc;
}

function BrowserFireEvent(obj,evt)
{
	if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
	var evts = obj.myEvents[evt];
	for (var i=0,len=evts.length;i<len;i++) evts[i]();
}
/* ****** */


/* *** extend Array *** */
Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

Array.prototype.contains = function (element) 
{
	for (var i = 0; i < this.length; i++) 
	{
		if (this[i] == element) 
		{
			return true;
		}
	}
	return false;
};
/* ****** */

function callbackChangeCategory()
{
}

function reloadFeed()
{
	// hide the comment iframe container and reload the current pagination
	paginate({next:current_next_param});
}

var current_next_param = 1;
function paginate(param_obj)
{
	current_next_param = param_obj.next; // set the current next param so if a comment is made, we can reload

	param_obj.callback = callbackPaginate;
	param_obj.is_post = false;
	loadXML(param_obj, "load_feed.xml.php");
}

function callbackPaginate(param_obj)
{
	// reset the comment form open flag
	comments_open = false;

	var feed = document.getElementById("feed");
	var main_containing_inner = feed.parentNode.cloneNode(true);
	var main_containing_block = feed.parentNode.parentNode.parentNode.cloneNode(true);

	// reset the grad border div
	main_containing_block.innerHTML = "";
	removeStyle(main_containing_block, "width");
	removeStyle(main_containing_block, "height");
	
	main_containing_block.appendChild(main_containing_inner); 

	// clear the current feed, append the passed feed_items
	var feed_items = param_obj.xml.getElementsByTagName("feed_item");
	feed.innerHTML = "";
	for(i=0; i<feed_items.length; i++)
	{
		feed_content_item = feed_items[i].firstChild.nodeValue;

		feed_content_item = feed_content_item.replace("<![CDATA[", "");
		feed_content_item = feed_content_item.replace("]]>", "");
		
		feed.innerHTML += feed_content_item;
	}
	
	// append the pagination
	var pagination_content = param_obj.xml.getElementsByTagName("pagination")[0].firstChild.nodeValue;
	pagination_content = pagination_content.replace("<![CDATA[", "");
	pagination_content = pagination_content.replace("]]>", "");
	
	feed.innerHTML += pagination_content;
	
	// copy the inner div containing the feed
	var inner_clone = feed.parentNode.cloneNode(true);

	// clear main container
	var blk5 = document.getElementById("blk5");
	blk5.innerHTML = "";
	
	blk5.appendChild(inner_clone);

	// re-apply the border	
	reapplyGradBorder(blk5);
}

function approve(param_obj)
{
	param_obj.action = "approve";
	param_obj.callback = callbackModerate;

	loadXML(param_obj, "/admin/moderate.xml.php");
}

function deny(param_obj)
{
	param_obj.action = "deny";
	param_obj.callback = callbackModerate;

	loadXML(param_obj, "/admin/moderate.xml.php");
}

function callbackModerate(param_obj)
{
	var xml = param_obj.xml;
	if(xml.getElementsByTagName("errors").length == 0)
	{
		// hide the feed item just moderated
		var feed_item_cont = document.getElementById("feed-item-cont" + param_obj.id);
		
		var t = new Tween(feed_item_cont.style, 'height', Tween.strongEaseOut, feed_item_cont.offsetHeight, 0, 0.5, "px");
		t.start();
	}
}

function deleteComment(comment_id)
{
	loadXML({id:comment_id, callback:callbackDeleteComment}, "/admin/delete_comment.xml.php");
}

function callbackDeleteComment(param_obj)
{
	var xml = param_obj.xml;
	if(xml.getElementsByTagName("errors").length == 0)
	{
		// hide the comment just deleted
		var comment = document.getElementById("comment" + param_obj.id);
		
		var t = new Tween(comment.style, 'height', Tween.strongEaseOut, comment.offsetHeight, 0, 0.5, "px");
		t.onMotionFinished = function()
		{
			addStyle(comment, "display", "none");
		}
		t.start();
	}	
}

function loadXML(param_obj, service)
{
	var xmlhttp;
	if(window.XMLHttpRequest)
	{
		xmlhttp = new XMLHttpRequest();
	}
	else if(window.ActiveXObject)
	{
		xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
	} 
	else
	{
		return false;
	}

	if(xmlhttp)
	{
		var params;
		service += "?";
		for(param in param_obj)
		{
			service += param + "=" + param_obj[param] + "&";
		}

		if(param_obj.is_post)
		{
			// get the service without any params
			var service_arr = service.split("?");
			service = service_arr[0];
			params = service_arr[1];

			xmlhttp.open("POST", service, true);

			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlhttp.setRequestHeader("Content-length", params.length);
			xmlhttp.setRequestHeader("Connection", "close");
		}
		else
		{
			service += "&rand=" + Math.random();	// random number for IE, otherwise xml is cached
			xmlhttp.open("GET", service, true);
		}

		xmlhttp.onreadystatechange = function()
		{
			if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
			{			
				if(xmlhttp.responseXML)
				{
					param_obj.xml = xmlhttp.responseXML;
				}
				else
				{
					param_obj.xml = xmlhttp.responseText;
				}
				
				// override the default response type
				if(param_obj.force_response_xml)
				{
					param_obj.xml = xmlhttp.responseXML;
				}
				else if(param_obj.force_response_text)
				{
					param_obj.xml = xmlhttp.responseText;
				}
				
				// evaluate the callback function 
				if(param_obj.callback != null)
				{
					eval(param_obj.callback(param_obj));
				}
				else
				{
					alert("param_obj.callback must be set");
				}
			}
		}
				
		xmlhttp.send(params);
	}
	else
	{
		alert("Browser does not support AJAX requests");
	}
}










function openVideoOverlay(param_obj)
{
	// set the title div
	// document.getElementById("overlay-video-title").innerHTML = param_obj.title;
	
	// set the description
	// document.getElementById("overlay-video-description").innerHTML = param_obj.description;
	
    //set flash player properties
	var flashvars = { };
	flashvars.autoPlay = "true";
	flashvars.flv = param_obj.video;
	flashvars.thumb = param_obj.thumb;
	
	var params = {};
	params.menu = "false";
	
	var attributes = {};
	attributes.id = "overlay-video-cont";
	attributes.name = "overlay-video-cont";
	
	//Stroke flash player and set the flash title on div element
	swfobject.embedSWF("/flv_player_v2_3.swf", "overlay-video-cont", "440", "330", "9.0.0", "/script/expressInstall.swf", flashvars, params, attributes);
	document.getElementById("overlay-video-title").innerHTML=param_obj.title;

	resizeOverlayLayers(0);

	// show all necessary layers
	addStyle(document.getElementById("overlay"), "display", "block");
	addStyle(document.getElementById("overlay-bg"), "display", "block");
	addStyle(document.getElementById("overlay-video"), "display", "block");
	
	//Kill SilverLight player layer
	hideSilverlightPlayer();	
}

function getWidthAndHeight() 
{
	resizeOverlayLayers(this.width);
}

function openImageOverlay(param_obj)
{
	var ovr_img = document.getElementById("overlay-image");
	ovr_img.getElementsByTagName("img")[0].src = param_obj.image_path;
	ovr_img.getElementsByTagName("p")[0].innerHTML = param_obj.caption ? param_obj.caption : "";

	var imageToResize=new Image();
	imageToResize.src=param_obj.image_path;
	imageToResize.onload = getWidthAndHeight;

	addStyle(document.getElementById("overlay"), "display", "block");
	addStyle(ovr_img, "display", "block");
	addStyle(document.getElementById("overlay-bg"), "display", "block");
	
	var ot = new OpacityTween(document.getElementById("overlay-bg"), Tween.strongEaseOut, 0, 70, 0.5);
	ot.start();
	
	//Kill SilverLight player layer
	//hideSilverlightPlayer();
}

function hideLayers(arr)
{
	for(i=0; i<arr.length; i++)
	{
		addStyle(document.getElementById(arr[i]), "display", "none");
	}
}


function closeOverlay(arr)
{
	removeStyle(document.getElementById("overlay-bg"), "display");
	removeStyle(document.getElementById("overlay-image"), "display");	
	removeStyle(document.getElementById("overlay-video"), "display");	
	removeStyle(document.getElementById("overlay"), "display");	
	var ovr_img = document.getElementById("overlay-image");
	ovr_img.getElementsByTagName("img")[0].src = "";
	
	//Rise SilverLight player layer
	//drawSilverlightPlayer();	
}

function resizeOverlayLayers(imageWidth)
{
	var viewport_height = document.documentElement.offsetHeight;
	var page_height = document.documentElement.scrollHeight;
	
	// set the height of the overlay bg
	if(page_height > viewport_height)
	{
		addStyle(document.getElementById("overlay-bg"), "height", page_height + "px");
	}
		
	//set left alignment
    var	leftOffset=parseInt((imageWidth / 2));
	
	// move the containing overlay div
	addStyle(document.getElementById("overlay"), "top", document.documentElement.scrollTop + 100 + "px");
	addStyle(document.getElementById("overlay"), "marginLeft", "-"+leftOffset+"px");
}

var comments_open = false;
function openComment(param_obj)
{
	// the comment form is hidden in the feed div. Move it to the offsetTop of the clicked anchor and display 
	var comment = document.getElementById("comment-cont");
	
	// add the id param to the url of the iframe
	var comment_iframe = document.getElementById("comment-iframe");
	if(comment_iframe.src.indexOf("?") != -1)
	{
		comment_iframe_path = comment_iframe.src.split("?");
	}
	
	comment_iframe_path = comment_iframe.src.indexOf("?") != -1 ? (comment_iframe.src.split("?"))[0] : comment_iframe.src;
	comment_iframe.src = comment_iframe_path + "?feed_item_id=" + param_obj.id;
	
	addStyle(comment, "display", "block");
	addStyle(comment, "top", param_obj.obj.offsetTop + param_obj.obj.offsetHeight + "px");

	// set the open flag, used to stop the page from reloading in eventolive.tpl
	comments_open = true;	
}

function openHiddenComments(param_obj)
{
	addStyle(document.getElementById('hidden-comments' + param_obj.id), 'display', 'block');
	addStyle(param_obj.obj.parentNode, 'display', 'none');
	
	// close the comment box (if open)
	addStyle(document.getElementById("comment-cont"), "display", "none");
	
	// reapply the border
	// copy the inner div containing the feed
	var inner_clone = document.getElementById("feed").parentNode.cloneNode(true);

	// clear main container
	var blk5 = document.getElementById("blk5");
	blk5.innerHTML = "";
	
	blk5.appendChild(inner_clone);

	// re-apply the border
	reapplyGradBorder(blk5);
	

}



function reapplyGradBorder(div_obj)
{
	// reset the height and width of div_obj
	removeStyle(div_obj, "width");
	removeStyle(div_obj, "height");

	// re-apply the border (after set period)
	setTimeout(function(){
		applyGradBorder(div_obj);
	}, 100);
}

function applyGradBorder(div_obj)
{
	// store the content
	var cont = div_obj.innerHTML;
	
	// set width and height vars before wiping (width -2)
	var width = div_obj.offsetWidth -2;
	var height = div_obj.offsetHeight;

	// wipe the content
	div_obj.innerHTML = "";
	
	// add 5 internal divs
	var int_divs = new Array();
	for(j=0; j<5; j++)
	{
		int_divs[j] = document.createElement("div");
		int_divs[j].className = "int-grad-border gb" + j;
		
		// set the width and height
		addStyle(int_divs[j], "width", (width + (2*j -1) > 0 ? width + (2*j -1) : 0) + "px");
		addStyle(int_divs[j], "height", (height + (2*j -1) > 0 ? height + (2*j -1) : 0) + "px");
		
		// append the div
		div_obj.appendChild(int_divs[j]);
	}
	
	int_divs[0].innerHTML = cont;
	
	// reset the containers width and height
	addStyle(div_obj, "width", (width > 0 ? width : 0) + "px");
	addStyle(div_obj, "height", (height > 0 ? height : 0) + "px");
}

function initGradBorders()
{
	var divs = document.getElementsByTagName("div");
	for(i=0; i<divs.length; i++)
	{
		if(hasClass(divs[i], "grad-border"))
		{
			applyGradBorder(divs[i]);
		}
	}
}

function init()
{
	initGradBorders();
}

AttachEvent(window, "load", init, false);
function drawSilverlightPlayer()
{
	//Setting variables
	var _width  = 440; 
	var _height = 330;
	var pathVideo = "http://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=4116";
	var pathXml = "";
	var autoPlay = false;		
	var url = "";
	if (pathXml!="")
		url = "xmlPath="+pathXml;
	else
		url = "videoPath="+pathVideo;
	url+=",auto=true"
	var layerToGet=document.getElementById("silverLightPlayer");
	
	//Change div properties if SilverLight is installed
	if (detectSilverLight())
	{
		var layerToFix=document.getElementById("silverLightPlayerLayerFix");
		if (layerToFix)
		{
			layerToFix.style.width='440px';
			layerToFix.style.height='330px';
			layerToFix.style.display='block';
			layerToFix.style.backgroundColor='#000000';
		}
	}
	
	//Stroke player
	var playerOptions="";
	playerOptions = "<object height="+_height+" width="+_width+" type=\"application/x-silverlight-2\" data=\"data:application/x-silverlight-2,\" id=\"pluginz\" name=\"pluginz\">" 
	+ "<param value=\"http://www.objects.rai.it/dl/objects/silverlight/raitv/Lettore_Rai_VOD.xap\" name=\"source\" id=\"source\">"
	+ "<param value=\"#0a0a0a\" name=\"background\">"
	+ "<param value=\"false\" name=\"windowless\">"
	+ "<param value=\"2.0.31005.0\" name=\"minRuntimeVersion\">"
	+ "<param value=\"true\" name=\"autoUpgrade\">"
	+ "<param value=\"silverLightPlayer\" name=\"parentElement\">"
	+ "<param value=\"true\" name=\"enableHtmlAccess\">"
	+ "<param value=\""+url+",auto=true\" name=\"initparams\">"
	+ "<div id=\"silverlight-base\" class=\"grad-border\"><div class=\"inner\">"
	+ "<a href=\"http://www.microsoft.com/silverlight/resources/install.aspx\" target=\"_blank\"><img src=\"/images/evento/logo_it_silverlight.jpg\" alt=\"\" /></a>"
	+ "<p>Installa Silverlight, il plug-in che ti consentir&agrave; la visione del video</p></div></div>"	
	+"</object>";
	
	//Disegna
	var layer=document.getElementById("silverLightPlayer");
	var parent=layer;	
	var movieclipContainer=document.createElement("div");
		movieclipContainer.id="movieclipContainer";
		movieclipContainer.className="box_video";
		movieclipContainer.innerHTML=playerOptions;	
		if (parent) 
			parent.parentNode.insertBefore(movieclipContainer, parent);
		if (layer)
			layer.style.display='block';		
}		

function hideSilverlightPlayer()
{
	var layer=document.getElementById("silverLightPlayer");
	var child=document.getElementById("movieclipContainer");
	if (layer) layer.parentNode.removeChild(child);	
}

function detectSilverLight()
{
	var browser = navigator.appName;
	var silverlightInstalled = false;
	if (browser == 'Microsoft Internet Explorer')
	{
		try 
		{
			var slControl = new ActiveXObject('AgControl.AgControl');
			silverlightInstalled = true;
		}
		catch (e) 
		{
		}
	}
	else 
	{
		try 
		{
			if (navigator.plugins["Silverlight Plug-In"]) 
			{
				silverlightInstalled = true;
			}
		}
		catch (e) 
		{
		}
	}
	return silverlightInstalled;
}

//Funzione che apre un div e chiude tutti gli altri //
function THISonTHAToff(code)
{
	fl = document.getElementsByTagName("a");
	for (i = 0; i < fl.length; i++) {
		if (fl[i].id.substr(0,8) == "lfotoPer") {
        	removeClass(fl[i],"hide");
        }
	}
	for (i = 0; i < fl.length; i++) {
		if (fl[i].id == "l"+code) {
        	addClass(fl[i],"hide");
        }
	}
	
    ff = document.getElementsByTagName("div");
    for (i = 0; i < ff.length; i++) {
        if (ff[i].id.substr(0,7) == "fotoPer") {
        	addClass(ff[i],"hide");
        }
    }
    for (i = 0; i < ff.length; i++) {
        if (ff[i].id == code) {
            if (hasClass(ff[i],"hide")) {
                removeClass(ff[i],"hide");
            }
        }
    }
}
