// Predicta
// Implementado em 27/10/2009
// Eduardo Faber

// TagATM_Titulo
// TagATM_Canal
// variável dentro de controles/video.ascx
 
var Player = null;

var currentVolume = 90;
var fullScreen = false;
var fPlayAR = false;
var currentPosition = 0;
var currentState = null; 
var previousState = null;

var AjaxEnviar = false;
var AjaxEmbed = false;
var AjaxLink = false;

function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
		window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}
}

addLoadEvent('mpl');

function playerReady(thePlayer)
{
	//Player = document.getElementById(thePlayer.id);	
	//addListeners();
	// envia o start do player
	//_ATM.AR.video.start(TagATM_Canal, TagATM_Titulo);
}

function addListeners()
{
	if (Player)
	{ 
		Player.addModelListener("STATE", "stateListener");
		Player.addControllerListener("MUTE", " muteListener");
		Player.addControllerListener("VOLUME", "volumeListener");
		Player.addViewListener("FULLSCREEN", "fullScreenListener");
		Player.addViewListener("SEEK", "seekListener");
		Player.addModelListener("TIME", "timeMonitor");
	} 
	else 
	{
		setTimeout("addListeners()",100);
	}
}

function timeMonitor(obj)
{
	currentPosition = obj.position;
}

function seekListener(obj)
{
	if (obj.position > currentPosition)
		_ATM.AR.video.forward(TagATM_Canal, TagATM_Titulo);	
	else
		_ATM.AR.video.rewind(TagATM_Canal, TagATM_Titulo);
	
	currentPosition = obj.position;
	
	if (currentState == 'IDLE' || currentState == 'PAUSED')
		fPlayAR = true;
	else
		fPlayAR = false;	
}

function fullScreenListener(obj)
{
	_ATM.AR.video.fullscreenOn(TagATM_Canal,TagATM_Titulo);
	fullScreen = true;	
}

function muteListener(obj)
{ 
    currentMute = obj.state; 
	if (currentMute) 
		_ATM.AR.video.mute(TagATM_Canal, TagATM_Titulo);
	else
		_ATM.AR.video.unmute(TagATM_Canal, TagATM_Titulo);	

}

function volumeListener(obj)
{ 
	if (obj.percentage > currentVolume)
		_ATM.AR.video.volumeUp(TagATM_Canal,TagATM_Titulo);
	else
		_ATM.AR.video.volumeDown(TagATM_Canal,TagATM_Titulo);
    currentVolume = obj.percentage; 
}

function stateListener(obj)
{
	currentState = obj.newstate; 
	previousState = obj.oldstate;
	
	//play
	if (currentState == 'PLAYING') 
	{
		if (fPlayAR)
			_ATM.AR.video.play(TagATM_Canal, TagATM_Titulo);
		fPlayAR = false;
	}
	//buffering
	if (currentState == 'BUFFERING')
	{
		if (fPlayAR)
			_ATM.AR.video.play(TagATM_Canal, TagATM_Titulo);
		fPlayAR = false;
	}
	//pause
	if (currentState == 'PAUSED')
	{
		_ATM.AR.video.pause(TagATM_Canal, TagATM_Titulo);
		fPlayAR = true;
	}
	//stop
	if (currentState == 'IDLE')
	{
		if (previousState == 'PLAYING' || previousState == 'BUFFERING' || previousState == 'PAUSED')
			_ATM.AR.video.stop(TagATM_Canal, TagATM_Titulo);
		fPlayAR = true;
	}
	//finish
	if (currentState == 'COMPLETED')
	{
		_ATM.AR.video.finish(TagATM_Canal, TagATM_Titulo);
		fPlayAR = true;
	}
}

// Funcoes já existentes
var Mailer =
(
	function()
	{
		var _http_obj_ = null,
			_comp_handler = null,
			_start_handler = null,
			_error_handler = null;

		function callBack()
		{
			//alert('callBack: ' + (typeof (_http_obj_)));
			try
			{
				if (typeof (_comp_handler) == "function")
				{
					_comp_handler(_http_obj_);
				}
				if (_http_obj_ != null && _http_obj_.readyState == 4 && _http_obj_.status == 200)
				{
					_http_obj_ = null;
				}
			}
			catch (ex)
			{
				if (typeof (_error_handler) == "function")
				{
					_error_handler(ex);
				}
				else
				{
					alert("[callBack]\r\nOcorreu um erro e entretanto o manipulador de erros não está definido.\r\n\r\n" + ex.message);
				}
			}
		}

		function constructor()
		{
		}

		constructor.setErrorHandler = function(func)
		{
			if (typeof (func) != "function") throw new Error("[setErrorHandler] A function is expected");
			_error_handler = func;
		};
		constructor.setStartHandler = function(func)
		{
			if (typeof (func) != "function") throw new Error("[setStartHandler] A function is expected");
			_start_handler = func;
		};
		constructor.setCompleteHandler = function(func)
		{
			if (typeof (func) != "function") throw new Error("[setCompleteHandler] A function is expected");
			_comp_handler = func;
		};
		constructor.send = function(data)
		{
			//_http_obj_ = null;
			try
			{
				if (typeof (_start_handler) != "function") throw new Error("Success event handler not defined");
				if (typeof (_start_handler) == "function") _start_handler(data);
				_http_obj_ = Ajax.Http.request("/portal/video/deliver.aspx", data, "POST", callBack);
				//alert(_http_obj_);
			}
			catch (ex)
			{
				if (typeof (_error_handler) == "function")
				{
					_error_handler(ex);
				}
				else
				{
					alert("[send]\r\nOcorreu um erro e entretanto o manipulador de erros não está definido.\r\n\r\n" + ex.message);
				}
			}
		};

		return constructor;
	}
)();

function MailerErrorHandler(ex)
{
	alert(ex.message);
}
function MailerStartHandler(data)
{
	var dv5 = document.getElementById("dv5");
	var el = document.getElementById("player");
	var a = findPos(el);
	dv5.style.left = a[0]+"px";
	dv5.style.top = a[1]+"px";
	dv5.style.display = "block";
}
function MailerSuccessHandler(http)
{
	//alert(http);
	if (http == null) return;
	//alert(http.status + ";" + http.readyState);
	if (http.readyState != 4) return;
	if (http.status != 200) return;

	var dv4 = document.getElementById("dv4");
	var dv5 = document.getElementById("dv5");
	var el = document.getElementById("player");
	var a = findPos(el);
	dv4.style.left = a[0]+"px";
	dv4.style.top = a[1]+"px";
	dv5.style.display = "none";
	dv4.style.display = "block";

	//alert(http.responseText);
	//window.status = http.responseText;
}
function sendMail(frm)
{
	Mailer.setErrorHandler(MailerErrorHandler);
	Mailer.setStartHandler(MailerStartHandler);
	Mailer.setCompleteHandler(MailerSuccessHandler);

	var _frm = frm;  //document.forms["FrmBuddy"];
	
	if (_frm["SenderMail"].value == "" || _frm["SenderMail"].value == "" || 
		_frm["MailTo"].value == "" || _frm["Comments"] == "")
	{
		alert("Preencha todos os campos!");
		return;
	}

	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

	if ( !emailPattern.test(_frm["SenderMail"].value) )
	{
		alert("Seu endereço de e-mail não está correto");
		return;
	}
					
	if ( !emailPattern.test(_frm["MailTo"].value) )
	{
		alert("O endereço de e-mail do destinatário não está correto");
		return;
	}

	var _parms = "fromName=" + _frm["SenderName"].value + "&" +
		"fromEmail=" + _frm["SenderMail"].value + "&" +
		"toName=" + escape(_frm["MailTo"].value) + "&" +
		"toEmail=" + escape(_frm["MailTo"].value);
	_parms += "&body=" + escape(_frm["Comments"].value);
	_parms += "&video=" + window.location.search.replace("?","");
	_frm["MailTo"].value = "";
	Mailer.send(_parms);
	// _ATM.AR.ajax.load(TagATM_Canal + '-Enviar-Sucesso', TagATM_Titulo)
}
function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		do
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft, curtop];
}

var _n_panel = 0;
function showPanel(n)
{
	if (n == _n_panel)
	{
		showPlayer();
		return;
	}
	_n_panel = n;
	var tab0 = document.getElementById("tr1"),
	dv1 = document.getElementById("dv1"),
	dv2 = document.getElementById("dv2"),
	dv3 = document.getElementById("dv3"),
	dv4 = document.getElementById("dv4");

	dv4.style.display = "none";

	//tab0.style.display = "none";
	var el = document.getElementById("mpl");

	el.sendEvent("PLAY", "false");

	var a = findPos(el);

	dv1.style.top = a[1]+"px";
	dv1.style.left = a[0]+"px";

	dv2.style.top = a[1]+"px";
	dv2.style.left = a[0]+"px";

	dv3.style.top = a[1]+"px";
	dv3.style.left = a[0]+"px";

	switch (n)
	{
		case 1:
			dv1.style.display = "block";
			dv2.style.display = "none";
			dv3.style.display = "none";
			if (! AjaxEnviar)
			{
				// _ATM.AR.ajax.load(TagATM_Canal + '-Enviar-Formulario', TagATM_Titulo);
				AjaxEnviar = true;
				AjaxEmbed = false;
				AjaxLink = false;
			}
			break;
		case 2:
			dv1.style.display = "none";
			dv2.style.display = "block";
			dv3.style.display = "none";
			if (! AjaxEmbed)
			{
				// _ATM.AR.ajax.load(TagATM_Canal + '-Embed', TagATM_Titulo);
				AjaxEnviar = false;
				AjaxEmbed = true;
				AjaxLink = false;				
			}			
			break;
		case 3:
			dv1.style.display = "none";
			dv2.style.display = "none";
			dv3.style.display = "block";
			if (! AjaxLink)
			{
				// _ATM.AR.ajax.load(TagATM_Canal + '-Link', TagATM_Titulo)
				AjaxEnviar = false;
				AjaxEmbed = false;
				AjaxLink = true;				
			}
			break;
	}

	el.style.visibility = "hidden";
}

function showPlayer()
{
	_n_panel = 0;
	var tab0 = document.getElementById("tr1"),
	dv1 = document.getElementById("dv1"),
	dv2 = document.getElementById("dv2"),
	dv3 = document.getElementById("dv3"),
	dv4 = document.getElementById("dv4");

	var el = document.getElementById("mpl");

	el.style.visibility = "visible";

	el.sendEvent("PLAY", "true");

	dv1.style.display = "none";
	dv2.style.display = "none";
	dv3.style.display = "none";
	dv4.style.display = "none";
	
	AjaxEnviar = false;
	AjaxEmbed = false;
	AjaxLink = false;
}

function EnvieAmigoVideoENoticia(form, cod) {
    try {
        if (form["SenderName"].value == "" || form["SenderMail"].value == "" ||
		form["MailTo"].value == "" || form["Comments"] == "") {
            alert("Preencha todos os campos!");
            return;
        }

        var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

        if (!emailPattern.test(form["SenderMail"].value)) {
            alert("Seu endereço de e-mail não está correto");
            return;
        }

        if (!emailPattern.test(form["MailTo"].value)) {
            alert("O endereço de e-mail do destinatário não está correto");
            return;
        }

        var _parms = "fromName=" + form["SenderName"].value + "&" +
		"fromEmail=" + form["SenderMail"].value + "&" +
		"toName=" + escape(form["MailTo"].value) + "&" +
		"toEmail=" + escape(form["MailTo"].value);
        _parms += "&body=" + escape(form["Comments"].value);
        _parms += "&video=" + window.location.search.replace("?", "");
        _parms += "&codVideo=" + cod;

        _envieAmigoVideoENoticia(_parms);
        // _ATM.AR.ajax.load(TagATM_Canal + '-Enviar-Sucesso', TagATM_Titulo);
    }
    catch (e) {
        alert("Ocorreu um erro (ENoticia): " + e);
    }
}

function EnvieAmigoVideo(form, cod) {
    try {
        if (form["SenderName"].value == "" || form["SenderMail"].value == "" ||
		form["MailTo"].value == "" || form["Comments"] == "") {
            alert("Preencha todos os campos!");
            return;
        }

        var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

        if (!emailPattern.test(form["SenderMail"].value)) {
            alert("Seu endereço de e-mail não está correto");
            return;
        }

        if (!emailPattern.test(form["MailTo"].value)) {
            alert("O endereço de e-mail do destinatário não está correto");
            return;
        }

        var _parms = "fromName=" + form["SenderName"].value + "&" +
		"fromEmail=" + form["SenderMail"].value + "&" +
		"toName=" + escape(form["MailTo"].value) + "&" +
		"toEmail=" + escape(form["MailTo"].value);
        _parms += "&body=" + escape(form["Comments"].value);
        _parms += "&video=" + window.location.search.replace("?", "");
        _parms += "&codVideo=" + cod;

        _envieAmigoVideo(_parms);
        // _ATM.AR.ajax.load(TagATM_Canal + '-Enviar-Sucesso', TagATM_Titulo);
    }
    catch (e) {
        alert("Ocorreu um erro (Default): " + e);
    }
}
