$(document).ready(function(){
	
	
	$('a.reader_list_trigger').click(function()
	{
		$('#readers').slideDown('fast').removeClass('conceal');
		$(this).hide();
		return false;
	});
	
	$('a.reader_list_close').click(function()
	{
		$('#readers').slideUp('fast');
		$('a.reader_list_trigger').show();
	});
	
	 $('textarea.translate').change(function() {
		
		$(this).removeClass('good');
		$(this).removeClass('warning');
		
	 	var label = 'label_' + $(this).attr('name');
		var label_content = $('td#'+label).html();
		
		var label_length = label_content.length;
		var this_length = $(this).attr('value').length;
		
		if (this_length > (Math.ceil(label_length*1.4)))
		{
			$('#inline_save').remove();
			$('#warn_'+label).remove();
			$(this).addClass('warning').after('<div id="warn_'+label+'" class="warning">Your translation is longer than the original, which may break the interface. <br /><br />Threshold for this string is <i>'+Math.ceil(label_length*1.4)+'</i> characters- translation has '+this_length+'</div>');
		}
		else
		{
			$('#inline_save').remove();
			$('#warn_'+label).remove();
			$(this).removeClass('warning');
			if (this_length != 0)
			{
				$(this).addClass('good').after('<div id="inline_save" class="good"><input name="submit" type="submit" class="submit" value="Save all now?" /></div>');	
			}
			else
			{
				$('#inline_save').remove();
				$(this).removeClass('good');
				$(this).removeClass('warning');
			}
		}
	});
	
	if ($('body').is('.region.rhha.index'))
	{
	
		{
		$('div.cg #slides').crossSlide({
		sleep: 2,
		fade: 2
		}, [
		{ src: '/assets/images/region/cg_main_rhha_1.jpg' },
		{ src: '/assets/images/region/cg_main_rhha_2.jpg' },
		{ src: '/assets/images/region/cg_main_rhha_3.jpg' },

		]);
			}

	}
	
	$('span.flag a').livequery('click', function() 
	{
		var href = $(this).attr('href');
		var span = $(this).parent('span');
		
		var dashboard = $(this).parents('div:eq(0)').hasClass('db');
		
		var parent_li = $(this).parents('li:eq(0)');
				
		span.html('<span id="zloader" style="position: absolute;left: 6px;top: 10px;"><img id="xzloader" src="/assets/images/loading_tiny.gif" /></span>');
				
		if (dashboard && $(this).is('.cancel'))
		{
			$.get(href, function(data) {
				parent_li.fadeOut('slow').remove();
				$("#zloader").remove();
			});
		}
		else
		{
			$(this).fadeOut('Fast').remove();

			$.get(href, function(data) {
				span.html(data);
				$("#zloader").remove();
			});
		}
		
		return false;
		
	});

	$("a#load_more").livequery('click', function() 
	{
		var href = $(this).attr('href');
		$('ul.items').after('<img style="margin-left: 570px" src="/assets/images/loading.gif" id="loader">');
		
		$('ul.items li.more').fadeOut('Fast').remove().after('<img src="/assets/images/loading.gif">');
		$.get(href, function(data) {
			$('ul.items').append(data);
			$("#loader").remove();
		});
		return false;
		
	});

	$('a.broadcast_read').click(function()
	{
		var href = $(this).attr('href');
		$.get(href, function(data) {
		});
		
		$(this).parents('li').fadeOut('Slow');
		return false;
	});
	
	$('input.resource_type_select').click(function()
	{
		var target = $(this).attr('id')+'_input';
		$('.res_active').fadeOut().removeClass('res_active');
		$('#'+target).addClass('res_active').fadeIn();
		
	});
	
    $('ul.sort, ul.filter').slideUp();
		
	$('.filter_trigger').click(function()
	{
		$(this).next('ul').not('.open').slideDown().addClass('open');
	});
	
$('ul.open').livequery(function(){ 
        $(this) 
            .hover(function() { 
            }, function() { 
				$(this).removeClass('open').slideUp('fast'); 
            }); 
    }); 
    
    $('ul.sort li a, ul.filter li a').click(function()
    {
    	var target = $(this).parents('ul').attr('id');
	
    	var text = $(this).html();
	
    	$('span.'+target).html(text);
    });
    
    
 var $container = $('body.region.facilities .sort_container');
    if ($container.length != 0)
    {
     
     $container.isotope({
        itemSelector : '.sort',
        getSortData : {
         
          category : function( $elem ) {
            return $elem.attr('data-category');
          },
         
          name : function ( $elem ) {
            return $elem.find('.name').text();
          }
        }
      });
      
      
      var $optionSets = $('#options .option-set'),
          $optionLinks = $optionSets.find('a');

      $optionLinks.click(function(){
        var $this = $(this);
        // don't proceed if already selected
        if ( $this.hasClass('selected') ) {
          return false;
        }
        var $optionSet = $this.parents('.option-set');
        $optionSet.find('.selected').removeClass('selected');
        $this.addClass('selected');
  
        // make option object dynamically, i.e. { filter: '.my-filter-class' }
        var options = {},
            key = $optionSet.attr('data-option-key'),
            value = $this.attr('data-option-value');
        // parse 'false' as false boolean
        value = value === 'false' ? false : value;
        options[ key ] = value;
        if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
          // changes in layout modes need extra logic
          changeLayoutMode( $this, options )
        } else {
          // otherwise, apply new options
          $container.isotope( options );
        }
        
        return false;
      });
    }
    
	$( ".sortable" ).sortable({
		placeholder: "ui-state-highlight",
		update : function () {
			order = $(this).sortable('serialize');
			region = $(this).attr('id');
			$.post("/en/admin_region_page/sort/"+region, { order: order},
			function(data) {
				alert("Data Loaded: " + data);
			});

		}
	});
	
	$('ul.dl').each(function()
	{
		$(this).children('li:odd').addClass('odd');
	});

	$('ul.items').each(function()
	{
		$(this).children('li:last').addClass('last');
	});
	
	$('a.container_close').click(function()
	{
		if ($(this).is('.closed'))
		{
			$(this).removeClass('closed').next('ul').slideDown('slow');
			$(this).parent('div').removeClass('closed');			
		}
		else
		{
			$(this).addClass('closed').next('ul').slideUp('fast');
			$(this).parent('div').addClass('closed');	
		}

	});

	//$( ".datepicker" ).datepicker();
	//http://trentrichardson.com/examples/timepicker/
	$('.datepicker').datetimepicker({
		stepMinute: 10
	});
	

	$('.tip').tipsy({gravity: 'e'});
	
	$('form select#country_id').livequery('change', function() 
	{
		var target = $(this).parent('fieldset').parent('form').attr('href');
		var country_id = $(this).val();
		$.post(target, { country_id: country_id },
		   function(data){
		     $('#region_label').after(data).remove();
		   });
	});
	
	$('form.account select#rhha_region_id').livequery('change', function() 
	{
		var target = $(this).parent('fieldset').parent('form').attr('href');
		var rhha_region_id = $(this).val();
		$.post(target, { rhha_region_id: rhha_region_id },
		   function(data){
		     $('#facility_label').after(data).remove();
		   });
	});
	
	// slightly different, since if it is flagged for a region we don't care about the facility
	$('form.post select#rhha_region_id').livequery('change', function() 
	{
		var target = $(this).parent('fieldset').parent('form').attr('href');
		var rhha_region_id = $(this).val();
		if (rhha_region_id == 0)
		{
			$('#facility_label').remove();
			return false;
		}
		$.post(target, { rhha_region_id: rhha_region_id },
		   function(data){
		     $('#facility_label').remove();
		     $('#rhha_region_id_label').after(data);
		   });
	});
	
	$("a.new_window, a.external").live('click', function(event) {
		
 		var newWindow = window.open($(this).attr('href'), '_blank');
  		if (newWindow) {
			if (newWindow.focus) {
				newWindow.focus();
				return false;
			}
  		} else {
			return true;
		}
	}); 

	$.preloadCssImages();

	$(".inline_label").labelify();

	$('.login_trigger').click(function()
	{
		if ($('#login').is('.hide'))
		{
			$('body').animate({
			    top: '0px'
			  }, 1000, "easeInOutBack", function() {
			    // Animation complete.
			  });
			  $('#login').removeClass("hide")
		}
		else
		{
			$('body').animate({
			    top: '-200px'
			 }, 1000, "easeInBack", function() {
			    // Animation complete.
			  });
			  $('#login').addClass("hide")
		}
		return false;
	});
	
	$('#auto_tab_controls li a').not('.link').click(function() {
		$('#auto_tabs .tab.open').removeClass('open').fadeOut();
		$('#auto_tab_controls .active').removeClass('active');
		
		var target = $(this).attr('href');
		$(target).addClass('open').fadeIn();
		
		$(this).addClass('active');
		
		return false;
	});

	$("table.tablesorter") 
	.tablesorter({widthFixed: true, widgets: ['zebra']});
	//.tablesorterPager({container: $("#pager")}); 
	
	$('input#update_password').click(function()
	{
		if ($('div#pw_fields').is('.open'))
		{
			$('div#pw_fields').slideUp().removeClass('open');
		}
		else
		{
			$('div#pw_fields').slideDown().removeClass('conceal').addClass('open');
		}
	});
	
	$(".editor_ref").colorbox({width:"500px", inline:true, href:"#editor_reference"});
	$(".map_ref").colorbox({width:"500px", inline:true, href:"#map_reference"});
	$("#cb_message_trigger").colorbox({width:"740px", inline:true, href:"#cb_message"});
	$(".colorbox_login").colorbox({width:"400px", inline:true});
	$(".colorbox").colorbox({width:"740px", inline:true});
	$(".lightbox").colorbox();
	$('a.show_message').each(function()
	{
		$(this).colorbox({width:"740px"});
	});
	
	$('a.reply').livequery(function(){ 
		$(this).colorbox({width:"740px"});
	});
	
	$('a.confirm, input.confirm, button.confirm').click(function() {
		return confirm("Are you sure? There is NO undo.");
	});
	
	$('a.comment_admin').click(function()
	{
		var target = $(this).attr('href');
		$('div'+target).removeClass('conceal');
		$(this).hide();
		return false;
	});

	$('#message').delay(4000).fadeOut(400);	
	
	
	$('.permissions.locked.updated').highlightFade({color:'#FF778B',speed:900});
	$('.permissions.open.updated').highlightFade({color:'#81E486',speed:900});
	
	
	
	$('#message').highlightFade({color:'#FDF88B',speed:900});

	$('a.comment_admin').click(function()
	{
		var target = $(this).attr('href');
		$('div'+target).removeClass('conceal');
		$(this).hide();
		return false;
	});
	
	
	$('div.edit_comment a.close').click(function()
	{
		$(this).parents('div.edit_comment').fadeOut();
		var href = $(this).parents('div.edit_comment').attr('id');
		
		$("a[href='#" + href + "']").fadeIn();
		return false;
	});

	
	
	
});
