
$(document).ready(function() {
    
	$('#aplusUser').focus();
	
	// Setup custom URL
	$('#aplusURL').change(function() {
		
		if ($(this).val() == "aplus:custom") {	
			$('#aplusCustom').slideDown();
			$('#aplusURLCust').focus();		
		} else {			
			if ($('#aplusCustom').is(':visible'))
				$('#aplusCustom').slideUp();		
			$('#aplusUser').focus();					
		}		
				
	});
	
	// Submit Button
	$('#aplusConnect').click(function() {
		
		aplusConnect(getaplusURL(), $('#aplusUser').val(), $('#aplusPass').val());
		
	});
	
	
	// 'Enter' handlers
	$('#aplusUser, #aplusPass, #aplusURL, #recaptcha_response_field').keypress(function(event) {
		if (event.keyCode == '13') {
			$('#aplusConnect').click();
			return false;	
		}
	});
	
	
});




function getaplusURL() {

	if ($('#aplusURL').val() == "aplus:custom")
		return $('#aplusURLCust').val();		
	else	
		return $('#aplusURL').val();
		
}


function aplusSetStatus(level) {

	$('#export-auth-status').hide();
	$('#export-success').hide();
	$('#export-auth-error').hide();
	$('#export-auth-error-critical').hide();
			
	switch (level) {
		
		case 1:  // Progress
			$('#export-auth-status').fadeIn();
			$('#export-connect-fields').fadeTo('slow', 0.25);
			return;
			
		case 2:  // Success
			$('#export-success').fadeIn('slow');
			$('#export-auth').delay(1000).slideUp('slow');
			return;
			
		case 3: // Non-Critical Error
			Recaptcha.reload();
			$('#export-auth-error').fadeIn();
			$('#export-connect-fields').fadeTo('fast', 1);
			$('#aplusConnect').removeAttr('disabled');
			return;
			
		case 4: // Critical Error
			$('#export-auth-error-critical').fadeIn();
			$('#export-auth > .insert-block-child-content').delay(1000).slideUp('slow');
			
		default:
			return;
		
	}

}

//
// START ALLOCATE AUTHENTICATION
//

function aplusConnect(url, user, pass) {
			
	$('#aplusConnect').attr('disabled', 'disabled');
		
	if (url.length == 0 || user.length == 0 || pass.length == 0 || $('#recaptcha_response_field').val().length == 0) {
		
		aplusSetConnectErr("Please enter a valid username and password. Additionally, please ensure you completed the security code.");
		
		if (url.length == 0) {
			$('#aplusURL').focus();
		}else if (user.length == 0) {
			$('#aplusUser').focus();
		}else if (pass.length == 0) {
			$('#aplusPass').focus();
		}else if ($('#recaptcha_response_field').val().length == 0) {
			$('#recaptcha_response_field').focus();
		}
		
		aplusSetStatus(3);
		
	} else {
	
		aplusSetStatus(1);
		
		aplusDoConnect(url, user, pass);
		
	}
	
}

function aplusDoConnect(url, user, pass) {
		
	url = Base64.encode(url);
	user = Base64.encode(user);
	pass = Base64.encode(pass);
	
	//var now = new Date();
	//var offset = now.getTimezoneOffset();
	
	$.post(
		"aplus-connect.php",
		{action: 'connect', url: url, user: user, pass: pass, r_challenge: $('#recaptcha_challenge_field').val(), r_response: $('#recaptcha_response_field').val()},
		aplusAuthComplete
	);
	
}

function aplusSetConnectErr(text, isCritical) {
	
	isCritical = typeof(isCritical) != 'undefined' ? isCritical : false;
		
	if (isCritical == true) {
		$('#export-auth-error-critical > p').text(text);	
		aplusSetStatus(4);		
	}else{
		$('#export-auth-error > p').text(text);		
		aplusSetStatus(3);		
	}
	
}

function aplusAuthComplete(data, textStatus, XMLHttpRequest) {
		
	if (data.substr(0, 2) == '1|') {
				
		$('#export-success-message > p > .export-download-ical').attr('href', 'fetch.php?calendar=' + data.substring(2));
		
		// Set Success
		aplusSetStatus(2);
		
	} else {
		
		// Check for errors
		switch (data) {
			
			case '-1': 
				aplusSetConnectErr('The Allocate+ URL provided was not valid. Please checked you have provided the correct URL.');
				return;
				
			case '-2': 
				aplusSetConnectErr('The credentials you provided were not accepted by Allocate+.');
				return;
				
			case '-3': 
				aplusSetConnectErr('Oops!\r\nA problem has occured when contacting Allocate+. Please try again later.');
				return;
				
			case '-4': 
				aplusSetConnectErr('Please check you have entered a valid username and password.');
				return;
				
			case '-5': 
				aplusSetConnectErr('Please check you typed the security code correctly.');
				return;
				
			case '-6':
				aplusSetConnectErr('The Allocate+ system is currently closed. You will need to try again when Allocate+ is in allocation mode.', true);
				return;
				
			case '-7':
				aplusSetConnectErr('No allocations could be found!\r\nAllocate+ may be currently closed, or in preference mode.', true);
				return;
				
			case '-8':
				aplusSetConnectErr('Allocate+ has reached the maximum number of logins. Try again soon.');
				return;				
										
			default:
				aplusSetConnectErr('An unknown error occured: ' + data);
				return;
				
		}
		
	}
}

/* Base 64 Encode / Decode -- http://www.webtoolkit.info/javascript-base64.html */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('5 H={h:"T+/=",R:z(7){5 8="";5 t,o,l,v,s,j,f;5 i=0;7=H.K(7);G(i<7.E){t=7.q(i++);o=7.q(i++);l=7.q(i++);v=t>>2;s=((t&3)<<4)|(o>>4);j=((o&I)<<2)|(l>>6);f=l&u;p(O(o)){j=f=D}y p(O(l)){f=D}8=8+k.h.m(v)+k.h.m(s)+k.h.m(j)+k.h.m(f)}B 8},S:z(7){5 8="";5 t,o,l;5 v,s,j,f;5 i=0;7=7.J(/[^A-Q-P-9\\+\\/\\=]/g,"");G(i<7.E){v=k.h.C(7.m(i++));s=k.h.C(7.m(i++));j=k.h.C(7.m(i++));f=k.h.C(7.m(i++));t=(v<<2)|(s>>4);o=((s&I)<<4)|(j>>2);l=((j&3)<<6)|f;8=8+d.b(t);p(j!=D){8=8+d.b(o)}p(f!=D){8=8+d.b(l)}}8=H.L(8);B 8},K:z(e){e=e.J(/\\r\\n/g,"\\n");5 a="";Z(5 n=0;n<e.E;n++){5 c=e.q(n);p(c<w){a+=d.b(c)}y p((c>X)&&(c<U)){a+=d.b((c>>6)|V);a+=d.b((c&u)|w)}y{a+=d.b((c>>N)|M);a+=d.b(((c>>6)&u)|w);a+=d.b((c&u)|w)}}B a},L:z(a){5 e="";5 i=0;5 c=0;5 x=0;5 F=0;G(i<a.E){c=a.q(i);p(c<w){e+=d.b(c);i++}y p((c>Y)&&(c<M)){x=a.q(i+1);e+=d.b(((c&W)<<6)|(x&u));i+=2}y{x=a.q(i+1);F=a.q(i+2);e+=d.b(((c&I)<<N)|((x&u)<<6)|(F&u));i+=3}}B e}};',62,62,'|||||var||input|output||utftext|fromCharCode||String|string|enc4||_keyStr||enc3|this|chr3|charAt||chr2|if|charCodeAt||enc2|chr1|63|enc1|128|c2|else|function||return|indexOf|64|length|c3|while|Base64|15|replace|_utf8_encode|_utf8_decode|224|12|isNaN|z0|Za|encode|decode|ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789|2048|192|31|127|191|for'.split('|'),0,{}))

