// Check for valid email
function checkEmail(email) { 
	var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var emailVal = $("#" + email).val();
	return pattern.test(emailVal);
}

// Include a javascript file dynamically
function includeJs(jsFilePath) {
	var js = document.createElement("script");

	js.type = "text/javascript";
	js.src = jsFilePath;

	document.body.appendChild(js);
}

// If we are not in IE...
if(!ie) {
	// Include the JS file needed
	includeJs('js/eyeball.js');
}

jQuery(document).ready(function($)
{
	
	// Check if we are on the right page. Pages without a custom scrollbar
	// wont have the library included on the page
	
	if( $.fn.jScrollPane )
	{
		var box = $('.cs .box');
		if(box.length > 0) { box.jScrollPane({showArrows: true}); }
	}
	
	// Hover over to see the information
	// IE variable is set with conditional statements in the html.
	
	if( $('.panel').length > 0 && ie == false )
	{
		// Create the top images. We only want to do this if javascript is enabled in the first place
		// so we can always see the info no matter what browser is viewing.
		$('.panel-one h1').before('<div class="panel-hover panel-one-hover"></div>');
		$('.panel-two h1').before('<div class="panel-hover panel-two-hover"></div>');
		$('.panel-three h1').before('<div class="panel-hover panel-three-hover"></div>');
		$('.panel-four h1').before('<div class="panel-hover panel-four-hover"></div>');
		
		var panel = $('.panel-hover');
		
		panel.hover(function(){
			//console.info('hover panel:'+$(this).attr('class'));
			$(this).animate({opacity: 0}, 500);
		}, function(){
			//console.info('out panel:'+$(this).attr('class'));
			$(this).stop(true,true).animate({opacity: 1}, 500);
		});
		
	}
	
	// Same with the gallery as above.
	
	if( $.fn.galleriffic )
	{
		
		// We only want these styles applied when javascript is enabled
		$('div.content').css('display', 'block');
		
		// Initially set opacity on thumbs and add
		// additional styling for hover effect on thumbs
		var onMouseOutOpacity = 0.67;
		
		$('#thumbs ul.thumbs li').opacityrollover({
			mouseOutOpacity:   onMouseOutOpacity,
			mouseOverOpacity:  1.0,
			fadeSpeed:         'fast',
			exemptionSelector: '.selected'
		});
		
		// Initialize Advanced Galleriffic Gallery
		gallery = $('#thumbs').galleriffic({
			delay:                     2500,
			numThumbs:                 15,
			preloadAhead:              15,
			enableTopPager:            false,
			enableBottomPager:         false,
			imageContainerSel:         '#slideshow',
			controlsContainerSel:      '#controls',
			captionContainerSel:       '#caption',
			loadingContainerSel:       '#loading',
			renderSSControls:          true,
			renderNavControls:         false,
			playLinkText:              'Play Slideshow',
			pauseLinkText:             'Pause Slideshow',
			prevLinkText:              '&lsaquo; Previous Photo',
			nextLinkText:              'Next Photo &rsaquo;',
			nextPageLinkText:          'Next &rsaquo;',
			prevPageLinkText:          '&lsaquo; Prev',
			enableHistory:             false,
			autoStart:                 false,
			syncTransitions:           true,
			defaultTransitionDuration: 900,
			onSlideChange:             function(prevIndex, nextIndex) {
				// 'this' refers to the gallery, which is an extension of $('#thumbs')
				this.find('ul.thumbs').children()
					.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
					.eq(nextIndex).fadeTo('fast', 1.0);

				// Update the photo index display
				this.$captionContainer.find('div.photo-index')
					.html('Photo '+ (nextIndex+1) +' of '+ this.data.length);
			},
			onPageTransitionOut:       function(callback) {
				this.fadeTo('fast', 0.0, callback);
			},
			onPageTransitionIn:        function() {
				var prevPageLink = this.find('a.prev').css('visibility', 'hidden');
				var nextPageLink = this.find('a.next').css('visibility', 'hidden');
				
				// Show appropriate next / prev page links
				if (this.displayedPage > 0)
					prevPageLink.css('visibility', 'visible');

				var lastPage = this.getNumPages() - 1;
				if (this.displayedPage < lastPage)
					nextPageLink.css('visibility', 'visible');

				this.fadeTo('fast', 1.0);
			},
			onImageAdded:              function(imageData, $li) {
				$li.opacityrollover({
					mouseOutOpacity:   onMouseOutOpacity,
					mouseOverOpacity:  1.0,
					fadeSpeed:         'fast',
					exemptionSelector: '.selected'
				});
			}
		});
		
		/**************** Event handlers for custom next / prev page links **********************/

		//gallery.find('a.prev').click(function(e) {
		$('a.prev').click(function(e) {
			gallery.previousPage();
			e.preventDefault();
		});

		//gallery.find('a.next').click(function(e) {
		$('a.next').click(function(e) {
			gallery.nextPage();
			e.preventDefault();
		});

		/****************************************************************************************/
		
		/* Adding and removing new galleries dynamically */
		
		var newGallery;
		var thisSelection;
		var c = 0;
		var oldImgCount = 0;
		var newImgCount = 0;
		
		$('.gallery-select a').click(function(e) {
			
			// Instead of return false
			e.preventDefault();
			
			// Run loading animation function
			$('.load-page').remove();
			menuIndex = $(this).parent().index();
			interval = setInterval('runLoader()',500);
			
			// Store the new selection
			thisSelection = $(this);
			
			// Store the new gallery html
			newGallery = $(".extra-galleries ."+ thisSelection.attr('class') +" li");
			
			// Grab the length of both
			oldImgCount = $('ul.thumbs li').length;
			newImgCount = newGallery.length;
			
			// First we need to insert the new images. Galleriffic will fade out while it is adding and deleting images.
			// If we remove all the images first, then insert the new ones, galleriffic will break. So do the opposite
			newGallery.each(function(i){ gallery.insertImage('<li>'+ $(this).html() +'</li>',0); });
			
			// Remove all the old images. By counting the amount of new items in the new gallery, we can use that as
			// our index and start removing from that point, effectively removing all the old images.
			for(c = oldImgCount; c > 0; c--) { gallery.removeImageByIndex(newImgCount); }
			
			// Remove selected class
			$('.selected-gallery').removeClass('selected-gallery');
			
			// Make new selection selected
			thisSelection.addClass('selected-gallery');
			
		});
	}
	
	
	// Campaign Monitor signup form
	
	if( $('#subForm').length > 0 )
	{
		// If the field is still on the default value, then remove it for easier adding
		$('#subForm #qdidjj-qdidjj').focus(function(){
			if($(this).attr('value') == 'email address...') {
				$(this).attr('value','');
			}
		});
		
		$('#subForm').submit(function(e) {
		  e.preventDefault();
			
		  // Grab form action
		  var formAction = this.action;
		  
		  // Hacking together id for email field
		  // Replace the xxxxx below:
		  // If your form action were http://mysiteaddress.createsend.com/t/r/s/abcde/, then you'd enter "abcde" below
		  var id = "qdidjj";
		  var emailId = id + "-" + id;
		  
		  // Validate email address with regex
		  if (!checkEmail(emailId)) {
			alert("Please enter a valid email address");
			return;
		  }
		  
		  // Serialize form values to be submitted with POST
		  var str = $(this).serialize();
		  
		  // Add form action to end of serialized data
		  // CDATA is used to avoid validation errors
		  //<![CDATA[
		  var serialized = str + "&action=" + formAction;
		  // ]]>
		  
		  // Submit the form via ajax
		  $.ajax({
			url: "php/cm.php",
			type: "POST",
			data: serialized,
			dataType: 'html',
			success: function(data){
			  // Server-side validation
			  if (data.search(/invalid/i) != -1) {
				alert('The email address you supplied is invalid and needs to be fixed before you can subscribe.');
			  }
			  else
			  {
				var $confirmation = $('#confirmation');
				$("#theForm").hide(); // If successfully submitted hides the form
				$confirmation.slideDown("slow");  // Shows "Thanks for subscribing" div
				$confirmation.prop('tabIndex', -1);
				$confirmation.focus(); // For screen reader accessibility
				// Fire off Google Analytics fake pageview
				var pageTracker = _gat._getTracker("UA-20045447-1");
				pageTracker._trackPageview("/newsletter_signup");
			  }
			}
		  });
		});
	}
	
	
	// Question form
	
	if( $('#questionForm').length > 0 )
	{
		var questionDataString;
		var formO = $('#questionForm');
		
		formO.validate({
			errorElement: "em",
			errorPlacement: function(error, element) {
				// Put error inside label
				error.appendTo( $('#label_'+element.attr("id")) );
			},
			submitHandler: function() {
				
				questionDataString = formO.serialize();
				
				$.ajax({
					type: "POST",
					url: "php/contact_poster.php",
					data: questionDataString + "&ajax=true",
					success: function() {
						
						formO.html("<div id='message'></div>");
						formO.find('#message').html("<br /><br /><h1>Question Sent</h1>")
						.append("<p><small>Thank you for your message. <br />We'll get back to you as quick as we can!</small></p>")
						.hide()
						.fadeIn('slow');
					}
				});
				
			},
			rules: {
				q_name: "required",
				q_email: {required:true, email:true},
				q_question: "required"
			}
		});
	}
	
	
	// Contact form
	
	if( $('#contactForm').length > 0 )
	{
		var contactDataString;
		var formcO = $('#contactForm');
		
		formcO.validate({
			errorElement: "em",
			errorPlacement: function(error, element) {
				// Put error inside label
				error.appendTo( $('#label_'+element.attr("id")) );
			},
			submitHandler: function() {
				
				contactDataString = formcO.serialize();
				
				$.ajax({
					type: "POST",
					url: "php/contact_poster.php",
					data: contactDataString + "&ajax=true",
					success: function() {
						
						formcO.html("<div id='message'></div>");
						formcO.find('#message').html("<br /><br /><h1>Quote Sent</h1>")
						.append("<p><small>Thank you for your message. <br />We'll get back to you as quick as we can!</small></p>")
						.hide()
						.fadeIn('slow');
					}
				});
				
			},
			rules: {
				r_company_name: "required",
				r_full_name: "required",
				r_email: {required:true, email:true},
				r_phone: {required:true, number:true},
				r_required_job: "required"
			}
		});
	}
	
});

// Global Gallery object
var gallery = $('#thumbs');
var galleryInterval;

// Custom loader for the gallery
var l_thumbs = $('#thumbs');
var l_object;
var interval;
var menuIndex;
function runLoader()
{
	// The gallery lowers the opacity to 0 while images are being loaded.
	// Check for that here every .5 of a second. If the opacity is back to one,
	// all images are loaded and visible. Which just means fading the loading image
	// in and out!
	if(l_thumbs.css('opacity') < 0.3) {
		//console.log('Loading images..');
		// Run loader
		l_object = $('.gallery-select li').eq(menuIndex);
		
		if(l_object.find('.load-page').length == 0 ) {
			l_object.append('<div class="load-page"><img src="images/ajax-loader.gif" alt ="" /></div>').
			find('.load-page', this).
			fadeIn('fast');
		}
		
	} else {
		if(l_object.find('.load-page').length > 0) {
			//console.info('Loading done.');
			clearInterval(interval);
			//gallery.previousPage().gotoIndex(0);
			gallery.previousPage();
			l_object.find('.load-page').fadeOut('fast',function(){ $(this).remove(); });
		}
	}
}
