var last_file_to_show = -1;
var next_file_to_show = 0;

$.ajaxSetup({ cache: false });

$(document).ready(function(){
	if($("#ItemVideoStatus").length > 0)
	{
		toggle_video_form_fields();
		$("#ItemVideoStatus").change(function(){
			toggle_video_form_fields();
		});
	}

	placeholdize();
	
	if($('.chars_remaining').length > 0)
	{
		$('.chars_remaining').parents("tr").find("textarea").keyup(function(){
			limit_field_length(this, 512);
		}).blur(function(){
			limit_field_length(this, 512);
		}).focus(function(){
			limit_field_length(this, 512);
		});
	}
	
	if($('.file').length > 0)
	{
		$('.grid_cell').mouseenter(function(){
			last_file_to_show = next_file_to_show;
			next_file_to_show = $(this).attr("id");
			if(next_file_to_show != last_file_to_show)
			{
				if($('#file_info_'+last_file_to_show).length > 0)
				{
					$('#file_info_'+last_file_to_show).fadeOut("normal", function(){
						$('#file_info_'+next_file_to_show).fadeIn("normal");
					});
				} else {
					$('#file_info_'+next_file_to_show).fadeIn("normal");
				}
			}
		});
		$('.media').mouseleave(function(){
			$('.file').fadeOut("fast");
			next_file_to_show = 0;
		});
	}
	
	if($("#ItemDatePublishedDate").length > 0)
	{
		$('#ItemDatePublishedDate').datepicker({
			"firstDay":1,
			"dateFormat":"yy-mm-dd"
		});
	}
	
	if($('#slideshow').length > 0)
	{
		$('#slideshow').crossSlide({
			sleep: 5,
			fade: 1
		}, images );
	}
	
	if($('.add_files').length > 0)
	{
		$('.add_files').click(function(){
			toggle_file_browser(true, true, "images", $(this).attr("id").substr(4));
		});
	}

	if($('.add_file').length > 0)
	{
		$('.add_file').click(function(){
			toggle_file_browser(true, false, "images", $(this).attr("id").substr(4));
		});
	}	

	if($('[name="itemFile"]').length > 0)
	{
		$('[name="itemFile"]').each(function(i){
			if($('#file_list_'+target_list, parent.document).find('#file'+$(this).val()).length > 0)
			{
				$(this).attr("checked", "checked");
			}
		});
		$('[name="itemFile"]').click(function(){
			if($(this).attr("checked"))
			{
				if($(this).attr("type") == "radio")
				{
					$('#file_list_'+target_list, parent.document).find('.itemFile').remove();
				}
				$(this).hide().after('<img src="/img/ajax-loader.gif" id="loader_'+$(this).val()+'" />');
				$.get("/files/name/"+$(this).val(), {}, function(data){
					$('#file_list_'+target_list, parent.document).append('<div class="file_preview itemFile" id="file'+data.MediaFile.id+'"><img src="/files/view/'+data.MediaFile.id+'/thumb" /><br />'+data.MediaFile.title+' <a href="#" class="delete_parent" title="Datei entfernen"><img src="/img/delete.png" alt="Datei entfernen" /></a><input type="hidden" name="data[Files]['+target_list+'][]" value="'+data.MediaFile.id+'" /></div>');
					$('#loader_'+data.MediaFile.id).remove();
					$('input[value="'+data.MediaFile.id+'"]').show();
				}, "json");
			} else {
				$('#file_list_'+target_list, parent.document).find('#file'+$(this).val()).remove();
			}
		});
	}


	if($('#add_category').length > 0)
	{
		$('#add_category').click(function(){
			if($('#ItemCategories').val() != "" && $('#category'+$('#ItemCategories').val()).length == 0)
			{
				$('#categories').append('<div class="category" id="category'+$('#ItemCategories').val()+'">'+$('#ItemCategories option[value="'+$('#ItemCategories').val()+'"]').text()+' <a href="#" class="delete_parent" title="Kategorie entfernen"><img src="/img/delete.png" alt="Kategorie entfernen" /></a><input type="hidden" name="data[Categories][]" value="'+$('#ItemCategories').val()+'" /></div>');
			}
		});
	}
	
	$('.delete_parent').live("click", function(){
		$(this).parent("div").fadeOut(function(){
			$(this).remove();
		});
	});
	
	
	$('a[href*=mailto]').each(function(){
		$(this).attr("href", str_replace(" [at] ", "@", str_replace(" [dot] ", ".", $(this).attr("href"))));
	});
	
	if($('#fileFilter').length > 0)
	{
		$('#fileFilter').change(function(){
			window.location = "/admin/files/popup/" + $(this).val() + "/" + $('#allow_multiple_selections').val() + "/" + target_list;
		});
	}
	
	if($('#url_title_src').length > 0 && $('#url_title_target').length > 0 && $('#url_title_src').val() == "")
	{
		$('#url_title_src').change(function(){
			$.get("/admin/items/url_title/", {'basic_title':$(this).val()}, function(data){
				$('#url_title_target').val(data);
			});
		});
	}
	
	if($('#pick_video').length > 0)
	{
		$('#pick_video').click(function(){
			toggle_video_selector(true);
		});
	}
	
	if($('#remove_video').length > 0)
	{
		$('#remove_video').click(function(){
			$('#ItemVideoPathPreview').val("");
		});
	}
	
	if($('.video_from_ftp').length > 0)
	{
		$('.video_from_ftp').click(function(){
			$('#ItemVideoPathPreview', parent.document).val($(this).attr("id"));
			top.toggle_video_selector(false);
		});
	}
	
	if($('.preview_video_toggle').length > 0)
	{
		$('.preview_video_toggle').click(function(){
			toggle_video_lightbox(true, $(this).attr("id").substr(6));
		});
	}
	
});


function placeholdize()
{
	if($('input[placeholder]').length > 0 || $('textarea[placeholder]').length > 0)
	{
		$('input[placeholder], textarea[placeholder]').placeHoldize();
	}
}


function toggle_video_lightbox(show, id)
{
	if(show == true)
	{
		$('body').append('<div id="overlay"></div>');
		$('#overlay').height($('body').height()+"px").click(function(){toggle_video_lightbox(false);});
		$('body').append('<div id="lightbox"></div>');
		$('body').append('<div id="close_button"></div>');
		$('#lightbox').css("left", ($('body').width() - $('#lightbox').outerWidth()) / 2);
		$('#close_button').css("left", (($('body').width() - $('#lightbox').outerWidth()) / 2) - 15).click(function(){
			toggle_video_lightbox(false, null);
		});
		$.post("/items/video", {"id" : id}, function(data){
			$('#lightbox').append(data);
			placeholdize();
			$('#player_form input[type="button"]').click(function(){
				submit_video_contact_form(id);
			});
		});
	} else {
		$('#close_button').remove();
		$('#overlay').remove();
		$('#lightbox').remove();
	}
}


function submit_video_contact_form(id)
{
	if(video_form_is_valid('#player_form'))
	{
		var name = $('#name').val();
		var firma = $('#firma').val();
		var telefon = $('#telefon').val();
		var email = $('#email').val();

		$('#player_form').empty().append('<div id="loading_indicator"></div>');
		if($('#player_form').hasClass("notify"))
		{
			$.post("/items/video_request/", {"id" : id, "name" : name, "firma" : firma, "telefon" : telefon, "email" : email}, function(data){
				if(!$('#player_form').hasClass("provide_download_link"))
				{
					$('#player_form').empty().append(data);
				}
			});
		}
		if($('#player_form').hasClass("provide_download_link"))
		{
			$.get('/items/video_link/', {"id" : id}, function(data){
				$('#player_form').empty().append(data);
			});
		}
	}
}


function video_form_is_valid(identifier)
{
	var errors = 0;
	var validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
	$(identifier + " input:text").each(function(i, e){
		if($(e).hasClass("placeholder-visible") || (!$(e).hasClass("placeholder-visible") && empty($(e).val())) || ($(e).attr("id") == "email" && $(e).val().search(validRegExp) == -1))
		{
			$(e).addClass("error");
			errors++;
		} else if($(e).hasClass("error")) {
			$(e).removeClass("error");
		}
	});
	return (errors == 0);
}


function toggle_video_selector(show)
{
	if(show == true)
	{
		$('body').append('<div id="overlay"></div>');
		$('#overlay').height($('body').height()+"px").click(function(){toggle_file_browser(false);});
		$('body').append('<iframe id="file_browser" src="/admin/files/videos" /><div id="close_hint">zum Schließen in den ausgegrauten Bereich klicken</div>');
	} else {
		$('#overlay').remove();
		$('#file_browser').remove();
		$('#close_hint').remove();
	}
}


function toggle_video_form_fields()
{
	if($("#ItemVideoStatus").val() > 0)
	{
		$("#ItemVideoStatus").parents("ul.form").find("li.reveal").fadeIn();
	} else {
		$("#ItemVideoStatus").parents("ul.form").find("li.reveal").fadeOut();
	}
}


function limit_field_length(field, length)
{
	$(field).parents("tr").find(".chars_remaining .count").text(length - $(field).val().length);
	$(field).val($(field).val().substr(0, 512));
}


function toggle_file_browser(show, allow_multiple_selections, filetype, target_list)
{
	if(show == true)
	{
		$('body').append('<div id="overlay"></div>');
		$('#overlay').height($('body').height()+"px").click(function(){toggle_file_browser(false, allow_multiple_selections);});
		$('body').append('<iframe id="file_browser" src="/admin/files/popup/'+filetype+'/'+(allow_multiple_selections ? 'multi/' : 'single/')+'/'+target_list+'" /><div id="close_hint">zum Schließen in den ausgegrauten Bereich klicken</div>');
	} else {
		$('#overlay').remove();
		$('#file_browser').remove();
		$('#close_hint').remove();
	}
}


