Array.max = function( array ){  return Math.max.apply( Math, array ); };

$.localScroll({
	easing:'easeInOutQuint'
});

$('.twitter-box ul').rotate({ timeout : 5000});


/*
var $html = $('html,body');
// How many pixels to scroll
var scrollHeight = 250;

if ($.browser.msie) {
    $('body').mousewheel(function(event, delta) {
    	currentDelta = delta;
        // disable native scroll
        if(event.preventDefault) {
            event.preventDefault();
        } else { // IE fix
            event.returnValue = false;
        };
        $html.stop().animate({
            scrollTop: $html.scrollTop() + (-delta * scrollHeight)
        }, 'slow');
    });
}
*/

/**
 * Dropdown menu toggler
 *
 * Inserts click toggle for menu
 * Author: Pete Luffman
 * www.merchantmarketinggroup.com
 */
 
var dropdownToggle = function(){
	
	var $dropdowns = $('.dropdown');
  	var $toggle = $('.dropdown-toggle', $dropdowns);
  	
  	$('> div', $dropdowns).css({ opacity: 0, display: 'none' });
  	
  	$toggle
  		.click(function(e){
  			var $el = $(this);
  			var $navItem = $el.parent();
  			var $dropdown =  $('> div', $navItem);
  			
  			if(!$navItem.hasClass('dropdown-open')){
				dropdown.open($dropdown);
			} else {
				dropdown.close($dropdown);
			}
  			
  			e.stopPropagation();
  			e.preventDefault();
  		});
  	
  	$('li', $dropdowns)
  		.click(function(e){
  			window.location = $(this).find("a").first().attr("href");
  			return false;
  		});
  	
  	$('body').click(function(){  
  		var $openDropdown = $dropdowns.filter('.dropdown-open').find('> div');
    	dropdown.close($openDropdown);
    });
    
    var dropdown = {
    	open : function($el){
    	
    		this.close($dropdowns.filter('.dropdown-open').find('> div'));
    		
    		$el
    			.css({display:'block'})
				.animate({ top: 25, opacity: 1 }, 150, function(){
					$el
						.css({opacity:''})
						.parent()
						.addClass('dropdown-open');
				});
    	},
    	close : function($el){
    		$el
    			.animate({ top: 5, opacity: 0 }, 150, function(){
					$el
						.css({display:'none'})
						.parent()
						.removeClass('dropdown-open');
				});
    	}
    };
}();


/**
 * Isotope client list
 *
 * Author: Pete Luffman
 * www.merchantmarketinggroup.com
 */
 
var clientlist = function(){
	
	var isoTime = 800;
	var $clients = $('.client-list');
	var $filters = $('#client-list-filters a');	
  
	$clients.isotope({
	  itemSelector : '.item',
	  layoutMode : 'fitRows',
	  animationOptions: {
	    duration: isoTime
	  }
	});
	
	$filters.click(function(e){
		
		e.preventDefault();
		
		var $el = $(this);
		var selector = $el.attr('data-filter');
		
		$clients.isotope({ filter: selector });
		
		setTimeout(callback, isoTime);

		$filters.removeClass('active');
		$el.addClass('active');
	});
	
	var callback = function(){ $('li:not(.isotope-hidden)', $clients).css({ opacity : '' }); };
}();


/**
 * Scrolling showcase
 * Requires jQuery.LocalScroll http://flesler.blogspot.com
 *
 * Author: Pete Luffman
 * www.merchantmarketinggroup.com
 */
 
 
var showcase = function(){
	
	var $nav = $('.work-showcase-nav');
	var $navItems = $('a', $nav);
	var $target = $('.work-showcase-items');
	
	$navItems
		.unbind() // Remove any event handlers
		.eq(0)
		.parent()
		.addClass('active');
	
	$nav.localScroll({ 
		target: $target,
		easing:'easeInOutQuint',  
		duration:1000,
		onBefore: function(el, el2){
			$navItems.parent().removeClass('active');
			$(el.currentTarget).parent().addClass('active');
		}
	});
}();


/**
 * Formfield label placeholder
 *
 * Author: Pete Luffman
 * www.merchantmarketinggroup.com
 */
 
var searchLabel = function(){

	var $input = $('.search-field');
	
	$input.each(function(){
		
		var $el = $(this);
		var $label = $('label[for="' + $el.attr('id') + '"]');
		
		$input.bind({
			focus : function(e){
				if($el.val() === '') $label.animate({ opacity : 0.5 }, 100);
			},
			blur : function(e){
				if($el.val() === '') $label.animate({ opacity : 1 }, 100);
			},
			keypress : function(e){
				if($el.val() === '') $label.animate({ opacity : 0 }, 100);
			}
		});
	});
}();


/**
 * Gallery Filter
 * Builds drop down lists for filtering the gallery page
 *
 * Author: Dave Essery 
 * www.merchantmarketinggroup.com
 */
 

//function to upper case the first letter of each word
String.prototype.capitalize = function() {
	var words = this.split(' ');
	
	for (var i=0; i < words.length; i++) 
	{
		var word = words[i];
		words[i] = word.charAt(0).toUpperCase() + word.slice(1);
	};
	
    return words.join(' ');
}

var galleryFilter = function(){

	var $filters = $('.filter-dropdown');
	var $filterLists = $('.link-list', $filters);
	var $container = $('.gallery ul');
	var $items = $('li', $container);

	
	var isoTime = 800;	
	var callback = function(){ $('li:not(.isotope-hidden)', $container).css({ opacity : '' }); };
	
	$container.isotope({
		itemSelector : '.item',
		resizable: false,
		masonry: {
			columnWidth: $container.width() / 4
		},
		animationOptions: {
			duration: isoTime
		}
	});
	
	$(window).smartresize(function(){
		$container.isotope({
			masonry: { columnWidth: $container.width() / 4 } // update columnWidth to a percentage of container width
		});
	});
	
	$('.item-hover', $container).css({opacity:0});
	
	$('a', $container).hover(
		function(){
			$('.item-hover', this).stop().show().animate({opacity:1}, 500);
		},
		function(){
			$('.item-hover', this).stop().animate({opacity:0}, 500, function(){$(this).hide()});
		}
	);
	
	$('a', $filterLists).click(function(e){
		
		e.preventDefault();
		
		var $el = $(this);
		// get href attr, remove leading #
		var href = $el.attr('href').replace( /^#/, '' ),
			// convert href into object
     		// i.e. 'filter=.inner-transition' -> { filter: '.inner-transition' }
     		option = $.deparam( href, true );
		
		// set hash, triggers hashchange on window
 		 $.bbq.pushState( option );
		
		setTimeout(callback, isoTime);

		$filters.removeClass('active');
		$el.addClass('active');
	});
	
	
	$(window).bind( 'hashchange', function( event ){
		// get options object from hash
		var hashOptions = $.deparam.fragment();
		// apply options from hash
		$container.isotope( hashOptions );
	})
	.trigger('hashchange'); // trigger hashchange to capture any hash data on init	
		
};

if($('.filter-work').length > 0) galleryFilter();


 

/**
 * Dropdown filtering
 *
 * Author: Pete Luffman
 * www.merchantmarketinggroup.com
 */
 

var dropdownFilter = function(){

	var $filters = $('.filter-dropdown');
	var $filterLists = $('.link-list', $filters);
	var heights = $filterLists.map(function(idx, el) { return $(this).outerHeight(); }).get();
	var origHeight = Array.max(heights);
	var isOpen = false;
	var duration = 500;

	$filterLists.css({ height: 0, opacity: 0 });

	$('h3, a', $filters).click(function(){
		
		if(!isOpen) {
			$filterLists
				.stop()
				.animate({ height: origHeight, opacity:1 }, duration, function(){ isOpen = true });
		} else {
			$filterLists
				.stop()
				.animate({ height: 0, opacity: 0 }, duration, function(){ isOpen = false });
		}
		
	});
}();

 
 
/**
 * Fixed position float
 *
 * Author: Pete Luffman
 * www.merchantmarketinggroup.com
 */
 
var fixedFloat = function(){

	var $article = $('.blog-article article');
	
	if($article.length) {
		var $content = $('section', $article);
		var $sideCol = $('.sidecol', $article);
		var $aside = $('aside', $sideCol);
		
		var offset = 120;
		var contentH = $content.height();
		var asideH = $aside.outerHeight(true);
		var top = $sideCol.offset().top - offset;
		var bottom = $sideCol.offset().top + contentH - offset;
		
		$sideCol.height(contentH);
		
		$(window).scroll(function (event) {
	
			var y = $(this).scrollTop();
	
			// Check if we're below the fold
			if ( (y >= top) && ((y + asideH) <= bottom) ) {
	
				$aside.css({
					position : 'fixed',
					top: offset,
					bottom: ''
				});
			
			} else if ((y + asideH) >= bottom) { 
				
				$aside.css({
					position : 'absolute',
					bottom: 0,
					top: ''
				});
				
			} else {
				// Reset position
				$aside.css({
					position : 'absolute',
					top: 0,
					bottom: ''
				});
			}
		});
	}
	
}();



/**
 * Parallax Scrolling
 *   
 * Author: Richard Shepherd
 * 		   www.richardshepherd.com
 * 		   @richardshepherd   
 *
 * Enhanced and extended by Pete Luffman 
 * www.merchantmarketinggroup.com
 */

var story = function(){
						
	// Cache objects
	var $window = $(window);
	var $container = $('.parallax');
	var $sections = $('> section', $container);
	var $captionBar = $('.caption-container', $container);
	var $captionPlaceholder = $('.caption', $captionBar);
	var $captions = $('.caption', $sections);
	var $csBttn = $('.case-study-button', $captionBar);
	var captionArr = [];
	var isUnsupported = $.browser.msie && parseInt($.browser.version) == 6 || Modernizr.touch;
	
	// Disable parallax if one slide
	if($sections.length == 1 && $('#case-study').length > 0) return false;
	 
	if(!isUnsupported) {
		$container.removeClass('parallax-disabled');
		
		// Cache the Y offset and the speed of each sprite
		$('[data-type]').each(function() {	
			$(this).data('offsetY', $(this).attr('data-offsetY'));
			$(this).data('Xposition', $(this).attr('data-Xposition'));
			$(this).data('speed', $(this).attr('data-speed'));
			$(this).data('title', $(this).attr('data-title'));
		}).css('background-attachment' , 'fixed');
	}
	
	/**
	* Create navigation
	*/
	
	var $nav = $('<ul class="ui-element story-nav" />').bind('slideChanged', function(e, index) {
			// Set pagination active state
			$('li',$nav)
				.eq(index)
				.addClass('active')
				.siblings()
				.removeClass('active');
		});
	
	/**
	* Dynamic captions
	*/
	
	captionArr = $captions.map(function() { return $(this).html(); });
	
	$captions.remove();

	$container.bind('slideChanged', function(e, index) {
		
		var caption = captionArr[index];
		var fadeSpeed = 250;

		if(index < captionArr.length) {
			
			$captionPlaceholder.html(caption);

			$captionPlaceholder.stop(true).css({visibility:'visible'}).animate({opacity:1}, fadeSpeed);
			$csBttn.stop(true).css({visibility:'visible'}).animate({opacity:1}, fadeSpeed);

		} else {
			
			$captionPlaceholder.stop().animate({opacity:0}, fadeSpeed, function(){ $(this).css({visibility:'hidden'}); });
			$csBttn.stop().animate({opacity:0}, fadeSpeed, function(){ $(this).css({visibility:'hidden'}); });
		}
	});
	
	var createNavItem = function(title){
		var $slideTitle = $('<div class="ui-bubble-tooltip">' + title + '<span></span></div>').hide().css({ opacity : 0 });
		var animSpeed = jQuery.support.opacity ? 150 : 0;	
		
		$('<li/>')
			.append($slideTitle)
			.click(function(){ 
				var index = $('li', $nav).index($(this));
				scrollToSlide(index);
			})
			.hover(
				function(e){ $slideTitle.show().animate({ right: 31, opacity: 1 }, animSpeed);	},
				function(e){ $slideTitle.animate({ right: 21, opacity: 0 }, animSpeed, function(){$(this).hide();}); }
			)
			.appendTo($nav);
	};
	
	var scrollToSlide = function(index){
		
		var $slide = $sections.eq(index);
		var target = getTarget($slide);
		
		$.scrollTo(target.element, 1000, { 
			offset: target.offset, 
			onAfter: function(){ 
				$nav.trigger('slideChanged', [index]); 
			},
			easing:'easeInOutQuint'
		});
	};
	
	var getTarget = function($slide){
		var target = {
			element: $('.content', $slide),
			offset: 0
		};
		
		if(target.element.length) { // Is content block
			target.offset = (-($window.height() - target.element.height()) / 2)  - 30;
		} else {
			target.element = $slide;
		}
		
		return target;
	};
	
	/**
	* Enable sections
	*/
				
	$sections.each(function(){
	
		// Store some variables based on where we are
		var $self = $(this),
			offsetCoords = $self.offset(),
			topOffset = offsetCoords.top,
			bottomOffset = topOffset + $self.height(),
			index = $sections.index($self);

		function calculateYPos(el) {
		
			// Scroll the background at var speed, the yPos is a negative value because we're scrolling it UP!	
			var yPos = -(($window.scrollTop() - (index * $self.height())) / el.data('speed'));
			var offsetY = el.data('offsetY');
			
			if(offsetY) {
				// If this element has a Y offset then add it on
				if (offsetY === 'bottom') {
					yPos -= 1750 - $window.height();
				} else {
					yPos += parseInt(offsetY);
				}
			}
					
			return yPos;
		};
		
	    $window.scroll(function() {
			
			var scrollBottom = $window.scrollTop() + $window.height();
			
			// If supported browser, move the background
			if (!isUnsupported) { 
			
				// If this section is in view
				if ( scrollBottom > topOffset && bottomOffset > $window.scrollTop() ) {
					 
					// Put together our final background position
					var coords = '50% '+ calculateYPos($self) + 'px';
	
					$self.css({ backgroundPosition: coords });
					
					// Check for other sprites in this section	
					$('[data-type="sprite"]', $self).each(function() {
						
						var $sprite = $(this);
						var yPos;
	
						if(index === 0) {
							yPos = calculateYPos($sprite);
								
						} else {
							yPos = calculateYPos($sprite) + ($window.height() / 2);
						}
						
						var coords = $sprite.data('Xposition') + ' ' + yPos + 'px';
						
						$sprite.css({ backgroundPosition: coords });													
					}); 
				};
			}
			
			if (scrollBottom > topOffset && scrollBottom < bottomOffset) {
				
				// Update nav position
				$nav.trigger('slideChanged', [index]);	
				
				// Update caption
				$container.trigger('slideChanged', [index]);	
			};

		});
		
		createNavItem($self.data('title'));
	});
	
	$('body').append($nav);
	
	//negative margin based off element height - 44 offset to account for heading
	$nav.css('margin-top', '-' + (($nav.height() / 2) -44) + 'px');
	
	$window.resize(function(){$window.scroll()}).scroll();
};

if($('.parallax').length > 0) story();



/**
 * Ajax Request
 * For Category Filter (Custom Module)
 *
 * Author: Dave Essery 
 * www.merchantmarketinggroup.com
 */

var ajax_filter =  {
	
	settings : {
		filters : '#category_filter',
		more : '#load_more',
		container : '.blog-list',		
		default_path : '/index.php/news/ajax'
	},
	
	init : function() {		
		var settings = this.settings,
			$filters = $(settings.filters);			
					
		$filters.find('fieldset').append('<input type="hidden" name="ajax" value="true" />');
			
		$('.category-list a, #category_filter .link-list a').live('click', function(e){
			var path = $(this).attr('href');	
			$('input[name=path]', $filters).val(path);
			$('input[name=search]', $filters).val('');
			ajax_filter.post(settings.filters, path);
			e.preventDefault();
		});
		
		$('input', $filters).focus(function(){
			$(this).keydown(function(e){
				if(event.keyCode == '13') {
					ajax_filter.post(settings.filters, settings.default_path);
					e.preventDefault();
				}
			});		
		});	
		
		$('button[type=submit]').click(function(e){
			ajax_filter.post(settings.filters, settings.default_path);
			e.preventDefault();
		});
		
		$more = $(settings.more);
		
		if($more) {
			$offset = $('input[name=offset]', $more);			
			if(!$offset.val()) {				
				$('fieldset', $more).prepend('<input type="hidden" name="offset" value="' + $('article').length + '" />');	
			}		
			$('input[name=limit]', $more).remove();		
			$('button', $more).live('click', function(e){
				ajax_filter.post(settings.more, $('input[name=path]', $filters).val());
				return false;
			});
		}		
	},
	
	post : function(form, path) {
		
		var settings = this.settings,
			$filters = $(settings.filters),
			$container = $(settings.container),
			$form = $(form),
			data = $form.serializeArray();
	
		if(path == '') {
			path = settings.default_path;
		}
		else {
			path = path.replace('filter', 'ajax');
		}
		
		$.ajax({
			type: "POST",
			url: path,
			data: data,
			dataType: 'html',
			success: function(data) {
			    if(form == settings.filters) {
					$container.find('article:not(:first)').remove();
					$container.find(settings.more).remove();
					$container.find('article').replaceWith(innerShiv(data));
				}
				else {
					$container.find(settings.more).replaceWith(innerShiv(data));
				}
			  },
			error: function(request, status, error) {
				alert('Sorry, no results could be found at this time.')
			}
		});
	}
	
}

if($('#category_filter').length)  ajax_filter.init();


/**
 * Form Validation
 * http://rocketsquared.com/wiki/Plugins/Validation
 */

$("#freeform").validate();


/**
 * Ajax File Uploader
 *
 * http://valums.com/ajax-upload/
 */

var AjaxFileUploader = function() {
	var uploader = new qq.FileUploader({
	    // pass the dom node (ex. $(selector)[0] for jQuery users)
	    element: document.getElementById('file-uploader'),
	    // path to server-side upload script
	    action: '/client-area/upload_ajax',
		debug: false,
		params: {
	        folder: $('#folder').val(),
			member: $('#member').val(),
			contact: $('#contact').val()
	    },
	    template: '<div class="qq-uploader">' + 
               		 '<div class="qq-upload-drop-area"><span>Drag and drop files here to upload</span></div>' +
		             '<div class="qq-upload-button"><button>Select file(s) manually</button></div>' +
		             '<ul class="qq-upload-list sand"></ul>' + 
		          '</div>'
	});
}

if($('#file-uploader').length) AjaxFileUploader();
