
	
/* Init */

jQuery(
  
  function ($) {

    $.Document = $(document);
    $.Body = $('body');
    $.Footer = $('body').find("#footer");

    $.Window = $(window);
    
    $.Scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $.Body;
    
    console.log($('[data-controller]'));
    
    $('[data-controller]').Instantiate();
    
    $.BaseUrl = "http://telegramme.co.uk";
    
    var $Postslength = 0;
    
        
  } 
 
);

$(document).ready(function(){

function InitAll(){
	console.log($('[data-controller]'));
}

});

/* ---------------------------------- */

/* Events */



/* ---------------------------------- */

/* Auto Start */

(function($) {

  $.fn.Instantiate = function() {
    
      this.each(function(i) { 

          var $self = $(this),
          $controller = $self.attr('data-controller');
          if ($self[$controller])
            $obj = $self[$controller](i);
            $Postslength = i+1;
          });
  }
})(jQuery);


(function($) {

  
   $.fn.homeSlideshow = function(loc) {
   	
     this.each(function() { 
          	 
			var $self = $(this);
			
          	$self.delay(loc*100).fadeIn();
          	


			$self.data("order",loc);
			
			var $slidesContainer = $self.find('#home_slideshow');
			
			var $pos=0;
			var $count = $slidesContainer.children().size();
			$slidesContainer.css("width", $count*940+"px");
			
			var maxHeit=0;
			var totWid=0;
			
 			var $itvl = setInterval(function(){autoAdvance()},5000);			
			

			$('#home_slideshow li').each(function(i){
				totWid += $(this).width();
				newHei = $(this).height();
				
				if(newHei>maxHeit){
					maxHeit = newHei;
				}
			});
			
			$self.css("height", maxHeit+"px");
			$slidesContainer.css("height", maxHeit+"px");
			$self.find(".button").css("marginTop", (maxHeit*0.5-60)+"px");
			
			$self.find('.border-bottom').css("marginTop", maxHeit-2+"px");
	
			$self.find(".next").click(function() {	
  				resetInterval();
  				$tmpPos = $pos;
				if($tmpPos<$count-1){
					$tmpPos++;
				}else{
					$tmpPos=0;
				}
				moveToSlide($tmpPos);
				return false;
			});
			
			$self.find(".prev").click(function() {
      			$tmpPos = $pos;
				if($tmpPos>0){
					$tmpPos--;
				}else{
					$tmpPos = $count-1;
				}
				moveToSlide($tmpPos);
				return false;
			});
			
	
								
			function resetInterval(){
				clearTimeout($itvl);
				$itvl = setInterval(function(){autoAdvance()},5000);
			}
			
			
			function autoAdvance()
			{
				$tmpPos = $pos;
				if($tmpPos<$count-1){
					$tmpPos++;
				}else{
					$tmpPos=0;
				}
				moveToSlide($tmpPos);
			}
			
			
			function moveToSlide($newPos){
	  			
	  			var _opt = {
					duration: 1000,
					easing: "easeInOutExpo"
				};
						
				//hide current		
				$slidesContainer.stop();
				$slidesContainer.animate(
				{
					marginLeft:0-$newPos*940+"px"
				},
				_opt
				);
			
				
				//change the current pos
				$pos = $newPos;
			}
			
			
						
			 
     });
     
   return this;
 
  }
    
    
})(jQuery);




(function($) {

  
   $.fn.workPost = function(loc) {
   	
     this.each(function() { 
          	 
			var $self = $(this);
			
          	$self.delay(loc*100).fadeIn();
          	

          	
          	if($self.data("activated") == false){
          		$self.data("activated", true);

			
			$self.data("order",loc);
			
			var $holder = $self.find('.slideshow');
			var $slidesContainer = $self.find('.slideshow-container');
			
			var $pos=0;
			var $count = $slidesContainer.children().size();
			
			var $prev = $self.find('a.prev');
			var $next = $self.find('a.next');

			var $nextpost = $self.find('.next_post_button');
			
			var $slidesInfo = $self.find('.slideshow-info');
			
			$self.find(".backtotop").click(function(){
 				scrolltoTop();
 			});
 	
 	
			$.Window.bind('scroll',function(e){ 
				if ( $.inview($self) ) {
					if(!$self.hasClass("inview")){
						$self.addClass("inview");
						resetInterval();
						setTimeout(function(){
							resetInterval();
							autoAdvance();
						},400);
							
						
						
					}
				}else{
					if($self.hasClass("inview")){
						$self.removeClass("inview");
					}
				}
			})//end bind
        
        
			/*
			$.Window.smartscroll(function(){
           		console.log("Asdadad");            
        	});
			*/
		
		//INIT SLIDESHOW INFO
		
 		
 		//SET BUTTONS VERTICAL POSITION
			$containerHeight = 0;
			$slidesContainer.find('li img').each(function(i){
			
				$(this).click(function() { //SET IMG CLICK TO NEXT SLIDE	
      				$tmpPos = $pos;
					if($tmpPos<$count-1){
						$tmpPos++;
					}else{
						$tmpPos=0;
					}
					moveToSlide($tmpPos, $pos);
					return false;
				});
			
			
							
				if($(this).height()>$containerHeight)
					$containerHeight = $(this).height();	
			});	//end img each
			

			$holder.css("height", $containerHeight);
			$prev.css("marginTop", $containerHeight/2-15+"px");
			$next.css("marginTop", $containerHeight/2-15+"px");
			//ENF OF BUTTONS POSITION
			
			
			function resetInterval(){
				clearTimeout($itvl);
				$itvl = setInterval(function(){autoAdvance()},4000);
			}
					 	
			function scrolltoTop(){
				_opt = {duration: 1000,easing: "easeInOutQuint"};
				$.Scroll.stop();
				$.Scroll.animate({scrollTop:0},_opt);
			}
				
			
			function autoAdvance()
			{			
				if(!$self.hasClass("inview")) return;
				
				$tmpPos = $pos;
				if($tmpPos<$count-1){
					$tmpPos++;
				}else{
					$tmpPos=0;
				}
				moveToSlide($tmpPos, $pos);
			}
			
			
			$prev.click(function() {
      			resetInterval();
      			$tmpPos = $pos;
				if($tmpPos>0){
					$tmpPos--;
				}else{
					$tmpPos = $count-1;
				}
				moveToSlide($tmpPos, $pos);
				return false;
			});
		
		
		  	$next.click(function() {
				resetInterval();
				$tmpPos = $pos;
				if($tmpPos<$count-1){
					$tmpPos++;
				}else{
					$tmpPos=0;
				}
				moveToSlide($tmpPos, $pos);
				return false;
			});
		
		
		
			function moveToSlide($newPos, $oldPos){
	  			updateSlideshowInfo($newPos);
	  			
	  			var _opt = {
					duration: 500,
					easing: "easeOutQuad"
				};
			
				$currentSlide = $slidesContainer.find("li").eq($oldPos);
				$newSlide = $slidesContainer.find("li").eq($newPos);
				
				
				//hide current		
				$currentSlide.stop();
				$currentSlide.animate(
				{
					opacity:0
				},
				_opt
				);
					

				//show new
				$newSlide.stop();
				$newSlide.animate(
				{
					opacity:1
				},
				_opt
				);
				
				//change the current pos
				$pos = $newPos;
			}
			
			
			function updateSlideshowInfo($newPos){
				
				$currentSlide = $slidesContainer.find("li").eq($newPos);
				$currentSlideCaption = $currentSlide.find("img").attr("alt");
				
				$newPos = $newPos+1;
				$total = $count;
				
				$slidesInfo.find("p.current_of_total").html($newPos+" <em>of</em> "+$total);
				$slidesInfo.find("p.image_caption").html($currentSlideCaption);
				//console.log($currentSlideCaption);
				//1 <em>of</em> 20
			}
			
			
			$nextpost.click(function() {
				$obj = $(this).parent().parent().parent();
				
				$nextPosOrder = $obj.data("order")+1;
				if($nextPosOrder < $Postslength){
					$nextPost = $obj.parent().find(".project-post").eq($nextPosOrder);
					$.ScrollToProject($nextPost);
				}else{
					$.ScrollToProject($obj);
				}


				return false;
			});
		
		updateSlideshowInfo($pos);

 		var $itvl = setInterval(function(){autoAdvance()},4000);
 			
			 	
	   }
     });
     
   return this;
 
  }
    
    
})(jQuery);

(function($) {

   $.fn.backToTop = function(loc) {
   	
    this.each(function() { 
    
          	 
	var $self = $(this);
		
		setTimeout(function(){
			scrollMe();
		},1000);
		
	   	if($self.data("activated") == true) return;
   	      		
    	$self.data("activated", true);
          		

	$self.click(function(){
		scrolltoTop();
	});
 	
 	
	$.Window.bind('scroll',scrollMe); 
	
	function scrollMe() {
		
		var fold = $.Window.height() + $.Window.scrollTop();
		
		if(fold > $.Footer.offset().top){ //if the footer is visible make the sticky div normal
			if($self.hasClass("fixed")){ //nested if to trigger only once
				$self.removeClass("fixed");
			}
		}else{ //else the footer is bellow the screen fold so make the sticky div fixed
			if(!$self.hasClass("fixed")){ //nested if to trigger only once
				$self.addClass("fixed");
			}
		}
				
	}
					
			 
    });
     
   	function scrolltoTop(){
		_opt = {duration: 1000,easing: "easeInOutQuint"};
		$.Scroll.stop();
		$.Scroll.animate({scrollTop:0},_opt);
	}


	return this;
 
  }
    
    
})(jQuery);




(function($) {

  
   $.fn.gridSlideshow = function(loc) {
   	
     this.each(function() { 
          	 
			var $self = $(this);
			
          	$self.delay(loc*100).fadeIn();
          	


			$self.data("order",loc);
			
			var $slidesContainer = $self.find('.grid_slideshow');
			
			var $pos=0;
			var $count = $slidesContainer.children().size();
			
 			var $itvl = setInterval(function(){autoAdvance()},4000);
 		
 		//SET BUTTONS VERTICAL POSITION
			$containerHeight = 0;
			$slidesContainer.find('li img').each(function(i){
			
				$(this).click(function() { //SET IMG CLICK TO NEXT SLIDE	
      				resetInterval();
      				$tmpPos = $pos;
					if($tmpPos<$count-1){
						$tmpPos++;
					}else{
						$tmpPos=0;
					}
					moveToSlide($tmpPos, $pos);
					return false;
				});
	
			});	//end img each
					
			function resetInterval(){
				clearTimeout($itvl);
				$itvl = setInterval(function(){autoAdvance()},4000);
			}
			
			
			function autoAdvance()
			{
				$tmpPos = $pos;
				if($tmpPos<$count-1){
					$tmpPos++;
				}else{
					$tmpPos=0;
				}
				moveToSlide($tmpPos, $pos);
			}
			
			
			function moveToSlide($newPos, $oldPos){
	  			
	  			var _opt = {
					duration: 500,
					easing: "easeOutQuad"
				};
				
				var _optOut = {
					duration: 500,
					easing: "easeOutQuad"
				};
			
				$currentSlide = $slidesContainer.find("li").eq($oldPos);
				$newSlide = $slidesContainer.find("li").eq($newPos);
				
				
				//hide current		
				$currentSlide.stop();
				$currentSlide.animate(
				{
					opacity:0
				},
				_optOut
				);
					

				//show new
				$newSlide.stop();
				$newSlide.animate(
				{
					opacity:1
				},
				_opt
				);
				
				//change the current pos
				$pos = $newPos;
			}
			
		
			
						
			 
     });
     
   return this;
 
  }
    
    
})(jQuery);



(function($) {  
   $.fn.formBox = function() {
   	
      	
   		var options = {
			url: 'http://telegramme.co.uk/mail.php',
			subject : 'Telegramme.co.uk - Contact Form',
			recievedMsg : 'Your message is now sent.<br>Thank you!',
			notRecievedMsg : 'Sorry but your message could not be sent<br>Try again later'
		};


     return this.each(function() { 
	
	      var $self = $(this);

       		$randomnumber1=Math.floor(Math.random()*11);
   			$randomnumber2=Math.floor(Math.random()*11);
		    $res = $randomnumber1 + $randomnumber2;

			var this_id_prefix = '#'+this.id+' ';

			$self.find("#hidden").val($res);
			
			$self.find("#humanlabel").html("<span class=\"red\"> * </span>"+$randomnumber1+" + "+$randomnumber2+" = ");
        
			
			//validate the form 
			$(this_id_prefix+"#contactForm").validate({
			
				
				//set the rules for the fild names
				rules: {
					name: {
						required: true,
						minlength: 2
					},
					company: {
						required: true,
						minlength: 2
					},
					email: {
						required: true,
						email: true
					},
					tel: {
						required: true,
						minlength: 8
					},					
					message: {
						required: true,
						minlength: 10
					},
					human: {
						required: true,
						equalTo: '#hidden'
					}
				},
				//set messages to appear inline
					messages: {
						name: "",
						company: "",
						email: "",
						tel: "",
						message: ""
					},			

				submitHandler: function() {
					$(this_id_prefix+'.holder').hide();
					$(this_id_prefix+'#loading').show();
$.ajax({
  type: 'POST',
  url: options.url,
  data: {subject:options.subject, name:$(this_id_prefix+'#name').val(), email:$(this_id_prefix+'#email').val(), message:$(this_id_prefix+'#message').val(), human:$(this_id_prefix+'#human').val()},
  success: function(data){
  
						$(this_id_prefix+'#loading').css({display:'none'}); 
						if( data == 'success') {
							$(this_id_prefix+'#callback').show().append(options.recievedMsg);
							setTimeout(function(){
								$(this_id_prefix+'.holder').show();
								$(this_id_prefix+'#callback').hide().html('');
							},10000);
						} else {
							$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
							setTimeout(function(){
								$(this_id_prefix+'.holder').show();
								$(this_id_prefix+'#callback').hide().html('');
							},4000);
						}
					},
  error:function(){
						$(this_id_prefix+'#loading').css({display:'none'}); 
						$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
                                        }
});		

				}
			});
			
			
			


		
     });
    return this;
  }
})(jQuery);






(function($) {  
   $.fn.mailChimp = function() {
   	
      	
   		var options = {
			url: 'http://telegramme.co.uk/mailchimp.php',
			recievedMsg : '<p>Wow!</p><p>Thanks dude...</p>',
			notRecievedMsg : '<p>Sorry,</p><p>Try again later...</p>'
		};


     return this.each(function() { 
	
	      var $self = $(this);

       		

			var this_id_prefix = '#'+this.id+' ';

	        
			
			//validate the form 
			$(this_id_prefix+"#mailchimpform").validate({
			
				
				//set the rules for the fild names
				rules: {
					name: {
						required: true,
						minlength: 2
					},
					email: {
						required: true,
						email: true
					},
				},
				//set messages to appear inline
					messages: {
						name: "",
						company: "",
						email: "",
						tel: "",
						message: ""
					},			

				submitHandler: function() {
					$(this_id_prefix+'.holder').hide();
					$(this_id_prefix+'#loading').show();
				$.ajax({
				  type: 'POST',
				  url: options.url,
				  data: {name:$(this_id_prefix+'#name').val(), email:$(this_id_prefix+'#email').val()},
				  success: function(data){
				  
										$(this_id_prefix+'#loading').css({display:'none'}); 
										if( data == 'success') {
											$(this_id_prefix+'#callback').show().append(options.recievedMsg);
											setTimeout(function(){
												$(this_id_prefix+'.holder').show();
												$(this_id_prefix+'#callback').hide().html('');
											},10000);
										} else {
											$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
											setTimeout(function(){
												$(this_id_prefix+'.holder').show();
												$(this_id_prefix+'#callback').hide().html('');
											},4000);
										}
									},
				  error:function(){
										$(this_id_prefix+'#loading').css({display:'none'}); 
										$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
				                                        }
				});		

				}
			});
			
			
			


		
     });
    return this;
  }
})(jQuery);






(function($) {  
   $.fn.footerShare = function() {


     return this.each(function() { 
	
	    var $self = $(this);
	    
		$buttons = $self.find(".buttons");
			
		$self.mouseover(function() {	
		});
		
		$self.mouseout(function() {
		
		});

		
     });
    return this;
  }
})(jQuery);



(function($) {  
   $.fn.Sidebar = function() {


     return this.each(function() { 
	
	    var $self = $(this);
	    var $height = $self.height();
	    var $totHeight = $height+204;
		
		//$.Window.smartscroll(function(){});

     });
    return this;
  }
})(jQuery);



(function($) {  
   $.fn.twitterBox = function() {


     return this.each(function() { 
	
	    var $self = $(this);
		
		var tweetMonth = '';
        var shortMonths = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
            
		var user = $self.data("user");
	    // using jquery built in get json method with twitter api, return only one result
	    $.getJSON('http://twitter.com/statuses/user_timeline.json?screen_name=' + user + '&count=5&callback=?', function(data)      {
	          
	        // result returned
	        var tweet = data[0].text;
	        var date = data[0].created_at;
	      
	      tweet = tweet.replace(/#(.*?)(\s|$)/g, '<span class="hash">#$1 </span>').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="$&">$&</a> ').replace(/@(.*?)(\s|\(|\)|$)/g, '<a href="http://twitter.com/$1">@$1</a>$2')
	      
	      
	      tweetDate = $.TwitterDate(date);					
	       
	      
	        // output the result
	        $("#tweet").html(tweet+'<br>'+tweetDate);
	    });

		
     });
    return this;
  }
})(jQuery);



    
    
        
    



//WORKERS
(function($) {

	$.TwitterDate = function (time) {
	
	
	var date = new Date(time),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
 
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
 
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
	}


	$.ScrollToProject = function ($obj) {
		$newScrollLoc = $obj.offset().top-10;
		
		var _opt = {
			duration: 600,
			easing: "easeInOutExpo"
		};
		
		$.Scroll.stop();
		$.Scroll.animate({
			scrollTop:$newScrollLoc,	
		},_opt);
		
		
		return true;	
	}
	
	   
    $.Debounce = function(func, threshold, execAsap){
          var timeout;

     	 return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null; 
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 200); 
      	};
    }
    
    
	$.distancefromfold = function($element) {
        var fold = $(window).height() + $(window).scrollTop();
       	return fold- $element.offset().top;
    };
    
    $.belowthefold = function($element) {
   		var fold = $(window).height() + $(window).scrollTop();
        return fold <= $element.offset().top;
    };
        
    $.abovethetop = function($element) {
        var fold = $(window).scrollTop();
        return fold >= $element.offset().top + $element.height();
    };
    
    $.inview = function($element) {
        return ($.abovethetop($element)!=true && $.belowthefold($element)!=true)
    };


    $.extend($.expr[':'], {
        "below-the-fold" : "$.belowthefold(a, {threshold : 0, container: window})",
        "above-the-fold" : "!$.belowthefold(a, {threshold : 0, container: window})"
    });
    

      
    
  
    
   
   
})(jQuery); 


(function($,sr){
	jQuery.fn[sr] = function(fn){  return fn ? this.bind('scroll', $.Debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartscroll')







