// ----------------- RIPRISTINO STATO DELLA PAGINA ------------- 
// Verifica se e' necessario ripristinare lo stato ed eventualmente lo ripristina
function checkMCState()
{
	var params = document.location.href.toQueryParams();
	
	if (params.mcstate)
	{	
		var cookieName = 'mcstate';
		
		var regexp = new RegExp(cookieName + '=([^;]+)');
		
		var result = regexp.exec(document.cookie);
		
		if (result == null) {
			return null;
		}
		
		restoreMCState(result);
	}
}

//----------------- RIPRISTINA STATO PAGINA -----------------
function restoreMCState (result) 
{
	var loadedState = result[1].evalJSON(true);
	
	selectMenuVoice ('corriere',  loadedState.corriereCat);
	selectMenuVoice ('community', loadedState.communityCat);
	
	if (loadedState.corriereCat == 0) 
	{
		restoreTabs('corriere');
	}
	else 
	{
		updateTabs (loadedState.corriereCat, 'tabs-corriere');
	}
	
	if (loadedState.communityCat == 0) 
	{
		restoreTabs('community');
	}
	else 
	{
		updateTabs (loadedState.communityCat, 'tabs-community');
	}
	tabSwitcherCorriere.tabSwitch ($(loadedState.corriereType));
	tabSwitcherCommunity.tabSwitch ($(loadedState.communityType));
	
	playlist.playListSettings.items = loadedState.playListItems;
	playlist.redraw();
	
	updateMainMedia ('mainsx-md', loadedState.mainMediaType, loadedState.mainMediaId, loadedState.mainMediaTitle, loadedState.mainMediaCategory, true)
	
}

function restoreMCPage (area)
{
	var params = document.location.href.toQueryParams();
	
	if (params.mcstate)
	{	
		var cookieName = 'mcstate';
		
		var regexp = new RegExp(cookieName + '=([^;]+)');
		
		var result = regexp.exec(document.cookie);
		
		if (result == null) {
			return null;
		}
		
		var loadedState = result[1].evalJSON(true);
		
		if (area == 'corriere') 
		{
			mediacenterRAPaginator.switchTo(loadedState.corrierePage);
		}
		else
		{
			mediacenterCUPaginator.switchTo(loadedState.communityPage);
		} 
	}	
}


// ---------------- APERTURA NUOVA FOTOGALLERY -------------- 
// Salva lo stato attuale e apre la galleria
function openGallery(mediaId, categoria, titolo) 
{
	saveMCState();
	
	document.location = '/Fotogallery/' + categoria + '/' + mediaId + '/0/' + titolo;
}

// ---------------- SALVATAGGIO STATO PAGINA -------------- 
// Salva lo stato della pagina
function saveMCState() 
{
	var liNameCorr = $$('.li_menu_0.selected')[0].id;
	var corriereCatId = liNameCorr.substring(liNameCorr.lastIndexOf('_')+1);
	
	var liNameComm = $$('.li_menu_1.selected')[0].id;
	var communityCatId = liNameComm.substring(liNameComm.lastIndexOf('_')+1);

	var tabNameComm =  $$('#tabs-community .tab_btn.selected')[0].id;
	var tabNameCorr =  $$('#tabs-corriere .tab_btn.selected')[0].id;
	
	var pageIndexCorr = mediacenterRAPaginator.currentPage;
	var pageIndexComm = mediacenterCUPaginator.currentPage;

	if (mainMediaType == null)
		mainMediaType = "";
	if (mainMediaId == null) 
		mainMediaId = "";
		
	try {
		if (mainMediaTitle == null)
			mainMediaTitle = "";
	} catch (e) {
		mainMediaTitle = "";
	}
	try {
		if (mainMediaCategory == null)
			mainMediaCategory = "";
	} catch (e) {
		mainMediaCategory = "";
	}
	
	var stateToSave = $H(
	{
		corriereType : tabNameCorr,
		communityType : tabNameComm,
		corriereCat : corriereCatId,
		communityCat : communityCatId,
		corrierePage : pageIndexCorr,
		communityPage : pageIndexComm,
		playListItems : playlist.playListSettings.items,
		mainMediaId : mainMediaId,
		mainMediaType : mainMediaType,
		mainMediaTitle: mainMediaTitle,
		mainMediaCategory: mainMediaCategory
	});
	
	var cookieName = 'mcstate';
	var cookieValue = stateToSave.toJSON();
	document.cookie = cookieName + '=' + cookieValue + ';'
}



// ---------------- SELEZIONA UNA VOCE DI MENU'-------------- 
function selectMenuVoice (menuArea, categoryId) 
{
	if (menuArea == 'corriere') 
	{
		 $$('.li_menu_0').each(function (li)
		{
			$(li).removeClassName ('selected');
		});
		
		$('li_menu_corriere_'+categoryId).addClassName ('selected');
		return;
	}
	
	if (menuArea == 'community') 
	{
		 $$('.li_menu_1').each(function (li)
		{
			$(li).removeClassName ('selected');
		});
		
		$('li_menu_community_'+categoryId).addClassName ('selected');
		return;
	}	
}

// ------------- ZONA FUNZIONI PLAYER --------------------

// some variables to save
var currentPosition;
var currentVolume;
var currentItem;
var currentVideoPlayed;
var playerReady;

// these functions are caught by the JavascriptView object of the player.
function getUpdate(typ,pr1,pr2,pid) {
	if(typ == "state") 
		{
			if (pr1 == 3)
			{
				var nextItem = playlist.getNextItem();
				if (nextItem != playlist.LISTEND) 
				{
					if(nextItem.mediaType == 'VIDEO')
						nextItem.mediaType = 'Video';
					else if(nextItem.mediaType == 'AUDIO')
						nextItem.mediaType = 'Audio';
					
					if (nextItem.mediaType)
					updateMainMedia ('mainsx-md', nextItem.mediaType, nextItem.mediaId, nextItem.titleFull, nextItem.category);
					
					//----  se necessario, scrolla di un elemento la playlist--------------
					if (
						playlist.scrollerConfig.scroller.containedWidth
						+ $(playlist.scrollerConfig.scroller.tabContained).offsetLeft   > (playlist.scrollerConfig.scroller.visibleLiCount * playlist.scrollerConfig.scroller.liWidth)
						)
					{
						$(playlist.scrollerConfig.scroller.tabContained).style.left = ($(playlist.scrollerConfig.scroller.tabContained).offsetLeft - playlist.scrollerConfig.scroller.liWidth) + 'px';		
					}
					//-----------------------------------------------------------------------------

					//---------------- evidenziazione nuovo elemento ----------------------
					$$('.media_list_li').each(function (li) 
					{ 
						$(li).removeClassName ('selected');
					});
					
					$('playlistLi_'+nextItem.itemIndex).addClassName ('selected');												
					//-----------------------------------------------------------------------------
				}
			}
			if (pr1 == 0 && currentVideoPlayed == false)
			{
				currentVideoPlayed = true;
				checkPlayerStatus();
			}
		}
	/*{ currentPosition = pr1; }
	else if(typ == "volume") { currentVolume = pr1; }
	else if(typ == "item") { currentItem = pr1; setTimeout("getItemData(currentItem)",100); }
	var id = document.getElementById(typ);
	id.innerHTML = typ+ ": "+Math.round(pr1);
	pr2 == undefined ? null: id.innerHTML += ", "+Math.round(pr2);
	if(pid != "null") {
		document.getElementById("pid").innerHTML = "(received from the player with id <i>"+pid+"</i>)";
	}*/
};

// These functions are caught by the feeder object of the player.
function loadFile(obj) { thisMovie("mpl").loadFile(obj); };

function addItem(obj,idx) { thisMovie("mpl").addItem(obj,idx); }

function removeItem(idx) { thisMovie("mpl").removeItem(idx); }

function getItemData(idx) {
	var obj = thisMovie("mpl").itemData(idx);
	var nodes = "";
	for(var i in obj) { 
		nodes += "<li>"+i+": "+obj[i]+"</li>"; 
	}
	document.getElementById("data").innerHTML = nodes;
};

// This is a javascript handler for the player and is always needed.
function thisMovie(movieName) {
    if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
};
	
	
function checkPlayerStatus () 
{
	if ($('mpl') && playlist.isPlaying == true) 
	{
		$('mpl').sendEvent('playpause');
	}
}
			
			
			
// ------------------------ AGGIORNA LA ZONA DEL MAIN MEDIA ---------------------
var mcTrackerUrlTemplate = new Template("/Mediacenter/#{type}/#{category}/#{id}/#{titolo}");
			
function updateMainMedia (divName, type, id, titolo, category, stopPlayer) 
	{
		if (stopPlayer) playlist.isPlaying = false;
		currentVideoPlayed = false;
		$(divName).innerHTML = '<img src="/res/img/loading.gif"/>';
		var url = '/mediacenter/'+type+'/'+type+'_'+id+'.shtml';
		new Ajax.Updater(divName, url, { method: 'get',evalScripts: true });
    
    var bannerFrameSrc = "/mediacenter_banner.shtml";
    if ((typeof(adArea) != 'undefined') && (adArea)) {
      bannerFrameSrc += "?adArea="+adArea;
    }
    if ((typeof(adSubArea) != 'undefined') && (adSubArea)) {
      bannerFrameSrc += "&adSubArea="+adSubArea;
    }
        
		$('banner_frame').src=bannerFrameSrc;
		$('mainsx-md').scrollTo();
		// sgalimberti: Call to urchin tracker
		if (typeof(pageTracker)!='undefined' && (pageTracker)) {
			var page = mcTrackerUrlTemplate.evaluate({ 
				type: type, id: id, titolo: titolo, category: category
			});
			pageTracker._trackPageview(page);
		}
	}	
			
// ------------------------ AGGIORNA IL FUNZIONAMENTO DEI TABS DELLA PAGINA --------------------			
function updateTabs (categoryId, tabsId) 
{
	if (categoryId >= 0) 
	{
		var filePrefix ;
		var tabSwitcherLocal;
		if (tabsId == 'tabs-corriere') {
			filePrefix = '/mediacenter/mcra_';
			tabSwitcherLocal = tabSwitcherCorriere;
			var filePostFix = '_0.shtml';					
			$('corriere-pagination').show();
			}
		if (tabsId == 'tabs-community') {
			filePrefix = '/mediacenter/mcu_';
			tabSwitcherLocal = tabSwitcherCommunity;
			var filePostFix = '_0.shtml';
			}
		
		$('tab_tutti_'+tabsId).rel= filePrefix+categoryId+filePostFix;
		
		var tabVideo = document.getElementById('tab_video_'+tabsId);
		tabVideo.rel = filePrefix+'Video_'+categoryId+filePostFix;
		
		var tabFoto = document.getElementById('tab_foto_'+tabsId);
		tabFoto.rel = filePrefix+'Galleria_'+categoryId+filePostFix;
		
		var tabAudio = document.getElementById('tab_audio_'+tabsId);
		tabAudio.rel = filePrefix+'Audio_'+categoryId+filePostFix;				
		
		tabSwitcherLocal.tabSwitch(tabSwitcherLocal.selLi);
		
		$('banner_frame').src='/mediacenter_banner.shtml';
	}
	else 
	{
		var filePrefix ;
		var tabSwitcherLocal;

		if (categoryId == '-1') 
		{
			filePrefix = '/piuvisti/';
		}
		
		if (categoryId == '-2') 
		{
			filePrefix = '/piuvotati/';
		}					
		
		if (tabsId == 'tabs-corriere') {
			filePrefix = filePrefix+'mcra_';
			tabSwitcherLocal = tabSwitcherCorriere;
			var filePostFix = '.html';					
			}
		if (tabsId == 'tabs-community') {
			filePrefix = filePrefix+'mcu_';
			tabSwitcherLocal = tabSwitcherCommunity;
			var filePostFix = '.html';
			}
		
		$('tab_tutti_'+tabsId).rel= filePrefix+'tutti'+filePostFix;
		
		var tabVideo = document.getElementById('tab_video_'+tabsId);
		tabVideo.rel = filePrefix+'video'+filePostFix;
		
		var tabFoto = document.getElementById('tab_foto_'+tabsId);
		tabFoto.rel = filePrefix+'foto'+filePostFix;
		
		var tabAudio = document.getElementById('tab_audio_'+tabsId);
		tabAudio.rel = filePrefix+'audio'+filePostFix;				
		
		tabSwitcherLocal.tabSwitch(tabSwitcherLocal.selLi);
	}
}		

//----------------------- RIPRISTINA I TABS ALLO STATO INIZIALE ------------------------
function restoreTabs (tabName) 
{
	
	$('tab_tutti_tabs-'+tabName).rel= 'tab:'+tabName+'-contentarea';
	
	var tabVideo = document.getElementById('tab_video_tabs-'+tabName);
	tabVideo.rel = 'tab:'+tabName+'-contentarea-video';
	
	var tabFoto = document.getElementById('tab_foto_tabs-'+tabName);
	tabFoto.rel = 'tab:'+tabName+'-contentarea-foto';
	
	var tabAudio = document.getElementById('tab_audio_tabs-'+tabName);
	tabAudio.rel = 'tab:'+tabName+'-contentarea-audio';				
	
	if (tabName=='corriere')
	{
		tabSwitcherCorriere.tabSwitch(tabSwitcherCorriere.selLi);
	}
	else 
	{
		tabSwitcherCommunity.tabSwitch(tabSwitcherCommunity.selLi);
	}
	
	$(tabName+'-pagination').hide();
	
	$('banner_frame').src='/mediacenter_banner.shtml';
}	
