// JavaScript Document

(function($){

	$.fn.shuffle = function() {
		return this.each(function(){
			var items = $(this).children().clone(true);
			return (items.length) ? $(this).html($.shuffle(items)) : this;
		});
	}
	
	$.shuffle = function(arr) {
		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	}
	
})(jQuery);

function rotateFP(){
	if ($('#fpHolder').find('div.singleFP').length > 1) {
		$currentImage = $('#fpHolder div.current');
		$nextImage = $('#fpHolder div.next');
		$queImage = $('#fpHolder div.next').next();
		if($queImage.length == 0)
		{
			$queImage = $('#fpHolder div:first');
		}
		
		$currentImage.fadeOut(1000);
		
		$nextImage.fadeIn(1000, function(){
			$currentImage.removeClass('current');
			$nextImage.removeClass('next').addClass('current');
			$queImage.addClass('next');
		});
	};
	
};

$(function() {
		   
	if($('#fpHolder').length)
	{
		$('#fpHolder div.singleFP').eq(1).addClass('next');
		setInterval('rotateFP()', 11000);
	}
						   
	$('#theImages').cycle({
		fx: 'fade',
		speed:  2500,
		timeout:  10000
	});
	
	$(".toggleLoginbtn").click(
		function()
		{
			$("ul#courtesySub").slideToggle("fast");

		}
	);
	
	$("input[type='text']").focus(function () {
         var inputValue = $(this).val();
		 if(inputValue == "Search ...")
		 {
			 $(this).val("");
		 }
    });
	
	$("input#searchField").blur(function () {
         var inputValue = $(this).val();
		 if(inputValue == "")
		 {
			 $(this).val("Search ...");
		 }
    });

	$('img#theLogoImage').hover(function() {
		var currentImg = $(this).attr('src');
		$(this).attr('src', $(this).attr('hover'));
		$(this).attr('hover', currentImg);
	}, function() {
		var currentImg = $(this).attr('src');
		$(this).attr('src', $(this).attr('hover'));
		$(this).attr('hover', currentImg);
	});
	
	/* Start Galleria and jCarousel */
	
	$('#gallery li').each(function(idx) {
        $(this).data('index', (++idx));
    });

    $('#gallery').jcarousel({
        scroll: 7,
        initCallback: initCallbackFunction
    })
    
    function initCallbackFunction(carousel) {
        $('#img').bind('image-loaded',function() {
            var idx =  $('#gallery li.active').data('index') - 3;
            
            carousel.scroll(idx);
            return false;
        });
        
        // hotkeys plugin: use arrows to control the gallery
        $(document).bind('keydown', 'right', function (evt){ $.galleria.next(); });
        $(document).bind('keydown', 'left', function (evt){ $.galleria.prev(); });
        $(document).bind('keydown', 'up', function (evt){ $('.jcarousel-next-horizontal').click(); return false; });
        $(document).bind('keydown', 'down', function (evt){ $('.jcarousel-prev-horizontal').click(); return false; });
    };

    // load and fade-in thumbnails
    $('#gallery li img').css('opacity', 0).each(function() {    
        if (this.complete || this.readyState == 'complete') { $(this).animate({'opacity': 1}, 300) } 
        else { $(this).load(function() { $(this).animate({'opacity': 1}, 300) }); }
    });

    
    $('#gallery').galleria({
        // #img is the empty div which holds full size images
        insert: '#img',
        
        // enable history plugin
        history: false,
        
        // function fired when the image is displayed
        onImage: function(image, caption, thumb) {        
            // fade in the image 
            image.hide().fadeIn(500);
            
            // animate active thumbnail's opacity to 1, other list elements to 0.6
            thumb.parent().fadeTo(200, 1).siblings().fadeTo(200, 0.6)
            
            // $('#img').data('currentIndex', $li.data('index')).trigger('image-loaded')
            
            $('#img')
                .trigger('image-loaded')
                .hover(
                    function(){ 
						if($('#img .caption').text() !== '')
						{
							$('#img .caption').stop().animate({height: 50}, 250) 
						}
					},
                    function(){ 
                        if (!$('#show-caption').is(':checked')) {
                            $('#img .caption').stop().animate({height: 0}, 250) 
                        }
                    }
                );
        },
        
        // function similar to onImage, but fired when thumbnail is displayed
        onThumb: function(thumb) {
            var $li = thumb.parent(),
                opacity = $li.is('.active') ? 1 : 0.6;
            
            // hover effects for list elements
            $li.hover(
                function() { $li.fadeTo(200, 1); },
                function() { $li.not('.active').fadeTo(200, opacity); }
            )
        }        
    }).find('li:first').addClass('active') // display first image when Galleria is loaded
    
    $('#img .caption').css('height', 0)
    
    $('#slideshow').hide()
    
    // this one is for Firefox, which loves to leave fields checked after page refresh
    $('#toggle-slideshow, #show-caption').removeAttr('checked')
    
    $('#show-caption').change(function(){
    	if (this.checked) {
    		$('#img .caption').stop().animate({height: 50}, 250)
    	} else {
            $('#img .caption').stop().animate({height: 0}, 250)   
        }
    })

  
    var slideshow,
        slideshowPause =  $('#slideshow-pause').val() 

    $('#slideshow-pause').change(function(){
        slideshowPause = this.value
        
        // clear interval when timeout is changed
        window.clearInterval(slideshow)

        // and set new interval with new timeout value
        slideshow = window.setInterval(function(){
            $.galleria.next()
        }, slideshowPause * 1000) // must be set in milisecond
    })

    $('input#toggle-slideshow').change(function(){
        if (this.checked) {
            $('#slideshow').fadeIn()
            
            // set interval when slideshow is enabled
            slideshow = window.setInterval(function(){
                $.galleria.next()
            }, slideshowPause * 1000)
        } else {
            $('#slideshow').fadeOut()
            
            // clear interval when slideshow if disabled
            window.clearInterval(slideshow)
        }
    })
	
	/* End Galleria and jCarousel */
	
	// Zebra Strip Table body tr
	$("tbody.zebra tr:odd").addClass("oddRow");
	
	// Signup Form Validation and Processing
	 $("input#signupSubmit").click(
		function()
		{
			var namePass = false;
			var emailPass = false;
			var emailPattern = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
			var nameVal = $("input#signupName").val();
			var emailVal = $("input#signupEmail").val();
			var nameAlert = "Need to input a name.\n";
			var emailAlert = "Need to input a valid email.\n";
			
			if(nameVal == "")
			{
				$("input#signupName").css({border : "1px solid #F00"});
				namePass = false;
			}
			else
			{
				$("input#signupName").css({border : "1px solid #CCC"});
				namePass = true;
			}
			
			if(emailVal == "" || !emailPattern.test(emailVal))
			{
				$("input#signupEmail").css({border : "1px solid #F00"});
				emailPass = false;
			}
			else
			{
				$("input#signupEmail").css({border : "1px solid #CCC"});
				emailPass = true;
			}
			
			if(namePass && emailPass)
			{
				// post form
				
				var nameValue = $("input#signupName").val();
				var emailValue = $("input#signupEmail").val();
				var companyValue = $("input#signupCompany").val();
				
				$("form#signupForm").before('<p class="signupMessage" style="padding-bottom:5px;">Processing&hellip;</p>').find("p.signupMessage").hide();
				$("p.signupMessage").show("blind", {direction: "vertical", easing: "easeOutCirc"}, 800);
				
				$.post(
					"/dyn/newsletter_signup.cfm", 
					{
						theName:nameValue,
						theEmail:emailValue,
						theCompany:companyValue
					}, 
					function(data)
					{
						// Do Something after data Posts
						$("p.signupMessage").remove();
						$("div.ui-effects-wrapper").remove();
						$("form#signupForm").before(data);
						$("input#signupName").val("");
						$("input#signupEmail").val("");
						$("input#signupCompany").val("");
						window.setTimeout(
							function()
							{
								$("p.signupMessage").hide("blind", {direction: "vertical", easing: "easeOutCirc"}, 1000, function(){$("p.signupMessage").remove();});
							}, 8000
						);
					}, 
					"html"
				);
			}
			else
			{
				var errorMessage = "Alert:\n\n"
				if(!namePass)
				{
					errorMessage += nameAlert;
				}
				if(!emailPass)
				{
					errorMessage += emailAlert;
				}
				alert(errorMessage);
			}
		}
	);
	
	// Validate Contact form
	$("form#contactForm input#contactSubmit").click(
		function()
		{
			var namePass = false;
			var emailPass = false;
			var emailPattern = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
			var nameVal = $("input#contactName").val();
			var emailVal = $("input#contactEmail").val();
			var nameAlert = "Need to input a name.\n";
			var emailAlert = "Need to input a valid email.\n";
			
			if(nameVal == "")
			{
				$("input#contactName").css({border : "1px solid #F00"});
				namePass = false;
			}
			else
			{
				$("input#contactName").css({border : "1px solid #CCC"});
				namePass = true;
			}
			
			if(emailVal == "" || !emailPattern.test(emailVal))
			{
				$("input#contactEmail").css({border : "1px solid #F00"});
				emailPass = false;
			}
			else
			{
				$("input#contactEmail").css({border : "1px solid #CCC"});
				emailPass = true;
			}
			
			if(namePass && emailPass)
			{
				// post form
				
				var nameValue = $("input#contactName").val();
				var emailValue = $("input#contactEmail").val();
				
				$("form#contactForm").before('<p class="signupMessage" style="padding-bottom:5px;width:90%;">Processing&hellip;</p>').find("p.signupMessage").hide();
				$("p.signupMessage").show("blind", {direction: "vertical", easing: "easeOutCirc"}, 800);
				
				$.post(
					"/dyn/sendEmail.cfm", 
					{
						theName:nameValue,
						theEmail:emailValue
					}, 
					function(data)
					{
						// Do Something after data Posts
						$("p.signupMessage").remove();
						$("div.ui-effects-wrapper").remove();
						$("form#contactForm").before(data);
						$("input#contactReset").click();
						window.setTimeout(
							function()
							{
								$("p.signupMessage").hide("blind", {direction: "vertical", easing: "easeOutCirc"}, 1000, function(){$("p.signupMessage").remove();});
							}, 8000
						);
					}, 
					"html"
				);
				return false;
			}
			else
			{
				var errorMessage = "Alert:\n\n"
				if(!namePass)
				{
					errorMessage += nameAlert;
				}
				if(!emailPass)
				{
					errorMessage += emailAlert;
				}
				alert(errorMessage);
				return false;
			}
		}
	);
	
	// Validate Owner Login form
	$("form#ownerForm input#ownerSubmit").click(
		function()
		{
			// post form
				
			var nameValue = $("input#ownerName").val();
			var numValue = $("input#ownerNumber").val();
			var subValue = $("input#ownerSubject").val();
			var messValue = $("textarea#ownerMessage").val();
			
			$("form#ownerForm").before('<p class="signupMessage" style="padding-bottom:5px;width:90%;">Processing&hellip;</p>').find("p.signupMessage").hide();
			$("p.signupMessage").show("blind", {direction: "vertical", easing: "easeOutCirc"}, 800);
			
			$.post(
				"/dyn/sendOwnerEmail.cfm", 
				{
					theName:nameValue,
					theNumber:numValue,
					theSubject:subValue,
					theMessage:messValue
				}, 
				function(data)
				{
					// Do Something after data Posts
					$("p.signupMessage").remove();
					$("div.ui-effects-wrapper").remove();
					$("form#ownerForm").before(data);
					$("input#ownerReset").click();
					window.setTimeout(
						function()
						{
							$("p.signupMessage").hide("blind", {direction: "vertical", easing: "easeOutCirc"}, 1000, function(){$("p.signupMessage").remove();});
						}, 8000
					);
				}, 
				"html"
			);
			return false;
		}
	);
		
});
