// Bubbly interface javascript. Requires jquery. 

jQuery(document).ready(function() {
				
	$=jQuery;
	
	// home link on top logo 
	$("h1#logotop").click(function(e){ window.location=bubbly_site_base_url; });
	
	// submit an entry form file input fields 
	$(".addimage.moreinput a").click(function(e) { 
		$("."+$(this).attr("rel")).slideDown(); 
		$(".more_"+jQuery(this).attr("rel")).hide();
		e.preventDefault(); 
	});
	$(".addimages a").click(function(e){
		$("."+$(this).attr("rel")).slideDown(); 
		$(".addimages").hide();
		e.preventDefault(); 							   
	});
	
	// submit entry: media URL fields 
	$(".addvideo.moreinput a").click(function(e) {
		var nextdivnum = $(this).attr("rel");
		$("#movieinputcontainer-"+nextdivnum).slideDown();
		nextdivnum = Number(nextdivnum);
		nextdivnum = nextdivnum+1;
		if (nextdivnum>12) $(".addvideo.moreinput").hide(); // 12 is hardcoded for now 
		$(this).attr("rel",nextdivnum);
		e.preventDefault(); 
	});
	
	// register: display name autopopulates on register form 
	$("#bubbly_register_firstname").bind('blur',function(e) { 
			if ($("#bubbly_register_display_name").val() == '') 
				$("#bubbly_register_display_name").val($("#bubbly_register_firstname").val());
		});
	$("#bubbly_register_lastname").bind('blur',function(e) { 
			if ($("#bubbly_register_display_name").val() == '' || jQuery("#bubbly_register_display_name").val() == $("#bubbly_register_firstname").val()) 
				$("#bubbly_register_display_name").val($("#bubbly_register_firstname").val()+' '+$("#bubbly_register_lastname").val());
		});
	// disable submit button on submit: Register & Edit Profile forms
	$("#bubbly_register").bind("submit",function() { 
		$("#bubbly_register_submit").attr('disabled', 'disabled');
		$("#bubbly_register .ajax-loader").show(); 											 
	});
	$("#edit_user_form").bind("submit",function() { 
		$("#profilesubmit").attr('disabled', 'disabled');
		$("#edit_user_form .ajax-loader").show(); 											 
	});
	
	// submit entry: onsubmit validate entry form and put a loading graphic on while uploading 
	$("#bubbly-submit-form").bind("submit",function() { 
		if ($("#bubbly-submit-title").val() != "" && $("#bubbly-submit-text").val() != "" ) {
			$("#bubbly-submit-button").attr('disabled', 'disabled');
			$("#bubbly-submit-form .ajax-loader").show(); 
		} else {
			$("#bubbly-submit-form .formerror").text("Please fill in at least the Title and Text fields");
			return false;
		}
	});
	
	// edit entry: onsubmit validate entry form and put a loading graphic on while uploading 
	$("#bubbly-edit-entry").bind("submit",function() { 
		if ($("#entry_title").val() != "" && $("#entry_content").val() != "" ) {
			$("#bubbly-edit-entry #submit").attr('disabled', 'disabled');
			$("#bubbly-edit-entry .ajax-loader").show(); 
		} else {
			$("#bubbly-edit-entry .formerror").text("Please fill in at least the Title and Text fields");
			return false;
		}
	});
	
	// qtips for entry browse view 
	$.each($('div.entry'),function(){
		var entryid = "#"+$(this).attr("id");
		var thecontent = "<span class='excerpt'>"+$(entryid+" .entry_excerpt").text()+"</span><br /> "+
			"<span class='date'>"+$(entryid+" .date").text()+"</span>";
		$(this).qtip({
			show: { event: "mouseover" },
			hide: { event: "mouseout" },
			content: thecontent, 
			position: { adjust: { x: 0, y: 25 }, at: "top center", my: "bottom center" },
			style: { tip: { corner: "bottomMiddle" }, classes: "ui-tooltip-light" }
		}
	);// end qtip
	});// end $each
	
	// privacy qtip on register form 
	$("#birthdatehelp").hide();
	$("#birthdatehelpicon").qtip({
			show: { event: "mouseover" },
			hide: { event: "mouseout" },
			content: $("#birthdatehelp").text(), 
			position: { adjust: { x: 0, y: 0 }, at: "right center", my: "left center" },
			style: { tip: { corner: "leftCenter" } }
	});
	
	// updated like button  
	$("a.entry_like_button").click(function(e) { 
		if (!$('body').hasClass('logged-in')) {
			bubblyPopupLoginForm("Please sign in to participate");
		} else {
			$(this).text('saving...'); 
			saveRating("like",this); 
		}
		e.preventDefault();  
	});
	
	// comment voting  
	jQuery(".bubbly_comment_rating_input .thumbsup_container").bind('mouseover',function(e){ upDownInputHoverEffect(this) });
	jQuery(".bubbly_comment_rating_input .thumbsup_container").bind('mouseout',function(e){ upDownInputHoverEffectOff(this) });
	jQuery(".bubbly_comment_rating_input .thumbsdown_container").bind('mouseover',function(e){ upDownInputHoverEffect(this) });
	jQuery(".bubbly_comment_rating_input .thumbsdown_container").bind('mouseout',function(e){ upDownInputHoverEffectOff(this) });
	jQuery(".bubbly_comment_rating_input .thumbsup_container").bind('click',function(e){ saveCommentUpDownRating(this) });
	jQuery(".bubbly_comment_rating_input .thumbsdown_container").bind('click',function(e){ saveCommentUpDownRating(this) });
	
	// login links 
	$(".bubbly_login_link").click(function(e){ bubblyPopupLoginForm(); e.preventDefault(); });
	
	// oembed - convert media links to embeded 
	if ($("a.oembed").oembed) $("a.oembed").oembed(null,{maxWidth:700});
	setTimeout("$('embed').attr('wmode','transparent');$('<param name=\"wmode\" value=\"transparent\">').insertAfter('param[name=movie]');",1000);
	
	// tiny obembed for edit entry forms 
	//$("a.open_tiny_oembed").click( function(e) { $(this).oembed(null,{autoplay: true, maxWidth: 300}); e.preventDefault(); }); 
	if ($("a.open_tiny_oembed").oembed) $("a.open_tiny_oembed").oembed(null,{maxWidth:300});
	
	// wysiwyg editors 
	var bubbly_tinymce_settings1 = {
		script_url : bubbly_site_template_url+'/bubbly/includes/tiny_mce/tiny_mce.js',
		mode : "textareas",
		theme : "advanced",
		plugins : "autoresize,autolink", 
		theme_advanced_buttons1 : "bold,italic,strikethrough,separator,link,unlink,separator,bullist,numlist,separator,blockquote,separator,undo,redo,separator,code", 
		theme_advanced_buttons2 : "", 
		theme_advanced_buttons3 : "", 
		theme_advanced_toolbar_location : "top", 
		theme_advanced_toolbar_align : "left"
	}; 
	var bubbly_tinymce_settings2 = {
		script_url : bubbly_site_template_url+'/bubbly/includes/tiny_mce/tiny_mce.js',
		mode : "textareas",
		theme : "advanced",
		plugins : "autoresize,autolink", 
		theme_advanced_buttons1 : "bold,italic,strikethrough,blockquote,separator,link,unlink,separator,undo,redo", 
		theme_advanced_buttons2 : "", 
		theme_advanced_buttons3 : "", 
		theme_advanced_toolbar_location : "top", 
		theme_advanced_toolbar_align : "left"
	}; 
	if ($(document).tinymce) {
		$('textarea.wysiwyg').tinymce(bubbly_tinymce_settings1);
		$('.bubbly_tinymcecontrols').show(); 
		$('.tinymceswitch').click(function(e){ 
		var textareaid = jQuery(this).attr('rel'); 
		if ($(this).hasClass('html')) {
			tinyMCE.execCommand('mceRemoveControl', false, textareaid);
			$(this).addClass('preview');
			$(this).text('Back to Preview Mode');
			$(this).removeClass('html');
		} else if (jQuery(this).hasClass('preview')) {
			tinyMCE.execCommand('mceAddControl', false, textareaid);
			$(this).addClass('html');
			$(this).html('View as HTML');
			$(this).removeClass('preview');
		}
		e.preventDefault(); 
		});
	}// end wysiwyg editors 
	
	// comment form 
	$("label[for=comment]").hide(); 
	if ($("#comment").text() == '') $("#comment").addClass("commentlabel");
	var bubbly_apply_tinymce_comment = function(e) {
		if ($(document).tinymce) { 
			$("#comment").tinymce(bubbly_tinymce_settings2);
		} 
	}
	bubbly_apply_tinymce_comment();

	// edit entry: tag editing 
	$("#bubbly-edit-entry .btag").click(function(e){
		var current_tags_string = $("#current_entry_tags").val();	
		var current_tags = current_tags_string.split(","); 
		var remove_tag = $(this).text(); 
		var new_tags_list = '';
		for (var i=0; i<current_tags.length; i++) {
			if (current_tags[i] != remove_tag && current_tags[i]!='' ) new_tags_list += current_tags[i]+",";
		}
		$("#current_entry_tags").val(new_tags_list);	
		$(this).fadeOut();
	});
	
	// edit entry: image deleting  
	$("#bubbly-edit-entry .delete-image").click(function(e){
		var imgID = $(this).attr("rel"); 
		var deleted_string = $("#set-deleted").val(); 
		if (!$(this).hasClass('on')) { 
			// delete the image 
			$(this).addClass('on'); 
			$(this).text('Undelete');
			$('#img'+imgID+' .img-title-label').text('This will be deleted when you save your changes.'); 
			$('#img'+imgID+' .img-title').hide();  
			$('#img'+imgID+' .featured-image').hide();
			$("#set-deleted").val(deleted_string+imgID+",");
		} else { // undelete the image 
			$(this).removeClass('on'); 
			$(this).text('Delete this');
			$('#img'+imgID+' .img-title-label').text('Caption'); 
			$('#img'+imgID+' .img-title').show();
			$('#img'+imgID+' .featured-image').show();
			var deleted = deleted_string.split(","); 
			var new_deleted_string = '';
			for (var i=0; i<deleted.length; i++) {
				if (deleted[i] != imgID && deleted[i] != '') new_deleted_string += deleted[i]+",";
			}
			$("#set-deleted").val(new_deleted_string);
		}
	});
	
	// edit entry: set featured image 
	$("#bubbly-edit-entry .featured-image").click(function(e){
		var imgID = $(this).attr("rel"); 
		if ($("#set-featured").val() != imgID) {
			$('.featured-image').removeClass('on');
			$('.featured-image').text('Make this primary');
			$(this).addClass('on'); 
			$(this).text('Primary image');
			$("#set-featured").val($(this).attr("rel")); 
		} 
	});
	
	// edit entry: video delete 
	$("#bubbly-edit-entry .delete-video").click(function(e){
		var toDelete=$(this).attr("rel"); 
		var deleted_videos_string = $("#set-deleted-videos").val();
		deleted_videos = deleted_videos_string.split(","); 
		if (!$(this).hasClass('on')) { // delete 
			$(this).addClass("on");
			$(this).text('Undo remove');
			$("#set-deleted-videos").val(deleted_videos_string+toDelete+",");
			$("#entry-video-"+toDelete+" .remove-msg").text('This video will be removed when you save.');
		} else { // undelete 
			$(this).removeClass("on");
			var new_deleted_string = '';
			for (var i=0; i<deleted_videos.length; i++) {
				if (deleted_videos[i] != toDelete && deleted_videos[i] != '') new_deleted_string += deleted_videos[i]+","; 
			}
			$("#set-deleted-videos").val(new_deleted_string);
			$(this).text('Remove this video');
			$("#entry-video-"+toDelete+" .remove-msg").text('');
		}
	});
	
	// edit entry: delete this entry form slide down  
	$("#bubbly-edit-entry .entry-delete-link a").click(function(e) {
		$("#bubbly-edit-entry #entry-delete-fields").slideDown(); 	
		$("#bubbly-edit-entry .entry-delete-link").hide(); 
		e.preventDefault(); 
	});

	// no auto thumbnails in galleries 
	$('.bentry-gallery img[title=Automatic Video Thumbnail]').hide(); 
	
	// corner ie fix 
	if (bubbly_detect_ie) { 
		$('.entry_like_button').corner("round 5px"); 
		$('.entry_comment_button').corner("round 5px"); 
	}
	
});// end document ready()

// save rating 
function saveRating(type,ref) {
	var entry_id = $(ref).attr("rel");
	var rating_handler = bubbly_site_template_url+"/bubbly/ajax/bubbly-ratings-handler.php?";
	var rating_url = rating_handler+"entryID="+entry_id;
	var rating_val = 0; 
	if (type="like") { // for "like" buttons 
		rating_val = 1; 
		if ($(ref).hasClass("liked")) rating_val = 0; // if they already liked it, this is an "unlike" 
		rating_url += "&rating="+rating_val;
		//alert("Sending: \n" +rating_url);
		$.ajax({ url: rating_url, success: function(data){
			returned = $.parseJSON(data);
			if (!returned.ratingerror) {
				if (rating_val) { // like vs. unlike 
					$(ref).addClass('liked');
					$(ref).html("liked <span>("+returned.ratingavg+")</span>"); 
				} else {
					$(ref).removeClass('liked');
					$(ref).html("like <span>("+returned.ratingavg+")</span>"); 
				}
				$("#rating-buttons-"+entry_id+" .rating-button-status").text(returned.ratingmsg);
			} else {
				$(ref).text("error"); 
				alert("Sent: \n" +rating_url+"\n\nReturned: \n"+returned);
			}
		}});
	}
}

// helper functions for background labels 
function addClassOnFocus(field) {
	$(field).addClass('filled');
	$(field).addClass('highlight');
}
function removeClassIfFilled(field) {
	if ( $(field).val() == '' ) $(field).removeClass('filled');
	$(field).removeClass('highlight');
}
function labelStatus() {
	if ($('#bubbly_sitewide_header #bubbly_login #log').val() != '') $('#bubbly_sitewide_header #bubbly_login #log').addClass('filled');
	if ($('#bubbly_sitewide_header #bubbly_login #pwd').val() != '') $('#bubbly_sitewide_header #bubbly_login #pwd').addClass('filled');
}

// Helper function for comment rating 
function saveCommentUpDownRating(ref) {
	var comment_id = jQuery(ref).attr("rel");
	var rating_val=0; 
	var rating_handler = bubbly_site_template_url+"/bubbly/ajax/bubbly-ratings-handler.php?";
	var returned;
	jQuery('#bubbly_comment_voting_'+comment_id+' .bubbly_comment_rating_msg').html("saving ...");
	if (jQuery(ref).hasClass('selected')) rating_val = 0;
	else if (jQuery(ref).hasClass('thumbsup_container')) rating_val = 1;
	else if (jQuery(ref).hasClass('thumbsdown_container')) rating_val = -1;
	var rating_url = rating_handler+"commentID="+comment_id+"&rating="+rating_val;
	jQuery.ajax({ url: rating_url, success: function(data){
		returned = jQuery.parseJSON(data);
		jQuery('#bubbly_comment_voting_'+comment_id+' .bubbly_comment_rating_msg').html(returned.ratingmsg);
		jQuery('#bubbly_comment_voting_'+comment_id).addClass('rated');
		//alert("returned.rating="+returned.rating);
		if (returned.rating == "1") {
			jQuery('#bubbly_comment_voting_'+comment_id+' .thumbsup_container').addClass('selected');
			jQuery('#bubbly_comment_voting_'+comment_id+' .thumbsdown_container').removeClass('selected');
		} else if (returned.rating == "-1") {
			jQuery('#bubbly_comment_voting_'+comment_id+' .thumbsdown_container').addClass('selected');
			jQuery('#bubbly_comment_voting_'+comment_id+' .thumbsup_container').removeClass('selected');
		} else if (returned.rating == 0) {
			jQuery('#bubbly_comment_voting_'+comment_id+' .thumbsdown_container').removeClass('selected');
			jQuery('#bubbly_comment_voting_'+comment_id+' .thumbsup_container').removeClass('selected');
		}
		jQuery('#bubbly_comment_voting_'+comment_id+' .thumbsup_container .num_ratings').html(returned.upvotes);
		jQuery('#bubbly_comment_voting_'+comment_id+' .thumbsdown_container .num_ratings').html(returned.downvotes);
	}});
}
function upDownInputHoverEffect(ref) {
	jQuery(ref).addClass('on');
}
function upDownInputHoverEffectOff(ref) {
	jQuery(ref).removeClass('on');
}

// Function to add auto suggest
function setSuggest(id) {
	jQuery('#' + id).suggest(
		bubbly_site_template_url+"/bubbly/ajax/tag-search.php?tax=btags",
		{ multiple:true, multipleSep: ","});
}; 

// Popup login screen 
function bubblyPopupLoginForm(message) {
	if (!message) message = "Sign in";
	tb_show(message,bubbly_site_template_url+"/bubbly/ajax/bubbly-login-popup.php?KeepThis=trueTB_iframe=true&height=300&width=500",'');
}

