$.getScript("/media/sffrd.library.js");

function clickBox(id) {
	$('#checkbox-'+id).each(
		function(i) {
			if (this.checked) 
				addID(id); 
			else {
				removeID(id);
				if (window.location.pathname == "/export/")
					window.location.reload();
			}
		}
	);
}

function syncCheckState() {
	var arr = cookie2array();
	// cycle through all the checkboxes in the list, and work on them
	$('.record-button input[@type=checkbox]').each(
		function(i) {
			// this ID exists in the array
			if (arr.has(this.value)) 
				this.checked = true;
			else
				this.checked = false;
		}
	);
}

function selectAll() {
	var arr = cookie2array();
	$('.record-button input[@type=checkbox]').each(
		function(i) { 
			this.checked = true;
			if (arr.missing(this.value)) 
				arr.push(this.value);
		}
	);
	array2cookie(arr); 
}

function unselectAll() {
	if (window.location.pathname == "/export/") {
		var confirmIt = confirm("Are you sure you want to remove these items?");
		if (confirmIt == false)
			return false;
	}
	$('.record-button input[@type=checkbox]').each(
		function(i) {
			this.checked = false;
			removeID(this.value);
		}
	);
	if (window.location.pathname == "/export/")
		window.location.reload();
}

function validateDownload() {
	if (getCountFlagged() < 1) {
		alert("There are no items currently flagged.");
		return false;
	}
	else
		return true;
}

function validateEmail() {
	var addr = prompt("Please enter your email address", getSavedEmail());
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if (addr == null) {
		return false;
	}
	else if (reg.test(addr) == false) {
		alert("Invalid email address!")
		return false;
	}
	else {
		$.cookie('sffrd_email', addr, {expires:5,path:'/'});
		return true;
	}
}

function getSavedEmail() {
	if ($.cookie('sffrd_email') == null)
		return '';
	else
		return $.cookie('sffrd_email');
}

function sendEmail(r_id) {
	if (!validateEmail())
		return false;
	else
		$.ajax({
			url: "/export/email/" + (r_id ? r_id + '/' : ''),
			success: function() { alert("The selected record(s) have been sent."); },
			error: function(obj, msg) { alert("There was an error sending the email: " + msg); }
		});
}

function syncPagingState() {
	var cur_page = getPaging();
	$('div.record-tools p.page-options a').each(
		function(i) {
			var name = $(this).attr("id");
			var num = name.substr(name.lastIndexOf('-')+1);
			if (cur_page == num)
				$(this).addClass("current");
			else
				$(this).removeClass("current");
		}
	)
}

$(document).ready(function(){syncCheckState();});
$(document).ready(function(){syncPagingState();});