$.fn.superfish.defaults = { 
    hoverClass:    'sfHover',          // the class applied to hovered list items 
    pathClass:     'overideThisToUse', // the class you have applied to list items that lead to the current page 
    pathLevels:    1,                  // the number of levels of submenus that remain open or are restored using pathClass 
    delay:         800,                // the delay in milliseconds that the mouse can remain outside a submenu without it closing 
    animation:     {opacity:'show'},   // an object equivalent to first parameter of jQuery’s .animate() method 
    speed:         'normal',           // speed of the animation. Equivalent to second parameter of jQuery’s .animate() method 
    autoArrows:    false,               // if true, arrow mark-up generated automatically = cleaner source code at expense of initialisation performance 
    dropShadows:   false,               // completely disable drop shadows by setting this to false 
    disableHI:     false,              // set to true to disable hoverIntent detection 
    onInit:        function(){},       // callback function fires once Superfish is initialised – 'this' is the containing ul 
    onBeforeShow:  function(){},       // callback function fires just before reveal animation begins – 'this' is the ul about to open 
    onShow:        function(){},       // callback function fires once reveal animation completed – 'this' is the opened ul 
    onHide:        function(){}        // callback function fires after a sub-menu has closed – 'this' is the ul that just closed 
};

function initSlideShows() {
	$('.slideshowhomepage div:first').fadeIn(1000, function() {
	    $('.slideshowhomepage').cycle({ 
	    	fx:    'fade', 
	    	timeout: 6000,
			speedIn: 4000,
			speedOut: 4000
	 	});
	});
	$('.slideshow div:first').fadeIn(1000, function() {
	    $('.slideshow').cycle({ 
	    	fx:    'fade', 
	    	timeout: 6000,
			speedIn: 4000,
			speedOut: 4000
	 	});
	});
}

function initBigTargets() {
	$("div.bigTarget a").bigTarget({
		hoverClass: 'over', // CSS class applied to the click zone onHover
		clickZone : 'div:eq(0)' // jQuery parent selector
	});		
	$("li.bigTarget a").bigTarget({
		hoverClass: 'over', // CSS class applied to the click zone onHover
		clickZone : 'li:eq(0)' // jQuery parent selector
	});		
}
function initMailingListSubmit() { 
	$('a#registerAnother').click(function () {
		location.reload();
	});
	var options = { 
		target:        '#hiddenDIV',   // target element(s) to be updated with server response 
	    beforeSubmit:  beforePost,  // pre-submit callback 
	    success:       afterPost  // post-submit callback 
	}
	$('#mailingList').validate({
	    submitHandler: function(form) {
			$('#mailingList').ajaxSubmit(options);
		}
	});
	// pre-submit callback 
	function beforePost() { 
		$('#submit').val('Sending…');
		$('#submit').addClass("sending"); 
		
		//$("#submit").hide();
		//$("#submitMessage").show();
	    // here we could return false to prevent the form from being submitted; 
	    // returning anything other than false will allow the form submit to continue 
	    return true; 
	} 
	// post-submit callback 
	function afterPost(rtn)  { 
	    if(rtn=="success") {
	      	$("#mailingList").hide();
			$("#notification").fadeIn("slow");
		}else{
	        //there was an error, so grab the UL in the content ID, 
	        //inside the hidden DIV, and put it into the Message Notification
	      $("#errorMessage").html(  $("#hiddenDIV #content ul").html() );
		  $("#hiddenDIV").empty(); 
	     }
	}
}
function initAlternateRows() {
	//$('.calEvent li:nth-child(odd)').addClass('alternate');
}
function initAutoComplete() {
	var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
	var statesabbv = [
	{abbv: "AL", name: "Alabama"}, 
	{abbv: "AK", name: "Alaska"}, 
	{abbv: "AR", name: "Arkansas"}, 
	{abbv: "AZ", name: "Arizona"}, 
	{abbv: "CA", name: "California"}, 
	{abbv: "CO", name: "Colorado"}, 
	{abbv: "CT", name: "Connecticut"}, 
	{abbv: "DE", name: "Delaware"}, 
	{abbv: "FL", name: "Florida"}, 
	{abbv: "GA", name: "Georgia"}, 
	{abbv: "HI", name: "Hawaii"}, 
	{abbv: "ID", name: "Idaho"}, 
	{abbv: "IL", name: "Illinois"}, 
	{abbv: "IN", name: "Indiana"}, 
	{abbv: "IA", name: "Iowa"}, 
	{abbv: "KS", name: "Kansas"}, 
	{abbv: "KY", name: "Kentucky"},
	{abbv: "LA", name: "Louisiana"}, 
	{abbv: "ME", name: "Maine"}, 
	{abbv: "MD", name: "Maryland"}, 
	{abbv: "MA", name: "Massachusetts"}, 
	{abbv: "MI", name: "Michigan"}, 
	{abbv: "MN", name: "Minnesota"}, 
	{abbv: "MS", name: "Mississippi"}, 
	{abbv: "MO", name: "Missouri"}, 
	{abbv: "MT", name: "Montana"}, 
	{abbv: "NE", name: "Nebraska"}, 
	{abbv: "NV", name: "Nevada"}, 
	{abbv: "NH", name: "New Hampshire"}, 
	{abbv: "NJ", name: "New Jersey"}, 
	{abbv: "NM", name: "New Mexico"}, 
	{abbv: "NY", name: "New York"}, 
	{abbv: "NC", name: "North Carolina"}, 
	{abbv: "ND", name: "North Dakota"}, 
	{abbv: "OH", name: "Ohio"}, 
	{abbv: "OK", name: "Oklahoma"}, 
	{abbv: "OR", name: "Oregon"}, 
	{abbv: "PA", name: "Pennsylvania"}, 
	{abbv: "RI", name: "Rhode Island"}, 
	{abbv: "SC", name: "South Carolina"}, 
	{abbv: "SD", name: "South Dakota"}, 
	{abbv: "TN", name: "Tennessee"}, 
	{abbv: "TX", name: "Texas"}, 
	{abbv: "UT", name: "Utah"}, 
	{abbv: "VT", name: "Vermont"}, 
	{abbv: "VA", name: "Virginia"}, 
	{abbv: "WA", name: "Washington"}, 
	{abbv: "WV", name: "West Virginia"}, 
	{abbv: "WI", name: "Wisconsin"}, 
	{abbv: "WY", name: "Wyoming"}
	];
	//$("#state").autocomplete(stateabbv);
	$("#state").autocomplete(statesabbv, {
		minChars: 0, max: 5, delay: 250, matchContains: false,  autoFill:false,
		formatItem: function(row) {return row.name; },
	    formatMatch: function(row) {return row.abbv + row.name; },
	    formatResult: function(row) {return row.abbv; }
	});
}
function initSWFobject() {
	$('#mapswf').flash({
	            src:'/images/swfs/map.swf',
	            width:'670',
	            height:'452',
	            version : '8.0.0'
	        });	
}
function initZindex() {
//	$(function() {
//		var zIndexNumber = 1000;
//		$('div').each(function() {
//			$(this).css('zIndex', zIndexNumber);
//			zIndexNumber -= 10;
//		});
//	});
	$('div#globalnav ul').css('zIndex', 1000);
//	$('div.slideshow').css('zIndex', 900);
}
function initSortCalendar() {
	var sortMonth = $('ul.months li');
	var sortCalendar = $('div.calEvent div.column ul li');
	$(sortCalendar).hide();
	$(sortCalendar).filter("."+ monthClass).fadeIn("slow");
	$(sortCalendar).filter("."+ monthClass +":even").addClass("alternate");
	$('ul.months li a').click(function () {
		var monthClass = $(this).attr("class");
		sortCalendar.hide();
		sortCalendar.filter("."+ monthClass).fadeIn("slow");
		sortCalendar.filter("."+ monthClass +":even").addClass("alternate");
		sortMonth.removeClass("current");
		$(this).parent().addClass("current");
		return false
	})
}
function initPlantFinder() {
	// Auto Suggest for Finder
	$("#plant-search input#keywords").focus(),
	$("#plant-search input#keywords").autocomplete("http://www.mtcubacenter.org/plant-finder/finder-auto-complete/", {
		minChars: 0,
		delay: 250,
		matchContains: false,
		autoFill:false,
		selectFirst: false,
		formatItem: function(data, i, n, value) {
            return value.split("::")[0];
        },
		formatResult: function(data,value) {
            return value.split("::")[0];
        }
	}).result(function(event, data, item) {
        //redirect to the URL in the string
        var url = item.split("::");
        window.location.href = url[1];
    });


	
	// Option Toggles
	$("div.option-block").hide();
	$("h3.toggler, h4.toggler").click(function () {
		$(this).next().slideToggle();
		$(this).toggleClass("active");
	});
	
	$("span.toggler-all").click(function () {
		if ($("div.option-block").is(":hidden")) {
			$("div.option-block").slideDown();
			$("h3.toggler").addClass("active");
			$(this).addClass("active");
		} else {
			$("div.option-block").slideUp();
			$("h3.toggler").removeClass("active");
			$(this).removeClass("active");
		}
	});
	
	
	// Question Mark Tooltips
	$('.plant-search h4 a.question-box').each(function() // This lets us use $(this) to refer to each element in the loop
	{
		$(this).qtip( // Create tooltips on the current element
		{ 
	    	content: $(this).next('.question-box-content'), // Grab the element next to (after) the element
	    	position: {
		    	corner: {
		        	target: 'topMiddle',
		         	tooltip: 'bottomLeft'
		      	}
		  	},
	   	  	style: { 
				background: '#e1e4d9',
				'font-size': 14,
				width: 550,
				border: {
			       width: 2,
			       color: '#677718'
			    },
				name: 'green',
				tip: 'bottomLeft'
			},
			hide: {
			fixed: true // Make it fixed so it can be hovered over
			}
	   });
	});
	// Question Mark Tooltips
	$('#plant-results h4 a.question-box').each(function() // This lets us use $(this) to refer to each element in the loop
	{
		$(this).qtip( // Create tooltips on the current element
		{ 
	    	content: $(this).next('.question-box-content'), // Grab the element next to (after) the element
	    	position: {
		    	corner: {
		        	target: 'topMiddle',
		         	tooltip: 'bottomRight'
		      	}
		  	},
	   	  	style: { 
				background: '#e1e4d9',
				'font-size': 14,
				width: 550,
				border: {
			       width: 2,
			       color: '#677718'
			    },
				name: 'green',
				tip: 'bottomRight'
			},
			hide: {
			fixed: true // Make it fixed so it can be hovered over
			}
	   });
	});
	
	// Results Page Limit URL Rewrites
	$(function() {        
        var uri = window.location.pathname; // gets the current url
        var currentNum = uri.substr(uri.lastIndexOf('num=')+4,2); // gets the current num= limit value
        
        $('.result-limit a').each(function() {
            var uri2 = window.location.pathname; // gets the current url again inside the link loop
            newNum = "num="+$(this).attr('title'); // gets the new number limit we need from the links title attribute
        	uri2 = uri2.replace(/num=[0-9]+/, newNum) // replaces the current num= value with the correct number limit we need
        	$(this).attr('href', uri2); // sets the href value of the link to the new url
        	
            if ($(this).attr('title') == currentNum) $(this).addClass('active'); // adds a class of active to the current number limit
        });
    }); 
    
    // Activates colorbox by simulating a click on the first of the 'more' images
    $("a#more-link").click(function(){ 
            $("a[rel='detail-image']:first").click(); 
            return false; 
    }); 
    // Assigns colorbox to the hidden images
    $("a[rel='detail-image']").colorbox({maxWidth:"900px", maxHeight:"600px", photo:true}); 
}

// Set the seasons cookie based on value from Flash Map
function setSeasonCookie(value)
{
    var $cookie_value = value;
    $.cookie('seasonCookie', $cookie_value, { expires: 30, path: '/'});
}

function setPlantTrialYearCookie(value) {
	var $plant_trial_year_cookie_value = value;
	if ( $.cookie("PlantTrialYearCookie") == null ) {
		$.cookie('PlantTrialYearCookie', 'yearOne', { expires: 30, path: '/'});
    }
//	if ( $.cookie("PlantTrialYearCookie") == "yearTwo" ) {
//		$.cookie('PlantTrialYearCookie', 'yearOne', { expires: 30, path: '/'});
//    }
	if ( $.cookie("PlantTrialYearCookie") == "yearOne" ) {
		$(".yearOne").fadeIn();
		$(".yearTwo").hide();
		initSlideShows();
    }
	if ( $.cookie("PlantTrialYearCookie") == "yearTwo" ) {
		$(".yearOne").hide();
		$(".yearTwo").fadeIn();
		initSlideShows();
    }
	$('a#yearOne').click(function() {
		$.cookie('PlantTrialYearCookie', 'yearOne', { expires: 30, path: '/'});
		$(".yearOne").fadeIn();
		$(".yearTwo").hide();
		initSlideShows();
	});
	$('a#yearTwo').click(function() {
		$.cookie('PlantTrialYearCookie', 'yearTwo', { expires: 30, path: '/'});
		$(".yearOne").hide();
		$(".yearTwo").fadeIn();
		initSlideShows();
	});
}
function initPlantTrials() {
	// Question Mark Tooltips
	$('.plant-trial-listing p a.question-box').each(function() // This lets us use $(this) to refer to each element in the loop
	{
		$(this).qtip( // Create tooltips on the current element
		{ 
	    	content: $('#question-box-content'), // Grab the element next to (after) the element
	    	position: {
		    	corner: {
		        	target: 'topMiddle',
		         	tooltip: 'bottomLeft'
		      	}
		  	},
	   	  	style: { 
				background: '#e1e4d9',
				'font-size': 14,
				width: 375,
				border: {
			       width: 2,
			       color: '#677718'
			    },
				name: 'green',
				tip: 'bottomLeft'
			},
			hide: {
			fixed: true // Make it fixed so it can be hovered over
			}
	   });
	});
	$("#show-details p a").click(function() {
		$("#details").slideDown();
		$("#show-details").hide();
		$("#hide-details").show();
		return false;
	});
	$("#hide-details p a").click(function() {
		$("#details").slideUp();
		$("#hide-details").hide();
		$("#show-details").show();		
		return false;
	});
}
$(document).ready(function() {
//	$('ul.globalnav').superfish();
	initSWFobject();
	initZindex();
	initSlideShows();
	initBigTargets();
	initMailingListSubmit();
	initAlternateRows();
	initAutoComplete();
//	initSortCalendar(); active init moved to calendar template to avoid conflict with colorbox
//	initPlantFinder(); active init moved to index and results templates to avoid conflict 
	setPlantTrialYearCookie();
	setSeasonCookie();
	});
