var accordion=function(){
	var tm=sp=10;
	function slider(n){this.nm=n; this.arr=[]}
	slider.prototype.init=function(t,c,k){
		var a,h,s,l,i; a=document.getElementById(t); this.sl=k?k:'';
		h=a.getElementsByTagName('dt'); s=a.getElementsByTagName('dd'); this.l=h.length;
		for(i=0;i<this.l;i++){var d=h[i]; this.arr[i]=d; d.onclick=new Function(this.nm+'.pro(this)'); if(c==i){d.className=this.sl}}
		l=s.length;
		for(i=0;i<l;i++){var d=s[i]; d.mh=d.offsetHeight; if(c!=i){d.style.height=0; d.style.display='none'}}
	}
	slider.prototype.pro=function(d){
		for(var i=0;i<this.l;i++){
			var h=this.arr[i], s=h.nextSibling; s=s.nodeType!=1?s.nextSibling:s; clearInterval(s.tm);
			if(h==d&&s.style.display=='none'){s.style.display=''; su(s,1); h.className=this.sl}
			else if(s.style.display==''){su(s,-1); h.className=''}
		}
	}
	function su(c,f){c.tm=setInterval(function(){sl(c,f)},tm)}
	function sl(c,f){
		var h=c.offsetHeight, m=c.mh, d=f==1?m-h:h; c.style.height=h+(Math.ceil(d/sp)*f)+'px';
		c.style.opacity=h/m; c.style.filter='alpha(opacity='+h*100/m+')';
		if(f==1&&h>=m){clearInterval(c.tm)}else if(f!=1&&h==1){c.style.display='none'; clearInterval(c.tm)}
	}
	return{slider:slider}
}();

var slider1;
window.addEvent('load', function() { 

	/** Cargamos el acordeón **/
	if($("slider")) {
		slider1=new accordion.slider("slider1");
		slider1.init("slider","0","open"); 
	}
	new SmoothScroll({ duration:700, links: '.smoothAnchors'}, window);
	mediaModal();
	if($('menu')) {
		// fancy menu
		new MorphList('menu-list', {
			transition: Fx.Transitions.Sine.easeIn,
			duration: 200/*,
			onClick: function(ev, item) {
				ev.stop();
			}*/
		});
	}

	if($('pictures-s')) {
		niniosPortlet();
		//console.info("Portlet: NiÃ±os");
	}

	/* Esto agrega dos event handlers a un div que contiene el tï¿½tulo de mediateca. 
	 * onMouseOver y onMouseOut. Actualmente no sirven aparentemente.*/
	if($('mediateca-title-show')) {
		
		var link_container  = $('mediateca-title-container');
		
		var mouseOver = function() {
			$('mediateca-title-show').style.display = "block";
		};
		
		var mouseOut = function() {
			$('mediateca-title-show').style.display = "none";	
		};
		
		link_container.addEvent('mouseover',mouseOver);
		link_container.addEvent('mouseout',mouseOut);
	}
	

	if($('mediaplayer')) {
		mediaplayerPortlet();
		//console.info("Portlet: Media player");
	}

	searchInit('searchForm', 'search');
	searchInit('searchForm2', 'search2');
	
	validateRegister();

	setCurrentDate();
	
	var welcomeUser = $('welcomeUser');
	if (welcomeUser) {
		welcomeUser.replaces($('showLogin'));
		welcomeUser.addClass('showUserWelcome');
		//console.info("Welcome " + welcomeUser.get('text'));
	} else {
		var usernameInput = $('j_username');
		var passwordInput = $('j_password');
		if(usernameInput) {
			inputStyled(usernameInput, 'usernameInput');
			inputStyled(passwordInput, 'passwordInput');
		}
	}
	
});


window.addEvent('domready', function() {
	if($('timeline-carousel')) {
		timeline();
		//console.info("Portlet: LÃ­nea de tiempo");
	} else {
		//console.warn("No existe la linea de tiempo");
	}
	triplePortlet();
	
	if($('searchResults')) {
		$$('#searchResults .ver').each(function(anImage) {
			SqueezeBox.assign(anImage, {
				size: {x: 680, y: 360}
			});
		});
	}
	
	if($('mediateca-destacados')) {
		$$('#mediateca-destacados .ver').each(function(anImage) {
			SqueezeBox.assign(anImage, {
				size: {x: 680, y: 360}
			});
		});
	}
});

function inputStyled(input, style) {
	input.addEvent('focus', function(){
		input.removeClass(style);
	});
	input.addEvent('blur', function(){
		if(this.value == '') {
			input.addClass(style);
		}
	});
	if(input.value.length == 0) {
		input.addClass(style);
	} else {
		input.removeClass(style);
	}
}

UTF8 = {
	encode: function(s){
		for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
			s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
		);
		return s.join("");
	},
	decode: function(s){
		for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
			((a = s[i][c](0)) & 0x80) &&
			(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
			o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
		);
		return s.join("");
	}
};

function getParam(paramName) {
     var regexS = "[\\?&]"+ paramName +"=([^&#]*)";
     var regex = new RegExp ( regexS );
     var tmpURL = window.location.href;
     tmpURL = unescape(tmpURL);
     var results = regex.exec( tmpURL );
     var param = "";
     if( results != null )
          param = results[1];
     return (UTF8.decode(param));
}


function searchInit(sF, sQ) {

	param = getParam("searchText");
	// Search
	var searchInput = $(sQ);
	if(searchInput) {
		if((searchInput.value == '') && (param == "")) {
			searchInput.value = 'Buscar';
		}
		if(param != "") {
			searchInput.value = param;
		}
		searchInput.addEvent('focus', function() {
			if(this.value != '' && this.value == 'Buscar') {
				this.value = '';
			}
		});
	
		searchInput.addEvent('blur', function() {
			if(this.value == '') {
				this.value = 'Buscar';
			}
		});
		
		

		var searchForm = $(sF);
		var portal_path = $('portal_path').value;
		searchForm.getElement('div').addEvent('click', function(){
			if (searchInput.value != '') {
				var textSearchInput = searchInput.value;
				searchForm.action = portal_path + "/busqueda?searchText="+ textSearchInput + "&page=1";
				searchForm.submit();
			}
		});

		searchInput.addEvent('keydown', function(event){
		    if (event.key == 'enter' && searchInput.value != '') {
				var textSearchInput = searchInput.value;
				searchForm.action = portal_path + "/busqueda?searchText="+ textSearchInput + "&page=1";
				searchForm.submit();
		    }

		});
	}
}

function triplePortlet() {

	var triples = $$('.triple-block');
	triples.forEach(function(triple) {
		new SimpleTabs(triple, {
			selector: 'h4',
			hover: true
		});
	});

}

function timeline() {
	var startPoint			= 18; //in pixels
	var totIncrement		= startPoint; //will be modified by 'previous' and 'next'
	var increment			= 125;
	var children = $('timeline-carousel').getChildren('li');
	var maxRightIncrement	= -(increment * (children.length) - 7 * increment);
	

	var fx = new Fx.Tween('timeline-carousel', {
		property: 'margin-left',
		duration: 350,
		transition: Fx.Transitions.Back.easeOut,
		wait: true
	});

	var livePos = false;
	children.forEach(function(child, index){
		if(child.getElement('a.vivo')) {
			livePos = index;
		}
	});

	if(livePos) {
		totIncrement = totIncrement - increment * livePos + increment * 3;
		fx.start(totIncrement);
	}
	//-------------------------------------
	// EVENTS for the button "previous"
	$('previous').addEvents({
		'click' : function(event){
			if(totIncrement<0){
				totIncrement = totIncrement+increment;
				/*fx.stop()*/
				fx.start(totIncrement);
			}
		}
	});

	//-------------------------------------
	// EVENTS for the button "next"
	$('next').addEvents({
		'click' : function(event){
			if((totIncrement-startPoint)>maxRightIncrement) {
				totIncrement = totIncrement-increment;
				/*fx.stop()*/
				/*fx.start(totIncrement);*/
				/*fx.tween('margin-left', totIncrement);*/
				fx.start(totIncrement);
			}
		}
	});

	//console.info("Grilla cargada con " + children.length + " elementos");
}

var ChildSlider = new Class({   

	Implements: [Options],

	options: {/*             
		onClick: $empty,
		onMorph: $empty,*/
	},

	initialize: function(sectionWrapper, menu, options) {
		var that = this;
		this.currentIndex = 0;
		this.lastIndex = 0;
		this.setOptions(options);
		this.menu = $(menu);
		this.menuitems = this.menu.getChildren();
		this.sections = $(sectionWrapper).getChildren();
		this.menuitems.each(function(menu, index) {
			menu.addEvents({
				mouseenter: function(e){ e.stop(); that.show(index); },
				mouseleave: function(e){ e.stop(); that.play(); },
				click: function(ev){ return false; }
			});
		});
		this.privatePlay = function(inc) {
			if (inc) {
				this.currentIndex++;
				if (this.currentIndex >= this.menuitems.length) this.currentIndex = 0;
			}
			this.sections[this.lastIndex].fade('out');
			this.menuitems[this.lastIndex].removeClass('current');
			var section = this.sections[this.currentIndex];
			var menu = this.menuitems[this.currentIndex];
			section.fade('in');
			menu.addClass('current');
			this.lastIndex = this.currentIndex;
			//console.info("Ãºltimo indice: " + this.lastIndex);
		}
		this.periodical = this.privatePlay.periodical(3000, this, true) ;
	},

	setCurrent: function(el, effect){
		if(this.current) this.current.removeClass('current');
		if(el) this.current = el.addClass('current');    
		return this;
	},       

	show: function(index) {
		$clear(this.periodical);
		this.currentIndex = index;
		this.privatePlay();
		return this;
	},

	play: function() {
		this.periodical = this.privatePlay.periodical(3000, this, true);
	}

});

function niniosPortlet() {
	new ChildSlider('pictures-s', 'menu-s');
}


function mediaplayerPortlet() {
	var s3 = new SWFObject("/recursos/media/swf/player.swf","ply","325","243","9","#FFFFFF");
		s3.addParam("allowfullscreen","true");
		s3.addParam("allowscriptaccess","always");
		s3.addParam("wmode","opaque");
		s3.addParam("flashvars", "file=http://200.47.87.253/LordoftheRings.flv&image=/recursos/media/images/mediaplayer-prev.jpg&backcolor=#06A9D2&frontcolor=#FFFFFF&screencolor=#000000&skin=/recursos/media/swf/bright.swf");
		s3.write("mediaplayer");
}

function mediaModal() {
	$$('#timeline-carousel .ver').each(function(aVideo) {
		/*var styleClass = aVideo.get('class');
		console.info("Video ID: " + aVideo.get('id') + " target: " + aVideo.get('id') + '-target');
		var id = "mb_" + aVideo.get('id') + '-target';
		console.info(id);*/
		SqueezeBox.assign(aVideo, {
			size: {x: 680, y: 360}
		});
	});
}

function livePlay(el) {
	var el = $(el);
	var liveVideo = el;
	var data = '';
	el.removeAttribute("onclick");

//	if (Browser.Engine.trident) {
//		data ='<object id="livePlayer" width="460" height="345" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject"><param name="FileName" value="mms://canal7envivo.telecomdatacenter.com.ar/canal7envivo"><param name="AutoStart" value="True"><param name="ShowStatusBar" value="0"><param name="ShowControls" value="0"><param name="DefaultFrame" value="mainFrame"><embed id="saa" type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" src="mms://canal7envivo.telecomdatacenter.com.ar/canal7envivo" width="460" height="345" showstatusbar="0" ShowControls="0"></embed></object>';
//	} else {
//		if(Browser.Engine.gecko) {
			data ='<div  style="z-index:2002;position:absolute;"><embed type="application/x-shockwave-flash" src="/recursos/media/swf/player.swf" id="plycanal7.video.video-player" name="plycanal7.video.video-player" bgcolor="#FFFFFF" quality="high" allowfullscreen="true" allowscriptaccess="always"	wmode="transparent" flashvars="type=rtmp&amp;streamer='+ urlLive + 
					'&amp;file=livestream&amp;backcolor=#06A9D2&amp;frontcolor=#FFFFFF&amp;screencolor=#000000&amp;skin=/recursos/media/swf/bright.swf" height="350" width="500"></embed></div>';
//		}
//	}
	liveVideo.innerHTML = data;
	//$('livePlayer').play();
	//$('livePlayer').stop();
}

function openLivePlayerPopUp(){
	$('livePlayerId').sendEvent('stop');
	var portal_path = $('portal_path').value;
	window.open(portal_path + '/live-video-popup','video','width=540,height=380,menubar=no,location=no,resizable=no,scrollbars=no,status=yes,maximize=no');
}

/**
* Deseleeciona todas opciones del menu y elige una que viene dada por el
* parametro menu
*/
var urlMenuMap = new Array();
urlMenuMap["inicio"] = "menu-inicio"; 
urlMenuMap["grilla"] = "menu-grilla"; 
urlMenuMap["mediateca"] = "menu-mediateca"; 
urlMenuMap["en-vivo"] = "menu-envivo"; 
urlMenuMap["programas"] = "menu-programas"; 
urlMenuMap["comunidad"] = "menu-comunidad"; 
urlMenuMap["institucional"] = "menu-institucional"; 
urlMenuMap["prensa"] = "menu-prensa"; 
urlMenuMap["ninguno"] = "ningun-menu-seleccionado"; 

function selectMenu(menu,requestedURL) {
	var menus = $("menu-list");
	if (menus != null) {
		var lis = menus.getElementsByTagName("li");
		if(!(menu && menu.length > 0)) {
			menu = "inicio";
		}
		for(var i = 0; i<lis.length; i++) {
			var li = lis[i];
			if(urlMenuMap[menu] == li.id) {
				li.setAttribute("class","current");
				li.setAttribute("className","current");
			}
			else {
				li.removeAttribute("class");
				li.removeAttribute("className");
			}
		}
	}
}

function setCurrentDate() {
	var div = $('current-date');
	if(div) {
		var mydate=new Date()
		var year=mydate.getYear()
		if (year < 1000) 
			year+=1900
		var day=mydate.getDay()
		var month=mydate.getMonth()
		var daym=mydate.getDate()
		if (daym<10)
			daym="0"+daym
		var dayarray=new Array("Domingo","Lunes","Martes","Mi&eacute;rcoles","Jueves","Viernes","S&aacute;bado")
		var montharray=new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
		div.innerHTML = "<span>"+dayarray[day]+" "+daym+" de "+montharray[month]+" de "+year+"</span>"; 
	}
}

function showRollup(div,show) {
	var divs = div.getElementsByTagName("div");
	for(var i=0; i<divs.length;i++) {
		var aDiv = divs[i];
		var className = "";
		if(aDiv.getAttribute("class")) {
			className = aDiv.getAttribute("class");
		}
		else {
			className = aDiv.getAttribute("className");
		}
		if((className == "text-box") || (className == "transparent-text-box")) {
			if(show) {
				aDiv.style.display="block";
			}
			else {
				aDiv.style.display="none";
			}
		}
		if(className == "video-text-box") {
			if(show) {
				aDiv.style.display="block";
			}
			else {
				aDiv.style.display="none";
			}
		}
	}
}

function openPlayer(id) {
	var portal_path = $('portal_path').value;
	window.open(portal_path + '/video/'+id,'video','width=530,height=370');
}

function imprimir() {
	print();
}

function imprimirRecurso(uuid) {
	window.open ("/hub/print/"+uuid,
			  "impresion-"+uuid,"location=0,status=0,scrollbars=1,width=500,height=500");	
}

function descargarRecurso(uuid) {
	window.open ("/hub/download/"+uuid,
			  "descargar-"+uuid,"location=0,status=0,scrollbars=1,width=950,height=250");	
}

function contacto() {
	var link = $('mail-contacto'); 
	if(link) {
		link.click();
	}
}

function cargarImagenFicha(imgID, imgSrc) {
	var img = $(imgID);
	if(img) {
		if(imgSrc.indexOf('recursos') != -1) {
			img.setAttribute("src",imgSrc);
		}
		else {
			img.setAttribute("src","/hub/image/"+imgSrc);
		}
	}
}

function muestra(actual, siguiente){
    if(obj=document.getElementById(actual)){
	if(actual!='formularioregistro'){
		doAjaxGame(document.getElementById("comentario"+actual));
	}else{
		doAjaxRegistro(document.getElementById("formRegistro"));
	}
	obj.style.display='none';

    }
    if(obj=document.getElementById(siguiente)){
	    obj.style.display='block';

    }

}


 function createFormParametersRegistro(aForm) {
formReg=document.getElementById('formRegistro');
//alert(formReg.Mail);

 var parameters = invoker.createParameters();
 parameters.fromSession = aForm.fromSession.value;
 parameters.username = document.formRegistro.Mail.value;
 parameters.action = aForm.action.value;
 parameters.comment = "Mail:" + document.formRegistro.Mail.value + " Nombre:" +document.formRegistro.username.value + " Localidad:" + document.formRegistro.localidad.value + " Edad:" + document.formRegistro.edad.value;
 parameters.contentID = 99999999999999999999;
 parameters.resourcePath = 99999999999999999999;
 parameters.commentsNumber = 0;
 return parameters;
 }


 /** Paso 2 - Creamos una funcion que agrega los parámetros en el objeto para luego mandarlos **/
 function createFormParametersGame(aForm) {
formReg=document.getElementById('formRegistro');
//alert(formReg.Mail);

 var parameters = invoker.createParameters();
 parameters.fromSession = aForm.fromSession.value;
 parameters.username = document.formRegistro.Mail.value;
 parameters.action = aForm.action.value;
 parameters.comment = "(" + aForm.contentID.value + ")" + document.formRegistro.Mail.value + " - " + aForm.comment.value;
 parameters.contentID = 99999999999999999999;
 parameters.resourcePath = 99999999999999999999;
 parameters.commentsNumber = 0;
 return parameters;
 }

 /** Paso 3 - Creamos una funcion que recibe la respueta JSON y realiza los cambios sobre el portlet **/
 function receiveAddCommentGame(aMessageResponse) {
 //alert(aMessageResponse.message);
 $("commentArea").value="";
 }

 /** Paso 4 - Creamos la función que realiza la llamada **/
 function addCommentGame(params) {
 /** "addComment" es el método del portlet que vamos a ejecutar **/
 /** receiveAddComment es la función que va a manejar la respuesta **/
 /** params son los parámetros que le vamos a pasar al método del portlet **/
 invoker.call("addComment",receiveAddCommentGame,params);
 }

 /** Crea los parámetros, realiza la llamada y retorna false para que no se haga el submit del formulario **/
 function doAjaxGame(form) {
 var parameters = createFormParametersGame(form);
 addCommentGame(parameters);
 return false;
 }
 function doAjaxRegistro(form) {
 var parameters = createFormParametersRegistro(form);
 addCommentGame(parameters);
 return false;
 }



function AjaxException(text) {
	this.message = text;
};

function AjaxResponseJSonParser() {
	this.parse = function(response) {
		if(response) { 
			var json = "";
			eval("json = "+response);
			return json;
		}
		else {
			throw this.createException();
		}
	};
	
	this.createException = function () {
		return new AjaxException("No se obtuvo ninguna respuesta del servidor");
	};
};

function AjaxResponseTextParser() {
	this.parse = function(response) {
		if(response) { 
			return response;
		}
		else {
			throw this.createException();
		}
	};
	
	this.createException = function () {
		return new AjaxException("No se obtuvo ninguna respuesta del servidor");
	}
};
function AjaxPortletInvoker(responseParser,portletURL) {
	this.parser = responseParser;
	this.url = portletURL;
	this.createRequest = function(callback) {
		var xmlHttp;
		try {
			xmlHttp=new XMLHttpRequest();
		}
		catch (e) {
			try	{
				xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (e) {
				try	{
					xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (e) {
					xmlHttp=false;
				}
			}
		}
		if(xmlHttp) {
			xmlHttp.parser = this.parser;
			xmlHttp.onreadystatechange=function() {
				if(this.readyState==4) {
					callback(this.parser.parse(this.responseText));
				}
			}
		}
		return xmlHttp;
	};
 
	this.call = function(method,callback,param) {
		var req = this.createRequest(callback);
		req.open("POST",this.createPortletURL(method,param),true);
		req.send(null);
	};
	
	this.createPortletURL = function(method,parameters) {
		var portletUrl = this.url + "&portlet_method="+method;
		if(parameters) {
			for(k in parameters) {
				var type = typeof k;
				if(type != 'function') {
					portletUrl = portletUrl + "&" + k + "=" + parameters[k];
				}
			}
		}
		return portletUrl;
	};

	this.createParameters = function() {
		var param = new Object(); 
		return param;
	};
	
};

function createTextInvoker(url) {
	return new AjaxPortletInvoker(new AjaxResponseTextParser(),url);
}

function createJSonInvoker(url) {
	return new AjaxPortletInvoker(new AjaxResponseJSonParser(),url);
}


