/* -------------------------------  */
/* AJAX FUNCTIONS FOR LOGING         */
/* -------------------------------  */

//Ajax manager
var managerLogin = new AjaxManager('managerLogin');

//Url for login
var url = "ajax/getLoginXML.aspx";
var userid = "";
var tempCode = '';

//logs user
function login()
{
	var emailField = document.getElementById("userEmail");
	var passwordField = document.getElementById("userPassword");
	
	if(emailField != null && emailField.value != "" && passwordField != null && passwordField.value != "")
	{
		doLogin(emailField.value, passwordField.value);
		var shoppingCart = document.getElementById("SHOPPING_CART");
		if(shoppingCart)
		{
			getAjaxContentNoCache('SHOPPING_CART','ajax/genericAjax.aspx?view=ShoppingCartItemsView&p1='+''+'&p2='+''+'&p3=true',true);
		}
	} 
	else
	{
		CreateLoginNotify("digite seu e-mail e senha");
	}
}

function login2()
{
	var frmRef = document.forms["formLogin"];
	var emailField = frmRef.userEmail.value;
	var passwordField = frmRef.userPassword.value;
	
	if(emailField != null && emailField!= "" && passwordField != null && passwordField!= "")
	{	
		doLogin2(emailField, passwordField);
		 
	}
	else
	{
		CreateLoginNotify("digite seu e-mail e senha");
	}
}
function login3()
{
	var frmRef = document.forms["formLogin2"];
	var emailField = frmRef.userEmail2.value;
	var passwordField = frmRef.userPassword2.value;
		
	if(emailField != null && emailField!= "" && passwordField != null && passwordField!= "")
	{	
		doLogin2(emailField, passwordField);
		 
	}
	else
	{
		CreateLoginNotify("digite seu e-mail e senha");
	}
}
function login4()
{
	var frmRef = document.forms["formLogin2"];
	var emailField = frmRef.userEmail2.value;
	var passwordField = frmRef.userPassword2.value;
	tempCode = frmRef.code.value;
		
	if(emailField != null && emailField!= "" && passwordField != null && passwordField!= "")
	{	
		doLogin3(emailField, passwordField);
	}
	else
	{
		CreateLoginNotify("digite seu e-mail e senha");
	}
}

function wait(millis)
{
	var date = new Date();
	var curDate = null;

	do { curDate = new Date(); }
	while(curDate-date < millis);
}

function Redirect()
{	
	var returnUrl = null;
	if(this.httpRequest.status == 200)
	{
		// XML loaded properly, parses it
		var xml = this.httpRequest.responseXML;
		var root = this.tools.SelectSingleNode(xml,'xml');
		var code = this.tools.GetNodeValue(this.tools.SelectSingleNode(root,'code'));
		var status = this.tools.GetNodeValue(this.tools.SelectSingleNode(root,'status'));
		var message = this.tools.GetNodeValue(this.tools.SelectSingleNode(root,'message'));
		var type = this.tools.GetNodeValue(this.tools.SelectSingleNode(root,'type'));
		if (message != "" && status == "false" || code =="") // se usuário inseriu pin number inválido - já foi para login.aspx, está logado mas é redirecionado pra home, recebendo mensagem de erro de pin
		{	
			window.location = "home.aspx?finalize="+status+"&message="+message;
		}
		else
		{	
			window.location = "home.aspx?finalize="+status+"&type="+type;
			
		}
	}
	else
	{
		if(returnUrl != null) 
		{
			location.href = returnUrl;
		}
	} 	
}

// GO TO HOME
function goToUrl(returnUrl)
{
	top.location.href = returnUrl;
}

//Calls ajax login function
function doLogin(email, password)
{
	AjaxLogin_Add(url, "email=" + email + "&password=" + password);
}
function doLogin2(email, password)
{
	AjaxLogin_Add2(url, "email=" + email + "&password=" + password);
}
function doLogin3(email, password)
{	
	AjaxLogin_Add3(url, "email=" + email + "&password=" + password);
}

//Adds item to shopping cart
function AjaxLogin_Add(url, post)
{
	//Chamada ajax
	managerLogin.Add(url, AjaxLogin_Parse, null, null, null, null, post);	
}
function AjaxLogin_Add2(url, post)
{
	managerLogin.Add(url, AjaxLogin_Parse2, null, null, null, null, post);	
}
// Login sem retorno
function AjaxLogin_Add3(url, post)
{
	managerLogin.Add(url, AjaxLogin_Parse3, null, null, null, null, post);	//chama AjaxManager via Ajax e retorna em AjaxLogin_Parse3
}

function pre_AjaxLogin_Parse3()
{
AjaxLogin_Parse3();
}

//Parses xml result for login
function AjaxLogin_Parse3()
{	
	if(this.httpRequest.status == 200)
	{	
		// XML loaded properly, parses it
		var xml = this.httpRequest.responseXML;
		var id = parseInt(this.tools.GetNodeValue2(xml, "xml/id/text()"));
		var status = parseInt(this.tools.GetNodeValue2(xml, "xml/status/text()"));

		if(id <= 0 || status != 1)
		{
			CreateLoginNotify("E-mail ou Senha inválidos.");
		}				
		if (id > 0 )// user has ID
		{	
			post = "user=" + id + "&code=" + tempCode;	
			managerLogin.Add("ajax/checkCard.aspx?", Redirect, null, null, null, null,post);//verifica cartão e retorna para redirect
		}		
	}
}

function AjaxLogin_Parse()
{
	if(this.httpRequest.status == 200)
	{
		// XML loaded properly, parses it
		var xml = this.httpRequest.responseXML;
		var id = parseInt(this.tools.GetNodeValue2(xml, "xml/id/text()"));
		var status = parseInt(this.tools.GetNodeValue2(xml, "xml/status/text()"));
		var name = this.tools.GetNodeValue2(xml, "xml/name/text()");
		var count = this.tools.GetNodeValue2(xml, "xml/count/text()");
		var price	 = this.tools.GetNodeValue2(xml, "xml/price/text()");
		var urlcart	 = this.tools.GetNodeValue2(xml, "xml/url_cart/text()");
		userid = id;
		var time = 0;
		if(id > 0 && status == 1)
		{
			url_cart = urlcart;
			drawLoggedUser(name);
			drawShoppingCart(count, price);
			if(retPopup == undefined){
				try{
					time = 1;
				}catch(e){}
			}
			if(time == 1)
				ShowItemsCart();
		}
		else
		{
			CreateLoginNotify("E-mail ou Senha inválidos.");
		}		
	}
}

function AjaxLogin_Parse2()
{
	if(this.httpRequest.status == 200)
	{
		// XML loaded properly, parses it
		var xml = this.httpRequest.responseXML;
		var id = parseInt(this.tools.GetNodeValue2(xml, "xml/id/text()"));
		var status = parseInt(this.tools.GetNodeValue2(xml, "xml/status/text()"));
		var name = this.tools.GetNodeValue2(xml, "xml/name/text()");
		
		if(id > 0 && status == 1)
		{
			// Verifica a existência uma URL de referência; caso exista, redireciona para esta
			var queryString = location.search.substr(1).split("&");
			var returnUrl = null;
			for(var i in queryString) {
				var param = queryString[i].split("=");
				if(param[0] == "returnUrl") {
					returnUrl = unescape(param[1]);
					break;
				}
			}
			
			if(returnUrl != null) {
			
				location.href = returnUrl;
			} else {
			
				var frmRef2 = document.forms["formLoginHidden"];
				
				if(frmRef2)
					location.href = frmRef2.action;
				else
					Go('../default.aspx');
			}
		}
		else
		{
			CreateLoginNotify("E-mail ou Senha inválidos.");
		}		

	}
}

function drawLoggedUser(name)
{
	var div = document.getElementById("divLoginAjax");
	if(div != null)
	{
		var html = "<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"0\">";
		html += "<tr>";
		html += "<td colspan=\"5\" align=\"center\" style=\"border-bottom: 1px dashed #D4D4D4;padding: 1px;\">\n";
		html += "Olá, " + name;
		html += "</td>";
		html += "</tr>";
		html += "<tr class=\"loggedButtons\">";
		html += "<td>";
		html += "<a href=\"";
		html += urlMyAccount + "&action=account\">Minha conta</a>";
		html += "</td>";
		html += "<td width=\"1\">|</td>";
		html += "<td>";
		html += "<a href=\"";
		html += urlMyAccount + "\">Minha Página</a>";
		html += "</td>";
		html += "<td width=\"1\">|</td>";
		html += "<td>";
		html += "<a href=\"#\" onclick=\"CheckShoppingCart();\">Sair</a>";
		html += "</td>";
		html += "</tr>";
		html += "</table>";
		
		div.innerHTML = html;
	}
}
// ************************************************************
// Notify
// ************************************************************

// Starts the monitoring thread - scripts.js
document.onmousemove = GetMousePosition;

var loginNotifyDiv = null;
var loginNotifyTimeout = -1;
var loginNotifyOffsetX = -150;
var loginNotifyOffsetY = 20;

function CreateLoginNotify(text)
{
	// Clears any pending timeouts
	if(loginNotifyTimeout!=-1)
	{
		window.clearTimeout(loginNotifyTimeout);
	}

	if(!loginNotifyDiv)
	{
		// Creates a div
		loginNotifyDiv = document.createElement('div');
		//loginNotifyDiv.className = 'loadingNotify'; //class that contains div style
		loginNotifyDiv.style.position = 'Absolute';
		loginNotifyDiv.style.fontWeight = 'bold';
		loginNotifyDiv.style.background = '#FFF';
		loginNotifyDiv.style.padding = '5px';
		loginNotifyDiv.style.margin = '10px';
		loginNotifyDiv.style.border = '2px solid #F00';
		
		document.body.appendChild(loginNotifyDiv);
	}

	// Updates the position
	loginNotifyDiv.style.left = currentMouseX + loginNotifyOffsetX + 'px';
	loginNotifyDiv.style.top  = currentMouseY + loginNotifyOffsetY + 'px';
	
	// Updates the text	
	loginNotifyDiv.innerHTML = text;
	
	// Schedules the notification destruction
	loginNotifyTimeout = window.setTimeout('DestroyLoginNotify()', 4000);
}

function DestroyLoginNotify()
{
	// Destroys the div and resets the parameters
	document.body.removeChild(loginNotifyDiv);
	loginNotifyDiv = null;
	loginNotifyTimeout = -1;
}
function DestroyLoginNotify2()
{
	// Destroys the div and resets the parameters
	window.opener.document.body.removeChild(loginNotifyDiv);
	loginNotifyDiv = null;
	loginNotifyTimeout = -1;
}
function CheckLogin()
{
	managerLogin.Add("ajax/getLoginXML.aspx?action=card", PopLogin, null, null, null, null,"");	
}

function PopLogin()
{
	var frmRef = document.forms["formCheckPin"];

	if(this.httpRequest.status == 200)
	{	
		var html = this.httpRequest.responseText;
		
		if(html == "deslogado")//redireciona para pagina de login caso usuário esteja deslogado e tente validar cartao
		{	
			document.getElementById('code').value = frmRef.pinid.value;
			frmRef.submit();
		} 
		else //checa o cartao do usuario 
		{			
			post = "user=" + html + "&code=" + frmRef.pinid.value;	
			managerLogin.Add("ajax/checkCard.aspx?", Redirect, null, null, null, null,post);
		}
	}	
}


// ************************************************************
// Notify finalize shopping
// ************************************************************

function CheckShoppingCart(){
	managerLogin.Add("ajax/checkShoppingCart.aspx", CheckShoppingCart_Return, null, null, null, null,"");
}

function CheckShoppingCart_Return()
{
	var html = this.httpRequest.responseText;
	if(html == "true")
		CreateShoppingNotify();
	else 
		window.location.href = "home.aspx?logout=true";
}

function DivAction(bool){
	DestroyLoginNotify();
	if (bool)
		window.location = "checkout.aspx";
	else
		window.location = "home.aspx?logout=true";
}

function CreateShoppingNotify()
{	
	if(!loginNotifyDiv)
	{
		// Creates a div
		loginNotifyDiv = document.createElement('div');
		loginNotifyDiv.className = 'alertBox';
		
		document.body.appendChild(loginNotifyDiv);
	}
	
	// Updates the position
	loginNotifyDiv.style.left = currentMouseX + loginNotifyOffsetX + 'px';
	loginNotifyDiv.style.top  = currentMouseY + loginNotifyOffsetY + 'px';

	var html  = "<h3>Existem itens adicionados ao seu carrinho, deseja finalizar sua compra?</h3>";
		html += "<a href=\"#\" onclick=\"javascript:DivAction(true);\">Sim</a>"
		html += "<a href=\"#\" onclick=\"javascript:DivAction(false);\">Não</a>"
		
	loginNotifyDiv.innerHTML = html;
} 

function CreateCardNotify(message)
{
	// Clears any pending timeouts
	if(loginNotifyTimeout!=-1)
	{
		window.clearTimeout(loginNotifyTimeout);
	}	
	if(!loginNotifyDiv)
	{
		// Creates a div
		loginNotifyDiv = document.createElement('div');
		loginNotifyDiv.className = 'alertBox_2';
		
		document.body.appendChild(loginNotifyDiv);
	}
	// Updates the position
	loginNotifyDiv.style.left = currentMouseX + loginNotifyOffsetX + 'px';
	loginNotifyDiv.style.top  = currentMouseY + loginNotifyOffsetY + 'px';
				
	loginNotifyDiv.innerHTML = message; 
	// Schedules the notification destruction
	loginNotifyTimeout = window.setTimeout('DestroyLoginNotify()', 4000);
}

function CreateCardNotify2(posX,posY,message)
{
	// Clears any pending timeouts
	if(loginNotifyTimeout!=-1)
	{
		window.clearTimeout(loginNotifyTimeout);
	}	
	if(!loginNotifyDiv)
	{
		// Creates a div
		loginNotifyDiv = document.createElement('div');
		loginNotifyDiv.className = 'alertBox_2';
		
		document.body.appendChild(loginNotifyDiv);
	}
	// Updates the position
	loginNotifyDiv.style.left = posX + loginNotifyOffsetX + 'px';
	loginNotifyDiv.style.top  = posY + loginNotifyOffsetY + 'px';
				
	loginNotifyDiv.innerHTML = message; 
	// Schedules the notification destruction
	loginNotifyTimeout = window.setTimeout('DestroyLoginNotify()', 4000);
	
}

function DestroyCardNotify()
{
	// Destroys the div and resets the parameters
	document.body.removeChild(loginNotifyDiv);
	loginNotifyDiv = null;
	loginNotifyTimeout = -1;
}

