/* javascript events are assigned here */
$(document).ready(function () {
   // sifr 
	var lubalin = new Font('lubalin_book.swf', {
		tags:'h1,h2',
		classFilter:'sifr'
	});
	lubalin.replace();


/**
*	@name							Elastic
*	@descripton						Elastic is Jquery plugin that grow and shrink your textareas automaticliy
*	@version						1.6
*	@requires						Jquery 1.2.6+
*	@author							Jan Jarfalk jan.jarfalk@unwrongest.com
*/

	(function($){ 
		$.fn.extend({  
			elastic: function() {
				
				//	We will create a div clone of the textarea
				//	by copying these attributes from the textarea to the div.
				var mimics = [
					'paddingTop',
					'paddingRight',
					'paddingBottom',
					'paddingLeft',
					'fontSize',
					'lineHeight',
					'fontFamily',
					'width',
					'fontWeight'];
				
				return this.each( function() {
					
					// Elastic only works on textareas
					if ( this.type != 'textarea' ) {
						return false;
					}
					
					var $textarea	=	$(this),
						$twin		=	$('<div />').css({'position': 'absolute','display':'none'}),
						lineHeight	=	parseInt($textarea.css('lineHeight'),10) || parseInt($textarea.css('fontSize'),'10'),
						minheight	=	parseInt($textarea.css('height'),10) || lineHeight*3,
						maxheight	=	parseInt($textarea.css('max-height'),10) || Number.MAX_VALUE,
						goalheight	=	0,
						i 			=	0;
					
					
					// Append the twin to the DOM
					// We are going to meassure the height of this, not the textarea.
					$twin.appendTo($textarea.parent());
					
					// Copy the essential styles (mimics) from the textarea to the twin
					var i = mimics.length;
					while(i--){
						$twin.css(mimics[i].toString(),$textarea.css(mimics[i].toString()));
					}
					
					// Sets a given height and overflow state on the textarea
					function setHeightAndOverflow(height, overflow){
						curratedHeight = Math.floor(parseInt(height,10));
						if($textarea.height() != curratedHeight){
							$textarea.css({'height': curratedHeight + 'px','overflow':overflow});
							
						}
					}
					
					
					// This function will update the height of the textarea if necessary 
					function update() {
						
						// Get curated content from the textarea.
						var textareaContent = $textarea.val().replace(/<|>/g, ' ').replace(/\n/g, '<br />').replace(/&/g,"&amp;");
						var twinContent = $twin.html();
						
						if(textareaContent+'&nbsp;' != twinContent){
						
							// Add an extra white space so new rows are added when you are at the end of a row.
							$twin.html(textareaContent+'&nbsp;');
							
							// Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height
							if(Math.abs($twin.height()+lineHeight - $textarea.height()) > 3){
								
								var goalheight = $twin.height()+lineHeight;
								if(goalheight >= maxheight) {
									setHeightAndOverflow(maxheight,'auto');
								} else if(goalheight <= minheight) {
									setHeightAndOverflow(minheight,'hidden');
								} else {
									setHeightAndOverflow(goalheight,'hidden');
								}
								
							}
							
						}
						
					}
					
					// Only run update when the textarea has focus
					$textarea.css({'overflow':'hidden'}).bind('focus',function() {
						self.periodicalUpdater = window.setInterval(function() {
							update();
						}, 50);
					}).bind('blur', function() {
						clearInterval(self.periodicalUpdater);
					});
					
					// Run update once when elastic is initialized
					update();
					
				});
				
			} 
		}); 
	})(jQuery);

	
	
	/* label over used to install default text in input 
		textfields based on their respective label*/
	jQuery.fn.labelOver = function(overClass) {
		return this.each(function(){
			var label = jQuery(this);
			var f = label.attr('for');
			if (f) {
				var input = jQuery('#' + f);
				
				this.hide = function() {
				  label.css({ textIndent: -10000 })
				}
				
				this.show = function() {
				  if (input.val() == '') label.css({ textIndent: 0 })
				}
	
				// handlers
				input.focus(this.hide);
				input.blur(this.show);
				label.addClass(overClass).click(function(){ input.focus() });
				
				if (input.val() != '') this.hide(); 
			}
		})
	};
	
	  
	  $.nyroModalSettings({
			processHandler: function(settings) {
				var url = settings.url;
				if (url && url.indexOf('http://www.youtube.com/watch?v=') == 0) {
					// if the player is on - pause it
          			$("#jquery_jplayer").pause();
					
					$.nyroModalSettings({
						type: 'swf',
						width: 630,
						height: 400,
						url: url.replace(new RegExp("watch\\?v=", "i"), 'v/')
					});
				};
				if (url && url.indexOf('http://s3.amazonaws.com/') == 0) {
					$.nyroModalSettings({
						type: 'image'
					});
				}
			}
		});

	  
			
	// media edit nyroModal assignments 
    $('a.nyroModal') 
	.livequery(function(event) { 
		$(this).nyroModal();
	});
	
	
	// detail modals edit nyroModal assignments 
    $('a.details_modals') 
	.livequery(function(event) { 
		$(this).nyroModal({height: 410});
	});
	
	
	// any time a close modal button visits the DOM for a shag
	$('a.nyroModalClose') 
	.livequery('click', function(event) { 
		$.nyroModalRemove();
		return false;
	});	
	
		
    // dropdown for experience / education    
    $('ul.dropdown li') 
	.livequery(function(event) { 
		$("ul.dropdown li").hover(function(){
			$(this).addClass("hover");
			$('ul:first',this).css('visibility', 'visible');
		}, function(){
			$(this).removeClass("hover");
			$('ul:first',this).css('visibility', 'hidden');
		});
		
		$("ul.dropdown li ul li:has(ul)").find("a:first").append(" &raquo; ");
			
	});	
	
	// endorsements hovering   
    $('div#endorser_list ul li') 
	.livequery(function(event) { 
		$(this).hover(function(){
			$(this).addClass("hover");
		}, function(){
			$(this).removeClass("hover");
		});
	});
	
	if($.browser.safari){
	// search result names hover   
    $('div.name_wrapper h2.sifr') 
	.livequery(function(event) { 
		$(this).hover(function(){
			$(this).addClass("hover");
		}, function(){
			$(this).removeClass("hover");
		});
	});
	};
	
	if($.browser.mozilla){
	// search result names hover   
    $('div.name_wrapper h2.sifr embed') 
	.livequery(function(event) { 
		$(this).hover(function(){
			$(this).addClass("hover");
		}, function(){
			$(this).removeClass("hover");
		});
	});
	};
	
	
    
    // set the "edit" buttons' visibility
    $('.detail_edit').show();
    
	// set focus to the first text field 
	// onload of any form
	$('input:text:first:visible') 
	.livequery(function(event) {
		if(!$('#Searchbox')) $(this).focus();
	});	
	
	// set focus to the first file upload field 
	// onload of any form
	$('input:file:first:visible') 
	.livequery(function(event) { 
		$(this).focus();
	});	
	
	// set focus to the bio form
	$('#bio_info') 
	.livequery(function(event) { 
		$(this).focus();
	});	
	
	$('input#song_file') 
	.livequery(function(event) { 
		$(this).focus();
	});	
	
	/* search controlbar commands */
	$("a#result_expand").click(function(){
		$('div.details').slideDown();
		$('div.mini_featured_song').slideDown();
		$('ul.search_controls li a').removeClass('active');
		$(this).addClass('active');
		return false;
	});
	
	$("a#result_condense").click(function(){
		$('div.details').slideUp();
		$('div.mini_featured_song').slideUp();
		$('ul.search_controls li a').removeClass('active');
		$(this).addClass('active');
		return false;
	});

	
	// Notice the use of the each() method to acquire access to each elements attributes
   $('#profile_content_actions a[tooltip], #contacts a[tooltip]').each(function()
   {
      $(this).qtip({
		content: $(this).attr('tooltip'), // Use the tooltip attribute of the element for the content
		style: {
			  padding: 10,
			  tip: true, // Give it a speech bubble tip with automatic corner detection
			  name: 'berklee' // Style it according to the preset 'cream' style
		   },
		position: { adjust: { screen: true, scroll: true } }
      });
   });

	
	// set the hints in fields that need them
	// find all the input elements with title attributes
	
	 $('label.hint') 
	.livequery(function(event) { 
		$('label.hint').labelOver('over');
	});
	
	// edit the status, toggle the edit with the read only controls / display
	$('#status_edit_trigger').click(function(){
		status_toggle();
		return false;
	});
	
	// assign the function to the status update button
	$('a#status_cancel') 
	.livequery(function(event) { 
		$(this).click(function(){
			status_toggle();
			return false;
		});
	});
	
	/* assign the character count on the textareas */
	
	// 75 character max for media
	$('textarea.textarea75') 
	.livequery(function(event) {
		$(this).dodosTextCounter(75, {counterDisplayElement: "div",counterDisplayClass: "counter_display"});
	});
	
	// 150 character max for resume details
	$('textarea.textarea150') 
	.livequery(function(event) { 
		$(this).dodosTextCounter(150, {counterDisplayElement: "span",counterDisplayClass: "counter_display"});
	});	
	
	// 200 character max for resume details
	$('textarea.textarea200') 
	.livequery(function(event) { 
		$(this).dodosTextCounter(200, {counterDisplayElement: "div",counterDisplayClass: "counter_display"});
	});	
	
	// 300 character max for resume details
	$('textarea.textarea300') 
	.livequery(function(event) { 
		$(this).dodosTextCounter(300, {counterDisplayElement: "div",counterDisplayClass: "counter_display"});
	});
	
	/**
	* DodosTextCounter - jQuery plugin for text limit for input or textarea. The counter shows how many chars are remaining.
	*						It will also disable the user from entering more characters after s/he reaches the maximum
	* Written by Ying Zhang aka Dodo
	* http://pure-essence.net/2008/05/30/dodos-text-counterdodos-text-counter/
	*/
	
	jQuery.fn.dodosTextCounter = function(max, options) {
		// if the counter display doesn't exist, the script will attempt to create it
		options = $.extend({
			counterDisplayElement: "span",					// tag for the counter display
			counterDisplayClass: "dodosTextCounterDisplay",	// class for the counter display
			addLineBreak: true								// whether to add <br /> after the input element before the counter display
		}, options);
	
		$(this).each(function(i) {
			updateCounter(this, max, options, i);
			$(this).keyup(function() {
				updateCounter(this, max, options, i);
				return this;
			});
		});
		return this;
	};

// endorsements drop down assignment
if($('#endorsement_count').text() != '0') {
	$("#endorsement_wrapper").click(function(){
		if ($("#endorser_list").is(':hidden')){
			$("#endorser_list").show();
			$(this).toggleClass('open');
		}else{
			$("#endorser_list").hide();
			$(this).toggleClass('open');
		}
		return false;
	});

	$('#endorser_list').click(function(e) {
		e.stopPropagation();
	});
	$(document).click(function() {
		$("#endorser_list").hide();
		$("#endorsement_wrapper").removeClass('open');
	});
}


}); // close document.ready



save_status = function() {
	jax.call('community','home,ajaxUpdate', jQuery('#userStatus').val()); 
	set_status(); 
	status_toggle(); 
	return false;	
};

set_status = function() {
	if($('#userStatus').val() != '') {
		$('#status_content').text($('#userStatus').val());
		$('#shout_timestamp').show();
	} else {
		$('#status_content').text('Open Mic: Tell the Network what you\'re up to!');
		$('#shout_timestamp').hide();
	}
	
};

status_toggle = function() {
	$('.status_readonly').toggle();
	$('.status_edit').toggle();
	if($('#status_counter')) $('#status_counter').html('150');
	if($('textarea#userStatus')) $('textarea#userStatus').val('').elastic().focus();
};

/*
bg_images_url = "/images/rails/bg_images/";
bg_images_count = 1;
bg_total = 15;
cycleImages = function() {
	if(bg_images_count != bg_total) {
		$("#bg-image").attr("src", bg_images_url + "bg_" + bg_images_count + ".jpg");	
		bg_images_count++;
	} else {
		$("#bg-image").attr("src", bg_images_url + "bg_"+ bg_total +".jpg");	
		bg_images_count = 1;
	}
};
*/

toggle_resume_details = function(detailToggle, linkText){
	
    ($('#'+detailToggle).css('display') == 'none') ? $('#'+detailToggle).slideDown('medium') : $('#'+detailToggle).slideUp('medium');
    
	var label = $("#"+linkText).html();
	if(label == "View More...") {
		$('#'+linkText).html('View Less');
	} else {
		$('#'+linkText).html('View More...');
	}
	return false;
};

/* CRUD indicator can be used in place of loading, canceling, saving, 
// and deleting, as long as both arguments are passed
*/

// getIndicator = loading, canceling, saving, or deleting
// setContainer is where you want the indicator to show - be sure the container is "position: relative"
crud_indicator = function(getIndicator, setContainer) { 	
	$('#'+getIndicator).clone().insertAfter('#'+setContainer); $('#'+getIndicator).show();
};

loading_indicator = function(setContainer, getIndicator) {
	$('#loading').clone().insertAfter('#'+setContainer); $('#loading').show();
};

canceling_indicator = function(setContainer) {
	$('#canceling').clone().insertAfter('#'+setContainer); $('#canceling').show();
};

saving_indicator = function(setContainer) {
	$('#saving').clone().insertAfter('#'+setContainer); $('#saving').show();
};

member_search_indicator = function() {
	$(":submit").attr('disabled', true);
	$(":submit").attr('src', '/images/rails/btn_search_disabled.gif');
	$('#searching').show();
};

deleting_indicator = function(setContainer) {
	$('#deleting').clone().insertAfter('#'+setContainer); $('#deleting').show();
};

endorsing_indicator = function() {
	$("#not_endorsed").hide();$("#endorsing").show();	
};

endorsed_indicator = function() {
	$("#endorsing").hide();$("#action_endorsed").fadeIn();
	$("#endorsement_wrapper").effect("highlight", {}, 1000);
};

endorsing_show = function() {
	$("#endorse").effect("transfer", { to: "#endorsement_wrapper" }, 1000);	
};

modal_save_indicator = function() {
	$('#modal_save_indicator').show();
	$('#btn_save').attr('value', 'saving...');	
	$('#btn_save').attr('disabled', 'disabled');	
};

uploading_indicator = function() {
	$('#upload_indicator').show();
	$('#btn_upload').attr('value', 'one moment...');	
	$('#btn_upload').attr('disabled', 'disabled');
};

success_indicator = function(setContainer) {
	$('#success').clone().insertAfter('#'+setContainer).fadeIn(200, function () {
		window.setTimeout(function() {
		 $('#success').remove();
		}, 800);
		
	}); 
};

deleted_indicator = function(setContainer) {
	$('#deleted').clone().insertAfter('#'+setContainer).fadeIn(200, function () {
		window.setTimeout(function() {
		 $('#deleted').remove();
		}, 800);
	}); 
};



function updateCounter(input, max, options, index) {
	var currentLength = 0;
	var val = $(input).val();
	if(val) {
		currentLength = val.length;
	}
	if(currentLength > max) {
		$(input).val(val.substring(0, max));
	} else {
		var charLeft = max - currentLength;
		var counterDisplay = options.counterDisplayElement + "." + options.counterDisplayClass + ":eq("+index+")";
		var createNew = $(counterDisplay).length == 0;
		if(createNew) {
			var element = document.createElement(options.counterDisplayElement);
			if(options.counterDisplayElement == 'input') {
				$(element).val(charLeft.toString());
			} else {
				$(element).html(charLeft.toString());
			}
			$(element).addClass(options.counterDisplayClass).insertAfter($(input));
			if(options.addLineBreak) {
				$(input).after("<br />");
			}
		} else {
			if(options.counterDisplayElement == 'input') {
				$(counterDisplay).val(charLeft.toString());
			} else {
				$(counterDisplay).html(charLeft.toString());
			}
		}
		
	}
};