////////////////////////////////////////////////////////////////////////////////
///// DYNAMIC SPECIES DROPDOWNS ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

function updateSpeciesSelect(){

  	var featuredSpecies = [];
  	
  	var idCollection =  jQuery('input[name^="species_id"]');
	var nameCollection = jQuery('input[name^="species_name"]');
	
	jQuery(nameCollection).each(function(index){
		
		if (Number(idCollection[index].value) > 0){
		
			var species = new Object;
			species.id = idCollection[index].value;
			species.name = jQuery(this).val();
			featuredSpecies.push(species);
			
		}
  		
 	});
 	
 	var options = '<option value="nan">&nbsp;</option>';
 	
 	for (var i = 0; i < featuredSpecies.length; i++) {
 	
 		options += '<option value="' + featuredSpecies[i].id + '">' + featuredSpecies[i].name + '</option>';
 		
 	}
 	
 	jQuery('select[name^="image_species"]').each(function(){
 		
 		var status = jQuery(this).val();	
 		jQuery(this).html(options);
 		jQuery(this).val(status);
 		
 	});

}




jQuery(document).ready(function(){
  
  ////////////////////////////////////////////////////////////////////////////////
  ///// ADDITIONAL BOXES /////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////
  
  function processCopy(object){
    
    var next;
    
    // Deal with NUMBER elements
    jQuery(object).find('.number').each(function(index){
      var current = parseInt(jQuery(this).html());
      next = current + 1;
      jQuery(this).html(next);
    });
    
    // Deal with SELECT elements
    jQuery(object).find(':input').each(function(index){
      jQuery(this).val('');
    });
    
    jQuery(object).find('.as').each(function(index){
    	var parts = jQuery(this).attr('id').split('_');
    	var startOfId = parts[0] + '_' + parts[1] + '_';
    	jQuery(this).attr('id', '' + startOfId + next + '');
    });
    
    jQuery(object).find("input:file").each(function(index){
       var parts = jQuery(this).attr('name').split('_');
       var number = Number(parts[2]) + 1;
       jQuery(this).attr('name', parts[0] + '_' + parts[1] + '_' + number);
    });
    
    // Deal with TEXT elements
    jQuery(object).find(':text').each(function(index){
      jQuery(this).removeAttr('readonly');
    });
    
    // Deal with IMAGE elements
    jQuery(object).find('img').each(function(index){
      jQuery(this).remove();
    });
    
    // Deal with TITLE elements
    jQuery(object).find('.title').each(function(index){
      jQuery(this).html('<em>Click to expand</em>');
    });
    
    return object;
    
  }
  
  // Append add more icons to containers with the correct class
  jQuery('.additionals').append('<div class="addmore">+</div>');
  
  jQuery('.addmore').live('click', function(){
    
    var lastElement = jQuery(this).prev('.additional');
    var copyElement = jQuery(lastElement).clone(true);
    
    copyElement = processCopy(copyElement);
    
    jQuery(lastElement).after(copyElement);
    
  });
  
  
  ////////////////////////////////////////////////////////////////////////////////
  ///// DATE PICKER //////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////
  
  jQuery('.datepicker').live('click', function(){
    
    jQuery(this).datepicker({
      altFormat: '@',
      dateFormat: 'dd/mm/yy',
      showOn:'focus'
    }).focus();
    
  });
  
  
  
  
  ////////////////////////////////////////////////////////////////////////////////
  ///// AUTHORS //////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////
  
  jQuery('.js_authors').live('focus', function(){
  	
  	jQuery(this).autosuggest("../wp-content/plugins/britishbirds/ajax/authors.php", {
    
	    minChars: 3, 
	    matchCase: false,
	    keyDelay: 200,
	    selectedItemProp: "name", 
	    selectedValuesProp: "value",
	    searchObjProps: "name",
	    startText: "", 
	    selectionLimit: 1,
	    start: function(){},
	    selectionRemoved: function(elem){
	      elem.remove();
	    }
	    
	  });
  	
  });
  
  
  
  
  ////////////////////////////////////////////////////////////////////////////////
  ///// SPECIES //////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////
  
  jQuery('.js_species').live('focus', function(){
	  
	  jQuery(this).autosuggest("/wp-content/plugins/britishbirds/ajax/species.php", {
	    
	    minChars: 3, 
	    matchCase: false,
	    keyDelay: 200,
	    selectedItemProp: "name", 
	    selectedValuesProp: "value",
	    searchObjProps: "name",
	    startText: "", 
	    selectionLimit: 1,
	    start: function(){},
	    selectionRemoved: function(elem){
	      elem.remove();
	    },
	    selectionAdded: function(elem){
	    	updateSpeciesSelect(); 
	    }
	    
	  });

	});
  
  jQuery('.js_species').change(function(){
  	
  	updateSpeciesSelect();
  	
  });
  
  
  
  
  
  
  
  
  
  
  ////////////////////////////////////////////////////////////////////////////////
  ///// PHOTOGRAPHER //////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////
  
  jQuery('.js_photographer').live('focus', function(){
  	
	  jQuery(this).autosuggest("../wp-content/plugins/britishbirds/ajax/photographers.php", {
	    
	    minChars: 3, 
	    matchCase: false,
	    keyDelay: 200,
	    selectedItemProp: "name", 
	    selectedValuesProp: "value",
	    searchObjProps: "name",
	    startText: "", 
	    selectionLimit: 1,
	    start: function(){},
	    selectionRemoved: function(elem){
	      elem.remove();
	    },
	    selectionAdded: function(elem){
	    	updateSpeciesSelect(); 
	    }
	    
	  });
	  
	});
  
  
  
  
  
  
  ////////////////////////////////////////////////////////////////////////////////
  ///// EXPANDABLE SECTIONS //////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////
  
  jQuery(".expanded").hide();
  
  //Expandable
  jQuery(".expandable .title").live('click', function(){
    jQuery(this).siblings(".expanded").slideToggle('slow');
    jQuery(this).parent().toggleClass('active');
    return false;
  });





	////////////////////////////////////////////////////////////////////////////////
	///// DELETE CONFIRMATION //////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////
  
  	jQuery('.delete_link').click(function(){
  		
  		// Return the value of a delete confirm 
	  	return confirm("Are you sure you wish to delete this entry?");
  		
  	});
  
  
  updateSpeciesSelect();
	
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///// LIGHTBOX JS /////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  
  // Set body height
  var bodyHeight = jQuery('body').height();
  
  jQuery('a.lightbox').click(function(e){
  	
  	// Cancel the link behavior
    e.preventDefault();
    
    // Get the A tag
    var href = jQuery(this).attr('href');
    var id = jQuery('#boxes');
    
    // Get the window height and width
    var winH = jQuery(window).height() - 100;
    var winW = jQuery(window).width();
    
    //Populate boxes
    jQuery.ajax({
	   url: "/wp-content/plugins/britishbirds/ajax/image.php",
	   data: {id : href, height : winH, width : winW},
	   dataType: "json",
	   success: function(data){
	     jQuery('#image_holder').append(data.image);
	     jQuery('#caption').html(data.caption);
	     jQuery('#boxes').css({width: data.width});
	     jQuery('#boxes').css('left', winW/2-$('#boxes').width()/2);
	   }
	});
    
    // Get the height of the modal
    var modalH = jQuery(id).height();
    
    // Define value of setTop for winH < modalH
    if ( winH < modalH ) {
    	var setTop = jQuery(window).scrollTop() + 20;
    }
    
    // Define value of setTop for winH > modalH
    if ( winH > modalH ) {
    	var setTop = (winH/2-modalH/2) + jQuery(window).scrollTop();
    }     
    
    var setTop = jQuery(window).scrollTop() + 15;
    
    // Set the popup window to center
    jQuery(id).css('top', (setTop + 'px'));
    jQuery(id).css('left', winW/2-jQuery(id).width()/2);
    
    // Transition effect
    jQuery(id).fadeIn(500);
    
    // Get the screen height and width
    var maskHeight = jQuery(document).height() + 20;
    var maskWidth = jQuery(window).width();
    
    // Set height and width to mask to fill up the whole screen
    jQuery('#mask').css({'width':maskWidth,'height':maskHeight,opacity: 0.9});
    
    // transition effect     
    jQuery('#mask').fadeIn(300);
     
	// If close button is clicked
    jQuery('.window .exit').live( 'click', function (e) {
        
        // Cancel the link behavior
        e.preventDefault();
        //Clear img
        jQuery('#image_holder').html('');
        jQuery('#image_holder').html('<a href="#" class="exit"></a>');
        //Fade out mask and lightbox
        jQuery('#mask, #boxes').fadeOut(300);
        
    });     
     
    // If mask is clicked
    jQuery('#mask').live( 'click', function (e) {
        //Clear img
        jQuery('#img_holder').closest('img').remove();
        //Fade out
        jQuery(this).fadeOut(300);
        jQuery('#boxes').fadeOut(300);
    });
  	
  });
	  
});

