var recipients = [];
var focusElement;

$(function() {
	$('#fetch').bind('click',function(e){GetGoogleContacts();e.preventDefault();});
	$('#y_fetch').bind('click',function(e){GetYahooContacts();e.preventDefault();});
	$('#h_fetch').bind('click',function(e){GetHotmailContacts();e.preventDefault();});
	$('#tabcontainer > ul').tabs();
	$('.addbtn a').bind('click',AddRcpts);
	$('#btn_add_rcpts').bind('click',function(e){AddManually();e.preventDefault();});
	$('#fftf_submit').bind('click',FFTFSubmit);
	
	
	
	//this is for IE arrays that do not support indexOf
	if(!Array.indexOf){
		Array.prototype.indexOf = function(obj){
			for(var i=0; i<this.length; i++){
				if(this[i]==obj){
				return i;
			}
		}
			return -1;
		}
	}
	
	$(document).keyup(function(e) {
		if (e.keyCode == 13) {
			switch (focusElement) {
				case 'g':
					GetGoogleContacts();
					break;
				case 'y':
					GetYahooContacts();
					break;
				case 'h':
					GetHotmailContacts();
					break;
				case 'm':
					AddManually();
					break;
			}
		}
   });
	
	$('#password').focus(function(e) {focusElement = 'g';});
	$('#y_password').focus(function(e) {focusElement = 'y';});
	$('#h_password').focus(function(e) {focusElement = 'h';});
	$('#new_rcpt').focus(function(e) {focusElement = 'm';});
	
});

function stopBubble(e) {
	var e = e || window.event;
	e.cancelBubble = true;   // stops IE
  	if (e.stopPropagation) { // stops others
	  	e.stopPropagation();
  	}
}

function GetGoogleContacts() {
	$('#g_emails').empty();
	ShowLoading('#g_emails');
	$.ajax({
		type: 'GET',
		url: 'http://mshctesting.sslpowered.com/Metodiev/NAA0801/google_import2.php',
		data: {email:$('#email').val(),password:$('#password').val()},
		dataType: 'jsonp',
		jsonp: 'jsonp_callback',
		timeout: 1000000,
		error: function(xhr) {
			$('#g_emails').text('There was an error while loading your contacts. Please try again.');
		},
		success: function(data) {
			$('#g_emails').empty();
			if (data.contacts.length==0) {
				$('#g_emails').text('We could not import any contacts. Please, check your login information and try again.');
			} else {
				for (j=0;j<data.contacts.length;j++) {
					var ee = $('<div></div>');
					$(ee).append("<input class='chk' type='checkbox' value='"+data.contacts[j]+"'/>");
					$(ee).append("<span>"+data.contacts[j]+"</span>");
					$('#g_emails').append(ee);
				}
				$("#section-1 .addbtn").show();
			}
		}
	});
}

function GetYahooContacts() {
	$('#y_emails').empty();
	ShowLoading('#y_emails');
	$.ajax({
		type: 'GET',
		url: 'http://mshctesting.sslpowered.com/Metodiev/NAA0801/yahoo_import2.php',
		data: {email:$('#y_email').val(),password:$('#y_password').val()},
		dataType: 'jsonp',
		jsonp: 'jsonp_callback',
		timeout: 1000000,
		success: function(data) {
			$('#y_emails').empty();
			if (data.contacts.length==0) {
				$('#y_emails').text('We could not import any contacts. Please, check your login information and try again.');
			} else {
				for (j=0;j<data.contacts.length;j++) {
					var ee = $('<div></div>');
					$(ee).append("<input class='chk' type='checkbox' value='"+data.contacts[j]+"'/>");
					$(ee).append("<span>"+data.contacts[j]+"</span>");
					$('#y_emails').append(ee);
				}
				$("#section-3 .addbtn").show();
			}
		},
		error: function(xhr) {
			$('#y_emails').text('There was an error while loading your contacts. Please try again.');
		}
	});
}

function GetHotmailContacts() {
	$('#h_emails').empty();
	ShowLoading('#h_emails');
	$.ajax({
		type: 'GET',
		url: 'http://mshctesting.sslpowered.com/Metodiev/NAA0801/hotmail_import2.php',
		data: {username:$('#h_email').val(),password:$('#h_password').val()},
		dataType: 'jsonp',
		jsonp: 'jsonp_callback',
		timeout: 1000000,
		success: function(data) {
			$('#h_emails').empty();
			if (data.contacts.length==0) {
				$('#h_emails').text('We could not import any contacts. Please, check your login information and try again.');
			} else {
				for (j=0;j<data.contacts.length;j++) {
					var ee = $('<div></div>');
					$(ee).append("<input class='chk' type='checkbox' value='"+data.contacts[j]+"'/>");
					$(ee).append("<span>"+data.contacts[j]+"</span>");
					$('#h_emails').append(ee);
				}
				$("#section-2 .addbtn").show();
			}
		},
		error: function(xhr) {
			$('#h_emails').text('There was an error while loading your contacts. Please try again.');
		}
	});
}

function AddRcpts(event) {
	var prnt = $(this).parent().parent();
	var i=0;
	$('.chk',prnt).each(function() {
		if ($(this).attr('checked')==true) {
			if (AddRecipient($(this).val()))
				i++;
		}
	});
	$('.feed',prnt).text(i+' recipients added');
	RenderRecipients();
	event.preventDefault();
}

function AddRecipient(email) {
	//check if it is a valid email
	if (!VerifyEmail(email)) { return false; }
	//check if it is already in the list
	if (recipients.indexOf(email) == -1) {
		recipients[recipients.length] = email;
		return true;
	}
	return false;
}

function ShowLoading(elem) {
	$("<span><img src='Assets/images/loading.gif' /> Loading...</span>").appendTo(elem);
}

function HideLoading() {
	$('#s').empty();
}

function RenderRecipients() {
	$('#rcpt_list').empty();
	for (j=0;j<recipients.length;j++) {
		var line = $("<div></div>");
		$("<a class='remove_rcpt' href='#'>X</a>").bind('click',{email:recipients[j]},RemoveRecipient).appendTo($(line));
		$('<span>'+recipients[j]+'</span>').appendTo(line);
		$(line).appendTo('#rcpt_list');
	}
}

function RemoveRecipient(event) {
	var i = recipients.indexOf(event.data.email);
	recipients.splice(i,1);
	$(this).parent().remove();
	event.preventDefault();
}

function AddManually() {
	var rcpts = $('#new_rcpt').val().split(",");
	var k=0;
	for (j=0;j<rcpts.length;j++) {
		if (AddRecipient(rcpts[j]))
			k++;
	}
	$('#new_rcpt').val('');
	$('#manual_status').text(k+' recipients added');
	RenderRecipients();
}

function FFTFSubmit(event) {
	var errors = '';
	if ($('#fname').val() == '')
		errors = 'First name\n';
	if ($('#lname').val() == '')
		errors += 'Last name\n';
	if ($('#friend_email').val() == '')
		errors += 'Your email';
	if (errors != '') {
		errors = 'Fill in the following fields\n' + errors;
		alert(errors);
		event.preventDefault();
	} else {
		if (recipients.length == 0) {
			alert('You have not added any recipients');
			event.preventDefault();
		} else {
			$('#hdn_fname').val($('#fname').val());
			$('#hdn_lname').val($('#lname').val());
			$('#hdn_email').val($('#friend_email').val());
			$('#emails').val(recipients.join(','));
		}
	}
}