window.addEvent('load', function() { 

	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();
	}
}

