var _connected = false;
var _swf = false;
var _selectedPhoto = null;
var _photoId = null;
var _selectedPhotoUserId = null;
var _selectedPhotoUserName = null;
var _bLoaded = false;
var __loading = false;
var _feedCopy = "Check my \"Stone Your Friends Photos\" album for Medusa's latest victim. Battle Medusa in CLASH OF THE TITANS: THE VIDEOGAME.\n\n The War of the Gods begins July 27th. Available on PS3 and XBOX 360. To Stone Your Friends visit http://clashofthetitansgame.com/stone";
var _friendFeedCopy = 'You are the latest victim of Medusa\'s stoning spell! Battle Medusa in CLASH OF THE TITANS: THE VIDEOGAME. The War of the Gods begins July 27th. Available on PS3 and XBOX 360. To Stone Your Friends visit http://clashofthetitansgame.com/stone';

/**
 * Clears the currently selected photo
 */
var clearSelection = function() {
	_selectedPhotoUserId = null;
	_selectedPhotoUserName = null;
	_photoId = null;
	sendToActionScript( 'clearSelection', null, 'success' );
}

/**
 * External entry point to login the user
 */
var ensureLogin = function() {
	//	Connected?
	FB.getLoginStatus(function(response) {
		if (response.session) {
			_connected = true;
			_userId = response.session.uid;
			window.setTimeout('_loadPhotos()',100);
		} else {
			_connected = false;
			sendToActionScript( 'ensureLogin', null, 'notconnected' );
			FB.login(function(response){
				if (response.session && response.perms) {
					_connected = true;
					_userId = response.session.uid;
					window.setTimeout('_loadPhotos()',100);
				} else {
					_connected = false;
					sendToActionScript( 'ensureLogin', null, 'notconnected' );
				}
			},{perms:'publish_stream,user_photos,friends_photos'});
		}
	});
}

/**
 * Load photos if not already loaded
 */
var _loadPhotos = function() {
	if (_bLoaded) {
		__loading = false;
		sendToActionScript( 'ensureLogin', null, 'connected' );
	} else {
		if ( ! __loading ) {
			__loading = true;
			if ( ! _bLoaded ) {
				$('div#thumbs').load(_myRoot+'?gp=1',function(){
					_be();
					_bLoaded = true;
					sendToActionScript( 'ensureLogin', null, 'connected' );
					__loading = false;
				});
			} else {
				sendToActionScript( 'ensureLogin', null, 'connected' );
			}
		}
	}
}

/**
 * Pops up the gallery of photos
 */
var choosePhoto = function(bForce) {
	if ( true == bForce || _checkStatus() ) {
		parent.$.fn.colorbox({innerWidth:886, innerHeight:542, inline : true, href:"#choose-photo-wrapper"});
	} else {
		ensureLogin();
	}
}

/**
 * Opens invitation window
 */
var inviteFriends = function() {
	$('div#invite-friends-wrapper').show();
}

/**
 * Initiates share
 */
var sharePhoto = function(sUrl,sOrigUrl) {
	if ( ! _selectedPhotoUserName || _selectedPhotoUserName == 'null' ) {
		_selectedPhotoUserName = 'Somebody';
		_selectedPhotoUserId = _userId;
	}

	var _sMessage = _selectedPhotoUserName + ' Just Got Stoned!';
	var _m = sUrl.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/);
	sUrl = 'http://' + _bu + '/tmp/' + _m[2].toString();

	//	Post photo, get id...
	$.post(_myRoot,
		{
			'msg' : _sMessage,
			'url' : sUrl,
			'token' : _at,
			'r' : 1,
			'sp' : 1
		},
		function(oData){
			if ( oData ) {
				_photoId = oData.id;
			}
		},
		'json'
	);

	sharePopup(sUrl);
}

var sharePopup = function(sUrl){
//	$.get('https://graph.facebook.com/'+_photoId,{access_token:_at},function(data){
//		_linkUrl = data.link;

		var _href = 'http://' + _bu + '/stone';
		var _actionHref = 'http://' + _bu + '/stone?share';
		var _crossPost = true;

		if ( ! _selectedPhotoUserName || _selectedPhotoUserName == 'null' ) {
			_selectedPhotoUserName = 'Somebody';
			_selectedPhotoUserId = _userId;
			_crossPost = false;
		}

		var _sMessage = _selectedPhotoUserName + ' Just Got Stoned!';

		//	post to my wall
		var _msg = {
			name : _sMessage,
			href : _href,
			caption : 'Beware of the Stare!',
			description : _feedCopy,
			media : [
				{ 'type': 'image', 'src': sUrl, 'href': _href}
			]
		};

		FB.ui({
				method: 'stream.publish',
				display: 'dialog',
				user_message_prompt : 'Add a personal note:',
				attachment: _msg,
				action_links : [
					{ 'text' : 'Stone Your Friends!', 'href': _actionHref}
				]
			},
			function(oResponse) {
				var _postId = false;
				var _msg = 'Problemas amigo';

				if (oResponse&&oResponse.post_id){
					_msg = 'success';
					_postId = oResponse.post_id;
				}

				sendToActionScript('sharePhoto',_postId,_msg);
			}
		);
			
		//	Post to friend's wall...
		if ( _crossPost ) {
			try {
				var _sMessage = ' just stoned ' + _selectedPhotoUserName;
				FB.api( '/' + _selectedPhotoUserId + '/feed', 'post', {
					'message' : _sMessage,
					'picture' : sUrl,
					'link' : _href,
					'name' : 'Stone Your Friends',
					'caption' : 'Beware of the Stare!',
					'description' : _friendFeedCopy
				});
			} catch (_ex) {}
		}
//	});
}

/**
 * Returns the selected picture
 */
var getSelectedPhoto = function() {
	sendToActionScript('getSelectedPhoto', _selectedPhoto, 'success');
}

var _be = function(){
	// Initially set opacity on thumbs and add
	// additional styling for hover effect on thumbs
	var onMouseOutOpacity = 0.67;
	$('#thumbs ul.thumbs li').opacityrollover({
		mouseOutOpacity:   onMouseOutOpacity,
		mouseOverOpacity:  1.0,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'
	});

	// Initialize Advanced Galleriffic Gallery
	$('#thumbs').galleriffic({
		delay:                     2500,
		numThumbs:                 20,
		preloadAhead:              20,
		enableTopPager:            true,
		enableBottomPager:         false,
		maxPagesToShow:            6,
		imageContainerSel:         '#slideshow',
		controlsContainerSel:      '#controls',
		captionContainerSel:       '#caption',
		loadingContainerSel:       '#loading',
		renderSSControls:          false,
		renderNavControls:         true,
		playLinkText:              '',
		pauseLinkText:             '',
		prevLinkText:              '&lsaquo; Previous Photo',
		nextLinkText:              'Next Photo &rsaquo;',
		nextPageLinkText:          'Next &rsaquo;',
		prevPageLinkText:          '&lsaquo; Prev',
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 900,
		onImageSelected:	   function(oImage) {
			_selectedPhoto = oImage.slideUrl;
			try
			{
				var _sTemp = $(oImage.caption.context).attr('id');
				if (_sTemp) {
					_sTemp = _sTemp.split('|');
					_selectedPhotoUserId = _sTemp[0];
					_selectedPhotoUserName = _sTemp[1];
				}
			} catch (e) {}

			$.fn.colorbox.close();
			sendToActionScript( 'choosePhoto', null, _selectedPhoto );
		},
		onSlideChange:             function(prevIndex, nextIndex) {
			// 'this' refers to the gallery, which is an extension of $('#thumbs')
			this.find('ul.thumbs').children()
				.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
				.eq(nextIndex).fadeTo('fast', 1.0);
		},
		onPageTransitionOut:       function(callback) {
			this.fadeTo('fast', 0.0, callback);
		},
		onPageTransitionIn:        function() {
			this.fadeTo('fast', 1.0);
		}
	});
}

/**
 * External entry point to login the user
 */
var swfLoaded = function() {
	_swf = true;
	if (_checkStatus()){
		_loadPhotos();
	}
}

var thisMovie = function(movieName) {
	if ( navigator.appName.indexOf("Microsoft") != -1 )
		return window[movieName];

	return document[movieName];
}

var sendToActionScript = function(sCallName,arResults,sStatus){
	try {
		switch ( sCallName )
		{
			case 'getSelectedPhoto':
				thisMovie("flashcontent").getSelectedPhoto( sCallName, arResults, sStatus );
				break;

			case 'shareSelectedPhoto':
				thisMovie("flashcontent").shareSelectedPhoto( sCallName, arResults, sStatus );
				break;

			case 'clearSelection':
				thisMovie("flashcontent").clearSelection( sStatus );
				break;

			case 'ensureLogin':
				thisMovie("flashcontent").ensureLogin( sStatus );
				break;

			case 'choosePhoto':
				thisMovie("flashcontent").choosePhoto( sStatus );
				break;

			case 'sharePhoto':
				thisMovie("flashcontent").sharePhoto( sStatus );
				break;
		}
	} catch (e) {}
}

/**
 * Checks the status of the FB user...
 */
var _checkStatus = function() {
	FB.getLoginStatus(function(response) {
		if (response.session) {
			_connected = true;
		} else {
			_connected = false;
		}
	});
	return _connected;
}

/**
 * Doc ready
 */
$(function() {
	// We only want these styles applied when javascript is enabled
	$('div.navigation').css({'overflow':'hidden','width' : '300px', 'float' : 'left'});
	$('div.content').css('display', 'block');

	$.getScript('http://connect.facebook.net/en_US/all.js',function(){
		FB.init({appId: '109769522400561', status: true, cookie: true, xfbml: true});

		FB.Event.subscribe('auth.sessionChange', function(response) {
			if (response.session) {
				_connected = true;
				_userId = response.session.uid;
				_loadPhotos();
			} else {
				_connected = false;
				sendToActionScript( 'ensureLogin', null, 'notconnected' );
			}
		});
	});
});
