$(document).ready(function(){
	
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///// SEARCH HISTORY JS ///////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  
  var registered = false;
  $('#saveSelected').click(function(e){
    
    e.preventDefault();
    
    if (!registered){
      
      $.ajax({
      url: "./ajax/email_check.php",
      async: false,
      success: function(data) {
        
        if (data == '0'){
          
          var id = $('#savesearch');
          var maskHeight = $(document).height();
          var maskWidth = $(window).width();
          $('#mask').css({'width':maskWidth,'height':maskHeight,opacity: 0.85});     
          $('#mask').fadeIn(300);
          var winH = $(window).height();
          var winW = $(window).width();
          $(id).css('top',  (winH/2-$(id).height()/2) + $(window).scrollTop() + 'px');
          $(id).css('left', winW/2-$(id).width()/2);
          $(id).fadeIn(500); 
         
          //return false;
          
        } else {
          
          $('#session-searches').append('<input type="hidden" name="save-session" value"TRUE">');
          $('#session-searches').submit();
          
        }
      
      }
     
     });
      
    }
    
  });
  if (window.location.hash=="#savesearch") {
    window.location.hash = null;
    $('#session-searches :checkbox:first').attr('checked', true);
    $('#saveSelected').trigger('click');
  }  
  
  $('#savesearchform').submit(function(e){
    e.preventDefault();
    var email = $(this).find('#fbemail').val();
    $.ajax({
      url: "./ajax/email_log.php",
      data: ({email : email}),
      async: false,
      success: function(data) {
        $('#mask, .window').fadeOut(300);
        $('#session-searches').append('<input type="hidden" name="save-session" value"TRUE">');
        registered = true;
        $('#session-searches').submit();
      }
    });
  });
  
  $('aside').each(function(){
  	if ($(this).html().length < 20){
  		$(this).css('display', 'none');
  	} 
  });
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///// INTERVENTION JS /////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  
  // Paragraph highlighting
  $('#keymessage a.parlink').click( function() {
  	var parLink = $(this).attr('id');
  	var parSplit = parLink.split('_');
  	// Remove 'p'
  	parSplit.shift();
  	
  	// Check if one of the paragraphs is already highlighted
  	if ($('.p_' + parSplit[0]).hasClass('highlighted')) {
  		
  		// If so, return to normal
  		$('.highlighted').removeClass('highlighted');
  		$('.parlink').css({
  			'border': 'none',
  			'text-decoration': 'underline',
  			'padding': '0'
  		});
  		
  	} else {
  		
  		// If not, apply styling to parlink and all relevant paragraphs
  		$('.parlink').css({
  			'border': 'none',
  			'text-decoration': 'underline',
  			'padding': '0'
  		});
  		$('.highlighted').removeClass('highlighted');
  		$(this).css({
  			'border': '1px solid #f5972c',
  			'text-decoration': 'none',
  			'padding': '0 2px'
  		});
  		$.each(parSplit, function(i, objValue) {
  			$('.p_' + objValue).addClass('highlighted');
  			$('.id_' + objValue).addClass('highlighted');
  		});
  		
  	}
	
	  return false;
	  
  });
  
  // Reference scrollto
  $('#evidence .ref').click( function() {
  	var parLink = $(this).attr('id');
  	var parSplit = parLink.split('_');
  	// Remove 'p'
  	parSplit.shift();
  		
	//Scroll to appropriate link and highlight it
	$('.id_' + parSplit + ' a').css('font-weight', 'bold');
	$('html,body').delay(300).animate({ scrollTop: $('.id_' + parSplit).offset().top }, { duration: 1000, easing: 'swing'});
	var that = $('.id_' + parSplit + ' a');
    setTimeout( function(){
      $(that).css('font-weight','normal');
    },5000);
    
	return false;
  });
  
  // Remove any empty paragraphs for keymessage
  $('p').filter(function() {
    return $.trim($(this).text()) === ''
  }).remove();
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///// SEARCH JS ///////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  
  //Allowing back buttons with tabs
  $('.interventions').hide();
  
  $('#outputOptions').submit(function(){
    if($('#outputOptions > fieldset.option2').find('input:checked').val() == '2'){
      var string = '';
      
      $('#results.active input:checkbox').each(function(index, value){
        string += $(value).val() + ',';
      });
      if($('.active').hasClass('summaries')){
        $(this).append('<input type="hidden" name="visible-summaries" value="' + string + '">');
      } else {
        $(this).append('<input type="hidden" name="visible-interventions" value="' + string + '">');
      }
    }
  });
  
  //Tabbing hash tag scripts
  if(window.location.hash=="#interventions") {
    $('.interventiontab').addClass('active');
    $('.summarytab').removeClass('active');
    $('.summaries').hide().removeClass('active');
    $('.interventions').show().addClass('active');
  } else {
    $('.summarytab').addClass('active');
    $('.interventiontab').removeClass('active');
    $('.interventions').hide().removeClass('active');
    $('.summaries').show().addClass('active');
  }
  
  //Show elements hidden for those w/o js
  $("#searchmore .title").show();
  
  //Highlight 'View supporting evidence' when intervention quick viewed
  $('#results.interventions .content a').css("font-weight", "normal");
  
  // Watch this search JS
  var watchRss = $('.watch').attr('href');
  // Replace href to enable modal
  $('.watch').attr({
    href: '#watchmodal'
  });
  //Add original href to modal link
  $('.modallink').attr({
    href: watchRss
  });
  //Hiding checkboxes in refine search
  var refinewrap = $(".refine .content div");
  var spans;
  for(var a = 0; a<refinewrap.length; a++) {
      spans = $(refinewrap[a]).find('span');
      for(var i = 0; i<spans.length; i++){
        if(i > 2){
          $(spans[i]).hide().addClass("hidden");
          $(spans[i]).siblings(".more").removeClass("hidden");
          $(spans[i]).parent().addClass("more_active");
        }
      }
    }
    
  $(".refine .more").toggle(
    function() {
      $(this).siblings(".hidden").show();
      $(this).text('Fewer').addClass('active');
    },
    function() {
      $(this).siblings(".hidden").hide();
      $(this).text('More').removeClass('active');
    }
  );
  
  //Hiding side bar
  $(".refine .hide").show().toggle(
    function() {
	  $(this).parent().removeClass('active');
      $('.summaries').addClass('large');
      $('.interventions').addClass('large');
      $(this).text('Show').addClass('active');
      return false;
    },
    function() {
	  $(this).parent().addClass('active');
      $('.summaries').removeClass('large');
      $('.interventions').removeClass('large');
      $(this).text('Hide').removeClass('active');
      return false;
    }
  );
  
  //Search active
  function searchFade() {
  	clearTimeout($.data(this, 'timer'));
  	$('#searchbox.notindex').removeClass("faded");
  	$.data(this, 'timer', setTimeout(function() {
      $('#searchbox.notindex').addClass("faded");
    }, 8000));
  }
  
  $('#searchbox.notindex').click(searchFade);
  $('#searchbox .title').click(searchFade);
  
  //Search tabs
  $('.interventiontab').click( function() {
  	$(this).addClass('active');
  	$('.summarytab').removeClass('active');
  	$('.summaries').fadeOut(200);
  	$('.interventions').delay(300).fadeIn(200).addClass('active');
  	location.hash = 'interventions';
  	return false;
  });
  $('.summarytab').click( function() {
  	$(this).addClass('active');
  	$('.interventiontab').removeClass('active');
  	$('.interventions').fadeOut(200);
  	$('.summaries').delay(300).fadeIn(200).addClass('active');
  	location.hash = 'summaries';
  	return false;
  });
  
  //Refine country script
  $('#country').live( "change", function() { 
  	var countryval = $(this).val();
  	var countrytext = $(this).find('option:selected').text();
  	$(this).parent().append('<span><input name="country_id[]" value="' + countryval + '" type="checkbox" checked="checked"/><label for="" title="' + countrytext + '">' + countrytext + '</label></span>');
  });
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///// GENERAL JS //////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  
  //Expandable sections
  $(".expanded").hide();
  
  function clickExpand() {
    $(this).siblings(".expanded").slideToggle('slow');
    $(this).parent().toggleClass('active');
    $(this).parent().siblings('.viewevidence').toggleClass('active');
    return false;
  };
  
  $(".expandable .title").click(clickExpand);
  //Select all for shpage
  $(".selectall").click(function() { 
  	  var checked_status = this.checked; 
      $(this).prev().prev().find("input[type='checkbox']").each(function() { 
      	this.checked = checked_status;
      }); 
  });
  
  //Shift click
  //Define function
  (function($) {
	$.fn.shiftClick = function() {
		var lastSelected;
		var checkBoxes = $(this);

		this.each(function() {
			$(this).click(function(ev) {
				if (ev.shiftKey) {
					var last = checkBoxes.index(lastSelected);
					var first = checkBoxes.index(this);

					var start = Math.min(first, last);
					var end = Math.max(first, last);

					var chk = lastSelected.checked;
					for (var i = start; i < end; i++) {
						checkBoxes[i].checked = chk;
					}
				} else {
					lastSelected = this;
				}
			})
		});
	  };
	})(jQuery);
  //Assign function
  $(function() {
	$('#shpage input[type=checkbox]').shiftClick();
  });
  $(function() {
	$('#results .content input[type=checkbox]').shiftClick();
  });
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///// HOMEPAGE JS /////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  
  //Homepage expandable copy changing
  $('#searchmore .title').toggle(
    function () {
        $(this).text('Hide options');
      },
      function () {
        $(this).text('More options');
      }
  );
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///// FAQ AND PUBLICATIONS JS /////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  
  //Synopses copy change
  $('.synopses .title').toggle(
    function () {
        $(this).text('Hide synopses');
      },
      function () {
          $(this).text('View synopses');
      }
  );
  
  //FAQ links
  $("#faq span").click( function() {
  	var myClass = $(this).attr('class');
  	$('#' + myClass).trigger('click');
  	$('html,body').delay(300).animate({ scrollTop: $('#' + myClass).offset().top }, { duration: 1000, easing: 'swing'});
  });
  
  //Code for opening syonopsis dropdown on publications page
  if (window.location.hash=="#synopsesopen") {
    $('.synopses .title').trigger('click');
    $('html,body').delay(300).animate({ scrollTop: $('.synopses .title').offset().top - '10' }, { duration: 1000, easing: 'swing'});
  	window.location.hash = '';
  }
  
  //Tabs on journal page
  $('.abouttab').click( function() {
  	$(this).addClass('active');
  	$('.issuestab').removeClass('active');
  	$('.issues').fadeOut(200);
  	$('.about').delay(300).fadeIn(200).addClass('active');
  	return false;
  });
  $('.issuestab').click( function() {
  	$(this).addClass('active');
  	$('.abouttab').removeClass('active');
  	$('.about').fadeOut(200);
  	$('.issues').delay(300).fadeIn(200).addClass('active');
  	return false;
  });
  //Assign issues as active on load
  $('.issuestab').addClass('active');
  $('.about').hide().removeClass('active');
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///// LIGHTBOX JS /////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  
  //Set body height
  var bodyHeight = $('body').height();
  
  //Replace hrefs to enable modals
  $("a[href='feedback.php']").attr({href: '#feedbackmodal',name: 'modal'});
  $("a[href='savesearch.php']").attr({href: '#savesearch',name: 'modal'});
  $("a[href='additionalevidence.php']").attr({href: '#additional',name: 'modal'});
  $("a[href='downloadreferencedetails.php']").attr({href: '#downloadreferencedetails',name: 'modal'});
  $("a[href='progress.php']").attr({href: '#progressmodal',name: 'modal'});
  $("a[href='whatisasynopsis.php']").attr({href: '#synopsismodal',name: 'modal'});
  $("a[href='tabshelp.php']").attr({href: '#tabshelp',name: 'modal'});
  
  //Select all the a tag with name equal to modal, and run fadein function
    $('a[name=modal]').click(function(e) {
        
        //Cancel the link behavior
        e.preventDefault();
        //Get the A tag
        var id = $(this).attr('href');
        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();
        //Get the height of the modal
        var modalH = $(id).height();
        //Define value of setTop for winH < modalH
        if ( winH < modalH ) {
        	var setTop = $(window).scrollTop() + 20;
        }
        //Define value of setTop for winH > modalH
        if ( winH > modalH ) {
        	var setTop = (winH/2-modalH/2) + $(window).scrollTop();
        }     
        //Set the popup window to center
        $(id).css('top', (setTop + 'px'));
        $(id).css('left', winW/2-$(id).width()/2);
        //transition effect
        $(id).fadeIn(500);
        //Get the screen height and width
        var maskHeight = $(document).height() + 20;
        var maskWidth = $(window).width();
        //Set height and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight,opacity: 0.85});
        //transition effect     
        $('#mask').fadeIn(300);
        //Change body height if necessary
        if ( maskHeight > bodyHeight ) {
        	$('body').css('min-height', maskHeight);
        }
    });
     
    //if close button is clicked
    $('.window .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();
        $('#mask, .window').fadeOut(300);
        $("body").css('min-height', '100%');
    });     
     
    //if mask is clicked
    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });
    
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///// ADVANCED SEARCH JS //////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  
  //Ajax Drop downs
  $(".js_drop").live( "change", function(evt) {
    var typ = $(this).attr('name');
    var opt = $(this).val();
    var parent = $(this);
    $.ajax({
      url: "./ajax/dropdowns.php",
      data: ({type : typ, option : opt}),
      async: false,
      success: function(data) {
        if(data.length > 50){
          $(parent).siblings().html(data);
          $(parent).siblings().slideDown(300);
        } else {
          $(parent).siblings().slideUp(300);
        }
      }
    });
  });
  
  $('select.narrow').hide();
  
  //Habitat
  var habitatset = $('.habitat.set').html();
  $('.habitat.set.notchanged:last select:first').live( "change", function(evt) {
  	$(this).parent().removeClass('notchanged');
  	
  	//Get number of current selects
  	var selectAmount = $(this).parent().parent().children('.habitat').length;
  	//Conditionally display AND
  	if ( (selectAmount % 3) == 0 ) {
     $(this).parent().parent().append('<span class="habitat set notchanged">' + habitatset + '</span');
    } else {
      $(this).parent().parent().append('<span class="and">OR</span><span class="habitat set notchanged new">' + habitatset + '</span');
    }
  });
  //Threat
  var threatset = $('.threat.set').html();
  $('.threat.set.notchanged:last select:first').live( "change", function(evt) {
  	$(this).parent().removeClass('notchanged');
  	
  	//Get number of current selects
  	var selectAmount = $(this).parent().parent().children('.threat').length;
  	//Conditionally display AND
  	if ( (selectAmount % 3) == 0 ) {
     $(this).parent().parent().append('<span class="threat set notchanged">' + threatset + '</span');
    } else {
      $(this).parent().parent().append('<span class="and">OR</span><span class="threat set notchanged new">' + threatset + '</span');
    }
  });
  //Action
  var actionset = $('.action.set').html();
  $('.action.set.notchanged:last select:first').live( "change", function(evt) {
  	$(this).parent().removeClass('notchanged');
  	
  	//Get number of current selects
  	var selectAmount = $(this).parent().parent().children('.action').length;
  	//Conditionally display AND
  	if ( (selectAmount % 3) == 0 ) {
     $(this).parent().parent().append('<span class="action set notchanged">' + actionset + '</span');
    } else {
      $(this).parent().parent().append('<span class="and">OR</span><span class="action set notchanged new">' + actionset + '</span');
    }
  });
  //Taxon
  var taxonset = $('.taxon.set').html();
  $('.taxon.set.notchanged:last select:first').live( "change", function(evt) {
  	$(this).parent().removeClass('notchanged');
  	
  	//Get number of current selects
  	var selectAmount = $(this).parent().parent().children('.taxon').length;
  	//Conditionally display AND
  	if ( (selectAmount % 3) == 0 ) {
     $(this).parent().parent().append('<span class="taxon set notchanged">' + taxonset + '</span');
    } else {
      $(this).parent().parent().append('<span class="and">OR</span><span class="taxon set notchanged">' + taxonset + '</span');
    }
  });
  //Continent
  var continentset = $('.continent.set').html();
  $('.continent.set.notchanged:last select:first').live( "change", function(evt) {
  	$(this).parent().removeClass('notchanged');
  	
  	//Get number of current selects
  	var selectAmount = $(this).parent().parent().children('.continent').length;
  	//Conditionally display AND
  	if ( (selectAmount % 3) == 0 ) {
     $(this).parent().parent().append('<span class="continent set notchanged">' + continentset + '</span');
    } else {
      $(this).parent().parent().append('<span class="and">OR</span><span class="continent set notchanged">' + continentset + '</span');
    }
  });
  //Country
  var countryset = $('.country.set').html();
  $('.country.set.notchanged:last select:first').live( "change", function(evt) {
  	$(this).parent().removeClass('notchanged');
  	
  	//Get number of current selects
  	var selectAmount = $(this).parent().parent().children('.country').length;
  	//Conditionally display AND
  	if ( (selectAmount % 3) == 0 ) {
     $(this).parent().parent().append('<span class="country set notchanged">' + countryset + '</span');
    } else {
      $(this).parent().parent().append('<span class="and">OR</span><span class="country set notchanged">' + countryset + '</span');
    }
  });
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///// TOOLTIPS JS /////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  
  // Create cookie function
  function createCookie(name,value,days) {
  	
  	if (days) {
  		var date = new Date();
  		date.setTime(date.getTime()+(days*24*60*60*1000));
  		var expires = "; expires="+date.toGMTString();
  	} else {
  	  var expires = "";
  	}
	
	  document.cookie = name+"="+value+expires+"; path=/";
	  
  }
  
  // Read cookie fuction
  function readCookie(name) {
    
    var nameEQ = name + "=";
  	var ca = document.cookie.split(';');
  	
  	for(var i=0;i < ca.length;i++) {
  		
  		var c = ca[i];
  		
  		while (c.charAt(0)==' '){
  		  c = c.substring(1,c.length);
  		}
  		
  		if (c.indexOf(nameEQ) == 0){
  		  return c.substring(nameEQ.length,c.length);
  		} 
  	}
  	
  	return false;
  
  }
  
  // Erase cookie fuction
  function eraseCookie(name) {
	  createCookie(name,"",-1);
  }
  
  // Select anchor tag with rel set to tooltip
  var help_currentstatus = readCookie('conservationevidence_help');

  // Store all titles and remove them
  if ( help_currentstatus == 0 ) {
  	$('html').find('[rel=tooltip]').each( function() {
      $(this).data('title', $(this).attr('title')).removeAttr('title');
  	});
  	$('#off').addClass('active');
  } else {
  	//Create base cookie
    createCookie('conservationevidence_help', 1, 365);
  	$('#on').addClass('active');
  }
  
  //Modify cookie on click
  $('#help #on').click( function() {
  	  
  	  // Change cookie
  	  createCookie('conservationevidence_help', 1, 365);
  	  
  	  // Change classes
  	  $(this).addClass('active');
  	  $('#help #off').removeClass('active');
  	  
  	  // Change var value
  	  help_currentstatus = 1;
  	  
  	  // Retrieve titles from data
	    $('html').find('[rel=tooltip]').each( function() {
	  	  var assign = $(this).data('title');
	  	  $(this).attr('title', assign);
	  	  
	  });
  	  return false;
  });
  
  $('#help #off').click( function() {
  	  
  	  // Change cookie
  	  createCookie('conservationevidence_help', 0, 365);
  	  
  	  // Change classes
  	  $(this).addClass('active');
  	  $('#help #on').removeClass('active');
  	  
  	  // Change var value
  	  help_currentstatus = 0;
  	  
  	  // Store titles in data
  	  $('html').find('[rel=tooltip]').each( function() {
	      $(this).data('title', $(this).attr('title')).removeAttr('title');
	      
  	  });
  	  
  	  return false;
  	  
  });
  
  //Function to run tooltip
  $('a[rel=tooltip], #searchbox.notindex input[type="text"], .ref').live({
    mouseover:
        function(e)
        {
        	//Run tooltip on conditional
			if (help_currentstatus == 1) {
            	//Get title
		        var title = $(this).attr('title');
		        //Remove the title attribute's to avoid the native tooltip from the browser
		        $(this).attr('title','');
		        //Set the X and Y axis of the tooltip
		        $('#tooltip').css('top', e.pageY + 25 );
		        $('#tooltip').css('left', e.pageX + -150 );
		        //Populate tooltip with title
		        $('#tooltip .inside').html('<p>' + title + '</p>');
		        //Show the tooltip with faceIn effect
		        $('#tooltip').stop(true).fadeTo( 500, 1.0);
	        }
        },
    mousemove:
        function(e)
        {
        	//Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
	        $('#tooltip').css('top', e.pageY + 25 );
	        $('#tooltip').css('left', e.pageX + -150 );
        },
    mouseout:
        function()
        {
        	if (help_currentstatus == 1) {
	        	//Get again
		        var title = $('#tooltip .inside p').html();
		        //Fade tooltip out
		        $('#tooltip').fadeOut('500');
		        //Replace title
		        $(this).attr('title',title);
	        }
        }
  });
  
  
  
///////////////////////////////////////////////////////////////////////////////////////////////////
///// FORM VALIDATION JS //////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
  
$('form.validate').submit(function(e) {
	
	$(this).find('.required').each(function() {
    	
    	if ($(this).val().length == 0) {
    		
        	$(this).prev('label').children('.small').addClass('formerrorlabel').end();
            $(this).parent().children('.displayerror').slideDown();
            e.preventDefault();
            
		} else {
    		
        	$(this).prev('label').children('.small').removeClass('formerrorlabel').end();
            $(this).parent().children('.displayerror').slideUp();
			
		}
		
	}); 
	
	$(this).find('#adhuman').each(function() {
    	
    	if ($(this).val() !== '8') {
    		
        	$(this).prev('label').children('.small').addClass('formerrorlabel').end();
            $(this).parent().children('.displayerror').slideDown();
            e.preventDefault();
            
		} else {
    		
        	$(this).prev('label').children('.small').removeClass('formerrorlabel').end();
            $(this).parent().children('.displayerror').slideUp();
			
		}
		
	}); 
});

  (function($){$.fn.autoSuggest=function(data,options){var defaults={asHtmlID:false,startText:"Enter Name Here",emptyText:"No Results Found",preFill:{},limitText:"No More Selections Are Allowed",selectedItemProp:"value",selectedValuesProp:"value",searchObjProps:"value",queryParam:"q",retrieveLimit:false,extraParams:"",matchCase:false,minChars:1,keyDelay:400,resultsHighlight:true,neverSubmit:false,selectionLimit:false,showResultList:true,start:function(){},selectionClick:function(elem){},selectionAdded:function(elem){},selectionRemoved:function(elem){elem.remove()},formatList:false,beforeRetrieve:function(string){return string},retrieveComplete:function(data){return data},resultClick:function(data){},resultsComplete:function(){}};var opts=$.extend(defaults,options);var d_type="object";var d_count=0;if(typeof data=="string"){d_type="string";var req_string=data}else{var org_data=data;for(k in data)if(data.hasOwnProperty(k))d_count++}if((d_type=="object"&&d_count>0)||d_type=="string"){return this.each(function(x){if(!opts.asHtmlID){x=x+""+Math.floor(Math.random()*100);var x_id="as-input-"+x}else{x=opts.asHtmlID;var x_id=x}opts.start.call(this);var input=$(this);input.attr("autocomplete","off").addClass("as-input").attr("id",x_id).val(opts.startText);var input_focus=false;input.wrap('<ul class="as-selections" id="as-selections-'+x+'"></ul>').wrap('<li class="as-original" id="as-original-'+x+'"></li>');var selections_holder=$("#as-selections-"+x);var org_li=$("#as-original-"+x);var results_holder=$('<div class="as-results" id="as-results-'+x+'"></div>').hide();var results_ul=$('<ul class="as-list"></ul>');var values_input=$('<input type="hidden" class="as-values" name="as_values_'+x+'" id="as-values-'+x+'" />');var prefill_value="";if(typeof opts.preFill=="string"){var vals=opts.preFill.split(",");for(var i=0;i<vals.length;i++){var v_data={};v_data[opts.selectedValuesProp]=vals[i];if(vals[i]!=""){add_selected_item(v_data,"000"+i)}}prefill_value=opts.preFill}else{prefill_value="";var prefill_count=0;for(k in opts.preFill)if(opts.preFill.hasOwnProperty(k))prefill_count++;if(prefill_count>0){for(var i=0;i<prefill_count;i++){var new_v=opts.preFill[i][opts.selectedValuesProp];if(new_v==undefined){new_v=""}prefill_value=prefill_value+new_v+",";if(new_v!=""){add_selected_item(opts.preFill[i],"000"+i)}}}}if(prefill_value!=""){input.val("");var lastChar=prefill_value.substring(prefill_value.length-1);if(lastChar!=","){prefill_value=prefill_value+","}values_input.val(","+prefill_value);$("li.as-selection-item",selections_holder).addClass("blur").removeClass("selected")}input.after(values_input);selections_holder.click(function(){input_focus=true;input.focus()}).mousedown(function(){input_focus=false}).after(results_holder);var timeout=null;var prev="";var totalSelections=0;var tab_press=false;input.focus(function(){if($(this).val()==opts.startText&&values_input.val()==""){$(this).val("")}else if(input_focus){$("li.as-selection-item",selections_holder).removeClass("blur");if($(this).val()!=""){results_ul.css("width",selections_holder.outerWidth());results_holder.show()}}input_focus=true;return true}).blur(function(){if($(this).val()==""&&values_input.val()==""&&prefill_value==""){$(this).val(opts.startText)}else if(input_focus){$("li.as-selection-item",selections_holder).addClass("blur").removeClass("selected");results_holder.hide()}}).keydown(function(e){lastKeyPressCode=e.keyCode;first_focus=false;switch(e.keyCode){case 38:e.preventDefault();moveSelection("up");break;case 40:e.preventDefault();moveSelection("down");break;case 8:if(input.val()==""){var last=values_input.val().split(",");last=last[last.length-2];selections_holder.children().not(org_li.prev()).removeClass("selected");if(org_li.prev().hasClass("selected")){values_input.val(values_input.val().replace(","+last+",",","));opts.selectionRemoved.call(this,org_li.prev())}else{opts.selectionClick.call(this,org_li.prev());org_li.prev().addClass("selected")}}if(input.val().length==1){results_holder.hide();prev=""}if($(":visible",results_holder).length>0){if(timeout){clearTimeout(timeout)}timeout=setTimeout(function(){keyChange()},opts.keyDelay)}break;case 9:case 188:tab_press=true;var i_input=input.val().replace(/(,)/g,"");if(i_input!=""&&values_input.val().search(","+i_input+",")<0&&i_input.length>=opts.minChars){e.preventDefault();var n_data={};n_data[opts.selectedItemProp]=i_input;n_data[opts.selectedValuesProp]=i_input;var lis=$("li",selections_holder).length;add_selected_item(n_data,"00"+(lis+1));input.val("")}case 13:tab_press=false;var active=$("li.active:first",results_holder);if(active.length>0){active.click();results_holder.hide()}if(opts.neverSubmit||active.length>0){e.preventDefault()}break;default:if(opts.showResultList){if(opts.selectionLimit&&$("li.as-selection-item",selections_holder).length>=opts.selectionLimit){results_ul.html('<li class="as-message">'+opts.limitText+'</li>');results_holder.show()}else{if(timeout){clearTimeout(timeout)}timeout=setTimeout(function(){keyChange()},opts.keyDelay)}}break}});function keyChange(){if(lastKeyPressCode==46||(lastKeyPressCode>8&&lastKeyPressCode<32)){return results_holder.hide()}var string=input.val().replace(/[\\]+|[\/]+/g,"");if(string==prev)return;prev=string;if(string.length>=opts.minChars){selections_holder.addClass("loading");if(d_type=="string"){var limit="";if(opts.retrieveLimit){limit="&limit="+encodeURIComponent(opts.retrieveLimit)}if(opts.beforeRetrieve){string=opts.beforeRetrieve.call(this,string)}$.getJSON(req_string+"?"+opts.queryParam+"="+encodeURIComponent(string)+limit+opts.extraParams,function(data){d_count=0;var new_data=opts.retrieveComplete.call(this,data);for(k in new_data)if(new_data.hasOwnProperty(k))d_count++;processData(new_data,string)})}else{if(opts.beforeRetrieve){string=opts.beforeRetrieve.call(this,string)}processData(org_data,string)}}else{selections_holder.removeClass("loading");results_holder.hide()}}var num_count=0;function processData(data,query){if(!opts.matchCase){query=query.toLowerCase()}var matchCount=0;results_holder.html(results_ul.html("")).hide();for(var i=0;i<d_count;i++){var num=i;num_count++;var forward=false;if(opts.searchObjProps=="value"){var str=data[num].value}else{var str="";var names=opts.searchObjProps.split(",");for(var y=0;y<names.length;y++){var name=$.trim(names[y]);str=str+data[num][name]+" "}}if(str){if(!opts.matchCase){str=str.toLowerCase()}if(str.search(query)!=-1&&values_input.val().search(","+data[num][opts.selectedValuesProp]+",")==-1){forward=true}}if(forward){var formatted=$('<li class="as-result-item" id="as-result-item-'+num+'"></li>').click(function(){var raw_data=$(this).data("data");var number=raw_data.num;if($("#as-selection-"+number,selections_holder).length<=0&&!tab_press){var data=raw_data.attributes;input.val("").focus();prev="";add_selected_item(data,number);opts.resultClick.call(this,raw_data);results_holder.hide()}tab_press=false}).mousedown(function(){input_focus=false}).mouseover(function(){$("li",results_ul).removeClass("active");$(this).addClass("active")}).data("data",{attributes:data[num],num:num_count});var this_data=$.extend({},data[num]);if(!opts.matchCase){var regx=new RegExp("(?![^&;]+;)(?!<[^<>]*)("+query+")(?![^<>]*>)(?![^&;]+;)","gi")}else{var regx=new RegExp("(?![^&;]+;)(?!<[^<>]*)("+query+")(?![^<>]*>)(?![^&;]+;)","g")}if(opts.resultsHighlight){this_data[opts.selectedItemProp]=this_data[opts.selectedItemProp].replace(regx,"<em>$1</em>")}if(!opts.formatList){formatted=formatted.html(this_data[opts.selectedItemProp])}else{formatted=opts.formatList.call(this,this_data,formatted)}results_ul.append(formatted);delete this_data;matchCount++;if(opts.retrieveLimit&&opts.retrieveLimit==matchCount){break}}}selections_holder.removeClass("loading");if(matchCount<=0){results_ul.html('<li class="as-message">'+opts.emptyText+'</li>')}results_ul.css("width",selections_holder.outerWidth());results_holder.show();opts.resultsComplete.call(this)}function add_selected_item(data,num){values_input.val(values_input.val()+data[opts.selectedValuesProp]+",");var item=$('<li class="as-selection-item" id="as-selection-'+num+'"></li>').click(function(){opts.selectionClick.call(this,$(this));selections_holder.children().removeClass("selected");$(this).addClass("selected")}).mousedown(function(){input_focus=false});var close=$('<a class="as-close">&times;</a>').click(function(){values_input.val(values_input.val().replace(","+data[opts.selectedValuesProp]+",",","));opts.selectionRemoved.call(this,item);input_focus=true;input.focus();return false});org_li.before(item.html(data[opts.selectedItemProp]).prepend(close));opts.selectionAdded.call(this,org_li.prev())}function moveSelection(direction){if($(":visible",results_holder).length>0){var lis=$("li",results_holder);if(direction=="down"){var start=lis.eq(0)}else{var start=lis.filter(":last")}var active=$("li.active:first",results_holder);if(active.length>0){if(direction=="down"){start=active.next()}else{start=active.prev()}}lis.removeClass("active");start.addClass("active")}}})}}})(jQuery);

  function makeSelection(selected){
  	$.ajax({
    	url: "./ajax/selection.php",
    	data: ({id : selected}),
    	async: false
   	});
  }
  
});
