/* this prevents dom flickering, needs to be outside of dom.ready event: */
document.documentElement.className += 'js_active';
/*end dom flickering =) */

jQuery.noConflict();



jQuery(document).ready(function(){
          
	
	// enhances contact form with ajax capabilities
	if(jQuery.fn.infinite_ajax_form)
	jQuery('.ajax_form').infinite_ajax_form();
	
	//smooth scrooling
	if(jQuery.fn.infinite_smoothscroll)
	jQuery('a.scrolllink').infinite_smoothscroll();
	
	//tooltips
	jQuery(".ttip[title]").tooltip({effect: 'bouncy'});
	
	
	input_labels();
	
	//activates the prettyphoto lightbox
	if(jQuery.fn.infinite_activate_lightbox)		
	jQuery('body').infinite_activate_lightbox();
	
	//activates the hover effect for image links
	if(jQuery.fn.infinite_activate_hover_effect)		
	jQuery('body').infinite_activate_hover_effect();
    
   

});


         
// -------------------------------------------------------------------------------------------
// Smooth scrooling when clicking on anchor links
// -------------------------------------------------------------------------------------------

(function($)
{
	$.fn.infinite_smoothscroll = function(variables) 
	{
		return this.each(function()
		{
			$(this).click(function() {
		
			   var newHash=this.hash;
			   
			   if(newHash != '' && newHash != '#' && !$(this).is('.comment-reply-link, #cancel-comment-reply-link'))
			   {
				   var container = $(this.hash);
				   
				   if(container.length)
				   {
					   var target = container.offset().top,
						   oldLocation=window.location.href.replace(window.location.hash, ''),
						   newLocation=this,
						   duration=800,
						   easing='easeOutQuint';
			
					   // make sure it's the same location      
					   if(oldLocation+newHash==newLocation)
					   {
					      // animate to target and set the hash to the window.location after the animation
					      $('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing, function() {
					
					         // add new hash to the browser location
					         window.location.href=newLocation;
					      });
					
					      // cancel default click action
					      return false;
					   }
					}
				}
			});
		});
	};
})(jQuery);	



function input_labels() {
    
    jQuery(':input[title]').each(function() {
  var jQuerythis = jQuery(this);
  if(jQuerythis.val() === '') {
    jQuerythis.val(jQuerythis.attr('title'));
  }
  jQuerythis.focus(function() {
    if(jQuerythis.val() === jQuerythis.attr('title')) {
      jQuerythis.val('');
    }
  });
  jQuerythis.blur(function() {
    if(jQuerythis.val() === '') {
      jQuerythis.val(jQuerythis.attr('title'));
    }
  });
  });
    
   
}

    
    // -------------------------------------------------------------------------------------------
// Ligthbox activation
// -------------------------------------------------------------------------------------------

(function($)
{
	$.fn.infinite_activate_lightbox = function(variables) 
	{
		var defaults = 
		{
			autolinkElements: 'a[rel^="prettyPhoto"], a[rel^="lightbox"], a[href$=jpg], a[href$=png], a[href$=gif], a[href$=jpeg], a[href$=".mov"] , a[href$=".swf"] , a[href*="vimeo.com"] , a[href*="youtube.com"] , a[href*="screenr.com"]'
		};
		
		var options = $.extend(defaults, variables);
		
		return this.each(function()
		{
			var elements = $(options.autolinkElements, this),
				lastParent = "",
				counter = 0;
		
			elements.each(function()
			{
				var el = $(this),
					parentPost = el.parents('.post-entry:eq(0)'),
					group = 'auto_group';
				
				if(parentPost.get(0) != lastParent)
				{
					lastParent = parentPost.get(0);
					counter ++;
				}
					
				if((el.attr('rel') == undefined || el.attr('rel') == '') && !el.hasClass('noLightbox')) 
				{ 
					el.attr('rel','lightbox'); 
					
					//manipulate the link in case we got a screenr video
					if(el.is('a[href*="screenr.com"]'))
					{
						var currentlink = el.attr('href');
						
						if(currentlink.indexOf('embed') !== -1)
						{
							el.attr('href', currentlink + '?iframe=true&width=650&height=396');
						}
						else
						{
							var append =  currentlink.substring(currentlink.lastIndexOf('/') + 1,currentlink.length);
							el.attr('href', 'http://www.screenr.com/embed/' + append + '?iframe=true&width=650&height=396');
						}
					}
				}
			});
			
			if($.fn.prettyPhoto)
			elements.prettyPhoto({ "theme": 'light_square' }); /* facebook /light_rounded / dark_rounded / light_square / dark_square */								
		});
	};
})(jQuery);	




// -------------------------------------------------------------------------------------------
// Hover effect activation
// -------------------------------------------------------------------------------------------

(function($)
{
	$.fn.infinite_activate_hover_effect = function(variables) 
	{
		var defaults = 
		{
			autolinkElements: 'a[rel^="prettyPhoto"], a[rel^="lightbox"], a[href$=jpg], a[href$=png], a[href$=gif], a[href$=jpeg], a[href$=".mov"] , a[href$=".swf"] , a[href*="vimeo.com"] , a[href*="youtube.com"]'
		};
		
		var options = $.extend(defaults, variables);
		
		return this.each(function()
		{
			$(options.autolinkElements, this).contents('img').each(function()
			{
				var img = $(this),
					a = img.parent(),
					preload = img.parents('.preloading'),
					$newclass = 'lightbox_video';
					
				if(a.attr('href').match(/(jpg|gif|jpeg|png|tif)/)) $newclass = 'lightbox_image';
				
				var bg = $("<span class='"+$newclass+"'></span>").appendTo(a);
				
				//bind
				img.hover(function()
				{					
					var height = img.outerHeight(), width = img.outerWidth(), pos =  img.position();			
					bg.css({height:height, width:width, top:pos.top, left:pos.left, display:'block'});
					
					if (img.css('opacity') >= 0.1) { preload.removeClass('preloading'); }
					img.stop().animate({opacity:0.5},400);
				},
				function()
				{
					img.stop().animate({opacity:1},400);
				});
			});						
		});
	};
})(jQuery);

// -------------------------------------------------------------------------------------------
// image preloader
// -------------------------------------------------------------------------------------------


(function($)
{
	$.fn.infiniteImagePreloader = function(variables, callback) 
	{
		var defaults = 
		{
			fadeInSpeed: 800,
			maxLoops: 10
		};
		
		var options = $.extend(defaults, variables);
			
		return this.each(function()
		{
			var container 	= $(this),
				images		= $('img', this).css({opacity:0, visibility:'visible', display:'block'}),
				parent = images.parent().addClass('preloading'),
				imageCount = images.length,
				interval = '',
				allImages = images ;
							
			
			var methods = 
			{
				checkImage: function()
				{
					images.each(function(i)
					{
						if(this.complete == true) images = images.not(this);
					});
					
					if(images.length && options.maxLoops >= 0)
					{
						options.maxLoops--;
						setTimeout(methods.checkImage, 500);
					}
					else
					{
						methods.showImages();
					}
				},
				
				showImages: function()
				{
					allImages.each(function(i)
					{
						var currentImage = $(this);
						currentImage.animate({opacity:1}, options.fadeInSpeed, function()
						{
							currentImage.parents().removeClass('preloading');
							if(allImages.length == i+1) 
							{
								methods.callback(i);
							}
						});
					});
				},
				
				callback: function()
				{				
					if (variables instanceof Function) { callback = variables; }
					if (callback  instanceof Function) { callback.call(this);  }
				}
			};
			
			if(!images.length) { methods.callback(); return }
			methods.checkImage();

		});
	};
})(jQuery);

// -------------------------------------------------------------------------------------------
// contact form ajax improvements
// -------------------------------------------------------------------------------------------

(function($)
{
	$.fn.infinite_ajax_form = function(variables) 
	{
		var defaults = 
		{
			sendPath: 'send.php',
			responseContainer: '#ajaxresponse'
		};
		
		var options = $.extend(defaults, variables);
		
		return this.each(function()
		{
			var form = $(this),
				form_sent = false,
				send = 
				{
					formElements: form.find('textarea, select, input[type=text], input[type=hidden]'),
					validationError:false,
					button : form.find('input:submit'),
					dataObj : {}
				};
			
			responseContainer = $(options.responseContainer+":eq(0)");
			
			send.button.bind('click', checkElements);
			
			function send_ajax_form()
			{
				if(form_sent){ return false; }
				
				form_sent = true;
				send.button.fadeOut(300);	
				
				responseContainer.load(form.attr('action')+' '+options.responseContainer, send.dataObj, function()
				{
					responseContainer.find('.hidden').css({display:"block"});
					form.slideUp(400, function(){responseContainer.slideDown(400); send.formElements.val('');});
				});
									
				
			}
			
			function checkElements()
			{	
				// reset validation var and send data
				send.validationError = false;
				send.datastring = 'ajax=true';
				
				send.formElements.each(function(i)
				{
					var currentElement = $(this),
						surroundingElement = currentElement.parent(),
						value = currentElement.val(),
						name = currentElement.attr('name'),
					 	classes = currentElement.attr('class'),
					 	nomatch = true;
					 	
					 	send.dataObj[name] = encodeURIComponent(value);
					 	
					 	if(classes.match(/is_empty/))
						{
							if(value == '')
							{
								surroundingElement.attr("class","").addClass("error");
								send.validationError = true;
							}
							else
							{
								surroundingElement.attr("class","").addClass("valid");
							}
							nomatch = false;
						}
						
						if(classes.match(/is_email/))
						{
							if(!value.match(/^\w[\w|\.|\-]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,4}$/))
							{
								surroundingElement.attr("class","").addClass("error");
								send.validationError = true;
							}
							else
							{
								surroundingElement.attr("class","").addClass("valid");
							}	
							nomatch = false;
						}
						
						if(nomatch && value != '')
						{
							surroundingElement.attr("class","").addClass("valid");
						}
				});
				
				if(send.validationError == false)
				{
					send_ajax_form();
				}
				return false;
			}
		});
	};
})(jQuery);

// Twitter feed for the footer

function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<p>“'+status+'” – <small>'+relative_time(twitters[i].created_at)+'</small></p>');
  }
jQuery('.loading').fadeOut(750, function() {
    jQuery('#footer-tweets').append(jQuery(statusHTML.join('')).hide().fadeIn(750));
});
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

jQuery(document).ready(function() {
var username = 'theflipgroup';
    jQuery.getScript('http://twitter.com/statuses/user_timeline/' + username + '.json?callback=twitterCallback2&count=1');
});

// -------------------------------------------------------------------------------------------
// Custom Tooltip Animation
// -------------------------------------------------------------------------------------------

(function($)
 {
$.easing.bouncy = function (x, t, b, c, d) {
    var s = 1.70158;
    if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
    return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
}

// create custom tooltip effect for jQuery Tooltip
$.tools.tooltip.addEffect("bouncy",

	// opening animation
	function(done) {
		this.getTip().animate({top: '+=15'}, 500, 'bouncy', done).show();
	},

	// closing animation
	function(done) {
		this.getTip().animate({top: '-=15'}, 500, 'bouncy', function()  {
			$(this).hide();
			done.call();
		});
	}
);
})(jQuery);

