/**
 * Tagger.fm Autotag 1.0
 * 
 * @author	Tijs Verkoyen <tijs@netlash.com>
 */
// create tagger-object if needed
if(!jsTagger) { var jsTagger = new Object(); }

jsTagger = {
	// data members
	baseUrl: 'http://tagger.fm',
	
	// initiates the object
	init: function() {
		// insert css into the head
		$('head').append('<link rel="stylesheet" type="text/css" media="screen" href="'+ jsTagger.baseUrl +'/autotag/1.0/layout/css/autotag.css" />');
	
		// bind clicks for autotag-buttons
		$('.taggerfmAutoTagButton').bind('click', function(evt) { jsTagger.autoTag.click(evt, $(this)); });
	},
	
	// end of the object
	eof: true
}

jsTagger.autoTag = {
	// data members
	timer: null,
		
	// click event
	click: function(evt, element) {
		evt.preventDefault();
		
		// reset fragment
		document.location.href = document.location.href.split('#')[0] + '#'; 
		
		// set timer
		jsTagger.autoTag.timer = setInterval('jsTagger.autoTag.checkUrl();', 500);
		
		// buil iframeUrl
		var iframeUrl = element.attr('href') +'&iframe=true&return='+ document.location.href;
		
		// build html
		var htmlToAppend = 	'<div id="taggerfmWrapper" style="display: none;">' +
							'	<iframe id="taggerfmIFrame" src="'+ iframeUrl +'" scrolling="no" frameborder="no" style="width: 520px; height: 292px;"></iframe>' +
							'</div>';
		
		// append the html into the body
		$('body').append(htmlToAppend);
		
		// position the box
		var left = parseInt(($('body').width() - $('#taggerfmWrapper').width()) / 2);
		$('#taggerfmWrapper').css('left', left);
		$('#taggerfmWrapper').css('top', 100);
		
		// show
		$('#taggerfmWrapper').show();
		
		// bind event
		$(document).keyup(function(evt) { if(evt.keyCode == 27) { jsTagger.autoTag.close(); } });
		$('#taggerfmWrapperClose').click(function(evt) { evt.preventDefault(); jsTagger.autoTag.close(); });
	},

	// check if the url has changed
	checkUrl: function() {
		// get chunks
		var chunks = document.location.href.split('#');
		
		// get fragment
		if(chunks.length > 1 && chunks[1] != '') {
			// check fragement
			if(chunks[1] == 'close') { jsTagger.autoTag.close(); }
		}
		
		// clear fragment
		document.location.href = chunks[0] + '#';  
	},
	
	// close
	close: function() {
		// fadeout
		$('#taggerfmWrapper').fadeOut(750, function() { $(this).remove(); });
		
		// unbind
		$(document).unbind('keypress');

		// clear timer
		clearInterval(jsTagger.autoTag.timer);
	},
	
	// end of the object
	eof: true		
}

// init the object
$(document).ready(function() { jsTagger.init(); });