var visit = 0;
var MSIE6 = false;
if (/MSIE 4/.test(navigator.userAgent) || /MSIE 5/.test(navigator.userAgent) || /MSIE 6/.test(navigator.userAgent)) {
	MSIE6 = true;
}

var regex = /^([a-zA-Z0-9_\.\-\+'])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

$(document).ready(function() {
//	var reg_email;
//	var tab_result;
//	var service_result;
//	var tracking_registration;
	
	$('a.external').attr('target', '_blank'); 
	
	$("img").each( function(index) { $(this).click( function () { if (this.blur) { this.blur(); }})});  //  because we don't like focus indicators
	  $("a").each( function(index) { $(this).click( function () { if (this.blur) { this.blur(); }})});
	
	
	$('#loginForm').submit(function() {
		$(this).ajaxSubmit({
						   beforeSubmit:	function()	{ 	return loginCheck(highlight=false,submitted=true); },
						   success:			loginReceive
						   });
		return false;
	});
	
});

function volunteerCheck(highlight,submitted,formData)
{
	
	fields = new Array();
	
	fields[0] = 'first_name';
	fields[1] = 'last_name';
	fields[2] = 'email';
	fields[3] = 'confirm_email';
	fields[4] = 'location';
	fields[5] = 'language_note';
	
	var errors = new Array();
	errors[0] = ($('#'+fields[0]).val() == '' ? 'Please insert your first name' : '');
	errors[1] = ($('#'+fields[1]).val() == '' ? 'Please insert your last name' : '');
	errors[2] = (!regex.test($('#'+fields[2]).val()) ? 'Please provide a valid email address' : '');
	errors[3] = ($('#'+fields[2]).val() != $('#'+fields[3]).val() ? 'Please check that both email addresses are correct' : '');
	errors[4] = ($('#'+fields[4]).val() == '' ? 'Please insert your location' : '');
	errors[5] = ($('#'+fields[5]).val() == '' ? 'Please insert your spoken languages' : '');
	
	
	scanPopErrorBox(fields,errors,highlight); // actually runs the check
	
	if(errors.join('').length > 0)
	{
		if(visit == 0)
		{
			Google_tracker('/volunteer_application_error');
			visit++;
		}
		for(var i = 0; i < fields.length; i++) {
			var el = document.getElementById(fields[i]);
			if (el) {
				el.onfocus = function() { volunteerCheck(this.id); }
				el.onblur = volunteerCheck;
			}
		}
		return false;
	}
	else
	{
		popErrorBox(fields[0],errors[0]); // clear errorbox
		if (submitted) {
					
		}
		$('#div_errors').hide();
		return true;
	}
}

function volunteerReceive(responseText, statusText) 
{
	if (responseText.length > 50) 
	{
		$('#volunteer_content').html(responseText);
		Google_tracker('/volunteer_application_succesfully');
	} 
	else 
	{
		switch(responseText)
		{
			case '0':
				popErrorBox('first_name','Please insert your first name');
				err = '';
			break;
			case '-1':
				popErrorBox('last_name','Please insert your last name');
				err = '';
			break;
			case '-2':
				popErrorBox('email','Please provide a valid email address');
				err = '';
			break;
			case '-3':
				popErrorBox('confirm_email','Please check that both email addresses are correct');
				err = '';
			break;
			case '-4':
				popErrorBox('location','Please insert your location');
				err = '';
			break;
			case '-5':
				popErrorBox('language_note','Please insert your spoken languages');
				err = '';
			break;
			case '-100':
				err = 'System error, please try again later';
			break;
			default:
				err = responseText;
			break;
		}
		if(visit == 0)
		{
			Google_tracker('/volunteer_application_error');
			visit++;
		}
		$('#div_errors').html(err);
		$('#div_errors').show();
	}
}

function loginCheck(highlight,submitted,formData)
{
	
	fields = new Array();
	
	fields[0] = 'loginemail';
	fields[1] = 'loginpass';
	
	var errors = new Array();
	errors[0] = (!regex.test($('#'+fields[0]).val()) ? 'Please provide a valid email address' : '');
	errors[1] = ($('#'+fields[1]).val() == '' ? 'Please enter your password' : '');
	
	
	scanPopErrorBox(fields,errors,highlight); // actually runs the check
	
	if(errors.join('').length > 0)
	{
		if(visit == 0)
		{
			Google_tracker('/Login_error');
			visit++;
		}
		for(var i = 0; i < fields.length; i++) {
			var el = document.getElementById(fields[i]);
			if (el) {
				el.onfocus = function() { loginCheck(this.id); }
				el.onblur = loginCheck;
			}
		}
		return false;
	}
	else
	{
		popErrorBox(fields[0],errors[0]); // clear errorbox
		if (submitted) {
					
		}
		$('#div_errors').hide();
		return true;
	}
}

function loginReceive(responseText, statusText) 
{
		switch(responseText)
		{
			case '1':
				document.location.href="/user";
			break;
			case '-1':
				popErrorBox('loginemail','This email does not appear to be valid.');
			break;
			case '-2':
				popErrorBox('loginpass','Please enter your password.');
			break;
			case '-3':
				alert('Sorry, a system error occurred.  Please try later.');
			break;
			case '-4':
				popErrorBox('loginpass','Sorry, these details were not recognised');
			break;
			default:
				alert(responseText);
			break;
		}
}

function loadphoto(photo_id)
{
	var url = "/index/loadphoto/";
	$.get(url + "format/html/", { photo_id : photo_id },
    	function(data)
    	{
    		$('#big_centre').html(data);
    	}
    );
}


function Google_tracker(page_name)
{
	setTimeout("Google_track('"+page_name+"')", 1000);		//delay to wait the footer to load: the footer initializes Google analytics
}

function Google_track(page_name)
{
	try{	pageTracker._trackPageview(page_name);	}
	catch(e){	}
}

function swapBox(id)
{
	highlight(id, 0);
	loadBox(id);	//load mini box in the centre
}

function loadBox(id)
{
	var url = "/index/load/";
	$.get(url + "format/html/", { index : id},
    	function(data)
    	{
    		$('#big_centre').html(data);
    	}
    );
}

function highlight(id, status)
{
	if(status == 1)
	{
		$('#box_mini_' + id).addClass('over');
	}
	else
	{
		$('#box_mini_' + id).removeClass('over');
	}

}

function locateObject(obj) {
	var myleft = 0;
	var mytop = 0;
	if (obj.id) {
		if (obj.offsetParent) {
			do {
				myleft += obj.offsetLeft;
				mytop += obj.offsetTop;
			} while (obj = obj.offsetParent);
		}
	}
	return new Array(myleft,mytop);
}

function popErrorBox(id,error,withold) { // withold=true stops the balloon appearing

	if (id.length) {
		if (obj = document.getElementById(id)) {
			var pos = locateObject(obj);
			if (error) {
				if (!withold) {
					if (!(errbox = document.getElementById('errbox'))) { // create an errorbox if it doesn't exist
						var errbox = document.createElement('div');
						errbox.setAttribute('id','errbox');
						document.body.appendChild(errbox);
						errbox.onclick = function() { $(this).hide(); } ;
						errbox.style.position = 'absolute';
						errbox.style.width='220px';
						errbox.style.padding = '0px';
						errbox.style.zIndex = '1200';
						errbox.style.cursor = 'pointer';
						errbox.style.display = 'none';
						errbox.innerHTML = '<div style="padding: 10px 5px 10px 35px; background: transparent url(/images/errorbox.' + (MSIE6?'gif':'png') + ') 0% 0% no-repeat;" id="errboxmsg"></div>'
										 + '<div style="height: 10px; background: transparent url(/images/errorbox.' + (MSIE6?'gif':'png') + ') 0% 100% no-repeat;">&nbsp;</div>';
			
					}
					
					document.getElementById('errboxmsg').innerHTML = error;
	
					var left = parseInt(pos[0]) + parseInt(obj.offsetWidth);
					var top  = parseInt(pos[1]) - 10; 
					
					errbox.style.left = left + 'px';
					errbox.style.top = top + 'px';
	
					if (errbox.style.display == 'none') {
						errbox.style.display = 'block';			
					}
				}
		
				obj.style.border = '1px solid red';
				
			} else {
				obj.style.border = '1px solid #666666';
			}
			
		} else if (errbox = document.getElementById('errbox')) {
			errbox.style.display="none"; // invalid call? Hide error box just in case
		}
	} else if (errbox = document.getElementById('errbox')) {
		errbox.style.display="none"; // invalid call? Hide error box just in case
	}

}

function scanPopErrorBox(fields,errors,highlight) {

	if (!document.getElementById(highlight)) {
			highlight = '';
	}

	if (errbox = document.getElementById('errbox')) {
		errbox.style.display="none"; // zap error box in case the current one has changed to be valid
	}
	var c = fields.length;		
	for (i=0;i<c;i++) {
		if (!highlight && errors[i]) {
			highlight = fields[i];
		}
		withold = (highlight?(fields[i]==highlight?false:true):true);
		popErrorBox(fields[i],errors[i],withold);
	}
}



