//Global Vars
var GB_ANIMATION = false;
var firstCreatePageView = true;
var dropDownRemoveCloseTimer;
var openDropDownRemoveID;
var openHeaderRemoveID;
var dropDownCloseTimer;
var openDropDownID;
var openHeaderID;
var dropDownDelay
var zIndexInterval;
var zIndexIntervalCount;
var initialPage;
var initialVideo;
var testConnection = false;
var checkIndex = 0;
var sessionID;
var sessionUserID;
var encSessionUserID;
var sharerID;
var mainCategory = 'Music';
var currentCategory;
var currentSubCategory;
var inFB;
var newUserID;
var newUserChoiceArray;
var newUserCategory;
var sessionFbUid;
var showRatingTimeout;
var showRatingTimeoutLarge;
var showRatingTimeoutFullScreen;
var commentPromptTimeout;


function changeMainCategory(cat, type, category, orderBy, info) {
	mainCategory = cat;
	if (sessionUserID!='160')  {
		//loadInitialMaps('homePage','default', null,'default', sessionUserID);
	}
	//else loadInitialMaps('floPages');
	loadInitialMaps(type, category, 'default', orderBy, info);
	
	if (mainCategory == 'Music') $('#searchInput').attr('value', 'Search any song or artist!'); 
	else if (mainCategory == 'Video') $('#searchInput').attr('value', 'Search any topic!'); 
}

function onSearchClick() {

	var searchForm = $('#searchInput');
	if($(searchForm).attr('value').match('Search any song or artist!') || 
		$(searchForm).attr('value').match('Search any topic.')) $(searchForm).attr('value','');
}


function getBaseURL(url) {
	
	url = url + '?sessionID='+sessionID+'&sessionUserID='+sessionUserID+'&encSessionUserID='+encSessionUserID
				+'&mainCategory='+mainCategory+'&inFB='+inFB;
	return url;
}

function displayWindow(windowWidth){
	var alertLeft = $(document).width()/2-windowWidth/2;
	if (inFB == 'true') alertLeft = 380 - windowWidth/2;
	$('#universalWindow').css('left', alertLeft);
	$('#universalWindow').show();
}

function displayAlert(alertWidth){
	var alertLeft = $(document).width()/2-alertWidth/2;
	if (inFB == 'true') alertLeft = 380 - alertWidth/2;
	$('#universalAlert').css('left', alertLeft);
	$('#universalAlert').show();
}

function closeWindow(){
	$('#universalWindow').fadeOut('slow');
}

function closeAlert(){
	$('#universalAlert').fadeOut('slow');
}

function closeSearchContent(id){
	$('#searchContent_'+id).empty();
}

function hideShareButtonContainer(){
	$('#shareButtonContainer').hide();
	$('#shareToggleButton').css('background-image', 'url(../images/shareToggleOpen.png)');
	$('#shareToggleButton').attr('href', 'javascript:showShareButtonContainer();');
}

function showShareButtonContainer() {
	$('#shareButtonContainer').show();
	$('#shareToggleButton').css('background-image', 'url(../images/shareToggle.png)');
	$('#shareToggleButton').attr('href', 'javascript:hideShareButtonContainer();');
}

function getPageURLForUser(sharingVariables){
	url = getBaseURL('/ajax/getPageURL.php');
	$('#universalWindow').load(url, function() {
		$('#urlInput').attr('value', 'http://flotate.com/'+sharingVariables);
		displayWindow(500);
	});	
}

function showSelectedStars(id, starIndex){
	clearTimeout(showRatingTimeout);
	for (i = 0; i < starIndex + 1; i++){
		$('#star'+i+'_'+id).attr('class', 'ratingStarFull');
	}
	for (j = starIndex + 1; j < 5; j++){
		$('#star'+j+'_'+id).attr('class', 'ratingStarEmpty');
	}
}

function showAverageRating(id, stars){
	showRatingTimeout = setTimeout(function(){displayAverageRating(id, stars);}, 50);
}

function displayAverageRating(id, stars){
	if (stars < 0) stars = 0;
	if ($('#'+id).attr('userRating') != null) stars = parseInt($('#'+id).attr('userRating'));	
	for (i = 0; i < 5; i++){
		if (i < Math.floor(stars)) $('#star'+i+'_'+id).attr('class', 'ratingStarFull');
		else if (i + .5 == stars) $('#star'+i+'_'+id).attr('class', 'ratingStarHalf');
		else if (i >= stars)  $('#star'+i+'_'+id).attr('class', 'ratingStarEmpty');
	}
}

function showAverageRatingLarge(id, stars){
	showRatingTimeoutLarge = setTimeout(function(){displayAverageRatingLarge(id, stars);}, 50);
}

function displayAverageRatingLarge(id, stars){
	if (stars < 0) stars = 0;
	if ($('#'+id).attr('userRating') != null) stars = parseInt($('#'+id).attr('userRating')); 	
	for (i = 0; i < 5; i++){
		if (i < Math.floor(stars)) $('#starLarge'+i+'_'+id).attr('class', 'ratingStarFullLarge');
		else if (i + .5 == stars) $('#starLarge'+i+'_'+id).attr('class', 'ratingStarHalfLarge');
		else if (i >= stars)  $('#starLarge'+i+'_'+id).attr('class', 'ratingStarEmptyLarge');
	}
}

function showSelectedStarsLarge(id, starIndex){
	clearTimeout(showRatingTimeoutLarge);
	for (i = 0; i < starIndex + 1; i++){
		$('#starLarge'+i+'_'+id).attr('class', 'ratingStarFullLarge');
	}
	for (j = starIndex + 1; j < 5; j++){
		$('#starLarge'+j+'_'+id).attr('class', 'ratingStarEmptyLarge');
	}
}

function saveRating(divID, rating) {
	var pageID = divID.split('_')[0];
	url = getBaseURL('/ajax/saveRating.php');
	url = url+'&pageID='+pageID+'&rating='+rating;
	$.ajax({
		url:url, 
		success: function() {
			$('#'+divID).attr('userRating', rating);
			$('#universalAlert').html('<div id = "mediumAlertBox"><div class = "alertText">Thanks for rating!</div></div>');
			displayAlert(200);
			var alertTimeout = setTimeout("closeAlert();", 2000);
		}
	});
}

function quickCreateListeners() {
	url = getBaseURL('/ajax/quickCreatePage.php');
	var quickCreateOptions = {
		success: redirectToPage,
		url: url		
	}
	$('#quickCreateForm').ajaxForm(quickCreateOptions);
}

function showQuickCreate(){
	url = getBaseURL('/ajax/quickCreate.php');
	$('#universalWindow').load(url+'&categoryChoice=null', function() {
		displayWindow(620);
		quickCreateListeners();
	});
}

function changeQuickCreateCategory(categoryChoice) {
		if (categoryChoice != mainCategory) changeMainCategory(categoryChoice);
		url = getBaseURL('/ajax/quickCreate.php');
		$('#mainWindowBox').empty();
		$('#mainWindowBox').load(url+'&categoryChoice='+categoryChoice, function() {
			quickCreateListeners();
		});
}	

function showUserSettings(){
	url = getBaseURL('/ajax/userSettings.php');
	$('#universalWindow').load(url, function() {
		displayWindow(620);
		userSettingsListeners();
	});
}

function userSettingsListeners(){
	url = getBaseURL('/ajax/updateUserSettings.php');
	var updateUserSettings = {
			success: finishUserSettingsUpdate,
			url: url
	};
	$('#editSettingsForm').ajaxForm(updateUserSettings);		
}

function finishUserSettingsUpdate(responseText){
	if (responseText.length > 10) {
		$('#universalAlert').html('<div id = "errorAlertBox"><div class = "alertText">We could not update your settings due to the following:<br><br>'+responseText+'</div></div>');
	}
	else {
		closeWindow();
		$('#universalAlert').html('<div id = "largeAlertBox"><div class = "alertText">Your settings were updated.</div></div>');
	}
	displayAlert(320);
	var alertTimeout = setTimeout("closeAlert();", 3000);
}

function sidebarlisteners(id){
	id = id;
	dbid = id.split('_')[0];
	url = getBaseURL('/ajax/updatecomments.php');
	url = url+'&p='+dbid+'&id='+id;
	var updateCommentOptions = {
			success: commentPostedActions,
			url: url
	};
	$('#commentForm_'+id).ajaxForm(updateCommentOptions);	
}

function showPageInfo(id) {
	id = id;
	dbid = id.split('_')[0];
	url = getBaseURL('/ajax/loadpageinfo.php');
	$.ajax({
		url:url+'&p='+dbid+'&id='+id,
		type:'html',
		success: function(html) {
			$('#commentsButton_'+id).attr('href' , 'javascript:closeComments("'+id+'");');
			if ($('#'+id).attr('name') == 'fullPage') $('#thebox').prepend(html);
			else $('#'+id).after(html);
			sidebarlisteners(id);
		}
	});
}

function closeComments(id){
	$('#comments_'+id).remove();
	$('#commentsButton_'+id).attr('href' , 'javascript:showPageInfo("'+id+'");');
}

function showFeedbackComment(tableID) {
	if (tableID==null)	$('#addFeedback').show();
	else $('#addFeedback_'+tableID).show();
}

function initializeFeedback() {
	displayWindow(620);
	url = getBaseURL('/ajax/loadFeedback.php');	
	var updateFeedbackOptions = {
			success: updateFeedback,
			url:url
	};
	$('.feedbackForm').ajaxForm(updateFeedbackOptions);
}

function showFeedback() {
	url = getBaseURL('/ajax/loadFeedback.php');
	$('#universalWindow').load(url,initializeFeedback);	
}

function updateFeedback(html) {
	$('#universalWindow').html(html);
	initializeFeedback();
}

function commentPostedActions(responseText) {
	$(responseText).each(function(){
		id = $(this).attr('id');
		return false;
	});
	id = id.split('pageInfoBox_')[1];
	$('#comments_'+id).html(responseText);
	sidebarlisteners(id);
}

function checkForConnect() {

	if(sessionFbUid=='333333333') {
		sessionFbUid = FB.Connect.get_loggedInUser();
		url = getBaseURL('/ajax/connectFbAccount.php');
		$.get(url+'&newFbId='+sessionFbUid);
	}
}

function shareVideoOnFacebook(videoTitle, videoID, parentID, parentTitleEnc) {
	FB.Connect.requireSession(function() {
		checkForConnect();
		url = getBaseURL('/ajax/getPageInfoToShare.php');
		$.get(url, {contentID: parentID},  function(pageInfo) {
			encodedPageInfo = eval('('+pageInfo+')');
			FB.ensureInit(function() {
				encodedPageInfo.videoTitle = videoTitle;
				encodedPageInfo.videoID = videoID;
				encodedPageInfo.images[0].href = encodedPageInfo.images[0].href+'&v='+videoID;
				encodedPageInfo.images[1] = {'src' : 'http://i2.ytimg.com/vi/'+videoID+'/default.jpg', 'href':encodedPageInfo.images[0].href};
				encodedPageInfo.url = "http://flotate.com/"+encodedPageInfo.linkID+parentTitleEnc+"&v="+encodedPageInfo.videoID;
				
				FB.Connect.showFeedDialog(137652207504, encodedPageInfo);
			});
			checkForFBContainer();
			
		});
	});
	
	checkForFBContainer();
}

function shareNewPageOnFacebook(contentID) {

	FB.Connect.requireSession(function() {
		checkForConnect();
		url = getBaseURL('/ajax/getPageInfoToShare.php');
		$.get(url, {contentID: contentID},  function(pageInfo) {
			encodedPageInfo = eval('('+pageInfo+')');
			FB.ensureInit(function() {
				encodedPageInfo.url = "http://flotate.com/"+encodedPageInfo.linkID+encodedPageInfo.urlTitle;
				FB.Connect.showFeedDialog(137643132504, encodedPageInfo);
			});
			checkForFBContainer();
			
		});
	});
	
	checkForFBContainer();
	
}

function sharePageOnFacebook(contentID) {

	FB.Connect.requireSession(function() {
		checkForConnect();
		url = getBaseURL('/ajax/getPageInfoToShare.php');
		$.get(url, {contentID: contentID},  function(pageInfo) {
			encodedPageInfo = eval('('+pageInfo+')');
			FB.ensureInit(function() {
				encodedPageInfo.url = "http://flotate.com/"+encodedPageInfo.linkID+encodedPageInfo.urlTitle;
				//FB.Connect.showFeedDialog(92622759634, encodedPageInfo);
				FB.Connect.showFeedDialog(137646872504, encodedPageInfo);
			});
			checkForFBContainer();
			
		});
	});
	
	checkForFBContainer();
}

function allowEmails() {
	FB.ensureInit(function() {
		FB.Connect.showPermissionDialog('email', function(callback) {
			if (callback!=null) {
				url = getBaseURL('/ajax/emailNotificationTrue.php');
				$.get(url);
			}
		});
		checkForFBContainer();
	});
}

function inviteFriends() {
	
	url = getBaseURL('/ajax/inviteFriends.php');
	GB_show('Invite Facebook Friends',url,500,755,'','',0);
	
}

function checkForFBContainer() {
	zIndexIntervalCount = 0;
	zIndexInterval = setInterval("changeFBZIndex();", 50);
}

function changeFBZIndex() {
	if (('.fb_popupContainer').length > 0) {
		$('.fb_popupContainer').css('z-index', 110000);
	}
	zIndexIntervalCount++;
	if (zIndexIntervalCount==10 && navigator.appVersion.match('MSIE')) {
		$('#headerContainer').hide();
		$('#headerContainer').show();
	}
	if (zIndexIntervalCount>100) clearInterval(zIndexInterval);
	
}

function openDropDown(dropDownID) {
	clearTimeout(dropDownDelay);
	cancelTimedCloseDropDown();
	if (dropDownID!=openDropDownID) {
		closeDropDown(openDropDownID);
	}
	dropDownDelay = setTimeout(function (){showDropDown(dropDownID);}, 200);
}

function showDropDown(dropDownID) {
	$('#'+ dropDownID).show();
	openDropDownID = dropDownID;
}

function cancelTimedCloseDropDown() {
	clearTimeout(dropDownCloseTimer);
}

function timedCloseDropDown(dropDownID) {
	dropDownCloseTimer = setTimeout('closeDropDown("'+dropDownID+'");',200);
}

function closeDropDown(dropDownID) {
	$('#'+dropDownID).hide();
	openDropDownID = null;
}

function giveThumbsUp(divID, choice, title, link, rating, parent) {
	if (divID.match('_')) {
		var video = $('#'+divID);
		if (choice != 'add') {
			$('#like_'+divID).attr('href', 'javascript:void(0);');
			$('#dislike_'+divID).attr('href', 'javascript:void(0);');
		}	
		if (choice == 'like') var newNumberLikes = parseInt($(video).attr('likerank')) + 1;
		else if (choice == 'dislike') var newNumberLikes = parseInt($(video).attr('likerank')) - 1;
		if (choice != 'add') $('#numberLikes_'+divID).html(newNumberLikes);
		var link = $(video).attr('videolink');
		if (choice == 'add') title = $(video).attr('realtitle');
		else var title = $(video).attr('title');
		var rating = $(video).attr('rating');
		var parentID = $(video).attr('parent');
		var parentDBID = $(video).attr('dbparent').split('_')[0]; 
	}	
	else {
		var parentID = parent;
		var parentDBID = parent.split('_')[0];
		$('#like_'+divID).attr('href', 'javascript:void(0);');
		$('#dislike_'+divID).attr('href', 'javascript:void(0);');
		if (link == currentLink && parent == currentDBParent) {
			$('#like_current').attr('href', 'javascript:void(0);');
			$('#dislike_current').attr('href', 'javascript:void(0);');
		}
	}	
	
	if ($('#'+parentID).attr('name') == 'fullPage') contentType = 'outerContent';
	else contentType = 'innerContent';

	url = getBaseURL('/ajax/giveThumbsUp.php');
	url = url+'&title='+title+'&link='+link+'&rating='+rating+'&parentID='+parentID+'&choice='+choice+
			'&parentDBID='+parentDBID+'&contentType='+contentType;

	$.get(url, function(returnInfo) {
		if (choice == 'add') {
			$('#'+divID).remove();
			$('#searchContainer_'+parentID).before(returnInfo);

		
		}
		
	});
	
	if (choice == 'like') $('#universalAlert').html('<div id = "mediumAlertBox"><div class = "alertText">You Like this video.</div></div>');
	else if (choice == 'dislike') $('#universalAlert').html('<div id = "mediumAlertBox"><div class = "alertText">You Dislike this video.</div></div>');
	else if (choice == 'add') $('#universalAlert').html('<div id = "mediumAlertBox"><div class = "alertText">Video added.</div></div>');

	displayAlert(240);
	var alertTimeout = setTimeout("closeAlert();", 2000);
}

function addToFavorites(contentID, contentTitle, contentRating) {
	
	if (contentTitle==null) {
		contentTitle = "";
	}
	if (contentRating==null) contentRating = "";
	
	url = getBaseURL('/ajax/favorites.php');
	
	$.get(url, { contentID: contentID, contentTitle:contentTitle, contentRating:contentRating }, function(data){
		
		if (data.match("notLoggedIn")) {
			//GB_show('Create an Account to Save Favorites','scripts/edituserinfo.php',500,545,'','',1);
			$('#universalAlert').html('<div id = "mediumAlertBox"><div class = "alertText">Sign up to save favorites!</div></div>');		
		}
		else {
			$('#universalAlert').html('<div id = "mediumAlertBox"><div class = "alertText">Saved to Favorites!</div></div>');
		}
		displayAlert(200);
		var alertTimeout = setTimeout("closeAlert();", 2000);
	});
}

function addToFriends(homepageID) {
	
	url = getBaseURL('/ajax/addToFriends.php');
	$.get(url, {homepageID:homepageID}, function(data){
		if (data.match("notLoggedIn")) {
			//GB_show('Create an Account to Save Favorites','scripts/edituserinfo.php',500,545,'','',1);
			$('#universalAlert').html('<div id = "mediumAlertBox"><div class = "alertText">Sign up to save friends!</div></div>');
		}
		else {
			$('#universalAlert').html('<div id = "mediumAlertBox"><div class = "alertText">Saved to Friends!</div></div>');
		}
		displayAlert(200);
		var alertTimeout = setTimeout("closeAlert();", 2000);
	});
}


function setClientHeight() {
	
	if (FB.CanvasClient!=null) {
		FB.CanvasClient.setCanvasHeight('900px');	
		FB.CanvasClient.scrollTo(0, 50);
	}
	else {
		setTimeout('setClientHeight();', 50);
	}
	
}

function initializeMainCategory() {
	
	if (inFacebook == true) {
		setFBPlayerHeight();
		setClientHeight();
	}
	else embedPlayer('350', '250');
		
	if (mainCategory == 'Music') $('#searchInput').attr('value', 'Search any song or artist!'); 
	else if (mainCategory == 'Video') $('#searchInput').attr('value', 'Search any topic!');
}

function startFlotate() {
	
	if ($('#fbcss').length >0) {
		inFB = 'true';
		inFacebook = true;
	}
	else {
		inFB = 'false';
		inFacebook = false;	
	}
	initializeMainCategory();
	
	$('#topSearchBox').keyup(autoComplete);
	//$('#searchInput').blur(removeAutoCompleteBox);
		
	if (initialPage!=null) {
		loadInitialMaps('floPage','default', null,'default', initialPage);
	}
	else {
		loadInitialMaps('homePage','default', null,'default', sessionUserID);
	}
	
	$('#leftNavPlayListContainer').sortable();
	$('#playListContainer').unbind('mousedown', determinePlayOrMove);
	$('#playListContainer').bind('mousedown', determinePlayOrMove);
	$('#universalWindow').draggable({handle: '#windowHeader'});

	if ($('#fbcss').length > 0) site = 'false';
	else site = 'true';

}

function closeGetStarted() {
	closeWindow();
	$('#blackout').hide();
}

function startGetStarted(stepNumber) {
	
	if(stepNumber == null) stepNumber = 0;
	
	var url = getBaseURL('/ajax/getStarted.php');
	url = url + '&stepNumber='+stepNumber;
	
	$.ajax({
		url: url,
		type: 'html',
		success: function(html){
			$('#blackout').show();
			$('#universalWindow').html(html);
			if (stepNumber == 0 || stepNumber == 10) displayWindow(740);
	
			if (stepNumber == 0) initiateSaveNewUser();
			if (stepNumber == 10) initiateSignIn();
		}
	});
}

function initiateSignIn() {
	
	var signInOptions = {
		success: checkSignInResponse,
		url: '/ajax/signIn.php'
	}
	$('#signInForm').ajaxForm(signInOptions);
}

function checkSignInResponse(responseText) {

	if(responseText.match('login failed')) {
		alert('login failed');
	}
	else redirectToFlotate();
}

function initiateSaveNewUser() {

	var saveNewUserOptions = {
		success: checkSaveNewUserResponse,
		url: '/ajax/saveNewNonFacebookUser.php'
	};
		
	$('#saveNewUserForm').ajaxForm(saveNewUserOptions);	
}

function checkSaveNewUserResponse(responseText) {

	if (responseText.match("following errors")) {
		alert(responseText);
	}
	else {
		newUserID = responseText.split("::::")[1];
		finishGetStarted();
	}
}

function getStartedSignUp() {

	FB.Connect.requireSession(function() {
		
		newUserID = FB.Connect.get_loggedInUser();
		finishGetStarted();
		
	});
}

function sendToSiteNoSignUp(){
	top.location.href='http://flotate.com/index.php?c=Music';
}

function finishGetStarted() {
	
	if (sessionUserID == null || sessionUserID == '160') {
		url = 'http://flotate.com/index.php?newUserID='+newUserID+'&c=Music';
		top.location.href = url;
	}
	
}

function showAboutFlotate(){
	
	var url = getBaseURL('/ajax/aboutFlotate.php');
	$.ajax({
		url: url,
		type: 'html',
		success: function(html){
			$('#universalWindow').html(html);
			displayWindow(720);
		}
	});
}

function logoutUser() {
	var url = getBaseURL('/ajax/logout.php');
	$.get(url, function() {
		FB.Connect.logout(function() { 
			top.location.href = "http://flotate.com";
		});
	}); 
	
}

function checkFacebookConnectStatus() {
	if (sessionUserID!='160') {
		startFlotate();
	}
	else {	
		if ((initialPage!=null || initialVideo!=null) && $('#fbcss').length > 0 ) timedRequestSignInFacebook();
		else timedCheckIfConnected();
		startFlotate();
	}
}

function requestSignInFacebook() {
	
	FB.Connect.requireSession(function() {
		logInAndRedirect();
	});	
	
	checkForFBContainer();
}

function checkIfConnected() {
	if (FB.Connect.get_loggedInUser()!=null) {
		logInAndRedirect();
	}	
}

function redirectToFlotate() {

	var urlEnd;
	if (initialPage!=null) urlEnd = '?p='+initialPage;
	if (initialVideo!=null) urlEnd = urlEnd+'&v='+initialVideo;
	if (sharerID!=null) urlEnd = urlEnd + '&s='+ sharerID;
	
	if ($('#fbcss').length > 0) {
		if (urlEnd!=null) top.location.href = 'http://flotate.com/'+ urlEnd;
		else top.location.href = 'http://flotate.com/';
	}
	else window.location.reload();
	
}

function logInAndRedirect() {
	url = getBaseURL('/ajax/setCookie.php');
	$.get(url+'&fb_uid='+FB.Connect.get_loggedInUser(), function(){
		redirectToFlotate();
	}); 
}

function timedRequestSignInFacebook() {
	
	if (FB.Connect!=null) requestSignInFacebook();
	else setTimeout('timedRequestSignInFacebook();',50);
	
}

function timedCheckIfConnected() {
	
	if (FB.Connect!=null) {
		setTimeout('checkIfConnected();', 100);
	}
	else setTimeout('timedCheckIfConnected();',50);
}

function timedMoveScreenDown() {
    
    if($('#fbcss').length>0) {
            if(FB.Connect!=null) {
            	FB.CanvasClient.setCanvasHeight('600px');
            	FB.CanvasClient.scrollTo(0, 50);
            }	
            else setTimeout('timedMoveScreenDown();', 100);	
    }
}

