var sideGroupHeight = '50px';
var roundeoinput = "Share something... (just start typing here).";
var defaultblogtitle = "Enter Blog Title";
var addComment = 'Add your comment here...';
var selectedTab = 'addMessage';
var tabGroup = 'microblog';
var searchPrompt = 'Search People...';
var clickedTab = false;
var profileSearchVal = 'Search by name, username, or location';
var hash = window.location.hash.substr(1);
var myCKEDITOR = false;

$(document).ready(function(){

	//check browser IE6
	if (jQuery.browser.msie) {
		if(parseInt(jQuery.browser.version) == 6) {
	  	$('#container').prepend('<div class="info info_bg">FYI:  We noticed that you are using an older Internet Browser that isn\'t fully supported by Roundeo.  Get a new browser and everything will work better and look better.  <br /><br />We suggest <li><a href="http://www.firefox.com/">http://www.firefox.com/</a></li><li><a href="http://www.microsoft.com/ie">http://www.microsoft.com/ie</a></li><li><a href="http://chrome.google.com/">http://chrome.google.com/</a></li></div>');
	  }
	}
	
	/*General text manipulation*/
	//truncate long urls in microblogs and comments
	$('.microblog_body a, .comment_body a').livequery(function(){
		var myString = $(this).text();
		if(myString.length > 70){
			$(this).text(myString.substring(0,70)+'...');
		}
	});
	
	/*End general text manipulation*/
	
/*
to enable people copy/pasting url after an ajax call - needs to be worked on more and integrate forward back functionality.  Finally, should probably be specific to each type (roundeo, albums, etc).
if(hash){
	//$('#content').load(hash);
	alert(hash);
}
*/
	//menu search
	$('#menu_search_input').val(searchPrompt);
	$('#menu_search_input').focus(function(){
		if($(this).val() == searchPrompt){
			$(this).val('');
		}
	});
	$('#menu_search_input').blur(function(){
	if($(this).val() == ''){
			$(this).val(searchPrompt);
		}
	});

	//sendto commands
	$('#sendto_options').livequery(function(){
		//open/close who sending to
		$('.changesendto').click(function(){
			$('#sendto_options').slideToggle();
		});
	});
	
	//visual hover for roundeo add form tabs
	$('#roundeo_add_tabs li').click(function(){
		//get the id that is being used.
		clickedTab = $(this).attr('id');
		var roundeoAddClickedUrl = $(this).find('.tab').attr('href');
		$(this).addClass('selectedtab');
		$(this).siblings().removeClass('selectedtab');
				
		if(clickedTab == 'addAlbum' && selectedTab != 'addAlbum'){
			var continueSwitch = checkBlogDraft();
			if(continueSwitch == true){//to keep from moving to another tab
				switchtoAlbum(roundeoAddClickedUrl);
			}
		}else if(clickedTab == 'addBlog' && selectedTab != 'addBlog'){
			switchtoBlog(roundeoAddClickedUrl);
		//check to see if we are coming back to roundeo form from blog or photo album
		}else if((clickedTab == 'addMessage' || 
							clickedTab == 'addLink' || 
							clickedTab == 'addPicture' || 
							clickedTab == 'addMedia') && tabGroup != 'microblog'){
			var continueSwitch = checkBlogDraft();
			if(continueSwitch == true){//to keep from moving to another tab if a draft in progress
				switchtoMicroblog(roundeoAddClickedUrl);
			}
		}
		return false;
	});
	
	$('#roundeoClassFilter .smallButton').livequery(function(){
		$(this).hide();
	});
	
	$('#roundeoClassFilter #RoundeoClass').livequery('change',function(){
		var options = {
			beforeSubmit: function(){
				$('.pagination:last').empty().addClass('loading_bg loadingPage').append('Loading ...');
				$('.post_container').slideUp();
			},
			success: function(response){
				$('#content').hide().html(response).slideDown();
			},
			dataType: 'html'
		}
		
		//set the url hash - todo later
		//window.location.hash = $(this).attr('href');
		$('#roundeoClassFilter').ajaxSubmit(options);
	});
	
	$('#roundeosFilter li div').livequery(function(){
		$(this).hide();
	});
	$('#GroupSelector').livequery('click',function(){
		$('#roundeosFilter li div').slideToggle('fast');
	});
	
	$(".roundeoTab").livequery('click',function(){
		$(this).siblings().removeClass('roundeoTabSelected');
		$(this).siblings().addClass('roundeoTab');
		$(this).addClass('roundeoTabSelected');
	});
	
	//invites
	$('.inviteLink').click(function(){
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
    var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3]/10);
    var lightboxLeft = (arrayPageSize[0] + arrayPageScroll[0]-300)/2;
		$('body').append('<div id="overlay"></div>');
		$("#overlay").hide().css({width: arrayPageSize[0]+'px', height: arrayPageSize[1]+'px'}).fadeIn();
		$.post($(this).attr('href'),{'xyz':''},function(data){
			$("#overlay").after('<div id="popup" class="invite">'+data+'</div>');
			$('#popup').css({top: lightboxTop+'px', left: lightboxLeft+'px'});
		},'html');
		return false;
	});
	$('#popup a.close').livequery('click',function(){
		$("#overlay").remove();
		$("#popup").remove();
	});
	$('#InviteMessage').livequery(function(){
		$(this).hide();
		$('#PopupInviteAddForm').find('#InviteSuccess').hide();//hide the success/fail message too
		$('#InviteSuccess').hide();
	});
	$('#toggleInviteText').livequery('click',function(){
		$(this).parents('form').find('#InviteMessage').slideToggle();
		return false;
	});
	
	//for the popup invite
	$("#PopupInviteAddForm").livequery('submit',function(){
		var thisForm = $(this);
		$(this).ajaxSubmit({
			beforeSubmit: function(){
				$(thisForm).find('input').attr('disabled','disabled');
				$('#PopupInviteAddForm').find('#InviteSuccess').empty().addClass('info loading_bg').append('Sending invite...').show();
			},
			dataType: 'json',
			success: function(data){
		 		$(thisForm).fadeOut();
	 			if(data.success){//then it posted, so let's show the message
					$('#PopupInviteAddForm').find('#InviteSuccess').removeClass('loading_bg').empty().addClass('success_bg').append(data.message).fadeIn();	
 				}else{
					$('#PopupInviteAddForm').find('#InviteSuccess').removeClass('loading_bg').empty().addClass('error_bg').append('We had a problem.  Sorry, please try again.').fadeIn();	
				}
				setTimeout(function(){
					$("#overlay").fadeOut().remove();
					$("#popup").fadeOut().remove();
	   		}, 1500);
			}
		});
		return false;
	});
	
	//profile searches
	$('#ProfileQ').val(profileSearchVal).addClass('dim');
	$('#ProfileQ').focus(function(){
		if($(this).val()==profileSearchVal){
			$(this).val('').removeClass('dim');
		}
	});
	$('#ProfileQ').blur(function(){
		if($(this).val() == ''){
			$(this).val(profileSearchVal).addClass('dim');
		}
	});
	
	$('.findBlurb').hide();
	$('.gotofindBlurb').click(function(){
		$(this).parents('li').find('.findBlurb').slideToggle();
		return false;
	});

	$('#toggleAllComments').livequery(function(){
		$(this).toggle(function(){
			$('.comments').slideDown('fast');
		},function(){
			$('.comments').slideUp('fast');
		});
	});
	
	//comment show/hide		
	$('.comment_content textarea').livequery(function(){
		$(this).val(addComment);
		$(this).addClass('dim');
		$(this).focus(function(){
			if($(this).val() == addComment){
				$(this).removeClass('dim');
				$(this).val('');
			}
		});
	});
	
	$('.getcommentlink').livequery(function(){
		$(this).click(function(){
			$(this).parents('.post_content').find('.comments').slideToggle();
			return false;
		});
	});
	
	$('.photocomments .getphotocommentlink').livequery(function(){
		$(this).click(function(){
			$(this).parents('.photocomments').find('.comments').slideToggle();
			return false;
		});
	});
	
	//formatting comment box
	$('.toggleFormatOn').livequery('click',function(){
		var myId = $(this).parents('.comment_view').find('textarea').attr('id');
		//set the text area to blank if it has generic stuff in it
		if($('#'+myId).val() == addComment){
			$('#'+myId).val('');
		}
		CKEDITOR.replace(myId,{toolbar: 'Basic', height: '100',resize_minHeight: '100',resize_maxWidth: '456',resize_minWidth: '456',removePlugins:'elementspath'});
		CKEDITOR.config.customConfig = '/ckeditor/config.js';
		window.myCKEDITOR = true;
  	$(this).hide();
	});
	
	$('.comment_content form').livequery('submit',function(){
		var commentdiv = $(this).parents('.comment_view');
		var myId = $(this).parents('.comment_view').find('textarea').attr('id');
		var thisform = $(this);
		if(window.myCKEDITOR == true){
			if(CKEDITOR.instances[myId]){
			//if(){//now check and see if this particular instance exists.
				//set the value of the real textarea equal to whatever is in the fckeditor.  even if its empty. we'll late cakephp handle the emtpy values for now
				$('#'+myId).val(CKEDITOR.instances[myId].getData());
				//clear the fckeditor
				CKEDITOR.instances[myId].setData('');
			}
		}
		
		$(this).ajaxSubmit({
			beforeSubmit: loading_comment(commentdiv,thisform),
			dataType: 'json',
			success: function(data){
				$(thisform).find('.commentsubmit').removeAttr('disabled');
				if(data.id){//then it posted, so let's show the message
					$(thisform).livequery(function(){$(this).find('.commentNotify').empty().removeClass('loading_bg').addClass('success_bg').append(data.message);});
					$(thisform).find('textarea').val('');
					$.post('/'+data.authUser+'/comments/view/'+data.id,{'xyz':''},function(response){
						$(commentdiv).before(response).hide().fadeIn();
						$('.commentNotify').hide();
					});
				}else{
					$(thisform).livequery(function(){$(this).find('.commentNotify').empty().removeClass('loading_bg').addClass('error_bg').append(data.message);});
				 	setTimeout(function(){
						$('.commentNotify').fadeOut();
	   			}, 3000);
		 		}
			}
		});
		return false;
	});
	
	//adding tags
	$('a.addtags').livequery('click',function(){
		//load the url here
		var myDiv = $(this).parents('.inlinetags').find('.addTagsDiv');
		myDiv.hide().empty();
		$.post($(this).attr('href'),{'xyz':''},function(data){
			myDiv.append(data).show();
		});
		return false;
	});	
	
	$('form#TagAddForm').livequery('submit',function(){
		var thisForm = $(this);
		$(this).ajaxSubmit({
				beforeSubmit: function(){
					$(thisForm).find('input').attr('disabled','disabled');
				},
				dataType: 'json',
 				success: function(data){
	 				if(data.tags){//then it posted, so let's show the message
	 					$(thisForm).parents('.inlinetags').css('padding-left','24px').addClass('success_bg');
	 					$(thisForm).parents('.inlinetags').find('.myTags').html(data.tags);
						$(thisForm).parents('.addTagsDiv').hide().empty();
 					}else{
				 	
				 }
				}
			});
		return false;
	});
	
	//delete tags
	$(".deletetag").livequery('click',function(){
		var href = $(this).attr("href");
		var myDelete = $(this);
		var myTags = $(this).parents('.inlinetags').find('.myTags');
		if(confirm('Delete all tags listed here?')){
			$(this).hide();
			$(this).parents('.inlinetags').css('padding-left','24px').addClass('loading_bg');
			$(myTags).html('Deleting...');
			$.post(href,{'xyz':''},function(data){
				if(data.success == true){
					$(myDelete).parents('.inlinetags').removeClass('loading_bg').addClass('success_bg');
					$(myTags).html(data.message);
				}else{
					alert(data.message);
				}
			},'json');	
		}
		return false;
	});
	
	//delete commments
	$(".deletecomment").livequery('click',function(){
		ajaxDelete($(this),'comment');
		return false;
	});
	//edit microblogs
	$('.editmicroblog').livequery('click',function(){
		if(confirm('Your microblog will be removed while you edit it.\nIt will also lose anything attached to it (e.g. pictures).\nDo you wish to continue?')){
			$(this).parents('.microblog_view').slideUp();
			switchtoMicroblog($(this).attr('href'));
		}
		return false;	
	});
	//delete microblogs
	$(".deletemicroblog").livequery('click',function(){
		ajaxDelete($(this),'microblog');
		return false;
	});
	//edit blogs
	$('.editblog').livequery('click',function(){
		if(confirm('Your blog will be removed while you edit it.\nDo you wish to continue?')){
			$(this).parents('.blog_view').slideUp();
			switchtoBlog($(this).attr('href'));
		}
		return false;	
	});
	
	//delete blogs
	$(".deleteblog").livequery('click',function(){
		ajaxDelete($(this),'blog');
		return false;
	});
	
	//have to put these here so that they are only used once, otherwise, since I'm reloading the scripts it's a pain
	//these are for blogs and used to be int he blogs.js file
	//delete blogdrafts
  $('.deleteBlogDraft').livequery('click',function(){
  	var myId = $(this).parent().attr('id');
  	if(confirm('Delete this blog draft?')){
	  	$('#'+myId).addClass('loading_bg').append('Deleting...');
	  	$.post($(this).attr('href'), {'xyz':''},function(data){
	  		if(data.success == true){
	  			$('#'+myId).removeClass().addClass('success_bg').fadeOut('slow');	
	  		}else{
	  			$('#'+myId).removeClass().addClass('error_bg');
	  			alert(data.message);
	  		}
			},'json');
		}
		return false;
  });
  //load blog draft form
	$('.draftBlog').livequery('click',function(){
		addNotificationIn('loading_bg','Loading blog draft for editing...');
		$('#roundeo_addform_container').load($(this).attr('href'),{'xyz':''},function(){
			addNotificationOut();
		});
		return false;
	});
	
	//delete albums
	$(".deletealbum").livequery('click',function(){
		ajaxDelete($(this),'album');
		return false;
	});
	//edit album
	$('.editalbum').livequery('click',function(){
		if(confirm('Edit your album (add/delete photos or rearrange)?')){
			$(this).parents('.album_view').slideUp();
			switchtoAlbum($(this).attr('href'));
		}
		return false;	
	});
	
	//all for side group animation
	$('.sideGroup').each(function(){
		var current = $(this);
    current.attr("box_h", current.height());
  });
	$('.sideGroup').css('height',sideGroupHeight);
	$('.sideGroup').hover(function(){
			sideGroupDown($(this));
		},
		function(){
			sideGroupUp($(this));	
	});
	
	//http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links
	$('a[href*=#]').each(function() {
		if (location.hostname == this.hostname
		&& this.hash.replace(/#/,'') ) {
		 var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
		 var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
		  if ($target) {
		 var targetOffset = $target.offset().top;
		 $(this).click(function() {
		   $('html, body').animate({scrollTop: targetOffset}, 400);
		   return false;
		 });
		 }
		}
	});
	//scroll, jump up and down
	$('.modelLink').livequery('click',function(){
		var rel = $(this).parents('#content').find('#'+$(this).attr('rel'));
		if(rel.length > 0){
			scrollTo(rel);
		}else{
			$(this).parents('.post_container').before('<div class="post_container"><div class="loading_bg loadingPage">Loading...</div></div>');
			scrollTo($(this).parents('.post_container').prev());
			$(this).parents('.post_container').prev().load($(this).attr('href'),function(){
				$(this).parents('.post_container').prev().hide().scrollDown();
			});
		}
		return false;
	});
	
	$('.up').livequery('click',function(){
		var targetOffset = $(this).parents('.post_container').prev();
		scrollTo(targetOffset);
		return false;
	});
	$('.down').livequery('click',function(){
		var targetOffset = $(this).parents('.post_container').next().next();
		scrollTo(targetOffset);
		return false;
	});
	
	//pagination for roundeos
	$('.pagination:last a').livequery('click',function(){
		var targetOffset = $('#content');
		scrollTo(targetOffset);
	});
	
	$('.pagination a, a.roundeoTabAjax').livequery('click',function(){
		$('.pagination:last').empty().addClass('loading_bg loadingPage').append('Loading ...');
		$('.post_container').slideUp();
		//set the url hash - todo later
		//window.location.hash = $(this).attr('href');
		$('#content').load($(this).attr('href'),function(){
			$(this).slideDown('fast');
		});
		return false;
	});
	
	/*Photo stuff can go here*/
	$('a.lightbox').livequery(function(){
		$(this).lightbox(
				{fileLoadingImage: "/img/loading.gif",
				fileBottomNavCloseImage:"/img/closelabel.gif",
				fitToScreen: true}
			);
	});
	
	//pagination for photos
	$('a.photoajax').livequery('click',function(){
		var targetOffset = $(this).parents('.album_view');
		scrollTo(targetOffset);
		$(this).parents('.album_view').find('.loadingPhotos').addClass('loading_bg').append('Loading..').show();
		$(this).parents('.album_view').parent().load($(this).attr('href'));
		return false;
	});
	
	$('a.rotateLeft').livequery('click',function(){
		$(".rotateImage").rotateLeft();
		return false;
	});
	
	$('a.rotateRight').livequery('click',function(){
		$(".rotateImage").rotateRight();
		return false;
	});
	
	//send contact support email:
	
	$('.popupLink').click(function(){
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
    var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3]/10);
    var lightboxLeft = (arrayPageSize[0] + arrayPageScroll[0]-550)/2;
		$('body').append('<div id="overlay"></div>');
		$("#overlay").hide().css({width: arrayPageSize[0]+'px', height: arrayPageSize[1]+'px'}).fadeIn();
		$.post($(this).attr('href'),{'xyz':''},function(data){
			$("#overlay").after('<div id="popup">'+data+'</div>');
			$('#popup').css({top: lightboxTop+'px', left: lightboxLeft+'px'});
		},'html');
		return false;
	});
	$('#ContactDontcomplete').livequery(function(){
		$(this).parent('div').hide();
	});
	$('#ContactContactForm').livequery('submit',function(){
		$(this).ajaxSubmit({
			beforeSubmit: function(){
				$('#ContactContactForm input').attr('disabled','disabled');
			},
			dataType: 'json',
			success: function(data){
				if(data.success){//then it posted, so let's show the message
					$('#ContactContactForm').append('<b><img src="/img/success_small.png" />'+data.message+'</b>');
					setTimeout(function(){
						$("#overlay").remove();
						$("#popup").remove();
	   			}, 2000);
				}else{
					alert(data.message);
					$('#ContactContactForm input').removeAttr('disabled');
		 		}
			}
		});
		return false;
	});	
});//end document ready

//function for going to an anchor, or actually any position
function scrollTo(targetOffset){
	$('html, body').animate({scrollTop: targetOffset.offset().top},400);
}

//for side groups sliding images.
function sideGroupDown(chosen){
    var open_height = $(chosen).attr("box_h") + "px";
    $(chosen).animate({"height": open_height}, {duration: "slow" });
}
function sideGroupUp(chosen){
	$(chosen).animate({"height": sideGroupHeight}, {duration: "slow" });
}
function loading_comment(id,thisform){
	$(thisform).find('.commentsubmit').attr('disabled','disabled');
	$(id).before("<div class='commentNotify loading_bg'>Adding comment...</div>");
}
//function for deleting view 'ajax'
function ajaxDelete(myDelete,type){
	var href = myDelete.attr("href");
	var id = myDelete.parents('.'+type+'_view').attr('id');
	if(confirm('Delete this '+type+'?')){
		$(myDelete).hide();
		$('#'+id).prepend("<div class='deleting'><img border=0 src='/img/indicator.gif'> Deleting</div>");
		$.post(href, {'xyz':''},function(data){
			if(data.success == true){
				$('#'+id).slideUp('fast');
			}else{
				alert(data.message);
			}
		},'json');	
	}
}
function switchtoBlog(roundeoAddClickedUrl){
	var oldTabGroup = window.tabGroup;
	window.selectedTab = 'addBlog';
	window.tabGroup = 'blog';
	//show loading
	addNotificationIn('loading_bg','Switching to Blog writer...');
	//do 'ajax' magic and load the form
	if(($('#MicroblogBody').val() != window.roundeoinput || $('#MicroblogBody').val() != 'undefined') && oldTabGroup == 'microblog'){
		$('#roundeo_addform_container').load(roundeoAddClickedUrl,{'data[Blog][body]': $('#MicroblogBody').val(),'data[Blog][draft]': true},function(){
			addNotificationOut();
		});
	}else{
		$('#roundeo_addform_container').load(roundeoAddClickedUrl,function(){
			addNotificationOut();
		});
	}
	
}

function checkBlogDraft(){
	var continueSwitch = true;
	if(window.selectedTab == 'addBlog'){//need to check if we need to update the blog draft and save it before switch.
		if(update_content() && confirm('Save blog draft?\nIf you cancel, your changes will be lost.')){
			autosave(update_content(),false);
			$('#addBlog').addClass('selectedtab');
			$('#addBlog').siblings().removeClass('selectedtab');
			continueSwitch = false;
		}
	}
	return continueSwitch;
	
}

function switchtoMicroblog(roundeoAddClickedUrl){
	window.selectedTab = window.clickedTab;
	window.tabGroup = 'microblog';
	window.keepClicked = true;
	//show loading
	addNotificationIn('loading_bg','Switching to Microblog writer...');
	//load the form
	$('#roundeo_addform_container').load(roundeoAddClickedUrl,function(){
		microblog_render(window.selectedTab);
		addNotificationOut();				
	});
}

function switchtoAlbum(roundeoAddClickedUrl){
	window.selectedTab = 'addAlbum';
	window.tabGroup = 'album';
	//show loading
	addNotificationIn('loading_bg','Switching to Album uploader...');
	
	$('#roundeo_addform_container').load(roundeoAddClickedUrl,function(){
		addNotificationOut();
	});
}

function addNotificationIn(myClass,message,fadeIn){
	if(fadeIn == undefined){
		fadeIn = true;
	}
	$('#addNotification').removeClass().addClass(myClass);
	$('#roundeoAddNotifier').empty().append(message);
	if(fadeIn){$('#addNotification').fadeIn();}
}

function addNotificationOut(timeout){
	if(timeout == undefined){
		timeout = false;
		$('#addNotification').fadeOut();
	}else{
		setTimeout(function(){$('#addNotification').fadeOut()},timeout);
	}
}
//lightbox functions
function getPageSize() {
  var jqueryPageSize = new Array($(document).width(),$(document).height(), $(window).width(), $(window).height());
  return jqueryPageSize;
};
function getPageScroll() {
  var xScroll, yScroll;

  if (self.pageYOffset) {
    yScroll = self.pageYOffset;
    xScroll = self.pageXOffset;
  } else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
    yScroll = document.documentElement.scrollTop;
    xScroll = document.documentElement.scrollLeft;
  } else if (document.body) {// all other Explorers
    yScroll = document.body.scrollTop;
    xScroll = document.body.scrollLeft;
  }

  var arrayPageScroll = new Array(xScroll,yScroll);
  return arrayPageScroll;
};
	    