function initKeyListener (event) {
	var key=(event.which) ? event.which : event.keyCode;
	switch (key)
	{
	case 27:
		UnloadOver();
		break;
	}
}
bind_initKeyListener = initKeyListener.bindAsEventListener();

function ShowMyOver (_top,_left) {
	arrayPageSize=getPageSize();
	
	$('cnt').insert({after: '<div id="wOver_overlay" style="display: none;"></div>'});	

	$('wOver_overlay').style.width=arrayPageSize[0]+'px';
	$('wOver_overlay').style.height=arrayPageSize[1]+'px';	
	$('wOver_overlay').appear({from:0, to: 0.5, duration: 0.2 });
	
	//SET WAIT
	$('cnt').insert({top: '<div id="wOver" style="display:none;"><div id="wOverContainer"><img src="/images/loader2.gif" width="16" height="16" border="0" align="absmiddle" /> loading...</div></div>'});
	//SET POS
	$('wOverContainer').setStyle({ 
		top: (_top?_top:(document.viewport.getScrollOffsets().top+Math.ceil((arrayPageSize[3]-$('wOverContainer').getHeight())/2)))+'px', 
		marginLeft: (_left?_left+'px':(document.viewport.getScrollOffsets().left+Math.ceil((arrayPageSize[2]-300)/2))+'px')
	});	

	$('wOver').appear({duration: 0.2});
}

function OpenMyPlayer(e,idl,idc,type) {
	var src=Event.element(e);
	if (src.tagName.toLowerCase()!='a')
		src=src.up('a');
	
	upDateView(idl,idc);
	ShowMyPlayer (src,idl,idc,type);
		
	return false;
}

function ShowMyPlayer (src,idl,idc,type) {
	ShowMyOver();
	
	var objHash = {};
	objHash.id_lezione=idl;
	objHash.id_contenuto=idc;
	objHash.type=type!=undefined?type:'V';	
	
	new Ajax.Request('/online/include/mycpm.php', {
		method: 'post', 
		parameters: objHash, 
		onSuccess: function(transport) {
			res=transport.responseText;
			if (res.startsWith('#')) {
				PrintError (res);
				CloseOver();
			}
			else {				
				arrayPageSize=getPageSize();
				$('wOver').remove();
				$('cnt').insert({top: '<div id="wOver" style="display: none; height: '+arrayPageSize[1]+'px;"><div id="wOverContainer" style="width: 720px;">'+res+'</div></div>'});				
				var _top=document.viewport.getScrollOffsets().top+Math.ceil(arrayPageSize[3]/2-280);
				/*if (Prototype.Browser.IE && bro.version<7) {
					var _left=document.viewport.getScrollOffsets().left+Math.ceil(arrayPageSize[2]/2-460);
					$('wOverContainer').setStyle({ 
						top: _top+'px', 
						left: _left+'px'
					});
				} else {				*/
					$('wOverContainer').setStyle({ 
						top: _top+'px'
					});
					$('wOver').setStyle({
						backgroundImage: 'url(/images/player_shadow.png)', 
						backgroundPosition: 'center '+(_top-75)+'px'
					});
				//}*/
				
				InitScroll('video_slide',0,false,true,false);
				InitScroll('audio_slide',0,false,true,false);
				$('wOver').appear({duration: 0.3, afterFinish: function() {
					InitPlayer (objHash.type,idc);
				}});
				Event.observe(window.document, "keyup", bind_initKeyListener);				
			}				
		},
		onFailure: function (transport) {
			PrintError(transport.responseText);
			CloseOver();
		},
		onException: function (request, exception) {
			PrintError("[ShowMyPlayer] Js Exception: " + exception);
			CloseOver();
		}
	});
}

function InitPlayer (_type,_selected) {	
	var toLoad=false;
	//VIDEO
	if ($('show_video')) {
		Event.observe($('show_video'), 'click', bind_cntLoad);
	
		$$('#video_slide_cnt a').each(function (s) {
			Event.observe(s, 'click', bind_cntScrollLoad);
		});
		if ($('video_slide_arrows')) {
			$$('#video_slide_arrows a').each(function (s) {
				Event.observe(s, 'click', bind_cntScrollPN);
			});
			$$('#video_slide_arrows a img').each(function (s) {
				Event.observe(s, 'click', bind_cntScrollPN);
			});
		}
		
		if (_selected==undefined)
			toLoad=$$('#video_slide_cnt a')[0];
		else
			toLoad=$('vt_'+_selected);
	}
	
	if ($('show_audio')) {
		Event.observe($('show_audio'), 'click', bind_cntLoad);
	
		$$('#audio_slide_cnt a').each(function (s) {
			Event.observe(s, 'click', bind_cntScrollLoad);
		});
		if ($('audio_slide_arrows')) {
			$$('#audio_slide_arrows a').each(function (s) {
				Event.observe(s, 'click', bind_cntScrollPN);
			});
			$$('#audio_slide_arrows a img').each(function (s) {
				Event.observe(s, 'click', bind_cntScrollPN);
			});
		}
		
		if (!toLoad) {
			if (_selected==undefined)
				toLoad=$$('#audio_slide_cnt a')[0];
			else
				toLoad=$('at_'+_selected);
		}
	}
	
	Event.observe($('show_info'), 'click', bind_infoLoad);		
	
	if (toLoad)
		LoadCnt(toLoad);
		
	return;	
}

function setActive (id) {	
	var act_id=($$('#player_right .active')[0]?$$('#player_right .active')[0].id:'');		
	if (act_id==id)
	{		
		return false;
	}
	var _set=true;
	switch (act_id)
	{
	case 'show_video':	
		if ($$('#video_slide_cnt a.active')[0])
			$$('#video_slide_cnt a.active')[0].removeClassName('active');
		break;		
	case 'show_audio':	
		if ($$('#audio_slide_cnt a.active')[0])
			$$('#audio_slide_cnt a.active')[0].removeClassName('active');
		break;		
	}	
	
	if (_set)
	{
		if (act_id)
			$(act_id).removeClassName('active');
	}
	
	$(id).addClassName('active');	
	
	return true;
}
///////////////////////////////////////////////
function bind_cntLoad (event) {
	event.stop();
	var src=Event.element(event);	
	
	return false;
}

function cntScrollLoad (event) {
	event.stop();
	var src=Event.element(event);
	var cnt=src.up('div',1);
	var btcnt='show_'+cnt.id.split('_').first();
	var act_src=$(cnt).down('div').down('a.active');
	
	if (act_src) {
		if (src.id==act_src.id) {
			if ($('player_txt').visible()) {
				$('player_txt').hide();
				$('player_cnt').show();
			}
			return false;
		}	
	}
	
	if (!$(btcnt).hasClassName('active'))
		setActive(btcnt);
	
	if ($(cnt).down('a.active')) {
		//STOP VIDEO AUDIO TODO
		var act_cnt=$(cnt).down('a.active');
		act_cnt.removeClassName('active');
	}	
	
	LoadCnt(src);
	
	return false;
}
bind_cntScrollLoad=cntScrollLoad.bindAsEventListener();

function videoLoad (event) {	
	event.stop();

	setActive('show_video');
	toggleCntSilde('video',true);

	if ($$('#video_slide_cnt a.active')[0]) {
		src=$$('#video_slide_cnt a.active')[0];
		src.removeClassName('active');		
	} else {
		src=$$('#video_slide_cnt a')[0];
	}
	LoadCnt(src);
	
	return false;
}
bind_videoLoad=videoLoad.bindAsEventListener();

function LoadCnt(src) {
	src.addClassName('active');
	var type=src.id.substr(0,1).toUpperCase();
	
	swfobject.embedSWF('/online/player.swf', 'flashPlayer', '480', '393', '8.0.0','/swf/expressInstall.swf', {'cnt':src.readAttribute('href'),'type':type}, params);
	
	var cnt_id='cnti_'+src.id.split('_').last();
	if ($(cnt_id))
		$('show_info').show();
	else
		$('show_info').hide();
}

function ScrollLeft (_delta,_type) {
	var _inc=0;
	var _sign=(_delta>0?1:-1);
	new PeriodicalExecuter(function(pe) {
		$(_type+'_slide').scrollLeft+=(23*_sign);
		_inc+=(23*_sign);
		if (Math.abs(_inc)>=Math.abs(_delta))
			pe.stop();
		}, .05);
}

function cntScrollPN (event) {
	event.stop();
	var src=Event.element(event);	
	if (src.tagName.toLowerCase()!='a')
		src=src.up('a');		
	
	//set PN
	switch (src.readAttribute('title').charAt(0)) {
	case 'n':
		delta=1;
		break;
	case 'p':
		delta=-1;
		break;
	default:		
		return false;
		break;
	}	

	ScrollLeft(46*delta,src.up('div').id.split('_').first());
	
	return false;
}
bind_cntScrollPN=cntScrollPN.bindAsEventListener();

/////////////////////////////
function infoLoad (event) {
	event.stop();
	
	//PAUSE VIDEO AUDIO
	$('player_cnt').hide();
	var act=$('player_right').down('a.active');
	var src=act.next('div').down('a.active');
	$('player_txt').innerHTML=src.next('span').innerHTML;
	$('player_txt').show();
	
	return false;
}
bind_infoLoad=infoLoad.bindAsEventListener();

/////////////////////////////
function upDateView(idl,idc) {
	var objHash = {};
	objHash.action='UPDATEVIEW';	
	objHash.id_lezione=idl;	
	objHash.id_contenuto=idl;		
	
	new Ajax.Request('/online/include/mycpm.php', {
		method: 'post', 
		parameters: objHash, 
		onSuccess: function(transport) {
			res=transport.responseText;
			if (res.startsWith('#')) {
				PrintError (res);				
			}
			else {
				if (!res.isJSON())
				{
					PrintError (res);
					return false;
				}
				data=res.evalJSON();
				if (!data.res)
					PrintError (data.msg);
				else
					enableNextLesson(objHash.id_lezione);
			}				
		},
		onFailure: function (transport) {
			PrintError(transport.responseText);
			CloseOver();
		},
		onException: function (request, exception) {
			PrintError("[upDateView] Js Exception: " + exception);
			CloseOver();
		}
	});
}

function enableNextLesson (idl) {
	if ($('ol_lezione'+idl).next('div.lezione')) {		
		var color=RGBcss2Hex($('ol_lezione'+idl).down('div.lezione_nome').getStyle('background')).toLowerCase();
		var nextLes=$('ol_lezione'+idl).next('div.lezione');		
		if (nextLes.down('div.lezione_nome').hasClassName('disabled')) {
			nextLes.down('div.lezione_nome').removeClassName('disabled');
			nextLes.down('div.lezione_nome').setStyle ({background: '#'+color});
			nextLes.down('div.lezione_nome').down('img').src='images/arrows/'+color+'.gif';
			//LOAD CNT
			loadLessonCnt(nextLes.id);
		}
	}
}

function loadLessonCnt (idl) {
	var objHash = {};
	objHash.action='GETLESSONCNT';	
	objHash.id_lezione=idl.substr(10);	
	
	new Ajax.Request('/online/include/mycpm.php', {
		method: 'post', 
		parameters: objHash, 
		onSuccess: function(transport) {
			res=transport.responseText;
			if (res.startsWith('#')) {
				PrintError (res);				
			}
			else {				
				$('ol_lezione_dett_'+idl.substr(10)).down('div').insert({bottom: res});
			}				
		},
		onFailure: function (transport) {
			PrintError(transport.responseText);
			CloseOver();
		},
		onException: function (request, exception) {
			PrintError("[loadLessonCnt] Js Exception: " + exception);
			CloseOver();
		}
	});	
}

var HexLookup = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
function RGB2Hex(rgb) {
    var Hex = "";
    while (rgb > 0) {
        Hex = HexLookup[rgb % 16] + Hex;
        rgb -= (rgb % 16);
        rgb /= 16;
    }
		if (Hex.length==1)
			Hex='0'+Hex;
    return Hex;
}
function RGBcss2Hex(str) {
    var vals = str.match(/\d+/g);
    var hex = "";
    for (var i = 0; i < vals.length; i++) {
        hex += RGB2Hex(vals[i]);
    }
    return hex;
}
