// page init
$(function(){
	ieHover('#nav li, div > div');
	initFormValidation();
	initOpenClose();
	initParralax();
	initTooltips();
	initAccordion();
});

// twitter status rendering
getTwitters('tweet', {
	id: 'heroofcharacter',
	count: 1,
	enableLinks: true,
	ignoreReplies: true,
	clearContents: true,
	template: '"%text%" <a href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'
});

// form validation
function initFormValidation() {
	var _easing = 'easeOutExpo';
	var _animSpeed = 850;

	var _errorClass = 'error';
	var _regEmail = /^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$/;

	$('form.validate-form').each(function(){
		var _form = $(this);
		function checkFields() {
			var _flag = false;
			_form.find('.'+_errorClass).removeClass(_errorClass);

			// email validation
			_form.find('input.required-email').each(function(){
				if(!_regEmail.test($(this).val())) addError($(this));
			});
			// radios validation
			var _radioflag = false;
			_form.find('input.valradio').each(function(){
				if($(this).is(':checked')) _radioflag = true;
			});
			if(!_radioflag) addError(_form.find('input.valradio').eq(0).parent())
			// inputs validation
			_form.find('input.required, textarea.required').each(function(){
				if(!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this));
			});
			// password validation
			var _password = null
			_form.find('input.validate-password').each(function(){
				if(!$(this).val().length || $(this).val().length < 4 || $(this).val().indexOf(' ')!=-1) addError($(this));
				if(!_password) _password = $(this).val();
				else if(_password != $(this).val()) addError($(this));
			});
			// validate date
			_form.find('input.month, input.day, input.year').each(function(){
				if(!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this).parents('ul.birthday-holder'));
			});

			// error class adding
			function addError(_obj) {
				_obj.parents('li').addClass(_errorClass);
				_flag=true;
			}
			return _flag;
		}

		// dd/mm/yyyy control
		_form.find('input.month, input.day, input.year').each(function(){
			$(this).keypress(function(e){
				if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) return false;
			});
		})

		// catch form submit event
		_form.submit(function(){
			if(checkFields()) {
				$.scrollTo(_form, _animSpeed, {easing:_easing});
				return false;
			}
		});
	});
}

// hover for IE
function ieHover(_list) {
	if ($.browser.msie && $.browser.version < 7) {
		$(_list).hover(function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
		});
	}
}

// accordion function
function initAccordion() {
	var _activeClass = 'active';
	var _slideSpeed = 500;

	$('ul.accordion').each(function(){
		var _accordion = $(this);
		var _items = _accordion.find('li:has(div)');
		_items.each(function(){
			var _holder = $(this);
			var _opener = _holder.find('>a.opener');
			var _slider = _holder.find('>div.slide');

			_opener.click(function(){
				var _levelItems = _holder.parent().children(':has(div)').not(_holder);

				if(_holder.hasClass(_activeClass)) {
					_slider.slideUp(_slideSpeed,function(){
						_holder.removeClass(_activeClass);
					});
				} else {
					_holder.addClass(_activeClass);
					_slider.slideDown(_slideSpeed);

					// collapse others
					_levelItems.find('>div.slide:visible').slideUp(_slideSpeed,function(){
						_levelItems.removeClass(_activeClass);
					})
				}
				return false;
			});

			if(_holder.hasClass(_activeClass)) _slider.show();
			else _slider.hide();
		});
	});
}

// tooltips function
function initTooltips() {
	var _fadeSpeed = ($.browser.msie ? 0 : 250);

	$('.generous-images ul li, ul.logos li').each(function(){
		var _opener = $(this);
		var _tooltip = _opener.find('div.tooltip').hide();

		_opener.hover(function(){
			_tooltip.fadeIn(_fadeSpeed)
		},function(){
			_tooltip.fadeOut(_fadeSpeed)
		});

	});
}

// parralax init
function initParralax() {
	$('#parralax').jparallax({});
}

// open-close init
function initOpenClose() {
	var _activeClass = 'open';
	$('div.text').each(function(){
		var _holder = $(this);
		var _opener = _holder.find('a.opener');
		_opener.click(function(){
			if(_holder.hasClass(_activeClass)) _holder.removeClass(_activeClass);
			else _holder.addClass(_activeClass);
			return false;
		})
	});
}

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery. Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*/
jQuery.easing.jswing=jQuery.easing.swing;jQuery.extend(jQuery.easing,{def:"easeOutQuad",swing:function(e,f,a,h,g){return jQuery.easing[jQuery.easing.def](e,f,a,h,g)},easeInQuad:function(e,f,a,h,g){return h*(f/=g)*f+a},easeOutQuad:function(e,f,a,h,g){return -h*(f/=g)*(f-2)+a},easeInOutQuad:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f+a}return -h/2*((--f)*(f-2)-1)+a},easeInCubic:function(e,f,a,h,g){return h*(f/=g)*f*f+a},easeOutCubic:function(e,f,a,h,g){return h*((f=f/g-1)*f*f+1)+a},easeInOutCubic:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f+a}return h/2*((f-=2)*f*f+2)+a},easeInQuart:function(e,f,a,h,g){return h*(f/=g)*f*f*f+a},easeOutQuart:function(e,f,a,h,g){return -h*((f=f/g-1)*f*f*f-1)+a},easeInOutQuart:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f+a}return -h/2*((f-=2)*f*f*f-2)+a},easeInQuint:function(e,f,a,h,g){return h*(f/=g)*f*f*f*f+a},easeOutQuint:function(e,f,a,h,g){return h*((f=f/g-1)*f*f*f*f+1)+a},easeInOutQuint:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f*f+a}return h/2*((f-=2)*f*f*f*f+2)+a},easeInSine:function(e,f,a,h,g){return -h*Math.cos(f/g*(Math.PI/2))+h+a},easeOutSine:function(e,f,a,h,g){return h*Math.sin(f/g*(Math.PI/2))+a},easeInOutSine:function(e,f,a,h,g){return -h/2*(Math.cos(Math.PI*f/g)-1)+a},easeInExpo:function(e,f,a,h,g){return(f==0)?a:h*Math.pow(2,10*(f/g-1))+a},easeOutExpo:function(e,f,a,h,g){return(f==g)?a+h:h*(-Math.pow(2,-10*f/g)+1)+a},easeInOutExpo:function(e,f,a,h,g){if(f==0){return a}if(f==g){return a+h}if((f/=g/2)<1){return h/2*Math.pow(2,10*(f-1))+a}return h/2*(-Math.pow(2,-10*--f)+2)+a},easeInCirc:function(e,f,a,h,g){return -h*(Math.sqrt(1-(f/=g)*f)-1)+a},easeOutCirc:function(e,f,a,h,g){return h*Math.sqrt(1-(f=f/g-1)*f)+a},easeInOutCirc:function(e,f,a,h,g){if((f/=g/2)<1){return -h/2*(Math.sqrt(1-f*f)-1)+a}return h/2*(Math.sqrt(1-(f-=2)*f)+1)+a},easeInElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return -(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e},easeOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return g*Math.pow(2,-10*h)*Math.sin((h*k-i)*(2*Math.PI)/j)+l+e},easeInOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k/2)==2){return e+l}if(!j){j=k*(0.3*1.5)}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}if(h<1){return -0.5*(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e}return g*Math.pow(2,-10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j)*0.5+l+e},easeInBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*(f/=h)*f*((g+1)*f-g)+a},easeOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*((f=f/h-1)*f*((g+1)*f+g)+1)+a},easeInOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}if((f/=h/2)<1){return i/2*(f*f*(((g*=(1.525))+1)*f-g))+a}return i/2*((f-=2)*f*(((g*=(1.525))+1)*f+g)+2)+a},easeInBounce:function(e,f,a,h,g){return h-jQuery.easing.easeOutBounce(e,g-f,0,h,g)+a},easeOutBounce:function(e,f,a,h,g){if((f/=g)<(1/2.75)){return h*(7.5625*f*f)+a}else{if(f<(2/2.75)){return h*(7.5625*(f-=(1.5/2.75))*f+0.75)+a}else{if(f<(2.5/2.75)){return h*(7.5625*(f-=(2.25/2.75))*f+0.9375)+a}else{return h*(7.5625*(f-=(2.625/2.75))*f+0.984375)+a}}}},easeInOutBounce:function(e,f,a,h,g){if(f<g/2){return jQuery.easing.easeInBounce(e,f*2,0,h,g)*0.5+a}return jQuery.easing.easeOutBounce(e,f*2-g,0,h,g)*0.5+h*0.5+a}});

// jquery.jparallax.js
// 0.9.1
// Stephen Band
//
// Dependencies:
// jQuery 1.2.6 (jquery.com)
//
// Project and documentation site:
// http://webdev.stephband.info/parallax.html


// CLOSURE

(function(jQuery) {


// PRIVATE FUNCTIONS

function stripFiletype(ref) {
  var x=ref.replace('.html', '');
  return x.replace('#', '');
}

function initOrigin(l) {
  if (l.xorigin=='left')	{l.xorigin=0;}	else if (l.xorigin=='middle' || l.xorigin=='centre' || l.xorigin=='center')	{l.xorigin=0.5;}	else if (l.xorigin=='right')	{l.xorigin=1;}
  if (l.yorigin=='top')		{l.yorigin=0;}	else if (l.yorigin=='middle' || l.yorigin=='centre' || l.yorigin=='center')	{l.yorigin=0.5;}	else if (l.yorigin=='bottom')	{l.yorigin=1;}
}

function positionMouse(mouseport, localmouse, virtualmouse) {

  var difference = {x: 0, y: 0, sum: 0};

	// Set where the virtual mouse is, if not on target
  if (!mouseport.ontarget) {

    // Calculate difference
    difference.x    = virtualmouse.x - localmouse.x;
    difference.y    = virtualmouse.y - localmouse.y;
    difference.sum  = Math.sqrt(difference.x*difference.x + difference.y*difference.y);

    // Reset virtualmouse
    virtualmouse.x = localmouse.x + difference.x * mouseport.takeoverFactor;
    virtualmouse.y = localmouse.y + difference.y * mouseport.takeoverFactor;

    // If mouse is inside the takeoverThresh set ontarget to true
    if (difference.sum < mouseport.takeoverThresh && difference.sum > mouseport.takeoverThresh*-1) {
    	mouseport.ontarget=true;
    }
  }
  // Set where the layer is if on target
  else {
    virtualmouse.x = localmouse.x;
    virtualmouse.y = localmouse.y;
  }
}

function setupPorts(viewport, mouseport) {

	var offset = mouseport.element.offset();

  jQuery.extend(viewport, {
    width: 		viewport.element.width(),
    height: 	viewport.element.height()
  });

  jQuery.extend(mouseport, {
    width:		mouseport.element.width(),
    height:		mouseport.element.height(),
    top:			offset.top,
    left:			offset.left
  });
}

function parseTravel(travel, origin, dimension) {

  var offset;
  var cssPos;

  if (typeof(travel) === 'string') {
    if (travel.search(/^\d+\s?px$/) != -1) {
      travel = travel.replace('px', '');
      travel = parseInt(travel, 10);
      // Set offset constant used in moveLayers()
      offset = origin * (dimension-travel);
      // Set origin now because it won't get altered in moveLayers()
      cssPos = origin * 100 + '%';
      return {travel: travel, travelpx: true, offset: offset, cssPos: cssPos};
    }
    else if (travel.search(/^\d+\s?%$/) != -1) {
      travel.replace('%', '');
      travel = parseInt(travel, 10) / 100;
    }
    else {
      travel=1;
    }
  }
  // Set offset constant used in moveLayers()
  offset = origin * (1 - travel);
  return {travel: travel, travelpx: false, offset: offset}
}

function setupLayer(layer, i, mouseport) {

  var xStuff;
  var yStuff;
  var cssObject = {};

  layer[i]=jQuery.extend({}, {
  	width:		layer[i].element.width(),
  	height:		layer[i].element.height()
  }, layer[i]);

  xStuff = parseTravel(layer[i].xtravel, layer[i].xorigin, layer[i].width);
  yStuff = parseTravel(layer[i].ytravel, layer[i].yorigin, layer[i].height);

  jQuery.extend(layer[i], {
  	// Used in triggerResponse
  	diffxrat:    mouseport.width / (layer[i].width - mouseport.width),
  	diffyrat:    mouseport.height / (layer[i].height - mouseport.height),
  	// Used in moveLayers
  	xtravel:     xStuff.travel,
  	ytravel:     yStuff.travel,
  	xtravelpx:   xStuff.travelpx,
  	ytravelpx:   yStuff.travelpx,
  	xoffset:     xStuff.offset,
  	yoffset:     yStuff.offset
  });

  // Set origin now if it won't be altered in moveLayers()
  if (xStuff.travelpx) {cssObject.left = xStuff.cssPos;}
  if (yStuff.travelpx) {cssObject.top = yStuff.cssPos;}
  if (xStuff.travelpx || yStuff.travelpx) {layer[i].element.css(cssObject);}
}

function setupLayerContents(layer, i, viewportOffset) {

  var contentOffset;

  // Give layer a content object
  jQuery.extend(layer[i], {content: []});
  // Layer content: get positions, dimensions and calculate element offsets for centering children of layers
  for (var n=0; n<layer[i].element.children().length; n++) {

	  if (!layer[i].content[n])          layer[i].content[n]             = {};
	  if (!layer[i].content[n].element)  layer[i].content[n]['element']  = layer[i].element.children().eq(n);

	  // Store the anchor name if one has not already been specified.  You can specify anchors in Layer Options rather than html if you want.
    if(!layer[i].content[n].anchor && layer[i].content[n].element.children('a').attr('name')) {
    	layer[i].content[n]['anchor'] = layer[i].content[n].element.children('a').attr('name');
	  }

	  // Only bother to store child's dimensions if child has an anchor.  What's the point otherwise?
	  if(layer[i].content[n].anchor) {
      contentOffset = layer[i].content[n].element.offset();
	  	jQuery.extend(layer[i].content[n], {
	  		width: 		layer[i].content[n].element.width(),
	  		height:		layer[i].content[n].element.height(),
	  		x:			  contentOffset.left - viewportOffset.left,
	  		y:			  contentOffset.top - viewportOffset.top
	  	});
	  	jQuery.extend(layer[i].content[n], {
	  	  posxrat:  (layer[i].content[n].x + layer[i].content[n].width/2) / layer[i].width,
	  	  posyrat:  (layer[i].content[n].y + layer[i].content[n].height/2) / layer[i].height
      });
	  }
  }
}

function moveLayers(layer, xratio, yratio) {

	var xpos;
	var ypos;
	var cssObject;

	for (var i=0; i<layer.length; i++) {

    // Calculate the moving factor
  	xpos = layer[i].xtravel * xratio + layer[i].xoffset;
    ypos = layer[i].ytravel * yratio + layer[i].yoffset;
    cssObject = {};
  	// Do the moving by pixels or by ratio depending on travelpx
    if (layer[i].xparallax) {
      if (layer[i].xtravelpx) {
        cssObject.marginLeft = xpos * -1 + 'px';
      }
      else {
        cssObject.left = xpos * 100 + '%';
        cssObject.marginLeft = xpos * layer[i].width *-1 + 'px';
      }
	  }
	  if (layer[i].yparallax) {
      if (layer[i].ytravelpx) {
        cssObject.marginTop = ypos * -1 + 'px';
      }
      else {
        cssObject.top = ypos * 100 + '%';
        cssObject.marginTop = ypos * layer[i].height * -1 + 'px';
      }
    }
    layer[i].element.css(cssObject);
	}
}

// PLUGIN DEFINITION **********************************************************************

jQuery.fn.jparallax = function(options) {

	// Organise settings into objects (Is this a bit of a mess, or is it efficient?)
	var settings = jQuery().extend({}, jQuery.fn.jparallax.settings, options);
	var settingsLayer = {
  			xparallax:				settings.xparallax,
  			yparallax:				settings.yparallax,
  			xorigin:					settings.xorigin,
  			yorigin:					settings.yorigin,
  			xtravel:          settings.xtravel,
  			ytravel:          settings.ytravel
  		};
  var settingsMouseport = {
  			element:					settings.mouseport,
				takeoverFactor:		settings.takeoverFactor,
				takeoverThresh:		settings.takeoverThresh
			};
	if (settings.mouseport) settingsMouseport['element'] = settings.mouseport;

	// Populate layer array with default settings
	var layersettings = [];
	for(var a=1; a<arguments.length; a++) {
		layersettings.push( jQuery.extend( {}, settingsLayer, arguments[a]) );
	}

	// Iterate matched elements
	return this.each(function() {

    // VAR

		var localmouse = {
					x:				0.5,
					y:				0.5
		};

    var virtualmouse = {
					x:				0.5,
					y:				0.5
		};

		var timer = {
		  running:		false,
		  frame:			settings.frameDuration,
		  fire:				function(x, y) {
		  	  				  positionMouse(mouseport, localmouse, virtualmouse);
                    moveLayers(layer, virtualmouse.x, virtualmouse.y);
		  	  				  this.running = setTimeout(function() {
		  	  				  	if ( localmouse.x!=x || localmouse.y!=y || !mouseport.ontarget ) {
		  	  				  		timer.fire(localmouse.x, localmouse.y);
		  	  				  	}
		  	  				  	else if (timer.running) {
		  	  				  		timer.running=false;
		  	  				  	}
		  	  				  }, timer.frame);
		  	  				}
		};

		var viewport	=	{element: jQuery(this)};

		var mouseport = jQuery.extend({}, {element: viewport.element}, settingsMouseport, {
		  xinside:          false,		// is the mouse inside the mouseport's dimensions?
			yinside:	        false,
			active:		        false,		// are the mouse coordinates still being read?
			ontarget:         false			// is the top layer inside the takeoverThresh?
		});

		var layer			= [];

    // FUNCTIONS

    function matrixSearch(layer, ref, callback) {
      for (var i=0; i<layer.length; i++) {
        var gotcha=false;
        for (var n=0; n<layer[i].content.length; n++) {
          if (layer[i].content[n].anchor==ref) {
            callback(i, n);
            return [i, n];
          }
        }
      }
      return false;
    }

    // RUN

    setupPorts(viewport, mouseport);

		// Cycle through and create layers
    for (var i=0; i<viewport.element.children().length; i++) {
			// Create layer from settings if it doesn't exist
			layer[i]=jQuery.extend({}, settingsLayer, layersettings[i], {
				element:	viewport.element.children('*:eq('+i+')')
			});

		  setupLayer(layer, i, mouseport);

      if (settings.triggerResponse) {
		    setupLayerContents(layer, i, viewport.element.offset());
		  }
		}



    // Set up layers CSS and initial position
    viewport.element.children().css('position', 'absolute');
		moveLayers(layer, 0.5, 0.5);

		// Mouse Response
		if (settings.mouseResponse) {
			jQuery().mousemove(function(mouse){
				// Is mouse inside?
				mouseport.xinside = (mouse.pageX >= mouseport.left && mouse.pageX < mouseport.width+mouseport.left) ? true : false;
				mouseport.yinside = (mouse.pageY >= mouseport.top  && mouse.pageY < mouseport.height+mouseport.top)  ? true : false;
				// Then switch active on.
				if (mouseport.xinside && mouseport.yinside && !mouseport.active) {
					mouseport.ontarget = false;
					mouseport.active = true;
				}
				// If active is on give localmouse coordinates
				if (mouseport.active) {
					if (mouseport.xinside) { localmouse.x = (mouse.pageX - mouseport.left) / mouseport.width; }
					else { localmouse.x = (mouse.pageX < mouseport.left) ? 0 : 1; }
					if (mouseport.yinside) { localmouse.y = (mouse.pageY - mouseport.top) / mouseport.height; }
					else { localmouse.y = (mouse.pageY < mouseport.top) ? 0 : 1; }
				}

				// If mouse is inside, fire timer
				if (mouseport.xinside && mouseport.yinside)  { if (!timer.running) timer.fire(localmouse.x, localmouse.y); }
				else if (mouseport.active) { mouseport.active = false; }
			});
		}

		// Trigger Response
		if (settings.triggerResponse) {
		  viewport.element.bind("jparallax", function(event, ref){

		    ref = stripFiletype(ref);

        matrixSearch(layer, ref, function(i, n) {
          localmouse.x = layer[i].content[n].posxrat * (layer[i].diffxrat + 1) - (0.5 * layer[i].diffxrat);
          localmouse.y = layer[i].content[n].posyrat * (layer[i].diffyrat + 1) - (0.5 * layer[i].diffyrat);

          if (!settings.triggerExposesEdges) {
            if (localmouse.x < 0) localmouse.x = 0;
            if (localmouse.x > 1) localmouse.x = 1;
            if (localmouse.y < 0) localmouse.y = 0;
            if (localmouse.y > 1) localmouse.y = 1;
          }

          mouseport.ontarget = false;

          if (!timer.running) timer.fire(localmouse.x, localmouse.y);
        });
		  });
		}

		// Window Resize Response
		jQuery(window).resize(function() {

		  setupPorts(viewport, mouseport);
		  for (var i=0; i<layer.length; i++) {
		    setupLayer(layer, i, mouseport);
      }
		});


	});
};

// END OF PLUGIN DEFINITION **********************************************************************

// PLUGIN DEFAULTS

jQuery.fn.jparallax.settings = {
	mouseResponse:		    true,						// Sets mouse response
	mouseActiveOutside:		false,					// Makes mouse affect layers from outside of the mouseport.
	triggerResponse:	    true,					  // Sets trigger response
  triggerExposesEdges:  false,          // Sets whether the trigger pulls layer edges into view in trying to centre layer content.
	xparallax:				    true,						// Sets directions to move in
	yparallax:				    true,						//
	xorigin:					    0.5,				    // Sets default alignment - only comes into play when travel is not 1
	yorigin:					    0.5,				    //
	xtravel:              1,              // Factor by which travel is amplified
	ytravel:              1,              //
	takeoverFactor:		    0.65,						// Sets rate of decay curve for catching up with target mouse position
	takeoverThresh:		    0.002,					// Sets the distance within which virtualmouse is considered to be on target, as a multiple of mouseport width.
	frameDuration:        25							// In milliseconds
};

// RUN

initOrigin(jQuery.fn.jparallax.settings);

jQuery(function() {

});


// END CLOSURE

})(jQuery);
