$(function(){

//------------------------------------//
// Dropdown Nav
//------------------------------------//
    //$('ul.sf-menu').superfish();
    $("ul.sf-menu").superfish().find('ul').bgIframe({opacity:false}); 


//------------------------------------//

//------------------------------------//
// Forms
//------------------------------------//
// clear the default text when the user clicks the input field
$('.search-input').click(function(){
    $(this).val("");
    $('#searchTickler').fadeOut();
});
//------------------------------------//

//------------------------------------//
// Homepage Banner and Corporate Sponsor Cycle
//------------------------------------//

    $('#cycleContent').cycle({ 
		fx:     'fade', 
		speed:  'slow', 
		timeout: 6000, 
		pager:  '#pager',
		pause:  1,
		before:   onBeforeBannerAds 
	});
	
	$('#corporatePartners').cycle({ 
		fx:     'fade',
        speed:   1000,
        timeout: 5000,
        next:   '#corporatePartners',
        pause:   1,
		before:   onBefore 
	});
	
	function onBefore(curr, next, opts, fwd){		
        //get the height of the current slide
        var $ht = $(this).height();
        //set the container's height to that of the current slide
        $(this).parent().css("height", $ht);   
	}
	
	function onBeforeBannerAds(curr, next, opts, fwd){		
        //get the height of the current slide
        var $ht = $(this).height();
        //set the container's height to that of the current slide
        //$(this).parent().parent().css("height", $ht);   
		//$(this).parent().parent().parent().css("height", $ht); 
	}
		
//------------------------------------//
// Form Tickler
//------------------------------------//
// Basically, we need to help the user know where to go once they click
// #linkSearch link.
    $('#linkSearch').click(function(){
        $('#searchTickler').fadeIn();
    });
//------------------------------------//	

//------------------------------------//
// Icons for various Links
//------------------------------------//
 //var iconPath = "/images/icons/"; //----------------------------for dev&prod
 var iconPath = "/images/icons/";
 $("a[href^='mailto:']").append('&nbsp;<img class="linkIcon" src="' + iconPath + 'iconEmail.gif" alt="Send Email" width="16" />');
 $('a.pdf').append('<img class="linkIcon" src="' + iconPath + 'iconPDF.gif" alt="PDF Download" height="16" width="16" />');
 $('a.xls').append('<img class="linkIcon" src="' + iconPath + 'iconXLS.gif" alt="Excel Download" height="16" width="16" />');
//------------------------------------// 

//------------------------------------//
// Modal Contact Form for mailto links
//------------------------------------//

	// If we're not on the homepage
	if (window.location.pathname != "/" && window.location.pathname != "/Default.aspx") {
		// Add the name "modal" to any mailto hrefs
		$("a[href^='mailto:']").attr("name", "modal");
	}
    
    var recipientEmail;
    var recipientName;   
    
    // Grab our contact form values
    var name = $("#name"),
	email = $("#email"),		
	message = $("#message"),	
	allFields = $([]).add(name).add(email).add(message),
	tips = $("#validateTips");

	function updateTips(t) {
		tips.text(t).effect("highlight",{},1500);
	}

	function checkLength(o,n,min,max) {

		if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			updateTips("Length of " + n + " must be between "+min+" and "+max+".");
			return false;
		} else {
			return true;
		}

	}

	function checkRegexp(o,regexp,n) {

		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass('ui-state-error');
			updateTips(n);
			return false;
		} else {
			return true;
		}

	}
	
    $("#dialogSendEmail").dialog({
			bgiframe: true,
			autoOpen: false,
			width: 340,
			height: 434,
			modal: true,
			resizable: false,
			buttons: {
				'Send E-mail': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');

					bValid = bValid && checkLength(email,"email",6,80);						

					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Invalid e-mail format.");
								
					if (bValid) {
						$('#users tbody').append('<tr>' +
							'<td>' + name.val() + '</td>' + 
							'<td>' + email.val() + '</td>' + 	
							'<td>' + message.val() + '</td>' + 	
							'</tr>'); 	
						
						// Send e-mail
						$.ajax({
			                type: "POST",
			                url: "/SendEmail.ashx",
			                data: 	"from=donotreply@fl-counties.com" +
			                        "&recipientname=" + recipientName + 
			                        "&email=" + email.val() + 
					                "&to=" + recipientEmail +
					                "&name=" + name.val() +
					                "&message=" + message.val(),
			                success: function(){
				                // Open the Thank you modal
				                $('#dialog_thankYou').dialog('open');
			                }			                
		                });
						
						// Close the modal
						$(this).dialog('close');	
						
						// Set the recipient's name
		                $('#recipientName').text(recipientName);
						
						// Open the thank you dialog box
						$('#dialogThankYou').dialog('open');
												
					}
				},
				Cancel: function() {
					$(this).dialog('close');	
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');	
			}
		});
		
		$("#dialogThankYou").dialog({
			bgiframe: true,
			autoOpen: false,
			width: 300,
			modal: true,
			resizable: false,
			buttons: {
				Ok: function() {
					$(this).dialog('close');		
					
					// Do a .NET postback on our hidden form button
				    //__doPostBack('ctl00$ctl00$btnSubmitContactForm','');
				}				
			}			
			
		});
		
		// jquery adds the dialog outside the form, let's move it inside so we can do .NET postback
		$("#dialogSendEmail").parent().appendTo(jQuery('form:first'));
		
		// jquery adds the dialog outside the form, let's move it inside
		$("#dialogThankYou").parent().appendTo(jQuery('form:first'));
		
		$('a[name=modal]').click(function(e) {
            // Cancel the link behavior
		    e.preventDefault();
		    
		    // Get the a tag
		    var id = $(this).attr('href');		
		    
		    // Set the recipient	 		   
		    recipientEmail = id.replace("mailto:", "");
		    recipientName = $(this).text();    
		    
		    // Set the recipient's name
		    $('#recipientEmail').text(recipientName);
		       
		    // Open the send email dialog box
		    $('#dialogSendEmail').dialog('open');
		});
		

//------------------------------------//
// Events (for homepage tabs)
//------------------------------------//
		//---Event View Tabs---//
        $('#tabset li a').click(function(){
            // Reset Everything
            $('#tabset li').removeClass();
            
            // Hide Everything
            $('.tab-content').hide();
            $('.text-holder').hide();          
            
            // Add the appropriate class to the li
            $(this).parent().addClass("active");
            
            // Show the appropriate div
            $($(this).attr('href')).show();
            
            if ($(this).attr('href') == "#tab1") {
                $('.text-holder').show(); 
            }
            
            // Don't scroll to the top of the page
            return false;
        });
    //---End Event View Tabs---//

	 // add zebra stripping
    $('table.with-stripes tr:odd').addClass("even");


	// Set specific variable to represent all iframe tags.
	if (document.getElementById && document.createTextNode){
 		addEvent(window,'load', doIframe);	
	}

	
});	//---End of onLoad event ---//


//------------------------------------//
// iFrame Auto-height
//------------------------------------// 
function doIframe(){
	o = document.getElementsByTagName('iframe');
	for(i=0;i<o.length;i++){		
		if (/\bautoHeight\b/.test(o[i].className)){	
			setHeight(o[i]);
			addEvent(o[i],'load', doIframe);
		}
	}
}

function setHeight(e){
	if(e.contentDocument){
		e.height = 35 + e.contentDocument.body.offsetHeight;
	} else {
		e.height = 35 + e.contentWindow.document.body.scrollHeight;
	}
}

function addEvent(obj, evType, fn){
	if(obj.addEventListener)
	{
	obj.addEventListener(evType, fn,false);
	return true;
	} else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
	return r;
	} else {
	return false;
	}
}


//------------------------------------//
// Events continued...
//------------------------------------//    
    
//---loadEvents---//
// This function handles the display of event data on the home page.
// It sets up the two event views: Calendar View and List View
function loadEvents(xml) {
// get today's date
var today = new Date();

// Takes the date in two formats:
// theDate: Mon Aug 12 2009
// dateText: 08/27/2009
   var outputHTML = function(theDate, dateText){
        // clear everything out previously
        $('.events').html("");

        // set the selected date in the HTML
        $('.selected-date').text(dateText);
        
        // select the day from our loaded xml
        $(xml).find("day[datestring='"+theDate+"']").each(function(){
            // 1. loop through each event for that day and...
            // 2. insert the event data into the DOM
            $(this).find("event").each(function(){     
                if ($(this).find("url").size() > 0) {                                          
                    $('<div class="event"><a></a><div class="desc"></div>') //create our HTML 
                    .find("a")
                    .attr("href", $(this).find("url").text())
                    .html($(this).find("title").text())
                    .end()
                    .find(".desc")
                    .html($(this).find("desc").text())
                    .end()
                    .appendTo(".events");     
                }
                else {
                    $('<div class="event"><h4></h4><div class="desc"></div>') //create our HTML 
                    .find("h4")                                
                    .html($(this).find("title").text())
                    .end()
                    .find(".desc")
                    .html($(this).find("desc").text())
                    .end()
                    .appendTo(".events");  
                }               
            });
        });
    };
//---End outputHTML---//        

//---Calendar View---//
    // format the date so that it's consistent across the browsers
    var formatDate = function(date){
        var monthName = new Array ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
        var dayName = new Array ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
        
        var theYear = date.getYear();
        if (date.getYear() <= 110){
            theYear = theYear + 1900;
        };
        
        var formattedDate = dayName[date.getDay()] + " " + monthName[date.getMonth()]  + " " + date.getDate()  + " " + theYear;
        
        return formattedDate;
    };
    
    $('#datepicker').datepicker({
        inline: true,
        dayNamesMin: ['S','M', 'T', 'W', 'T', 'F', 'S'],       
        beforeShowDay: function(date){
            var theDate = formatDate(date);
            
            // if there are events for the day
            if ($(xml).find("day[datestring='"+theDate+"']").size() > 0) {
               //make the day clickable and give it a class "has-events"               
               return [true, 'has-events']          
            } 
            else { 
               return [false,'no-events'] 
            };
        },
        onSelect: function(dateText, datepicker){
            // convert dateText to the default format that we're using.
            var theDate = formatDate(new Date(dateText));
            outputHTML(theDate, dateText)
        }
    });
    
    // on page load, If there are any events for today
    if ($(xml).find("day[datestring='"+formatDate(today)+"']").size() > 0){
        //spit them out
        outputHTML(today.toDateString(),((today.getMonth()+1)+"/"+today.getDate()+"/"+today.getFullYear()));
    };
//---End Calendar View--//
                
//---List View--//   
     
    // create our UL
    $('<ul id="eventsGrid"></ul>').appendTo("#tab2");
    
    // for each day
    $(xml).find("day").each(function(){
        // set up the date
        theDate = new Date($(this).attr("datestring"));
        var currentDate = new Date();  
                                                  
        // don't show past events   
        if (Date.parse(theDate) >= Date.parse(currentDate)) {    
        
            theDate = (theDate.getMonth()+1)+"/"+theDate.getDate();
            
            var theTitle = "";
            
            // for each event
            $(this).find("event").each(function(){
                // set up the title
                theTitle = $(this).find("title").text()  
                // Trim it if its too long
                if (theTitle.length >= 33){
                    theTitle = theTitle.substr(0,33)+"...";
                }
                
                // put it all together now
                // determine if link or h4 should be shown based on existence of Url node  
                if ($(this).find("url").size() > 0) {                                                                
                    $("<li><strong></strong><a></a></li>")
                    .find("strong")
                    .html(theDate)
                    .end()
                    .find("a")
                    .attr("href", $(this).find("url").text())
                    .html($(this).find("title").text())
                    .end()       
                    .appendTo("#eventsGrid");                            
                }
                else {
                    $("<li><strong></strong><span></span></li>")
                    .find("strong")
                    .html(theDate)
                    .end()
                    .find("span")
                    .html(theTitle)
                    .end()    
                    .appendTo("#eventsGrid");                          
                }                            
                                
            });
        } // date comparison        
    });
    
    // add zebra stripping
    $('#eventsGrid li:even').addClass("striped");
    
//---End List View--//
};
//---End loadEvents---//


//---displayErrorMessage--//    
// This function displays an error message to the site visitor
// if for some reason, the event xml fails to load.
    var displayErrorMessage = function(){
        
    };
//---End displayErrorMessage---//


 $('ul#nav li:first-child ul').addClass('first');


