
// tele_utils.js -- utility functions for telecommutetojuryduty

// make sure jQuery exists
if( typeof jQuery !== "undefined" ){

	// want this to run on everypage once the DOM is ready...
	jQuery(function(){
		// off until i find a better way to prevent spamming of errors
		// setupErrorEmail();
	});

}

function setupErrorEmail(){
	window.onerror = function( message, url, line){
		requestErrorBeEmailed(message, url, line);
	}
}


function requestErrorBeEmailed( message, url, line ){
	url = url || document.location.href;
	line = line || "";
	// print to the console
	// debug_console( 'message emailed: ' + message + " url: " + url + " line: " + line  );

	// make ajax get request to have php email the issue 
	jQuery.get( '/misc/php_mail.php', {"message": message, "url": url, "line": line}, function(){
		// console.log("successful ajax get request!");
	});
}


function getLastFMFaves(){
	
	var lastfm_list = jQuery('#lastfm_list'),
			numSongs = 8;
	
	// show the little spinny thing
	var ajax_loader_img = jQuery(getAjaxLoaderDiv()),
			getURL = 'http://ws.audioscrobbler.com/2.0/?method=user.getlovedtracks&user=dguzzo&api_key=0785c632735040190ebe0b60d1cd4c3e&limit=' + numSongs + '&format=json&callback=?';
	lastfm_list.append(ajax_loader_img);
	
	jQuery.getJSON( getURL, 
		function(data) {
			//debug_console(data);
	    var img, artist, date;
	
			// ajax call complete, remove the spinny thing
			ajax_loader_img.remove();

	    jQuery.each(data.lovedtracks.track, function(i, item) {

	        if (item.image !== undefined) {
						img = "<a href='" + item.artist.url + "' target='_blank'><img class='artist_img' width='50' height='50' src='" + item.image[0]['#text'] + "'></a>";
	        }
	        else {
						img = "";
	        }

	        artist = "<a class='artist_name' href='" + item.artist.url + "' target='_blank'>" + item.artist.name + "</a>";
	        date = "<span class='loved_date'>loved on "+item.date['#text']+"</span>";

	        lastfm_list.append('<li class="containerInset">' + img + artist + ' <a class="song" href="' + item.url + '" target="_blank">' + item.name + '</a>'+ date +'</li>');
	    });

	});
	
}

// from ~> http://tweet.seaofclouds.com/ 
function loadTweets(selector, limit, favorites){

	debug_console( 'loading tweets...', "debug");

	limit = limit || 4;
	favorites = (favorites === undefined) ? true : false;

	jQuery(function(){
		jQuery(selector).tweet({
			avatar_size: 32,
			count: limit,
			username: "YouSoPunny",
			favorites: favorites,
			loading_text: "loading list..."
		});
		
	});
	
}

// little widget that shows my last 5 flickr favorites
function getFlickrFaves(limit){

	limit = limit || 6;

	var faves_list = jQuery('#flickrFaves');
	faves_list.empty(); //make sure it's empty (for the home page ajax tabs; otherwise more li elements get appended)
	
	var ajax_loader_img = jQuery(getAjaxLoaderDiv());
	faves_list.append(ajax_loader_img);
	
	jQuery.getJSON( 'http://api.flickr.com/services/rest/?method=flickr.favorites.getPublicList&api_key=79f2e11b6b4e3213f8971bed7f17b4c4&user_id=49782305@N02&extras=url_sq,url_t,url_s,url_m,url_z,url_l,url_o,path_alias&format=json&jsoncallback=?', 
		
		function(data) {
			
			var rest_photos = data;
			
			jQuery.getJSON( 'http://api.flickr.com/services/feeds/photos_faves.gne?id=49782305@N02&format=json&jsoncallback=?', 
			function(data) { 
				
				ajax_loader_img.remove();
				
				jQuery.each(data.items, function(i, item) {
					if( i >= limit ){
						return;
					}
			    faves_list.append('<li class="full_transparent"><a href=' + item.link + ' target="_blank" class="flickrFaveItem"><img src=' + rest_photos.photos.photo[i].url_sq + ' width="75" height="75"></li>');
			
					jQuery(".full_transparent", faves_list).fadeTo(600, 1);
			
			} )} );
			
	});	
	
}

function getSoundcloud(){
	
	var oembed_mikes_djsets = "http://soundcloud.com/oembed?format=js&url=http://soundcloud.com/mporecchia/sets/dj-mixes/&callback=?";

	jQuery.getJSON( oembed_mikes_djsets, function(data){
	  // console.log(data); 
	    jQuery('#soundcloud').append(data.html);
	});
	
}

// TODO this should just be a file with html, and use jQuery.get() to pop it in place
function IEcheck(){
	
	if( !jQuery.support.boxModel ){

		var box = jQuery( 
			"<div id='boxModelWarningWrapper'> \
			<div id='grayBG'></div> \
			<div id='boxModelWarning'> \
			<div> \
			<p>If you're seeing this message, you must be using an antiquated browser *slightly frowny face*</p> \
			<p>Don't feel bad: luckily there are many alternatives that provide modern capabilities and excellent browsing features and speed. Here are some suggestions:</p> \
			<ul> \
			<li><a href='http://www.google.com/chrome/'>Google Chrome</a></li> \
			<li><a href='http://www.mozilla.com/en-US/firefox/new/'>Mozilla Firefox</a></li> \
			<li><a href='http://windows.microsoft.com/en-US/internet-explorer/products/ie/home'>Internet Explorer 9</a></li> \
			</ul> \
			<div class='clr'>&nbsp;</div> \
			<div id='boxModelWarningClose'><a href='#'>Continue anyway?</a></div> \
			<div> \
			</div> \
			</div> \
			</div>"

		);

		jQuery('body').prepend(box);

		jQuery('#boxModelWarningClose').click( function(){
			jQuery('#boxModelWarningWrapper').remove();
		});

	}
	
}

function getAjaxLoaderDiv(){

	var loader = "<div class='ajax_loader'> \
					<img src='/images/ajax-loader.gif'> \
					</div>";
					
		return loader;

}

// min and max are inclusive! for example, randomRange(0, 2) will either return 0, 1, or 2.
function randomRange(min,max){
	return Math.round(((max-min) * Math.random()) + min);
}


function setupSecondaryLinks(){

	// Archives
	if( jQuery('#archives-2 h3').length) {
		jQuery('#archives-2 h3').toggle( function(){
			jQuery(this).toggleClass('downTriangle');
			jQuery('#archives-2 ul').slideDown();
		}, function(){
			jQuery(this).toggleClass('downTriangle');
			jQuery('#archives-2 ul').slideUp();
			});
	}
	
	// Friends list
	if( jQuery('#linkcat-24 h3').length) {
		jQuery('#linkcat-24 h3').toggle( function(){
			jQuery(this).toggleClass('downTriangle');
			jQuery('#linkcat-24 .blogroll').slideDown();
		}, function(){
			jQuery(this).toggleClass('downTriangle');
			jQuery('#linkcat-24 .blogroll').slideUp();
			});
	}
	
	// Music
	if( jQuery('#linkcat-25 h3').length) {
		jQuery('#linkcat-25 h3').toggle( function(){
			jQuery(this).toggleClass('downTriangle');
			jQuery('#linkcat-25 ul').slideDown(200);
		}, function(){
			jQuery(this).toggleClass('downTriangle');
			jQuery('#linkcat-25 ul').slideUp(280);
			});
	}
	
	// Categories
	if( jQuery('#categories-2 h3').length) {
		jQuery('#categories-2 h3').toggle( function(){
			jQuery(this).toggleClass('downTriangle');
			jQuery('#categories-2 ul').slideDown(200);
		}, function(){
			jQuery(this).toggleClass('downTriangle');
			jQuery('#categories-2 ul').slideUp(280);
			});
	}
	
}

/* round a number to a certain number of decimal places */
function roundNumber(num, dec) {
	return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}


function isMobileDevice(){
	if( navigator.userAgent.match(/Android/i) ||
			navigator.userAgent.match(/webOS/i) ||
			navigator.userAgent.match(/iPhone/i) ||
			navigator.userAgent.match(/iPod/i)
	 ){
		return true;
	}
	return false;
}


function debug_console( text, type, trace ){

	if( typeof console !== "undefined" && console ){
		
		type = (type) ? type : "log";
		
		switch( type ){
			case "log":
			console.log( text );
			break;
			
			case "info":
			console.info( text );
			break;
			
			case "warn":
			console.warn( text );
			break;
			
			case "error":
			console.error( text );
			break;
			
			default:
			console.log( text );
			break;
			
		}

		if( trace ){
			console.trace();
		}
		
	}
	else{
		// IE
	}
}

// from here ~~> http://www.netlobo.com/url_query_string_javascript.html
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

