﻿var documentReady;

$(function() {
	RenderPortfolio();

	toolTip = $('#tooltip');

	WireUpEventHandlers();

	OpenPage('portfolio');	
					 
	LoadTwitterStatus();
	
	documentReady = true;
});

function RenderPortfolio() {
	$.each(clients, function(index, value) {
  		$('#portfolio_nav').prepend(
		'<div class="portfolio_navitem" id="' + value.Id + '"><img src="images/portfolio/' + value.Id + '_small.png" alt="' + value.Url +'" /></div>');
	});
	
	// rounded corner hack- this is a todo
	if (!$.browser.msie)
		$('.portfolio_navitem img').css('margin-bottom', '0px');
}

function WireUpEventHandlers() {
	$('.portfolio_navitem').bind('mouseenter', function(e) { ShowToolTip(e, $(this).attr('id')); })
                   		   .bind('mousemove', function(e) { MoveToolTip(e); })
                   		   .bind('mouseleave', function(e) {  HideToolTip(e, false); })
						   .bind('click', function(e) { return ShowFullSize($(this).attr('id')); });
						   				   
	$('#tooltip').bind('mouseleave', function(e) { HideToolTip(e, false); });
	
	$('#fullsize').bind('mouseover', function() { $('#details').fadeIn(); })
				  .bind('mouseout', function() { $('#details').fadeOut(); });
}

function SendMail() {
	var email = $('#txtEmail').val();
	var content = $('#txtContent').val();
	if (email == '' || content == '') 
		{
		alert('Email and Content are both required.');
		return false;
		}
	alert('Thank you. Your message is being sent.');
	return true;
}

//  -----------  //
//      Nav      //
//  -----------  //

function OpenPage(name) {
	if (!$('#' + name).is(':visible'))
		{
		// reset nav images
		$('#nav > div').removeClass('current');
		
		// change selected nav image
		$('#nav_' + name).addClass('current');
		
		// hide all pages
		$('.page').hide();
		
		// show desired page
		$('#' + name).show();
		}
}

//  -----------  //
//   Portfolio   //
//  -----------  //

function GetClient(id) {
	var client = null;
	for (var i = 0; i < clients.length; i++)
		if (clients[i].Id == id) {
			client = clients[i];
			break;
		}
	return client;
}

function PopulatePortfolioDetail(id) {
	var client = GetClient(id);
	if (client == null) return;
	
	if (client.IsDesign)
		$('#client_isdesign').show();
	else
		$('#client_isdesign').hide();
		
	if (client.IsProgramming)
		$('#client_isprogramming').show();
	else
		$('#client_isprogramming').hide();
		
    $('#client_name').text(client.Name);
    $('#client_copy').html(client.Description);
}

var fullSizeVisible;

function ShowFullSize(id) {
	var client = GetClient(id);
	if (client == null) return;
	
	fullSizeVisible = true;
	HideToolTip(null, true);
	
	$('#fullsize').attr('src', 'images/portfolio/' + id + '.png');
	if (client.Url != null && client.Url != '')
		$('#url').show().html('<a href="' + client.Url + '" target="_blank">Open Website in New Window</a>');
	else
		$('#url').hide();

	var popup = $('#popup');
	var body = $('body');
	// popup not visible; can't get measurements
	var popupHeight = 712;
	var popupWidth = 665;
	var top = (body.height() > popupHeight) ? 20 : 12;
    var left = Math.max(0, (body.width() - popupWidth) / 2);
    popup.css('top', top + 'px')
    	 .css('left', left + 'px');
    $('#overlay').fadeIn('slow', function() { popup.fadeIn('slow'); });
}

function HideFullSize() {
	fullSizeVisible = false;
	$('#popup').fadeOut('slow', function() { $('#overlay').fadeOut('slow'); });
}

function Client(id, name, description, url, isDesign, isProgramming) {
    this.Id = id;
    this.Name = name;
    this.Description = description;
    this.Url = url;
    this.IsDesign = isDesign;
    this.IsProgramming = isProgramming;
}

//  -----------  //
//    Tooltip    //
//  -----------  //

var toolTip;
var toolTipShown;
var isAtRightEdge;
var isAtBottomEdge;
var toolTipOffsetX = 20;
var crownHeight = 82;
var toolTipWidth = 320;

function ShowToolTip(e, id) {
    // don't show tooltip if document is not loaded
    if (documentReady && !fullSizeVisible) {
        toolTipShown = true;

		PopulatePortfolioDetail(id);

        // show tooltip with text
        toolTip.show();
    }
}

function MoveToolTip(e) {
    if (toolTipShown && documentReady && !fullSizeVisible) {
        isAtRightEdge = (e.clientX + toolTipOffsetX + toolTipWidth) > $(window).width();
        var toolTipOffsetY = isAtRightEdge ? 20 : -(crownHeight);
        isAtBottomEdge = (e.clientY + toolTipOffsetY + toolTip.outerHeight()) > $(window).height();
        
        if (isAtRightEdge) {
            toolTip.css('left', 'auto')
            	   .css('right', -$(window).scrollLeft() + 'px');
            if (!isAtBottomEdge) {
            	toolTip.css('top', (e.pageY + toolTipOffsetY) + 'px')
            		   .css('bottom', 'auto');
            }
        }
        if (isAtBottomEdge) {
        	toolTip.css('top', 'auto');
        	toolTip.css('bottom', -$(window).scrollTop() + 'px');
        	if (!isAtRightEdge) {
        		toolTip.css('left', (e.pageX + toolTipOffsetX) + 'px');
        	}
        }
        if (!isAtRightEdge && !isAtBottomEdge) {
            toolTip.css('bottom', 'auto')
            	   .css('right', 'auto')
            	   .css('left', (e.pageX + toolTipOffsetX) + 'px')
                   .css('top', (e.pageY - crownHeight) + 'px');
        }
        
       	AdjustToolTipWidth();
    }
}

function HideToolTip(e, forceHide) {
    if (typeof (toolTip) == 'undefined' || (typeof (e) == 'undefined' && !forceHide)) return;
    
    if (!forceHide && IsMouseOverToolTip(e)) return;
    
    toolTip.css('left', "-1000px").css('right', 'auto').css('width', 'auto');
   
   	AdjustToolTipWidth();
}

function AdjustToolTipWidth() {
	// if IE7, tooltip's width goes all wonky.. this is a workaround
	if (toolTip.width() != toolTipWidth)
    	toolTip.width(toolTipWidth);
}

function IsMouseOverToolTip(e){
    var offset = toolTip.offset();
    var isOverToolTip =  (e.pageX > offset.left && isAtRightEdge &&
    	e.pageY > offset.top && isAtBottomEdge);
    return isOverToolTip;
}

//  -----------  //
//    Twitter    //
//  -----------  //

var isLoadingTwitter = true;

function LoadTwitterStatus() {
	// tack on Twitter loader script
	$('body').append('<script src="http://twitter.com/statuses/user_timeline/someweather.json?callback=twitterCallback2&amp;count=1" type="text/javascript"></script>');

	// and while we wait on Twitter, we can watch some pretty ellipses
	setTimeout('LoadingTick()', 1000);
}

function LoadingTick() {
	if (isLoadingTwitter) {
		var ellipses = $('#ellipses');
		var numberOfDots = ellipses.text().length;
		var numberOfDots = (numberOfDots == 3) ? 0 : numberOfDots + 1;
		ellipses.html('');
		for (var i = 0; i < numberOfDots; i++) {
			ellipses.append('.');
		}
		setTimeout('LoadingTick()', 1000);
	}
}

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('<div class="tweet"><span>' + status + '</span>&nbsp;&nbsp;<nobr><a target="_blank" href="http://twitter.com/' + username + '/statuses/' + twitters[i].id + '">' + relative_time(twitters[i].created_at) + '</a></nobr></div>');
    }
    
    $('#gatheringupdates').fadeOut(function() { 
    	$('#twitter_updates').html(statusHTML.join(''));
    	$('.tweet').fadeIn();
    });
    
    isLoadingTwitter = false;
}

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';
    }
}
