// Tooltip by Alen Grakalic (http://cssglobe.com)

this.tooltip = function(){	
		xOffset = '-20';
		yOffset = 10;		
	$("a.tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

(function($) {
 
 // Twitter feed
 
  $.fn.tweet = function(o){
    var s = {
      username: ["bsabaric"],              // [string]   required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"]
      avatar_size: null,                      // [integer]  height and width of avatar if displayed (48px max)
      count: 4,                               // [integer]  how many tweets to display?
      intro_text: null,                       // [string]   do you want text BEFORE your your tweets?
      outro_text: null,                       // [string]   do you want text AFTER your tweets?
      join_text:  null,                       // [string]   optional text in between date and tweet, try setting to "auto"
      auto_join_text_default: "i said,",      // [string]   auto text for non verb: "i said" bullocks
      auto_join_text_ed: "i",                 // [string]   auto text for past tense: "i" surfed
      auto_join_text_ing: "",             	// [string]   auto tense for present tense: "i was" surfing
      auto_join_text_reply: "i replied to",   // [string]   auto tense for replies: "i replied to" @someone "with"
      auto_join_text_url: "i was looking at", // [string]   auto tense for urls: "i was looking at" http:...
      loading_text: null,                     // [string]   optional loading text, displayed while tweets load
      query: null                             // [string]   optional search query
    };

    $.fn.extend({
      linkUrl: function() {
        var returning = [];
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"$1\">$1</a>"))
        });
        return $(returning);
      },
      linkUser: function() {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"http://twitter.com/$1\">@$1</a>"))
        });
        return $(returning);
      },
      linkHash: function() {
        var returning = [];
        var regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all&from='+s.username.join("%2BOR%2B")+'">#$1</a>'))
        });
        return $(returning);
      },
      capAwesome: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(a|A)wesome/gi, 'AWESOME'))
        });
        return $(returning);
      },
      capEpic: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(e|E)pic/gi, 'EPIC'))
        });
        return $(returning);
      },
      makeHeart: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/[&lt;]+[3]/gi, "<tt class='heart'>&#x2665;</tt>"))
        });
        return $(returning);
      }
    });

    function relative_time(time_value) {
      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);
      if(delta < 60) {
      return 'less than a minute ago';
      } else if(delta < 120) {
      return 'about a minute ago';
      } else if(delta < (45*60)) {
      return (parseInt(delta / 60)).toString() + ' minutes ago';
      } else if(delta < (90*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';
      }
    }

    if(o) $.extend(s, o);
    return this.each(function(){
      var list = $('<ul class="tweet_list">').appendTo(this);
      var intro = '<p class="tweet_intro">'+s.intro_text+'</p>'
      var outro = '<p class="tweet_outro">'+s.outro_text+'</p>'
      var loading = $('<p class="loading">'+s.loading_text+'</p>');
      if(typeof(s.username) == "string"){
        s.username = [s.username];
      }
      var query = '';
      if(s.query) {
        query += 'q='+s.query;
      }
      query += '&q=from:'+s.username.join('%20OR%20from:');
      var url = 'http://search.twitter.com/search.json?&'+query+'&rpp='+s.count+'&callback=?';
      if (s.loading_text) $(this).append(loading);
      $.getJSON(url, function(data){
        if (s.loading_text) loading.remove();
        if (s.intro_text) list.before(intro);
        $.each(data.results, function(i,item){
          // auto join text based on verb tense and content
          if (s.join_text == "auto") {
            if (item.text.match(/^(@([A-Za-z0-9-_]+)) .*/i)) {
              var join_text = s.auto_join_text_reply;
            } else if (item.text.match(/(^\w+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+) .*/i)) {
              var join_text = s.auto_join_text_url;
            } else if (item.text.match(/^((\w+ed)|just) .*/im)) {
              var join_text = s.auto_join_text_ed;
            } else if (item.text.match(/^(\w*ing) .*/i)) {
              var join_text = s.auto_join_text_ing;
            } else {
              var join_text = s.auto_join_text_default;
            }
          } else {
            var join_text = s.join_text;
          };

          var join_template = '<span class="tweet_join"> '+join_text+' </span>';
          var join = ((s.join_text) ? join_template : ' ')
          var avatar_template = '<a class="tweet_avatar" href="http://twitter.com/'+ item.from_user+'"><img src="'+item.profile_image_url+'" height="'+s.avatar_size+'" width="'+s.avatar_size+'" alt="'+item.from_user+'\'s avatar" border="0"/></a>';
          var avatar = (s.avatar_size ? avatar_template : '')
          var date = '<a href="http://twitter.com/'+item.from_user+'/statuses/'+item.id+'" title="view tweet on twitter">'+relative_time(item.created_at)+'</a>';
          var text = '<span class="tweet_text">' +$([item.text]).linkUrl().linkUser().linkHash().makeHeart().capAwesome().capEpic()[0]+ '</span>';
          
          // until we create a template option, arrange the items below to alter a tweet's display.
          list.append('<li>' + avatar + join + text + '<br />' + date + '</li>');

          list.children('li:odd').addClass('tweet_even');
          list.children('li:even').addClass('tweet_odd');
          list.children('li:first').addClass('tweet_first');
          list.children('li:last').addClass('tweet_last');
        });
        if (s.outro_text) list.after(outro);
      });

    });
  };
  
  // Scrolleable
  
	$.tools = $.tools || {version: {}};
	$.tools.version.scrollable = '1.0.5';
	var current = null;		
	function Scrollable(root, conf) {   
		var self = this;  
		if (!current) { current = self; }		
		function bind(name, fn) {
			$(self).bind(name, function(e, args)  {
				if (fn && fn.call(this, args.index) === false && args) {
					args.proceed = false;	
				}	
			});	
			return self;
		}
		$.each(conf, function(name, fn) {
			if ($.isFunction(fn)) { bind(name, fn); }
		});   
		var horizontal = !conf.vertical;				
		var wrap = $(conf.items, root);				
		var index = 0;		
		function find(query, ctx) {
			return query.indexOf("#") != -1 ? $(query).eq(0) : ctx.siblings(query).eq(0);	
		}		
		var navi = find(conf.navi, root);
		var prev = find(conf.prev, root);
		var next = find(conf.next, root);
		var prevPage = find(conf.prevPage, root);
		var nextPage = find(conf.nextPage, root);
		$.extend(self, {
			getIndex: function() {
				return index;	
			},
			getConf: function() {
				return conf;	
			},
			getSize: function() {
				return self.getItems().size();	
			},
			getPageAmount: function() {
				return Math.ceil(this.getSize() / conf.size); 	
			},
			getPageIndex: function() {
				return Math.ceil(index / conf.size);	
			},
			getRoot: function() {
				return root;	
			},
			getItemWrap: function() {
				return wrap;	
			},
			getItems: function() {
				return wrap.children();	
			},
			getVisibleItems: function() {
				return self.getItems().slice(index, index + conf.size);	
			},
			/* all seeking functions depend on this */		
			seekTo: function(i, time, fn) {
				// default speed
				if (time === undefined) { time = conf.speed; }
				// function given as second argument
				if ($.isFunction(time)) {
					fn = time;
					time = conf.speed;
				}
				if (i < 0) { i = 0; }				
				if (i > self.getSize() - conf.size) { return self; } 				
				var item = self.getItems().eq(i);					
				if (!item.length) { return self; }				
				// onBeforeSeek
				var p = {index: i, proceed: true};
				$(self).trigger("onBeforeSeek", p);				
				if (!p.proceed) { return self; }
				if (horizontal) {
 					var left = -item.position().left;					
					wrap.animate({left: left}, time, conf.easing, fn ? function() { fn.call(self); } : null);
				} else {
					var top = -item.position().top;										
					wrap.animate({top: top}, time, conf.easing, fn ? function() { fn.call(self); } : null);							
				}	
				// navi status update
				if (navi.length) {
					var klass = conf.activeClass;
					var page = Math.ceil(i / conf.size);
					page = Math.min(page, navi.children().length - 1);
					navi.children().removeClass(klass).eq(page).addClass(klass);
				} 
				// prev buttons disabled flag
				if (i === 0) {
					prev.add(prevPage).addClass(conf.disabledClass);					
				} else {
					prev.add(prevPage).removeClass(conf.disabledClass);
				}
				// next buttons disabled flag
				if (i >= self.getSize() - conf.size) {
					next.add(nextPage).addClass(conf.disabledClass);
				} else {
					next.add(nextPage).removeClass(conf.disabledClass);
				}				
				current = self;
				index = i;				
				// onSeek after index being updated
				$(self).trigger("onSeek", {index: i});				
				return self; 
			},			
			move: function(offset, time, fn) {
				var to = index + offset;
				if (conf.loop && to > (self.getSize() - conf.size)) {
					to = 0;	
				}
				return this.seekTo(to, time, fn);
			},
			next: function(time, fn) {
				return this.move(1, time, fn);	
			},
			prev: function(time, fn) {
				return this.move(-1, time, fn);	
			},
			movePage: function(offset, time, fn) {
				return this.move(conf.size * offset, time, fn);		
			},
			setPage: function(page, time, fn) {
				var size = conf.size;
				var index = size * page;
				var lastPage = index + size >= this.getSize(); 
				if (lastPage) {
					index = this.getSize() - conf.size;
				}
				return this.seekTo(index, time, fn);
			},
			prevPage: function(time, fn) {
				return this.setPage(this.getPageIndex() - 1, time, fn);
			},  
			nextPage: function(time, fn) {
				return this.setPage(this.getPageIndex() + 1, time, fn);
			}, 
			begin: function(time, fn) {
				return this.seekTo(0, time, fn);	
			},
			end: function(time, fn) {
				return this.seekTo(this.getSize() - conf.size, time, fn);	
			},
			reload: function() {
				return load();	
			},
			click: function(index, time, fn) {
				var item = self.getItems().eq(index);
				var klass = conf.activeClass;			
				  // check that index is sane
				if (index < 0 || index >= this.getSize()) { return self; }
				// special case with two items
				if (conf.size == 2) {
					if (index == self.getIndex()) { index--; }
					self.getItems().removeClass(klass);
					item.addClass(klass);					
					return this.seekTo(index, time, fn);
				}
				if (!item.hasClass(klass)) {				
					self.getItems().removeClass(klass);
					item.addClass(klass);
					var delta = Math.floor(conf.size / 2);
					var to = index - delta;
					// next to last item must work
					if (to > self.getSize() - conf.size) { 
						to = self.getSize() - conf.size; 
					}
					if (to !== index) {
						return this.seekTo(to, time, fn);		
					}				 
				}
				return self;
			},
			// callback functions
			onBeforeSeek: function(fn) {
				return bind("onBeforeSeek", fn); 		
			},
			onSeek: function(fn) {
				return bind("onSeek", fn); 		
			}
		});
		// prev button		
		prev.addClass(conf.disabledClass).click(function() { 
			self.prev(); 
		});
		// next button
		next.click(function() { 
			self.next(); 
		});
		// prev page button
		nextPage.click(function() { 
			self.nextPage(); 
		});
		// next page button
		prevPage.addClass(conf.disabledClass).click(function() { 
			self.prevPage(); 
		});		
		// keyboard
		if (conf.keyboard) {			
			// keyboard works on one instance at the time. thus we need to unbind first
			$(document).unbind("keydown.scrollable").bind("keydown.scrollable", function(evt) {
				var el = current;	
				if (!el || evt.altKey || evt.ctrlKey) { return; }
				if (horizontal && (evt.keyCode == 37 || evt.keyCode == 39)) {					
					el.move(evt.keyCode == 37 ? -1 : 1);
					return evt.preventDefault();
				}	
				if (!horizontal && (evt.keyCode == 38 || evt.keyCode == 40)) {
					el.move(evt.keyCode == 38 ? -1 : 1);
					return evt.preventDefault();
				}
				return true;
			});	 
		}
		// navi 			
		function load() {			
			// generate new entries
			if (navi.is(":empty") || navi.data("me") == self) {
				navi.empty();
				navi.data("me", self);
				for (var i = 0; i < self.getPageAmount(); i++) {		
					var item = $("<" + conf.naviItem + "/>").attr("href", i).click(function(e) {							
						var el = $(this);
						el.parent().children().removeClass(conf.activeClass);
						el.addClass(conf.activeClass);
						self.setPage(el.attr("href"));
						return e.preventDefault();
					});
					
					if (i === 0) { item.addClass(conf.activeClass); }
					navi.append(item);					
				}
			// assign onClick events to existing entries
			} else {
				// find a entries first -> syntaxically correct
				var els = navi.children(); 
				els.each(function(i)  {
					var item = $(this);
					item.attr("href", i);
					if (i === 0) { item.addClass(conf.activeClass); }
				  item.click(function() {
						navi.find("." + conf.activeClass).removeClass(conf.activeClass);
						item.addClass(conf.activeClass);
						self.setPage(item.attr("href"));
					});
					
				});
			}
			// item.click()
			if (conf.clickable) {
				self.getItems().each(function(index, arg) {
					var el = $(this);
					if (!el.data("set")) {
						el.bind("click.scrollable", function() {
							self.click(index);		
						});
						el.data("set", true);
					}
				});				
			}
			// hover
			if (conf.hoverClass) {
				self.getItems().hover(function()  {
					$(this).addClass(conf.hoverClass);		
				}, function() {
					$(this).removeClass(conf.hoverClass);	
				});
			}			
			return self;
		}
		load();
		// interval stuff
		var timer = null;
		function setTimer() {
			// do not start additional timer if already exists
			if (timer) { return; }
			// construct new timer
			timer = setInterval(function()  {
				// check if interval is being changed dynamically during runtime
				if (conf.interval === 0) {					
					clearInterval(timer);
					timer = 0;
					return;
				}			
				self.next();				
			}, conf.interval);
		}	
		if (conf.interval > 0) {			
			// when mouse enters, autoscroll stops
			root.hover(function() {			
				clearInterval(timer);		
				timer = 0;
			}, function() {		
				setTimer();	
			});
			setTimer();	
		}
	} 
	// jQuery plugin implementation
	$.fn.scrollable = function(conf) { 
		// already constructed --> return API
		var el = this.eq(typeof conf == 'number' ? conf : 0).data("scrollable");
		if (el) { return el; }		
		var opts = {
			// basics
			size: 3,
			vertical:false,			
			clickable: false,
			loop: false,
			interval: 0,			
			speed: 400,
			keyboard: true,			
			// other
			activeClass:'active',
			disabledClass: 'disabled',
			hoverClass: null,			
			easing: 'swing',
			// navigational elements
			items: '.items',
			prev: '.prev',
			next: '.next',
			prevPage: '.prevPage',
			nextPage: '.nextPage',			
			navi: '.navi',
			naviItem: 'a',
			api:false,
			// callbacks
			onBeforeSeek: null,
			onSeek: null
		}; 
		$.extend(opts, conf);		
		this.each(function() {			
			el = new Scrollable($(this), opts);
			$(this).data("scrollable", el);	
		});
		return opts.api ? el: this; 
	};
	
})(jQuery);


// and All together...


$(document).ready(function(){
	
	// init Tooltip
	tooltip();
	
	// tweeter feed
	
	$("#twitter-feed").tweet({
		username: "bsabaric",
		join_text: "auto",
		avatar_size: null,
		count: 3,
		auto_join_text_default: "",
		auto_join_text_ed: "",
		auto_join_text_ing: "",
		auto_join_text_reply: "",
		auto_join_text_url: "",
		loading_text: "Loading tweets..."
	});
	
	// flickr feed
							   
	$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=73342161@N00&lang=en-us&format=json&jsoncallback=?", function(data){																																   			var iStart = Math.floor(Math.random()*(11));	
		// Reset our counter to 0
		var iCount = 0;								
		var htmlString = "<ul>";					
		$.each(data.items, function(i,item){
			// Let's only display 9 photos (a 3x3 grid), starting from a random point in the feed					
			if (iCount > iStart && iCount < (iStart + 7)) {
				var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");		
				htmlString += '<li><a href="' + item.link + '" target="_blank">';
				htmlString += '<img src="' + sourceSquare + '" alt="' + item.title + '" title="' + item.title + '"/>';
				htmlString += '</a></li>';
			}
			// Increase our counter by 1
			iCount++;
		});		
	$('#flickr-feed').html(htmlString + '</ul><div class="clear"></div>');
	});
	
	// init filter content
	
	$('ul#filter-portfolio a, #nav-sec a').click(function() {
		$(this).css('outline','none');
		$('ul#filter-portfolio .active, #nav-sec .active').removeClass('active');
		$(this).parent().addClass('active');
		var filterVal = $(this).text().toLowerCase().replace(' ','-');
		if(filterVal == 'all') {
			$('ul#latest-work li.hidden, .content-main.hidden').fadeIn('slow').removeClass('hidden');
		} else {
			$('ul#latest-work li, .content-main').each(function() {
				if(!$(this).hasClass(filterVal)) {
					$(this).fadeOut('normal').addClass('hidden');
				} else {
					$(this).fadeIn('slow').removeClass('hidden');
				}
			});
		}
		return false;
	});
	
	// init Scrolleable
	
	$(function() {		
		$(".scrollable, .scrolleable-test").scrollable();
	});
	
	// scroll to top
	
	$('a[href=#top]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
	});
	
	// cycle
	
	$('#quotes').cycle({ 
		fx:    'scrollDown', 
		speed:  200,
		timeout:  8000,
		cleartypeNoBg: true
	 });

	
});
