var const_state_add_opinion = 1;
var const_state_show_opinion = 2;

function species_page_ready(){

	$("a[@rel='single_numeric_property_edit']").click(function()
		{
			property_panel_init($(this).parent());

			$.ajax({
				type: "POST",cache: false,url: "gears/gear_single_numeric_edit.php",
				data: "taxon_id=" + taxon_id + "&user_id=" + user_id + "&" + cp.serialize(),
				success: function(msg){
					cp.find(".results").append(msg);
					show(cp.find(".results"));					
					cp.find("input[@name='save_single_numeric_edit_button']").click(save_single_numeric_edit);
					cp.find("input[@name='cancel_single_numeric_edit_button']").click(function(){
						reset_elements();
					});
				}
			});
			return false;
		});

	$("a[@rel='multiple_numeric_property_edit']").click(function()
		{
			property_panel_init($(this).parent());

			$.ajax({
				type: "POST",cache: false,url: "gears/gear_multiple_numeric_edit.php",
				data: "taxon_id=" + taxon_id + "&" + cp.serialize(),
				success: function(msg){
					cp.find(".results").append(msg);
					show(cp.find(".results"));					
					cp.find("input[@name='save_multiple_numeric_edit_button']").click(save_multiple_numeric_edit);
					cp.find("input[@name='cancel_multiple_numeric_edit_button']").click(function(){
						reset_elements();
					});
				}
			});

			return false;
		});

	$("a[@rel='multiple_text_property_delete']").click(text_property_delete_init);
	$("a[@rel='multiple_text_property_edit']").click(text_property_edit_init);


	$("a[@rel='multiple_text_property_add']").click(function()
		{
			reset_elements();
			property_on($(this).parent());
			cp.find("input[@name='property_value_text']").val("");

			hide($(this));
			show(cp.find("div[@class='work_area']"), 'block');
			hide(cp.find("span[@class='actions']"));

			return false;
		});
		
	$("a[@rel='get_lists']").click(function()
		{		
			if (logged_in) {
				cp = $(this).parent().parent();	
				cp.find(".results").html('');

				reset_elements();				

				$.ajax({
					type: "POST",cache: false,url: "gears/gear_list_get_all.php",
					data: "taxon_id=" + taxon_id,
					success: function(msg){
						cp.find(".results").append(msg);
						show(cp.find(".results"));
						showBox($("div#lists_box"));
						$("*[@name='close_lists']").click(function(){
							hideBox($("div.box_div"));
						});						
						$("input[@name='save_to_list']").click(save_to_list);						
						$("a[@name='list_create_new']").click(list_create_new);
					}	

				});			
			}
			else{show_register_box(true, taxon_id);}
				
		
			return false;
		});
		
	$("a[@rel='get_contributors']").click(function()
		{			
			cp = $(this).parent().parent();	
			cp.find(".results").html('');
		
			reset_elements();				

			$.ajax({
				type: "POST",cache: false,url: "gears/gear_get_contributors.php",
				data: "taxon_id=" + taxon_id,
				success: function(msg){					
					cp.find(".results").append(msg);
					show(cp.find(".results"));
					showBox($("div#contributors_box"));
					$("*[@name='close_contributors']").click(function(){
						hideBox($("div.box_div"));
					});					
				}	
				
			});				
		
			return false;
		});		

	$("input[@name='save_text_property_button']").click(save_text_property);

	$("input[@name='image-previous']").click(function(){handle_image_nav((image_pos > 0), (image_pos-=1), (image_pos == 0), 'image-previous', 'image-next');});
	$("input[@name='image-next']").click(function(){handle_image_nav((image_pos < image_array.length-1), (image_pos+=1), (image_pos == image_array.length-1), 'image-next', 'image-previous');});

	$("#save_opinion_text_button").click(function()
		{
			var parent = $(this).parent();
			
			if (parent.find(".opinion_textarea").val().length < 50) {
				alert('Opinions must be greater than 50 characters long. Current character count: ' + parent.find(".opinion_textarea").val().length);
				parent.find(".opinion_textarea").focus();
			}
			else {
				set_busy($(this), "Saving ");
			
				$.ajax({
					type: "POST",cache: false,url: "gears/gear_save_opinion_text.php",
					data: "taxon_id=" + taxon_id + "&user_id=" + user_id + "&opinion_text=" + parent.find(".opinion_textarea").val(),
					dataType: "json",
					success: function(json){
						if (json.succeeded) {							
							parent.find(".opinion_text").html(convert_linefeed_to_br(parent.find(".opinion_textarea").val()));
							setup_opinion_elements(const_state_show_opinion);
							parent.find("input[@id='cancel_opinion_text_button']").css('display','none');
							if (json.date_added.length > 0) {parent.find("span[@class='opinion_date_added']").text('You wrote on ' + json.date_added);}
							if (json.date_edited.length > 0) {parent.find("span[@class='opinion_date_edited']").text('(Last edit was on ' + json.date_edited + ')');}
							opinion_added = true;						
							//alert('here');
							feedback(parent.find(".feedback"),'Opinion saved');
						}
						else {show_register_box(true, taxon_id);}
						
						reset_elements();
						$("#save_opinion_text_button").val('Add Your Opinion / Experience');
					}
				});				
			}	
						
		});

	$(".edit_opinion_text_button").click(function()
		{
			var parent = $(this).parent();			
			parent.find(".opinion_textarea").attr('rows','10');
			setup_opinion_elements(const_state_add_opinion);
			if (!opinion_added) {
				parent.find("input[@id='cancel_opinion_text_button']").css('display','none');
			}	
			else{
				parent.find("input[@id='cancel_opinion_text_button']").css('display','inline');
			}	
			window.location.hash = 'opinions';				
		});

	$("#cancel_opinion_text_button").click(function()
		{
			setup_opinion_elements(const_state_show_opinion);
			$(this).css('display','none');
		});

	$("a[@name='show-lb']").click(function()
		{
			if (image_array.length > 0) {
				$("img[@id='taxon-image-large']").attr({src:bucket_taxon_images_path_large + image_array[image_pos]});
				$(".taxon_image_info_copy").html($(".taxon_image_info").html());
				$(".taxon_image_copyright_member").html('<a href="' + statistics_script + image_user_id_array[image_pos] + '">' + image_username_array[image_pos] + '</a> <acronym title="' + acronym_text + '">(' + image_user_pop_edits_array[image_pos] + ')</acronym>');
				$(".taxon_image_member_contact").html('<a href="/privmsg.php?mode=post&u=' + image_user_id_array[image_pos] + '">contact</a>');				

				handle_image_like_cell();

				showBox($("div#lightbox"));
			}			
			else {
				if (logged_in) {				
					showBox($("div#image_upload"));
				}
				else{show_register_box(true, taxon_id);}
			}	
			return false;
		});	

	$("a[@name='image_upload_link']").click(function()
		{
			if (logged_in) {
				$("input[@name='image_file']").val("");
				showBox($("div#image_upload"));
				return false;
			}
			else{show_register_box(true, taxon_id);}
		});

	$("input[@name='image_upload_cancel']").click(function()
		{
			hideBox($("div.box_div"));			
		});
		
	$("input[@class='upload_image_button']").click(function()
		{		
			if ($("input[@name='image_file']").val().length == 0) {
				alert('You must choose an image from your computer.');
			}
			else if ($("#certify_image:checked").val() == null) {
				alert('You must certify that you own full copyright of this image.');				
			}
			else {
				$("input[@name='image_file']").parent().submit();
				$("div#image_upload").html('Uploading image, please wait...<br/><br/>This may take a few moments depending on the file size of the image and your internet connection speed.');
			}
		});		
		
	$("textarea[@class='opinion_textarea']").click(function()
		{
			if (!logged_in) {
				show_register_box(true, taxon_id);
			}
		});		
		
	$(".opinion_like").click(function()
		{			
			var this_id = $(this).attr("rel");
			var this_parent = $(this).parent();
			
			if (logged_in) {
				this_parent.html('<span class="processing">Saving...</span>');

				$.ajax({
					type: "POST",cache: false,url: "gears/gear_save_opinion_like.php",
					data: "opinion_id=" + this_id,
					dataType: "json",
					success: function(json){					
						if (json.succeeded) {
							this_parent.html('<b>You like this opinion</b><br/>(' + json.opinion_likes + ' ' + (json.opinion_likes != 1 ? 'people like' : 'person likes') + ' this opinion)');
						}
						else {
							show_register_box(true, taxon_id);
							this_parent.html(old_html);
						}
					}
				});
			}
			else {
				show_register_box(true, taxon_id);
			}				
			
			return false;
		});	
		
	$("a[@rel='start_track']").click(function()
		{			
			if (logged_in) {
				$(".track_taxon").html('<span class="processing">Saving...</span>');

				$.ajax({
					type: "POST",cache: false,url: "gears/gear_track_taxon_start.php",
					data: "taxon_id=" + taxon_id,
					dataType: "json",
					success: function(json){
						if (json.succeeded) {
							$(".track_taxon").html('<b>You Are Now <a href="' + plant_tracking_script + '">Watching</a> This Plant</b>');
						}
					}
				});
			}
			else {
				show_register_box(true, taxon_id);
			}			

			return false;
		});
		
	$("a[@rel='stop_track']").click(function()
		{
			$(".track_taxon").html('<span class="processing">Saving...</span>');

			$.ajax({
				type: "POST",cache: false,url: "gears/gear_track_taxon_stop.php",
				data: "taxon_id=" + taxon_id,
				dataType: "json",
				success: function(json){
					if (json.succeeded) {
						$(".track_taxon").html('<b>You Have Stopped Watching This Plant</b>');
					}
					else {
						show_register_box(true, taxon_id);
					}
				}
			});

			return false;
		});	
		
	$("a[@class='my_garden_action']").click(function()
		{					
			var my_garden_action = $(this).attr("rel");			

			$.ajax({
				type: "POST",cache: false,url: "gears/gear_taxon_my_garden.php",
				data: "taxon_id=" + taxon_id + "&action=" + my_garden_action,
				dataType: "json",
				success: function(json){
					if (json.succeeded) {
						switch(my_garden_action) {
							case "add":
								$(".my_garden_action_panel").html('<a href="' + garden_script + '-' + user_id + '"><img src="images/add-to-my-garden-success.gif" border="0"></a>')
								break;
							case "remove":
								$(".my_garden_action_panel").html('<a href="' + garden_script + '-' + user_id + '"><img src="images/remove-from-my-garden-success.gif" border="0"></a>')
								break;								
						}
					}
					else {
						show_register_box(true, taxon_id);
					}
				}
			});

			return false;
		});		

	$("input[@name='cancel_button']").click(reset_elements);	

	$("form#no_submit").submit(function(){return false;});
}


function save_single_numeric_edit() {

	set_busy($(this), "Saving ");

	$.ajax({
		type: "POST",cache: false,url: "gears/gear_save_single_numeric_edit.php",
		data: "taxon_id=" + taxon_id + "&user_id=" + user_id + "&" + cp.find("form").serialize(),
		dataType: "json",
		success: function(json){
			if (json.succeeded) {
				cp.find("ul[@class='property_list']").html('<li><span class="property_value">' + json.property_value + '</span></li>');
				cp.find("input[@name='property_value_id']").attr({value:json.property_value_id});
				cp.find(".results").append(json.message);
				cp.find("strong").addClass("property_name_on");
				feedback(cp.find(".feedback"), 'Saved');
				reset_elements();
			}
			else {
				reset_elements();
				show_register_box(true, taxon_id);
			}
		}
	});
}

function save_multiple_numeric_edit() {

	set_busy($(this), "Saving ");

	var updated_content = '';

	$.ajax({
		type: "POST",cache: false,url: "gears/gear_save_multiple_numeric_edit.php",
		data: "taxon_id=" + taxon_id + "&user_id=" + user_id + "&" + cp.find("form").serialize(),
		dataType: "json",
		success: function(json){
			if (json.succeeded) {

				cp.find("[@class*='property_list']").empty();
				cp.find("input[@name*='number_of_selected_values']").remove();

				for(i=1;i<=json.updated_values_cnt;i++) {
					updated_content += '<li><span class="property_value">' + eval('json.property_value'+ i) + '</span></li>';
					updated_content += '<input type="hidden" name="property_value_id' + i + '" value="' + eval('json.property_value_id'+ i) + '">';
				}

				updated_content += '<input type="hidden" name="number_of_selected_values" value="' + json.updated_values_cnt + '">';
				if (json.updated_values_cnt > 0){
					cp.find("strong").attr("class", "property_name_on");
				}	
				else {
					cp.find("strong").attr("class", "property_name");
				}	

				cp.find("[@class*='property_list']").html(updated_content);

				feedback(cp.find(".feedback"),'Saved');
				reset_elements();

			}
			else {
				reset_elements();
				show_register_box(true, taxon_id);				
			}
		}
	});
}

function text_property_edit_init() {
	reset_elements();
	var this_element = $(this);
	property_on($(this).parent().parent().parent().parent());

	var info_arr = this_element.attr("id").split("_");

	hide(cp.find("span[@class='actions']"));
	hide(cp.find("a[@rel='multiple_text_property_add']"));
	hide(cp.find("span[@name='property_value" + info_arr[1] + "']"));

	cp.find("span[@name='property_value" + info_arr[1] + "']").after('<form class="work_area" id="no_submit" name="edit_multiple_text"><input type="text" name="edited_text" value="' + cp.find("span[@name='property_value" + info_arr[1] + "']").text() + '"><input type="button" name="save_edit_button" class="app_button" value="Save"> <input type="button" name="cancel_edit_button" class="app_button" value="Cancel"></form>');
	cp.find("form").submit(function(){return false;});

	cp.find("input[@name='cancel_edit_button']").click(function(){
		cp.find("form[@name='edit_multiple_text']").remove();
		reset_elements();
	});
	cp.find("input[@name='save_edit_button']").click(function(){

		if (!validate_text(cp.find("input[@name='edited_text']").val())) {return false;}

		set_busy($(this), "Saving ");

		$.ajax({
			type: "POST",cache: false,url: "gears/gear_save_edit_text_property.php",
			data: "taxon_id=" + taxon_id + "&hash_text=" + info_arr[1] + "&" + cp.serialize() + "&" + cp.find("form[@name='edit_multiple_text']").serialize(),
			dataType: "json",
			success: function(json){				
				if (json.succeeded) {
					cp.find("span[@name='property_value" + info_arr[1] + "']").text(cp.find("input[@name='edited_text']").val());
					cp.find("span[@name='property_value" + info_arr[1] + "']").attr("name","property_value"+json.hashed);
					cp.find("a[@id='" + info_arr[0] + "_" + info_arr[1] + "']").attr("id",info_arr[0]+"_"+json.hashed);
					reset_elements();
				}
				else {					
					reset_elements();
					show_register_box(true, taxon_id);
				}
			}
		});
	});

	return false;
}

function text_property_delete_init() {

	var parent = $(this).parent().parent();
	var cp = parent.parent().parent();
	var info_arr = $(this).attr("id").split('_');			

	if(confirm("Are you sure you want to DELETE this?")) {
		$.ajax({
			type: "POST",cache: false,url: "gears/gear_delete_text_property.php",
			data: "taxon_id=" + taxon_id + "&property_id=" + info_arr[0] + "&hash_text=" + info_arr[1],
			dataType: "json",
			success: function(json){
				if (json.succeeded) {				
					if (json.property_value_cnt > 0) {
						cp.find("strong").attr("class", "property_name_on");
					}	
					else {
						cp.find("strong").attr("class", "property_name");
					}	

					feedback(cp.find(".feedback"),'Saved');
					parent.remove();
				}
				else {
					show_register_box(true, taxon_id);
					reset_elements();
				}
			}
		});
	}	

	return false;
}

function save_text_property(obj) {

	if (!validate_text(cp.find("input[@name='property_value_text']").val())) {return false;}

	set_busy(cp.find("input[@name='save_text_property_button']"), "Saving ");

	$.ajax({type: "POST",cache: false,url: "gears/gear_save_add_text_property.php",
		data: "taxon_id=" + taxon_id + "&" + cp.serialize(),
		dataType: "json",
		success: function(json){
			if (json.succeeded) {
				cp.find("ul[@class='property_list']").append('<li><span name="property_value' + json.hashed + '">' + json.property_value_text + '</span> <span class="actions"><a href="#" class="edit_text_link" id="' + json.property_id + '_' + json.hashed + '" rel="multiple_text_property_edit">edit</a> | <a href="#" class="delete_text_link" id="' + json.property_id + '_' + json.hashed + '" rel="multiple_text_property_delete">delete</a></span></li>');
				cp.find("a[@class='edit_text_link']").click(text_property_edit_init);
				cp.find("a[@class='delete_text_link']").click(text_property_delete_init);
				cp.find("input[@name='save_text_property_button']").val("Save");
				cp.find("strong").attr("class", "property_name_on");
				feedback(cp.find(".feedback"),'Saved');
				reset_elements();
			}
			else {
				cp.find("input[@name='save_text_property_button']").val("Save");
				reset_elements();
				show_register_box(true, taxon_id);				
			}
		}
	});
}

function save_to_list() {

	if ($("input[@name='new_list_flag']").val() == 1) {
		if ($("input[@name='list_name']").val().length == 0) {
			alert('List name cannot be blank');
			$("input[@name='list_name']").focus();		
			return;
		}
	}
	
	set_busy(cp.find("input[@name='save_to_list']"), "Saving ");

	$.ajax({type: "POST",cache: false,url: "gears/gear_list_save_to.php",
		data: "taxon_id=" + taxon_id + "&" + cp.serialize(),
		dataType: "json",
		success: function(json){
			if (json.succeeded) {
				feedback(cp.find(".feedback"),'Saved');
				reset_elements();
				hideBox($("div.box_div"));
			}
			else {
				alert(json.message);
				//$('div#overlay').show();
			}
		}
	});
	
}

function list_create_new() {
	hide($("div[@name='list_select_box']"));
	show($("div[@name='list_input_box']"));
	$("input[@name='new_list_flag']").val(1);
	$("input[@name='save_to_list']").val('Create List and Save Plant');
	return false;	
}

function handle_image_nav(image_in_bounds, new_image_position, image_at_bounds, button_1, button_2) {
	if (image_in_bounds) {image_pos = new_image_position;}
	$("img[@name='taxon-image']").attr({src:bucket_taxon_images_path_medium + image_array[image_pos]});
	$(".taxon_image_info").html('Image added by<br/><a href="' + statistics_script + image_user_id_array[image_pos] + '">' + image_username_array[image_pos] + '</a> <acronym title="' + acronym_text + '">(' + image_user_pop_edits_array[image_pos] + ')</acronym>');
	$(".taxon_image_info_copy").html($(".taxon_image_info").html());
	$(".taxon_image_copyright_member").html('<a href="' + statistics_script + image_user_id_array[image_pos] + '">' + image_username_array[image_pos] + '</a> <acronym title="' + acronym_text + '">(' + image_user_pop_edits_array[image_pos] + ')</acronym>');
	$(".taxon_image_member_contact").html('<a href="/privmsg.php?mode=post&u=' + image_user_id_array[image_pos] + '">contact</a>');				
	if (lightbox_flag = true) {$("img[@id='taxon-image-large']").attr({src:bucket_taxon_images_path_large + image_array[image_pos]});}
	if (image_at_bounds) {			
		$("input[@name='" + button_1 + "']").attr("disabled","disabled");
		$("input[@name='" + button_2 + "']").attr("disabled","");					
	}
	else {
		$("input[@name='" + button_2 + "']").attr("disabled","");					
	}				
	$("span[@name='current-image-number']").text(image_pos+1);
	handle_image_like_cell();
	
}

function handle_image_like_cell() {
	if (image_belongs_to_array[image_pos] == 1) {

		if (liked_array.toString().indexOf(image_image_id_array[image_pos]) !== -1) {
			$(".image_like_cell").html('<b>You like this image</b><br/>(' + liked_array_image_liked_count[liked_array.toString().indexOf(image_image_id_array[image_pos])] + ' ' + (liked_array_image_liked_count.toString().indexOf(image_image_id_array[image_pos]) != 1 ? 'people like' : 'person likes') + ' this image)');
		}
		else if (image_liked_array[image_pos] == 1) {
			$(".image_like_cell").html('<b>You like this image</b><br/><a href="' + image_likes_script + image_image_id_array[image_pos] + '">' + image_liked_count_array[image_pos] + '</a> ' + (image_liked_count_array[image_pos] != 1 ? 'people like' : 'person likes') + ' this image');
		}
		else {
			$(".image_like_cell").html('<a href="#" class="image_like" rel="' + image_image_id_array[image_pos] + '">I like this image</a><br/><a href="' + image_likes_script + image_image_id_array[image_pos] + '">' +  image_liked_count_array[image_pos] + '</a> ' + (image_liked_count_array[image_pos] != 1 ? 'people like' : 'person likes') + ' this image');
			$(".image_like").click(image_like);
		}
		
		$(".image_like_cell").css('padding-right','10px');
	}
	else if (image_liked_count_array[image_pos] > 0) {					
		$(".image_like_cell").html('<a href="' + image_likes_script + image_image_id_array[image_pos] + '">' + image_liked_count_array[image_pos] + '</a> ' + (image_liked_count_array[image_pos] != 1 ? 'people like' : 'person likes') + ' your image');
		$(".image_like_cell").css('padding-right','10px');
	}
	else {					
		$(".image_like_cell").html('');
		$(".image_like_cell").css('padding-right','0px');
	}
}

function setup_opinion_elements(state) {
switch(state) {
// Adding an opinion
case const_state_add_opinion:
$(".opinion_date_added").css('display','none');
$(".opinion_date_edited").css('display','none');
$(".opinion_textarea").css('display','block');
$(".opinion_textarea").val(convert_br_to_linefeed($("#opinion_text").html()));
$("#save_opinion_text_button").css('display','inline');
$("#cancel_opinion_text_button").css('display','inline');
$("#opinion_text").css('display','none');
$(".edit_opinion_text_button").css('display','none');
break;
// Show opinion
case const_state_show_opinion:
$(".opinion_date_added").css('display','inline');
$(".opinion_date_edited").css('display','inline');
$(".opinion_textarea").css('display','none');
$("#save_opinion_text_button").css('display','none');
$("#cancel_opinion_text_button").css('display','none');
$("#opinion_text").css('display','block');
$(".edit_opinion_text_button").css('display','inline');
break;						
}
}

function property_panel_init(obj) {
	reset_elements();
	property_on(obj);
	cp.find(".results").empty();
	hide($("a[@class='edit_link']"));
}

function property_on(obj) {
	cp = obj;
	cp.attr('class','property_on');
}

function reset_elements() {
	hide_all();
	for(var i=elements_off.length-1;i>=0;i--) {elements_off[i].css('display','inline');elements_off.pop();}
	$("form[@name='edit_multiple_text']").remove();
	clearInterval(anim_interval);
	$(".app_button").attr("disabled","");
	$(".edit_link").css("display","inline");
	$(".property_on").attr('class','property_off');
}

function validate_text(val) {

	var form_errors = false;
	var form_error_string = '';

	if(val == '') {
		form_errors = true;
		form_error_string += "- You must enter a value\n";
	}
	if (form_errors) {
		alert(form_error_string);
		return false;
	}

	return true;
}

jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
};