/**
 * ACG Cardholder Login
 */

// includes
var inclBase = location.protocol+'//'+location.hostname+(-1!=location.pathname.indexOf('pl_test/')?'/acgpl_test/':'/acgpl/');
document.write('<script type="text/javascript" src="'+inclBase+'js/utils.js"></script>');
document.write('<script type="text/javascript" src="'+inclBase+'js/json.js"></script>');
document.write('<script type="text/javascript" src="'+inclBase+'js/md5.js"></script>');


function Loaded()
{
	hideElemVis('cardselect');
}
window.onload = Loaded;

function LoginCheckHandler(resp)
{

	if (resp.indexOf('[') < 0 && resp.indexOf('{') < 0)
	{
		setDivText('msg', 'Error. Please try again.');
		return;
	}

	// parse response
	var respData = json_parse(resp);

	// count the cards
	var numCards = 0;
	var firstId = 0;
	for (key in respData)
	{
		if (!numCards)
			firstId = key;
		++numCards;
	}
	
	// nothing in card popup list
	document.loginform.id.options.length = 0;

	// just one so we're good
	if (1 == numCards) {
		setDivText('msg', 'Logging in...');
		
		// inject id for post
		document.loginform.id.options[0] = new Option(respData[firstId], firstId, true, false);
		document.loginform.submit();
	}
	
	// multiple accounts
	else 
		if (numCards > 1) {
			var o = 0;
			for (key in respData) 
				document.loginform.id.options[o++] = new Option(respData[key], key, false, false);
			
			setDivText('msg', 'Multiple cards found. Please select one:');
			showElemVis('cardselect');
		}
		else
		{
			setDivText('msg', 'Login not found.');
			//setDivText('msg', 'Login not found, password = ' + md5('12345'));
		}
}

function LoginClicked()
{
	var email = document.loginform.email.value;
	var password = document.loginform.password.value;
	var id = document.loginform.id.value;
	
	// selected card and ready to go
	if (parseInt(id) > 0)
	{
		setDivText('msg', 'Logging in...');
		document.loginform.submit();
		return;
	}
	
	if ('' == email)
	{
		setDivText('msg', 'Please enter email.');
		return;
	}

	if ('' == password)
	{
		setDivText('msg', 'Please enter password.');
		return;
	}

	// encode password
	password = MD5(password);
	
	setDivText('msg', 'Checking...');
	
	var url = serviceUrl('logincheck');
	var params = 'e=' + email + '&p=' + password;
	httpPost(url, params, LoginCheckHandler);
}
function LoginSubmit()
{
	LoginClicked();
	return false;
}

