
Array.prototype.contains = function (element) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element) {
			return true;
		}
	}
	return false;
}

Array.prototype.remove = function (element) {
    for(var i = 0, n = 0; i < this.length;i++) {
        if(this[i] != element) {
            this[n++] = this[i];
        }
    }
    this.length--;
}


$(document).ready(function() { 
	autoSelectFields();
	
	// auto scroll sighted species
	$jScroller.add("#recentlysighted_container","#recentlysighted_scroller","left",1,true);
	$jScroller.start();
	
	
});

function autoSelectFields() {
	$("input, textarea").focus(
		 function() {
			// only select if the text has not changed
			if(this.value == this.defaultValue) {
				this.select();
			}
		 }
	)
}

function obj(id) {
	return document.getElementById(id);
}

function debug(s) {
	$('#debug').html($('#debug').html() + '<br>' + s);
}

function encode(str) {
	return encodeURIComponent(str);
}

function keyVal(s) {
	return '&' + s + '=' + encode($('#'+s).val());
}

function val(s) {
	try {
		return $(s).val();
	}
	catch (e) {}
	return '';
}

function toZero(s, len) {
	s = s + '';
	if (s.length < len)	 {
		var tmp = '';
		for (var i = 0; i < len - s.length; i++) {
			tmp += '0';
		}
		return tmp + s;
	}
	return s;
}

function refreshUrl() {
	var url = location.href;
	if (url.indexOf('#') != -1)	{
		url = url.substring(0, url.indexOf('#'));
	}
	location.href = url;
}

function locateUrl(url) {
	location.href = url;
}

function wait(func, second) {
	setTimeout(func, second*1000);
}

function checkall(subfix) {
	var bChecked = obj('chkall'+subfix).checked;
	var chks = document.getElementsByName('chk'+subfix);
	for (var i = 0; i < chks.length; i++) {
		chks[i].checked = bChecked;
	}
}

function getCheckedValue(chk) {
	var s = '';
	var chks = document.getElementsByName(chk);
	for (var i = 0; i < chks.length; i++) {
		if (chks[i].checked) {
			if (s != '') s+= ',';
			s += chks[i].value;
		}
	}
	return s;
}

function showMessage(message, container) {
	if (container != null && container != '')	{
		container += ' ';
	}
	else {
		container = '';
	}
	if (message == null) message = 'do you have some message to show?';
	$(container + '#comnMsg .alertInfo').html(message);
	$(container + '#comnMsg').show();
	$(container + '#errorMsg').hide();
}

function showError(error, container) {
	if (container != null && container != '')	{
		container += ' ';
	}
	else {
		container = '';
	}
	if (error == null) error = 'do you have some error to show?';
	$(container + '#errorMsg .alertInfo').html(error);
	$(container + '#errorMsg').show();
	$(container + '#comnMsg').hide();
}

function login() {
	//$('#loginBox').empty();
	
	Boxy.load(base_url + 'login/popup/', {modal:true, title:'Sign In', 
		afterShow: function() {
			loginValidate();
		}
	});
}

function loginValidate() {
	// validate signup form on keyup and submit
	$('#login_username').focus();
	var validator = $("#login_form").validate({
		rules: {
			login_username: "required"
		},
		messages: {
			login_username: "Please enter your login username."
		},
		// specifying a submitHandler prevents the default submit, good for the demo
		submitHandler: function() {
			loginSubmit();
		}
	});
}

function loginSubmit() {
	$.ajax({
		type: 'POST',
		url: base_url + 'login/popup',
		data: $('#login_form').serialize(),
		dataType: "json",
		success: function(data){
			if (data.status == 'error') {
				showError('Login error.', '#loginBox');
			}
			else if (data.status == 'login_error_inactive') {
				showError('You have not yet activated your account.', '#loginBox');
			}
			else if (data.status == 'login_error_password') {
				showError('Invalid Password.', '#loginBox');
			}
			else if (data.status == 'login_error_username') {
				showError('Invalid Username.', '#loginBox');
			}
			else if (data.status == 'success') {
				showMessage('Login success.', '#loginBox');
				wait('refreshUrl()', 0.5);
			}
			else {
				wait('refreshUrl()', 0.5);
			}
		}
	});
}

function getSpeciesDir(speciesName) {
	if (speciesName == null) return '';
	return speciesName.replace(/ /g, '_');
}

function _page_onload() {
	$('#loading').hide();
	
	$('#loading').ajaxStart(function(){
		$(this).css('top', (jQuery(window).scrollTop()) + 'px');
	  $(this).show(); 
	});
	
	$('#loading').ajaxStop(function(){
  	$(this).hide(); 
	});
}

function dateDiff(interval, date1, date2) {
  var objInterval = {'D' : 1000 * 60 * 60 * 24, 'H' : 1000 * 60 * 60,
                     'M' : 1000 * 60, 'S' : 1000, 'T' : 1};
  interval = interval.toUpperCase();
  var dt1 = Date.parse(date1.replace(/-/g, '/'));
  var dt2 = Date.parse(date2.replace(/-/g, '/'));
  try {
    return Math.round((dt2 - dt1) / eval('(objInterval.' + interval + ')'));
  }
  catch (e) {
    return e.message;
  }
	//alert(dateDiff('D', '2007-4-1', '2007/04/19'));
}

function getGeocodingData(point) {
	var data = new Object();
	try {data.location = point.address;} catch(e){}
					//try {data.street = point.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;} catch(e){}
					try {
							var street = '';
							if (typeof(point.AddressDetails.Country.AdministrativeArea.Locality) == "undefined") 
								street = point.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName; 
							else street = point.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
							data.street = street;
						}
						catch (e) {}
					//try {data.city = point.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;} catch(e){}
					try {
							var city = '';
							if (typeof(point.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) == "undefined") 
								city = point.AddressDetails.Country.AdministrativeArea.Locality.LocalityName; 
							else city = point.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
							data.city = city;
						}
						catch (e) {}
					try {data.state = point.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;} catch(e){}
					//try {data.postcode = point.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;} catch(e){}
					try {
							var postcode = '';
							if (typeof(point.AddressDetails.Country.AdministrativeArea.Locality) == "undefined") 
								postcode = point.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber; 
							else postcode = point.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
							data.postcode = postcode;
						}
						catch (e) {}
					try {data.country = point.AddressDetails.Country.CountryNameCode;} catch(e){}
					try {data.latitude = point.Point.coordinates[1];} catch(e){}
					try {data.longitude = point.Point.coordinates[0];} catch(e){}
		return data;
}