// JavaScript Document
jQuery(document).ready(function()
{

////////////////////////////////////////////////////////////////////////////////////
//
// 	flicker steram setup
//

$('#flickr_stream').jflickrfeed({								
									 
	limit: 12, // how much imges
	qstrings: {	id: '69258799@N02'}, // your flickr id
	itemTemplate:'<li>' + '<a rel="fancyzoom_group" href="{{image}}" title="{{title}}">' + '<img src="{{image_s}}" alt="{{title}}" />' + '</a>' + '</li>'
	}, function(data) {jQuery('#flickr_stream a').fancybox(); // activate lightbox on flickr thumb
	
});

////////////////////////////////////////////////////////////////////////////////////
//
//	reveals the extension of the file and automatically adds icon // used in links to download
//  To add a new extension for recognition, just follow the settings below.
//

$("a[href$='.pdf']").addClass("pdf");
$("a[href$='.doc']").addClass("doc");
$("a[href$='.zip']").addClass("zip");


////////////////////////////////////////////////////////////////////////////////////
//
//	full size slideshow settings
//

jQuery('.slide_entry_full ul').cycle({
		fx: 'fade',        
		speed:  'slow',
		pager:  '#nav_thumbs_full',
        timeout: 8000,
		pause: 1,
		pagerAnchorBuilder: function(idx, slide) {return '#nav_thumbs_full li:eq(' + (idx) + ') a';}
	});

///////////////////////////////////////////////////////////////////////////////////// 
//
//	regular size slideshow settings
//

jQuery('.slide_entry ul').cycle({
		fx: 'blindY',
		easing: 'easeOutExpo',
		speed:  'slow',
		before: onBefore,
        after: onAfter,
        timeout: 8000,
		pager:  '#number',
		pause: 1
	});

function onAfter() {
 jQuery(".main_title").delay(100).animate({left: '0px' }, 700, 'easeOutBack');
 jQuery(".subtitle").delay(200).animate({left: '0px' }, 700, 'easeOutBack');
}
function onBefore() {
    jQuery(".main_title, .subtitle").animate({left: '-650px' }, 500);
} 

////////////////////////////////////////////////////////////////////////////////////
//
//	half size slideshow settings
//

jQuery('.slide_entry_half').cycle({
		fx: 'fade',
		before: onBeforeHalf,
        after: onAfterHalf ,
		speed:  'slow',
		next: '.go_next',
        timeout: 8000,		
		pause: 1
	});

function onAfterHalf() {
 jQuery(".main_title_half").delay(100).animate({right: '0px' }, 700, 'easeOutExpo');
 jQuery(".subtitle_half").delay(200).animate({right: '0px' }, 700, 'easeOutExpo');
 jQuery(".go_next, .go_read").delay(200).animate({bottom: '0px' }, 700, 'easeOutBack');
}
function onBeforeHalf() {
    jQuery(".main_title_half").animate({right: '-470px' }, 500);
	jQuery(".subtitle_half").animate({right: '-470px' }, 500);
	jQuery(".go_next, .go_read").animate({bottom: '-100px' }, 700);
} 

///////////////////////////////////////////////////////////////////////////////////// 
//
//	post gallery settings // portfolio gallery settings
//

jQuery('.portfolio_showcase, .post_gallery ul, .gallery_fullwidth').cycle({
		fx: 'fade',
		speed:  'slow',
        timeout: 4000,
		pager:  '#number',
		pause: 1
	});

////////////////////////////////////////////////////////////////////////////////////

tentativo_clientslide();
tentativo_iconshover();
tentativo_imagehover();
tentativo_masonry();
tentativo_navigation();
tentativo_toggle();
tentativo_accordion();
tentativo_tabs();
tentativo_lightbox();

});

///////////////////////////////////////////////////////////////////////////////////// 

//----------
// client login and search
//----------
function tentativo_clientslide(){
	
	$("#client_slide > div").css("display", "none");
		
			$(".slide_down a").click(function(){
				$("#client_slide").show().animate({top: '250px' }, 700, 'easeOutBack');
				$("#fade_bg").fadeTo(250, 0.25);
				return false;
			});
      		
      		$("#c_login a").click(function(){
				$("#client_login").show();
			});
			
			$("#c_search a").click(function(){
				$("#client_search").show();
			});
						
			$("#fade_bg, .close").click(function(){
				$("#client_slide").animate({top: '-400px' }, 300, function() {
					$("#client_slide > div").css("display", "none");
					$("#fade_bg").fadeOut({speed:2000});
				});
				
				return false;
			});
			
}

//----------
// icons hover
//----------
function tentativo_iconshover(){
	$(".equal_columns").hover(function(){
		$(this).find("img").animate({right: "25px"}, "fast");
		}, function() {
		$(this).find("img").animate({right: "10px"}, "fast");
	});
}

//----------
// image hover
//----------
function tentativo_imagehover(){
	
	$(".gallery_item, .wrap_image ").hover(function() {
				$(this).find("img").animate({opacity: 0.7}, "slow");
				$(this).find(".over_image").animate({opacity: "show", top: "50%"}, "slow","easeOutExpo");
			}, function() {
				$(this).find("img").animate({opacity: 1}, "fast");
				$(this).find(".over_image").animate({opacity: "hide", top: "-60"}, "fast");
			});
}


//----------
// masonry and filter
//----------
function tentativo_masonry(){
	
	
	var speed = 500,  // animation speed
    $wall = $('#main').find('.wrap_page');

	$wall.masonry({
	  // only apply masonry layout to visible elements
	  itemSelector: '.portfolio_box:not(.invis)',
	  animate: true,
	  animationOptions: {
		duration: speed,
		queue: false
	  }
	});


$('#filtering-nav a').click(function(){
  var colorClass = '.' + $(this).attr('class');

  if(colorClass=='.all') {
    // show all hidden boxes
    $wall.children('.invis')
      .toggleClass('invis').fadeIn(speed);
  } else {  
    // hide visible boxes 
    $wall.children().not(colorClass).not('.invis')
      .toggleClass('invis').fadeOut(speed);
    // show hidden boxes
    $wall.children(colorClass+'.invis')
      .toggleClass('invis').fadeIn(speed);
  }
  $wall.masonry();

  return false;
});

}


//----------
// main navigation
//----------
function tentativo_navigation(){
		  
	$("#nav a").removeAttr('title');
	$("#nav ul").css({display: "none"});
		$(" #nav li").hover(function(){									 
			$(this).find('ul:first').css({visibility: "visible",display: "none"}).slideDown(400,"easeInOutQuart");},
			function(){
			$(this).find('ul:first').css({visibility: "hidden"});
	});
		
}


//----------
// toggle
//----------
function tentativo_toggle(){
	
	$('.toggle h3').each(function() {
		var tis = $(this), state = false, answer = tis.next('div').hide().css('height','auto').slideUp();
		tis.click(function() {state = !state; answer.slideToggle(state);tis.toggleClass('active',state);});
	});

}


//----------
// accordion
//----------
function tentativo_accordion(){
	
	$(".accordion p.accordion_head").click(function(){
														   
	$('.accordion_head').removeClass('accordion_select');
	$(this).addClass('accordion_select');
			
    $(this).next("div.accordion_body").slideToggle(300).siblings("div.accordion_body").slideUp("slow");
    $(this).siblings();
	});
	   
}

//----------
// tabs
//----------
function tentativo_tabs(){
	
	var tabContainers = $('div.tabs > div');
        tabContainers.hide().filter(':first').show();
                        
	$('.tabs .tab_navigation a').click(function () {
			tabContainers.hide();
			tabContainers.filter(this.hash).show();
			$('.tabs .tab_navigation a').removeClass('selected');
			$(this).addClass('selected');
			return false;
	}).filter(':first').click();
	
}

//----------
// fancybox lightbox
//----------
function tentativo_lightbox(){
	
	$("a[rel=fancyzoom]").fancybox();
	
	$("a[rel=fancyzoom_group]").fancybox();
	
	//----------
	// fancybox vimeo 
	//----------
	$("a[rel=fancyvimeo]").click(function() {
		$.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'title'			: this.title,			
				'href'			: this.href.replace(new RegExp("[0-9]", "i"), 'moogaloop.swf?clip_id=1'),
				'type'			: 'swf',
				'swf'			: {'wmode':'transparent','allowfullscreen':'true'}
		});

	return false;
	});	
	
	//----------
	// fancybox youtube 
	//----------
	$("a[rel=fancytube]").click(function() {
		$.fancybox({
				'padding'             : 0,
				'autoScale'   : false,
				'transitionIn'        : 'none',
				'transitionOut'       : 'none',
				'title'               : this.title,
				'width'               : 680,
				'height'              : 495,
				'href'                : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				'type'                : 'swf',    // <--add a comma here
				'swf'                 : {'allowfullscreen':'true', 'wmode':'opaque'} // <-- flashvars here
		}); 

	return false;
	});	
	
}

//----------
// contact
//----------

/* holder for form variables */
var stringVars='';

/* Function to clear form */
function clearForm()
{
	for(i=0; i< document.contact.elements.length; i++)
	{
		if(document.contact.elements[i].type.search(/text/) != -1)
		{
			document.contact.elements[i].value='';
		}
	}
}

/* Function to submit form */
function submitForm()
{
	if(document.getElementById('errorSpanTR').style.display == 'none')
	{
		document.getElementById('errorSpanTR').style.display='inline';
	}
	
	document.getElementById('errorSpan').innerHTML = '<img src="images/loading.gif">';
	
	for(i=0; i< document.contact.elements.length; i++)
	{
		switch(document.contact.elements[i].type)
		{
			case 'text':
			case 'textarea':
			case 'radio':
			case 'select-one':
			stringVars += escape(document.contact.elements[i].name)+'='+escape(document.contact.elements[i].value)+'&';
			break;		
			case 'checkbox':
			if (document.contact.elements[i].checked){
				temp = document.contact.elements[i].name;
				temp = temp.replace(/\[]/,'');
				stringVars += escape(temp)+'='+escape(document.contact.elements[i].value)+'&';	
			}
		}
	}
	doCall();
}
function doCall()
{
	http.open("GET", 'contact.php?' + stringVars, true);
	http.onreadystatechange = handleHttpResponse;
	http.send(null);
}

function handleHttpResponse()
{
	if (http.readyState == 4)
	{
		var response = http.responseText;				
		document.getElementById('errorSpan').innerHTML = response;
		
		if(response.search(/<!---->/) != -1){
			clearForm();
		}
	}
}

function getHTTPObject()
{ 
	var xmlhttp;
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	return xmlhttp;
}
var http = getHTTPObject(); 


//----------
// Flickr
//----------
(function($) {
	$.fn.jflickrfeed = function(settings, callback) {
		settings = $.extend(true, {
			flickrbase: 'http://api.flickr.com/services/feeds/',
			feedapi: 'photos_public.gne',
			limit: 20,
			qstrings: {
				lang: 'en-us',
				format: 'json',
				jsoncallback: '?'
			},
			cleanDescription: true,
			useTemplate: true,
			itemTemplate: '',
			itemCallback: function(){}
		}, settings);

		var url = settings.flickrbase + settings.feedapi + '?';
		var first = true;

		for(var key in settings.qstrings){
			if(!first)
				url += '&';
			url += key + '=' + settings.qstrings[key];
			first = false;
		}

		return $(this).each(function(){
			var $container = $(this);
			var container = this;
			$.getJSON(url, function(data){
				$.each(data.items, function(i,item){
					if(i < settings.limit){
					
						// Clean out the Flickr Description
						if(settings.cleanDescription){
							var regex = /<p>(.*?)<\/p>/g;
							var input = item.description;
							if(regex.test(input)) {
								item.description = input.match(regex)[2]
								if(item.description!=undefined)
									item.description = item.description.replace('<p>','').replace('</p>','');
							}
						}
						
						// Add Image Sizes
						// http://www.flickr.com/services/api/misc.urls.html
						item['image_s'] = item.media.m.replace('_m', '_s');
						item['image_t'] = item.media.m.replace('_m', '_t');
						item['image_m'] = item.media.m.replace('_m', '_m');
						item['image'] = item.media.m.replace('_m', '');
						item['image_b'] = item.media.m.replace('_m', '_b');
						delete item.media;
						
						// Use Template
						if(settings.useTemplate){
							var template = settings.itemTemplate;
							for(var key in item){
								var rgx = new RegExp('{{' + key + '}}', 'g');
								template = template.replace(rgx, item[key]);
							}
							$container.append(template)
						}
						
						//itemCallback
						settings.itemCallback.call(container, item);
					}
				});
				if($.isFunction(callback)){
					callback.call(container, data);
				}
			});
		});
	}
})(jQuery);

//----------
// Twitter
//----------
var tweetUsers = ['macosamx']; // Your Twitter username
var buildString = "";

$(document).ready(function(){

	$('#twitter-ticker').slideDown('slow');
	
	for(var i=0;i<tweetUsers.length;i++)
	{
		if(i!=0) buildString+='+OR+';
		buildString+='from:'+tweetUsers[i];
	}
	
	var fileref = document.createElement('script');
	
	fileref.setAttribute("type","text/javascript");
	fileref.setAttribute("src", "http://search.twitter.com/search.json?q="+buildString+"&callback=TweetTick&rpp=3"); // How meny tweets to display 
	
	document.getElementsByTagName("head")[0].appendChild(fileref);
	
});

function TweetTick(ob)
{
	var container=$('#tweet-container');
	container.html('');
	
	$(ob.results).each(function(el){
	
		var str = '	<div class="tweet">\
					<div class="avatar"><a href="http://twitter.com/'+this.from_user+'" target="_blank"><img src="'+this.profile_image_url+'" alt="'+this.from_user+'" /></a></div>\
					<div class="txt">'+formatTwitString(this.text)+'</div>\
					<div class="time">'+relativeTime(this.created_at)+'</div>\
					<div class="user"><a href="http://twitter.com/'+this.from_user+'" target="_blank">'+this.from_user+'</a></div>\
					</div>';
		
		container.append(str);
	
	});
	
}

function formatTwitString(str)
{
	str=' '+str;
	str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
	str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
	str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
	return str;
}

function relativeTime(pastTime)
{	
	var origStamp = Date.parse(pastTime);
	var curDate = new Date();
	var currentStamp = curDate.getTime();
	
	var difference = parseInt((currentStamp - origStamp)/1000);

	if(difference < 0) return false;

	if(difference <= 5)				return "Just now";
	if(difference <= 20)			return "Seconds ago";
	if(difference <= 60)			return "A minute ago";
	if(difference < 3600)			return parseInt(difference/60)+" minutes ago";
	if(difference <= 1.5*3600) 		return "One hour ago";
	if(difference < 23.5*3600)		return Math.round(difference/3600)+" hours ago";
	if(difference < 1.5*24*3600)	return "One day ago";
	
	var dateArr = pastTime.split(' ');
	return dateArr[4].replace(/\:\d+$/,'')+' '+dateArr[2]+' '+dateArr[1]+(dateArr[3]!=curDate.getFullYear()?' '+dateArr[3]:'');
}
