/*

 *

 *  PatrikTotero.com javascript

 *  Latest update:091222

 *  By: Patrik Totero

 *  
 
*/

/*

/*
OBJECTS
*/
var SYS = {};
var SITE = {};
var FUNCTIONS = {};



/*
ON DOM LOAD
*/
$(document).ready(function() {
	
	if ($.browser.msie && $.browser.version.substr(0,1)<9) {
		$('html, body').css({'background':'none'});
		$('body').empty();
		$('body').append('<h1>Patrik Totero</h1><h2>Portfolio - webdevelopment, SEO and Internet Marketing</h2>');
		$('body').append('<p>This site is built on HTML5 and CSS3 for testing purpose. You are using Internet Explorer which does not support this (since it is a crappy browser). May I suggest using <a href="http://www.mozilla.com/en-US/" title="Download FireFox">FireFox</a>, <a href="http://www.apple.com/safari/download/" title="Download Safari">Safari</a> or <a href="http://www.google.com/chrome/" title="Download Google Chrome">Google Chrome</a> for a better web experience?<br /><br />I am sorry for any inconvenience this may have caused you.</p>');
		return;
	}	
	
	SYS.Init();	
	SITE.Init();
	
});

/*SYSTEM*/
SYS.Init = function(){
	
	// Window settings
	this.mouseX;
	this.mouseY;
	this.winWidth = $(window).width();
	this.winHeight = $(window).height();
	this.docHeight  = $(document).height();

	$(window).resize( function(){
		SYS.winWidth = $(window).width();
		SYS.winHeight = $(window).height();
	});
	$(window).scroll(function(){
		this.scrollPos = $(window).scrollTop();
	});
	
	// Twitter settings
	this.twitterAccount = 'DonSanto'; // User name
	this.numberOfTweets = 10
	this.twitterUpdateInterval = 3 // minutes
	this.twitterUpdate = false;
	this.lastTweetId = '';
	
	// Tweetmeme
	//this.tweetmeme_url = 'http://www.patriktotero.com';
	//this.tweetmeme_source = 'DonSanto';
};

/*SITE*/
SITE.Init = function(){
	
	FUNCTIONS.ToolTip();
	FUNCTIONS.TwitterPosts();
	FUNCTIONS.TweetMeme();
	
};

/*FUNCTIONS*/

FUNCTIONS.ResetWindow = function() {
	SYS.docHeight  = $(document).height();
};
FUNCTIONS.ToolTip = function() {
	
    $('[title]').live('mouseover', function() {
    	$('body').append('<span class="tooltip"></span>');
        $('.tooltip').html($(this).attr('title'));
        $('.tooltip').css({ display: 'block', opacity: 0.8 });
        $(this).attr('title', '');
		$(this).attr('name', 'tooltip');
    });

    $('[name="tooltip"]').live('mouseout', function() {
        $(this).attr('title', $('.tooltip').html());
        $(this).removeAttr('name');
        $('.tooltip').remove();
    });
    
    $('[name="tooltip"]').live('mousemove', function() {
    	FUNCTIONS.MouseMove();
        if (SYS.mouseX + $('.tooltip').width() + 55 > SYS.winWidth) {
            $('.tooltip').css({
                left: SYS.mouseX - 30 - $('.tooltip').width()
            });
        } else {
            $('.tooltip').css({
                left: SYS.mouseX + 15
            });
        }
        if (SYS.mouseY  + $('.tooltip').height() + 30 > SYS.docHeight) {
            $('.tooltip').css({
                top: SYS.mouseY - $('.tooltip').height() - 20
            });
        } else {
            $('.tooltip').css({
                top: SYS.mouseY + 8
            });
        }
        //console.log(SYS.winHeight);
        //console.log(SYS.mouseY +' - '+SYS.docHeight);
    });
};
FUNCTIONS.MouseMove = function(){
	$(document).mousemove(function(e){
		SYS.mouseX = e.pageX;
		SYS.mouseY = e.pageY;
	});
};
FUNCTIONS.TwitterPosts = function(twitterUpdate){
	if(SYS.twitterUpdate == false) $('#content').children(':eq(0)').append('<article id="twitter" class="loading"><h2>My latest Tweets</h2></article><hr />');
	$.ajax({
		type: 'GET',
		url: 'http://twitter.com/status/user_timeline/' + SYS.twitterAccount + '.json?count=' + SYS.numberOfTweets + '&callback=?',
		cache: false,
		data: "{ }",
		contentType: "application/json; charset=utf-8",
		dataType: 'json',
		error: function() {
			if(SYS.twitterUpdate == false) $('#twitter').append('<p class="error">Twitter could not deliver the posts. Please try to reload the page</p>');
		},
		success: function(result){

			if(SYS.twitterUpdate == false){
				// Fetch Twitter posts first time
				for(var i=0; i<result.length; i++){			
					//FUNCTIONS.MakeTwitterLinks(result[i]);
					// Find and make links
					var regEx = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
					var newResult = result[i].text.replace(regEx,'<a href="$1">$1</a>');
					var regEx = /[\@]+([A-Za-z0-9-_]+)/ig;
					newResult = newResult.replace(regEx,'<a href="http://twitter.com/$1" title="twitter.com/$1">@$1</a>'); 
					var regEx = /[\#]+([A-Za-z0-9-_]+)/ig;
					newResult = newResult.replace(regEx,'<a <a href="http://search.twitter.com/search?q=%23$1" title="Search for tweets taged [$1] on Twitter">#$1</a>');
					var created = result[i].created_at.substring(0, result[i].created_at.lastIndexOf(':'));
    				$('#twitter').append('<p>' + newResult + '<br /><span>Posted on ' + created + ' | <a href="http://twitter.com/' + SYS.twitterAccount + '/statuses/' + result[i].id + '" title="Permanent link to post on Twitter">Permalink</a> </span></p>');
    			}
    			SYS.lastTwitterId = result[0].id;
 		  		$('#twitter').find('p').hide();
   		  		
   		  	// Update Twitter posts
    		}else if(SYS.twitterUpdate == true){//&&
    			for(var i=result.length-1; i>=0; --i){				
    				//FUNCTIONS.MakeTwitterLinks(result[i]);
    				// Find and make links
					var regEx = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
					var newResult = result[i].text.replace(regEx,'<a href="$1">$1</a>');
					var regEx = /[\@]+([A-Za-z0-9-_]+)/ig;
					newResult = newResult.replace(regEx,'<a href="http://twitter.com/$1" title="twitter.com/$1">@$1</a>'); 
					var regEx = /[\#]+([A-Za-z0-9-_]+)/ig;
					newResult = newResult.replace(regEx,'<a <a href="http://search.twitter.com/search?q=%23$1" title="Search for tweets taged [$1] on Twitter">#$1</a>');
					var created = result[i].created_at.substring(0, result[i].created_at.lastIndexOf(':'));
					if(result[i].id > SYS.lastTwitterId){
    					$('#twitter h2').after('<p>' + newResult + '<br /><span>Posted on ' + created + ' | <a href="http://twitter.com/' + SYS.twitterAccount + '/statuses/' + result[i].id + '" title="Permanent link to post on Twitter">Permalink</a> </span></p>');
    					$('#twitter p').eq(0).hide().slideDown('slow');
    				}
    			}
    			SYS.lastTwitterId = result[0].id;
    		}else{return}
		},
		complete: function(){
			if(SYS.twitterUpdate == false){
				$('#twitter').removeClass('loading');
				$('#twitter').find('p').fadeIn();
				SYS.twitterUpdate = true;
			}
			$('#twitter p:odd').addClass('alt');
			FUNCTIONS.TwitterAccountStatus();
			FUNCTIONS.ResetWindow();
			setTimeout( function(){
				FUNCTIONS.TwitterPosts();
      		}, SYS.twitterUpdateInterval * 60 * 1000);
		}	
	});
};
FUNCTIONS.TwitterAccountStatus = function(){
	$.ajax({
		type: 'GET',
		url: 'http://twitter.com/account/rate_limit_status/' + SYS.twitterAccount + '.json?callback=?',
		cache: false,
		data: "{ }",
		contentType: "application/json; charset=utf-8",
		dataType: 'json',
		error: function() {
			if(twitterUpdate == false) $('#content').children(':eq(0)').append('<article id="twitter"><span class="error">Twitter could not deliver the account status at this time.</span></article>');
		},
		success: function(result){
			if($('#twitterlimit').length == 0){
				$('#twitter h2').after('<span id="twitterlimit">' + result.remaining_hits + '/' + result.hourly_limit +' remaining calls to Twitter this hour</span>');
				$('#twitterlimit').hide();
			}else{
				$('#twitterlimit').remove();
				$('#twitter h2').after('<span id="twitterlimit">' + result.remaining_hits + '/' + result.hourly_limit +' remaining calls to Twitter this hour</span>');
				$('#twitterlimit').hide();
			}
		},
		complete: function(){
			$('#twitterlimit').fadeIn('slow');
		}	
	});
};
FUNCTIONS.MakeTwitterLinks = function(result){
	// Find and make links
	var regEx = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	var newResult = result.text.replace(regEx,'<a href="$1">$1</a>');
	var regEx = /[\@]+([A-Za-z0-9-_]+)/ig;
	newResult = newResult.replace(regEx,'<a href="http://twitter.com/$1" title="twitter.com/$1">@$1</a>'); 
	var regEx = /[\#]+([A-Za-z0-9-_]+)/ig;
	newResult = newResult.replace(regEx,'<a <a href="http://search.twitter.com/search?q=%23$1">#$1</a>');
};
FUNCTIONS.TweetMeme = function(){
	var tweetmeme_url = 'http://www.patriktotero.com';
	var tweetmeme_source = 'DonSanto';
	
	(function(){var _url=window.location.href;var _url=_url.replace(/((?:\?|&)?fbc_receiver=.+)?(?:#.*)?$/,"");var url=escape((typeof tweetmeme_url=="string")?tweetmeme_url:((typeof TWEETMEME_URL=="string")?TWEETMEME_URL:_url)).replace(/\+/g,"%2b");var source=(typeof tweetmeme_source=="string")?escape(tweetmeme_source):((typeof TWEETMEME_SOURCE=="string")?escape(TWEETMEME_SOURCE):false);var style=(typeof tweetmeme_style=="string")?escape(tweetmeme_style):((typeof TWEETMEME_STYLE=="string")?escape(TWEETMEME_STYLE):"normal");var service=(typeof tweetmeme_service=="string")?escape(tweetmeme_service):((typeof TWEETMEME_SERVICE=="string")?escape(TWEETMEME_SERVICE):false);var service_api=(typeof tweetmeme_service_api=="string")?escape(tweetmeme_service_api):((typeof TWEETMEME_SERVICE_API=="string")?escape(TWEETMEME_SERVICE_API):false);var alias=(typeof tweetmeme_alias=="string")?escape(tweetmeme_alias):((typeof TWEETMEME_ALIAS=="string")?escape(TWEETMEME_ALIAS):false);var src="http://api.tweetmeme.com/button.js";switch(style){case"compact":var h=20;var w=90;break;case"rednose":var h=61;var w=50;break;default:var h=61;var w=50;break}src+="?url="+url;src+="&style="+style;if(source!=false){src+="&source="+source}if(service){src+="&service="+service}if(service_api){src+="&service_api="+service_api}if(alias){src+="&alias="+alias}
	
	$('#content article p').eq(0).before('<div id="tweetmeme"><iframe src="'+src+'" height="'+h+'" width="'+w+'" frameborder="0" scrolling="no"></iframe></div>');
	
	tweetmeme_url=null;TWEETMEME_URL=null;tweetmeme_source=null;TWEETMEME_SOURCE=null;tweetmeme_service=null;TWEETMEME_SERVICE=null;tweetmeme_service_api=null;TWEETMEME_SERVICE_API=null;tweetmeme_style=null;TWEETMEME_STYLE=null})();
};








