/**************************************************************************************
 *	
 *	network.js
 *	This file holds much of the jQuery functionality of the network.
 *
 **************************************************************************************/


/* The following code block allows us to character-limit textareas. */

/* jQuery MaxLength for INPUT and TEXTAREA fields v1.0
 * Last updated: Oct 15th, 2009. This notice must stay intact for usage 
 * Author: JavaScript Kit at http://www.javascriptkit.com/
 * Visit http://www.javascriptkit.com/ for full source code
 */

var thresholdcolors=[['20%','darkred'], ['10%','red']] //[chars_left_in_pct, CSS color to apply to output]
var uncheckedkeycodes=/(8)|(13)|(16)|(17)|(18)/  //keycodes that are not checked, even when limit has been reached.
thresholdcolors.sort(function(a,b){return parseInt(a[0])-parseInt(b[0])}) //sort thresholdcolors by percentage, ascending

function setformfieldsize($fields, optsize, optoutputdiv){
	var $=jQuery
	$fields.each(function(i){
		var $field=$(this)
		$field.data('maxsize', optsize || parseInt($field.attr('data-maxsize'))) //max character limit
		var statusdivid=optoutputdiv || $field.attr('data-output') //id of DIV to output status
		$field.data('$statusdiv', $('#'+statusdivid).length==1? $('#'+statusdivid) : null)
		$field.unbind('keypress.restrict').bind('keypress.restrict', function(e){
			setformfieldsize.restrict($field, e)
		})
		$field.unbind('keyup.show').bind('keyup.show', function(e){
			setformfieldsize.showlimit($field)
		})
		setformfieldsize.showlimit($field) //show status to start
	})
}

setformfieldsize.restrict=function($field, e){
	var keyunicode=e.charCode || e.keyCode
	if (!uncheckedkeycodes.test(keyunicode)){
		if ($field.val().length >= $field.data('maxsize')){ //if characters entered exceed allowed
			if (e.preventDefault)
				e.preventDefault()
			return false
		}
	}
}

setformfieldsize.showlimit=function($field){
	if ($field.val().length > $field.data('maxsize')){
		var trimmedtext=$field.val().substring(0, $field.data('maxsize'))
		$field.val(trimmedtext)
	}
	if ($field.data('$statusdiv')){
		$field.data('$statusdiv').css('color', '').html( ($field.data('maxsize') - $field.val().length + ' chars left') )
		var pctremaining=($field.data('maxsize')-$field.val().length)/$field.data('maxsize')*100 //calculate chars remaining in terms of percentage
		for (var i=0; i<thresholdcolors.length; i++){
			if (pctremaining<=parseInt(thresholdcolors[i][0])){
				$field.data('$statusdiv').css('color', thresholdcolors[i][1])
				break
			}
		}
	}
}


/* The following code block executes when the page is initially loaded, and does a lot of setup work */
$(document).ready( function() {

	// *** Network Page JS ***
	
    // The followowing code block defines the Select All and Select None actions
    // These actions are used in the sidebar on the search filters.
    $("A[href='#select_all']").click( function() {
        $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', true);
        return false;
    });

    // Select none
    $("A[href='#select_none']").click( function() {
        $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', false);
        return false;
    });
    
    
    // Collapsible Filters
	$("#ui_filters > li > a.collapsed + ul").slideUp("medium");
	
	$("#ui_filters > li > a").click(function() {
		$(this).toggleClass("expanded").toggleClass("collapsed").parent().find('> ul').slideToggle("medium");
	});
	
	// Expand & Collapse ALL filters
	$('#ui_sidebar .expand_all').click(function() {
        $('#ui_filters > li > a.collapsed').addClass('expanded').removeClass('collapsed').parent().find('> ul').slideDown('medium'); });
	$('#ui_sidebar .collapse_all').click(function() {
	    $('#ui_filters > li > a.expanded').addClass('collapsed').removeClass('expanded').parent().find('> ul').slideUp('medium'); });



	// *** Profile Edit Page JS ***

	// Activate the validation rules for the main profile editing form
	$("#updateuser").validate();

	//get INPUTs and TEXTAREAs on page with "data-maxsize" attr defined
	var $targetfields = $("input[data-maxsize], textarea[data-maxsize]");
	setformfieldsize($targetfields);



	// *** Main Profile Page JS ***

	// Initially collapse personal filters.
	$("#personal_filters_table").hide();
	
	// Collapse or Show table with list of personal filters.
	$("#show_personal_filters").click(function() {
	
		$(this).toggleClass("expanded").toggleClass("collapsed");
		$("#personal_filters_table").slideToggle("medium");
		return false;
	});

	// Hide extra rows here for nice degradation.
    $("#fellow-updates.widget table tr").slice(6).hide();

	// Add a listeners to expand / contract the Updates drawer
	$("#show_all_updates").click( function() {
	
		$(this).toggleClass("expanded").toggleClass('collapsed');
		$("#fellow-updates.widget table tr").slice(6).toggle();
		return false;
	});

	// Simple function to enable "Scroll To" functionality
	$(".scrollto").click(function(event){
		//prevent the default action for the click event
		event.preventDefault();

		//get the full url - like mysitecom/index.htm#home
		var full_url = this.href;

		//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
		var parts = full_url.split("#");
		var trgt = parts[1];

		//get the top offset of the target anchor
		var target_offset = $("#"+trgt).offset();
		var target_top = target_offset.top;

		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop:target_top}, 500);
	});
	
	// Set the updates table to sort, disable second column.  DISABLE FOR NOW. Doesn't work with slicing table.
	// $("#fellow-updates table").tablesorter({ headers: { 1: { sorter: false }}});

	

	// *** Updates Page JS ***
	$("#add-update-form").hide();
	
	// Collapse or Show update form
	$("#make_an_update").click(function() {
	
		$(this).toggleClass("expanded").toggleClass("collapsed");
		$("#add-update-form").slideToggle("medium");
		return false;
	});
	

});




