$( function() {
	$( '#siteHeader .nav .homeButton' ).click( function() {
		window.location = 'http://www.kingnitram.com/';
	});
});




/* -- JQUERY ADDRESS ROUTINES ----------------------------------------
 *
 *
 */
function parseSWFAddressParamsFor( $_value ) {
	var _param = $_value.match( /.+\=/ );
	if( _param != null ) {
		_param = _param[0].substring( 0, _param[0].length-1 );
		var _value = $_value.match( /\=.+/ );
		_value = _value[0].substring( 1 );
		var _data = {};
		_data[_param] = _value;
		return _data;
	}
	else return null;
}
function updatePageTitleWith( $_title ) {
	if( $_title != '' )
		$.address.title( $_title );
	else $.address.title( 'King Nitram & the Merry Universe!' );
	$( 'meta[name="keywords"]' ).attr( 'content', $_title );
}
function updateLinkThumbWith( $_thumb ) {
	$( '#link-thumb' ).replaceWith( 
		'<link id="link-thumb" rel="image_src" href="' + $_thumb + '" />' 
	);
}



/* -- SITE HEADER ROUTINES ----------------------------------------
 *
 *
 */
function initSiteHeader() {
	setTimeout( function() {
		transformHeader();
	}, 2000 );
}

function transformHeader() {
	$( '.kn-logo-big' ).hide();
	$( '.kn-logo-small' ).show();

	// show random status
	getRandomStatus();
	
	// show random art
	getRandomArt();
}

// get random status
function getRandomStatus() {
	$.ajax({
		url: '_scripts/api.php',
		data: {
			action: 'getRandomStatus'
		},
		dataType: 'json',
		success: function( $_result ) {
			$( '#balloon' ).fadeOut( function() {
				$( this ).css( 'top', '-1000px' ).show();
				resizeAndShowBalloonFor( $_result.message );
			});

			setTimeout( function() {
				getRandomStatus();
			}, 60000 );
		}
	});
}
function resizeAndShowBalloonFor( $_message ) {
	$( '.balloon-text' ).html( $_message );
	$( '.balloon-middle' ).height( 0 );

	var _balloonTopHeight = $( '.balloon-top' ).height();
	var _balloonBottomHeight = $( '.balloon-bottom' ).height();
	var _minHeight = _balloonBottomHeight + _balloonTopHeight - 40;
	var _textHeight = $( '.balloon-text' ).height();
	if( _textHeight > _minHeight ) {
		var _extraHeight = _textHeight - _minHeight;
		$( '.balloon-middle' ).height( _extraHeight );
	}
	var _textOffsetTop = ($( '#balloon' ).height() - _textHeight ) / 2 + 4;
	$( '.balloon-text' ).css( 'top', _textOffsetTop+'px' );
	$( '#balloon' ).hide().css( 'top', '45px' ).fadeIn();;
}

// get random art
function getRandomArt() {
	$.ajax({
		url: '_scripts/api.php',
		data: {
			action: 'getRandomThreads',
			type: 'typeImage',
			limit: 5
		},
		dataType: 'json',
		success: function( $_result ) {
			//console.log( $_result );
			var _thumbs = '';
			$.each( $_result, function( $_key, $_value ) {
				//console.log( $_value );
				_thumbs += '<div class="thumb-button">' +
					'<a href="?tid=' + $_value.threadId + '" rel="address:tid=' + $_value.threadId + '" address="true">' +
                    '<img src="_data/images/' + $_value.imageData.smallFile + '" alt="' + $_value.title + '" border="0" />' +
                    '</a></div>';
			});	
			$( '#art-sample' ).html( _thumbs );

			setTimeout( function() {
				getRandomArt();
			}, 60000 );
		}
	});
}
								

// -- NAVIGATION ROUTINES ---------------------------
//
//
function gotoSelectedImageAlbum() {
	window.location = 'http://www.kingnitram.com/image.php?g=' + document.imageAlbumsSelectForm.imageAlbumsSelect.value;
}

function gotoSelectedAudioAlbum() {
	window.location = 'http://www.kingnitram.com/audio.php?g=' + document.audioAlbumsSelectForm.audioAlbumsSelect.value;
}



// -- REPLACE A DIV WITH AJAX REQUEST -----------------------------------------
//
//
function replaceDivWithRequest( div, request ) {
	$.ajax({
		type: "GET",
		url: request,
		success: function( result ) {
			document.getElementById( div ).innerHTML = result;
			onFbLogin();
		}
	 });
}

// -- FACEBOOK --------------------------------------
//
//
function onFbLogin() {
	var fbInfo = FB.Facebook.apiClient.users_getInfo( 
		FB.Facebook.apiClient.get_session().uid, 
		['uid', 'name', 'pic_square_with_logo'],
		renderFbCommentForm
	);
}

function fbs_click() {
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,heigt=436');
	return false;
}


function fbRequestStreamPublish( message, mediaType, mediaData, action, actionLink, description, caption ) {
	var media;
	if( mediaType == 'image' ) {
		media = [{
			'type': 			'image',
			'src': 				mediaData.source,
			'href': 			mediaData.link
		}];
	}
	else if( mediaType == 'audio' ) {
		media = [{
			'type':				'mp3',
			'src': 				mediaData.source,
			'title':			mediaData.title,
			'artist':			mediaData.artist,
			'album':			mediaData.album
		}];
	}
	var attachments = {
		'name': 			'King Nitram & the Merry Universe!',
		'href': 			actionLink,
		'description': 		description,
		'caption': 			caption,
		'media': 			media
	};
	var actionLinks = [{ 
		"text": 			action, 
		"href": 			actionLink
	}];
	FB.Connect.streamPublish( message, attachments, actionLinks );//, null, null, null, handleStreamPublishResult );
}


	
// -- SUBMIT A COMMENT --------------------------------------------------------
//
//
// render fb comment form
function renderFbCommentForm( userInfo ) {
	// ids for each comment form
	var commentForms = [{
			addCommentTemplateId: 'addImageCommentTemplate',
			fbAddCommentTemplateId: 'fbuAddImageCommentTemplate'
		},
		{	addCommentTemplateId: 'addAudioCommentTemplate',
			fbAddCommentTemplateId: 'fbuAddAudioCommentTemplate'
		},
		{	addCommentTemplateId: 'addWidgetCommentTemplate',
			fbAddCommentTemplateId: 'fbuAddWidgetCommentTemplate'
		}
	];
	for( var i=0; i < commentForms.length; i++ ) {
		var addCommentTemplate = document.getElementById( commentForms[i].fbAddCommentTemplateId );
		if( addCommentTemplate != null ) {
			addCommentTemplate = addCommentTemplate.innerHTML;
			addCommentTemplate = addCommentTemplate.replace(
				/\[FBUID\]/g,
				userInfo[0]['uid']
			);
			addCommentTemplate = addCommentTemplate.replace(
				/\[NAME\]/g,
				userInfo[0]['name']
			);
			addCommentTemplate = addCommentTemplate.replace(
				/\[AVATAR\]/g,
				userInfo[0]['pic_square_with_logo']
			);
			addCommentTemplate = addCommentTemplate.replace(
				/\[FB_THUMB\]/g,
				"<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>"
			);
			addCommentTemplate = addCommentTemplate.replace(
				/\[FB_WELCOME\]/g,
				"<div style='font-size:13px;'>Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name>.</div>"+
				"<div style='font-size:11px;margin-bottom:5px;'>You are signed in with your Facebook account.</div>"
			);
			addCommentTemplate = addCommentTemplate.replace(
				/\[FB_NOTES\]/g,
				"<div style='font-size:11px;margin-top:8px;font-style:italic;'>Comments left here will NOT appear on your Facebook Wall<br />unless yu grant permission afterwards. Thank you!</div>"
			);
			//alert( addCommentTemplate );
			document.getElementById( commentForms[i].addCommentTemplateId ).innerHTML = addCommentTemplate;
		}
	}
	// because this is XFBML, we need to tell Facebook to re-process the document 
	FB.XFBML.Host.parseDomTree();
}

// submit comment type for thread id
function submitCommentTypeForThreadId( type, threadId ) {
	// data
	var query = "?action=submitComment"+
		"&threadId="+document.getElementById( type ).threadId.value+
		"&uid="+document.getElementById( type ).uid.value+
		"&fbuid="+document.getElementById( type ).fbuid.value+
		"&name="+document.getElementById( type ).name.value+
		"&comment="+document.getElementById( type ).comment.value;

	// add guest attributes
	if( type == 'guestAddImageCommentForm' || type == 'guestAddAudioCommentForm' || type == 'guestAddWidgetCommentForm' ) {
		query += "&email="+document.getElementById( type ).email.value;
	}
	// add facebook attributes
	else {
		query += "&fbuid="+document.getElementById( type ).fbuid.value+
			"&avatar="+escape( document.getElementById( type ).avatar.value );
	}

	// web service
	$.ajax({
		type: "GET",
		url: '_scripts/api.php'+query,
		success: function( result ) {
			if( type == 'guestAddImageCommentForm' || type == 'fbuAddImageCommentForm' ) {
				getHomepageImageDataFor( threadId );
			}
			else if( type == 'guestAddAudioCommentForm' || type == 'fbuAddAudioCommentForm' ) {
				getHomepageAudioDataFor( threadId );
			}
			else if( type == 'guestAddWidgetCommentForm' || type == 'fbuAddWidgetCommentForm' ) {
				getWidgetSocialDataFor( threadId );	
			}
			
			// prompt to publish to facebook
			var comment = document.getElementById( type ).comment.value;
			var mediaData;
			var action = document.getElementById( type ).callbackAction.value;
			var actionLink = document.getElementById( type ).callbackURL.value;
			
			var description = document.getElementById( type ).mediaDescription.value;
			var caption = document.getElementById( type ).mediaCaption.value;
			
			if( type == 'fbuAddImageCommentForm' || type == 'fbuAddWidgetCommentForm' ) {
				mediaData = {
					source: document.getElementById( type ).mediaSource.value,
					link: actionLink
				};
				fbRequestStreamPublish( comment, 'image', mediaData, action, actionLink, description, caption );
			}
			else if( type == 'fbuAddAudioCommentForm' ) {
				mediaData = {
					source: document.getElementById( type ).mediaSource.value,
					title: document.getElementById( type ).mediaTitle.value,
					artist: document.getElementById( type ).mediaArtist.value,
					album: document.getElementById( type ).mediaAlbum.value
				};
				fbRequestStreamPublish( comment, 'audio', mediaData, action, actionLink, description, caption );
			}
			
		}
	 });
}







// -- AJAX REQUESTS -------------------------------
//
//
// image data
function getHomepageImageDataFor( threadId ) {
	replaceDivWithRequest( 
		'imageContent', 
		'ajax_homepage_imageContent.php?tid='+threadId
	);
}
// image album data
function getImageAlbumDataForSelected() {
	replaceDivWithRequest( 
		'imageContent', 
		'ajax_homepage_imageContent.php?g='+document.imageAlbumsSelectForm.imageAlbumsSelect.value 
	);
}


// audio data
function getHomepageAudioDataFor( threadId ) {
	replaceDivWithRequest( 
		'audioContent', 
		'ajax_homepage_audioContent.php?tid='+threadId 
	);
}
// audio album data
function getAudioAlbumDataForSelected() {
	var currentURL = new String( location.href );
	location = currentURL.replace(/\?.*/,'') + '?g='+document.audioAlbumsSelectForm.audioAlbumsSelect.value;
	/*replaceDivWithRequest( 
		'audioContent', 
		'ajax_homepage_audioContent.php?ag='+document.audioAlbumsSelectForm.audioAlbumsSelect.value 
	);
	*/
}








