;(function($, undefined) {

    
    var util = {
    /*
        // Include script, if it doesn't already exist
        registerScript: function(url, callback) {
            
            if (typeof callback != 'function') {
                throw 'Not a valid callback';
            };
            
            // We don't want to include the same script twice
            var found = false;
            var getProtocol = /^https?:/;
            $('script[src]').each(function() {
                
                if ($(this).attr('src').replace(getProtocol, '') == url.replace(getProtocol, '')) {
                    found = true;
                    return false;
                };
            
            });
            
            if (found) {
                callback.call();
                return;
            };
            
            // All good
            $.getScript(url, callback);
        
        
        },
        // Strips the url() off when you receive a background image's value
        stripBackgroundImageWrapper: function(str) {
        
            return str.replace(/^url\(["']?(.*?)["']?\)$/, '$1');
            // Stupid IDE is taking the single quote above as a delimiter. This will fix it -> '
        
        },
        */
        // Ensure a form can only be submit once
        submitOnce: function(form) {
            $(form).find('button[type=submit]').click(function() {
                $(this).prop('disabled', true );
                
                if ( ! form.valid()) {
                    $(this).prop('disabled', false);
                } else {
                    $(this).after('<div class="inline-loading">Sending… Please Wait.</div>');
                    form.submit();
                };
                         
            });
        },
        
        // Set the hash
        // http://stackoverflow.com/questions/1489624/modifying-document-location-hash-without-page-scrolling/1489802#1489802
        setHash: function(hash) {
            hash = hash.replace( /^#/, '' );
            
            if ( ! hash) {
                // A blank hash will force the browser to `_top`.
            	window.location.hash = '!';
            	return;
            }
            
            var fx, node = $( '#' + hash );
            if ( node.length ) {
              fx = $( '<div />' )
                      .css({
                          position:'absolute',
                          visibility:'hidden',
                          top: $(window).scrollTop() + 'px' 
                      })
                      .attr( 'id', hash )
                      .appendTo( document.body );
              node.attr( 'id', '' );
            }
            document.location.hash = hash;
            if ( node.length ) {
              fx.remove();
              node.attr( 'id', hash );
            }
        
        },
		
        // Empty start select
        addSelectEmptyValue: function(select) {
           select.each(function() {
              var select = $(this);
              
              var blankOption = $('<option />', { html: '', value: '' }).prependTo(select);
              select[0].selectedIndex = 0;
              
              select.focus(function() {
                 if (blankOption.length) {
                    blankOption.remove();
                 };
              })
              
              
           
           });
        }

    
    };

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  
	
	// Generic on DOM ready stuff
	$(function() {
		
  
    	// Add some classes to body for CSS hooks
    	/*	
    	// Get browser 
    	$.each($.browser, function(i) {
    	    $('body').addClass(i);
    	    return false;  
    	});
    	
    	
    	// Get OS
    	var os = [
    		'iphone',
    		'ipad',
    		'windows',
    		'mac',
    		'linux'
    	];
    	
    	var match = navigator.appVersion.toLowerCase().match(new RegExp(os.join('|')));
    	if (match) {
    	    $('body').addClass(match[0]);
    	};
    	
    	*/
    	
    	// jQuery Validation library defaults
    	
    	if ('validator' in $) {
    	
        	$.validator.setDefaults({ 
                errorPlacement: function(error, element) {
                    element.closest('.input-container').append(error);
                }
            });
        
        }
        
        // Input label for search in sidebar.
    	
    	$('#search input').inputLabel({
    		customLabel: 'Search our site:'
    	});

		// Make certain external links open in a new window.
		// Jakob Nielsen would love that.
		var validProtocols = ['http:', 'https:'];
		
		$(document.links).filter(function (){
			return $(this).parents('#content').length && $.inArray(this.protocol, validProtocols) !== -1 && this.hostname != window.location.hostname;
		}).newWindow();
		
		// Remove disabled submit buttons
		$('form button[type="submit"]:disabled').prop('disabled', false);

	});



	
			

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  


	var gallery = (function() {
		
		var ul;
		
		var init = function() {
            
            ul =  $('<ul />', { id: 'jump-to' });
            
            ul.hide();
			
			var gallery = $('#gallery'),
			     length = gallery.find('> ul > li').length;
            
            // If only one image, don't bother with gallery.
            if (length <= 1) {
                return false;
            };
            
            var hidden = $('<div />').hide().appendTo('body');
            
        	
        	for (var i = 0; i < length; i++) {
        		// Maximum thumbs to display
        		if (i > 12) {
        			break;
        		};
        		
        		// The i beneath was being bound to i and therefore always equal to the last increment
        		(function() {
        		
	        		var li = $('<li />'),
	        		    button = $('<button type="button" />', { 'html': i + 1 });
	        		
	        		button.appendTo(li);
	        		
	        		li.appendTo(ul);
	        		
	        		var index = i;
	        		
	        		if (index === 0) {
	        			li.addClass('active');
	        		}
	        		
	        		li.click(function() {
		        		hidden.find('a').eq(index).click();
	        		});
        		
        		})();
        		
        	};
        	
        	ul.insertAfter(gallery).fadeIn(500);  
            
            gallery.find('ul').cycle({ 
                fx:     'fade', 
                speed:  800, 
                timeout: 5000, 
                pager: hidden,
                updateActivePagerLink:  function(element, index) {
                	setActive(index);
                },
                pagerClick: function(index) {
                	setActive(index);
                }
            });

		};
		
		var setActive = function(index) {
        	ul
        	 .find('li')
        	  .eq(index)
        	  .addClass('active')
        	   .siblings()
        	   .removeClass('active')
        };

	
		$(init);
	
	})();

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  

	var dates = (function() {
	
		var init = function() {
    		if ( ! $('body').hasClass('dates')) {
				return;
			}
			
			var infoRows = $('#content table tr.info-row');
			
			infoRows.each(function() {
		    	$(this).find('td > *').wrapAll('<div />').parent().hide();
		    });
			
			
			
			infoRows
			 .hide()
			 .siblings()
			 .find('a')
			  .click(function(event) {
				event.preventDefault();
				
				var a = this,
				    nextTr = $(a).closest('tr').next();
				
				nextTr
				 .show()
				 .find('td > div')
				  .slideToggle(500, function() {
				  
				  	if ($(this).is(':hidden')) {
				  		nextTr.hide();

 						util.setHash('');
				  	} else {
 						util.setHash(a.hash);
				  	}
				  
				  });
				
			});
			
			// Handle hash
			var hash = window.location.hash;
			
			if (hash) {
				$(hash).prev().find('a').click();
			}
			
		};
		
		$(init);
	
	})();

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  

    
    var seminars = (function() {
        
        var init = function() {
    		 if ($('body').hasClass('seminars-events')) {
        		  $('#content table tbody a').each(function() {
        		      var href = this.href + (this.search ? '&' : '?') + 'modal=true';
        		      
        		      $(this)
        		       .fancybox({
        		          width: 700,
        		          height: 500,
        		          type: 'iframe',
        		          href: href
        		       });
        		 
        		  });
    		 
    		 
    		 } else if ($('body').hasClass('seminar-view')) {
    		 
        		  $('#content a button').click(function(e) {
        		        $(this).prop('disabled', true).closest('a').after('<div class="inline-loading">Please Wait…</div>');
        		  });
    		 
             } else if ($('body').hasClass('seminar-register')) {
    		  
    		      var form = $('#content form');
    		      
    		      util.addSelectEmptyValue(form.find('select'));
    		      
    		      form.validate({
                      rules: {
                          // Validation rules
                          'company-name': {
                              required: true
                          },
                          
                          'name': {
                              required: true
                          },
        
                          'email': {
                              required: true,
                              email: true
                          },
                          
                          'postcode': {
                            minlength: 3,
                            digits: true
                          },
                          
                          'attendance': {
                            digits: true,
                            min: 1
                          }
                         
        
                      },
                      
                       messages: {
                          'company-name': {
                              required: 'Your company name is required.'
                          },
        
                          'name': {
                              required: 'Your name is required.'
                          },
        
                          'email': {
                              email: 'Your email must be valid.'
                          },
                          
                          'postcode': 'Your postcode must be valid.',
                          
                          'attendance': 'There must be at least one person attending.'
                             
                      }
                      
                      
                  });
                  
              
                  util.submitOnce(form); 
    		 
             } else if ($('body').is('.seminar-register-complete, .modal')) {
    		 
    		    var closeButton = $('<button type="button" class="pretty">Close</button>');
    		    
    		    closeButton.appendTo('#content');
    		    
    		    closeButton.click(function() {
    		      parent.$.fancybox.close();
    		    });
    		 
             };
        };
        
        $(init);
    })();
	
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  

    var newsletter = (function() {
        var init = function() {
    		 
    		 if ( ! $('body').hasClass('subscribe-newsletter')) {
    		 	return;
    		 };
    		 
    		 var form = $('#content form');
             
    		 $.validator.addMethod('lists', function(value, elem, param) {
			    return $(elem).closest('.input-container').find(':checkbox:checked').length;
			}, 'You need to select at least one.');
			    		 
    		 form.validate({
                  rules: {
                      // Validation rules
    				  'lists[]' : {
    				  	lists: true
    				  },
                      'email': {
                          required: true,
                          email: true
                      }
                  },
                  
                   messages: {
                      
                      'email': {
                          required: 'Your email is required.',
                          email: 'Your email must be valid.'
                      }
                          
                  }
              });
              
              util.submitOnce(form); 
    
        };
        
        $(init);
    
    })();	

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  


    var contactForm = (function() {
        var init = function() {
    		 
    		 if ( ! $('body').hasClass('contact')) {
    		 	return;
    		 };
    		 
    		 var form = $('#content form');
             
             var textareasMaxLength = data.maxText;		 
    
    		 
    		 
    		 form.validate({
                  rules: {
                      // Validation rules
                      'full-name': {
                          required: true
                      },
    
                      'email': {
                          required: true,
                          email: true
                      },
                      
                      'website': {
                          required: true,
                          url: true
                      },
    
                      'enquiry': {
                          required: true,
                          maxlength: textareasMaxLength
    
                      }        
    
                  },
                  
                   messages: {
                      'full-name': {
                          required: 'Your name is required.'
                      },
    
                      'email': {
                          required: 'Your email is required.',
                          email: 'Your email must be valid.'
                      },
                      
                      'website': {
                          required: 'Your website is required.',
                          url: 'Your website must be valid.'
                      },
    
                      'enquiry': {
                          required: 'Message is required.',
                          maxlength: 'Your message is too long. Please use less than ' + textareasMaxLength + ' characters.'
    
                      }        
    
                  }
              });
              
              util.submitOnce(form); 
      
    
        };
        
        $(init);
    
    })();
    
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  
    
    

})(jQuery);
