/**
 * Multicall General Javascript. Put any site-wide 'onDocReady' functions here.
 *
 * @author     Mike Barnlund <mike@chaordix.com>
 */

var current_form = null;
var formid = '';
var formselector = '';
var forceSubmit = false;
var current_button_id = false;

$(document).ready(function() {

	// ======================== Follow Buttons ===========================

	$(".followbutton").click( function() { return onItemFollow(this); } );

	// ======================== Required Form Fields ==============================

	$('label.required').prepend('<span class="require">* </span>')

	// ========================== Help Text Control ===========================

	// Elements (input, textarea, select) inside a .helpcontainer show the help text
	var helpContainers = '.helpcontainer input, .helpcontainer textarea, .helpcontainer select';
	applyHelpContainerBindings($(helpContainers));

	// ========================== Voting Widget Control =======================

	$( '.activevote' ).click( function() { return onVoteClick(this); } );

	// ========================== jGrowl Form Errors ==========================

	if ( $( '.form_errors li' ).length > 0 ) {
		$.jGrowl( '<div class="errors"><label class="error">Submission Error</label>' + $( '.form_errors' ).html() + '</div>', { sticky: true } );
	}

	// ====================== Admin Reports ================================

	$('table.altrows tr:odd td').addClass('alt');

	// ====================== Points Breakdown ================================

	var bdownVisible = false;

	$( '#bdownbutton' ).click( function() {
		if (bdownVisible == false) {
			var distance = $( '.slider .points' ).css( 'height' );
			$('.slider').animate( { 'top': '-' + distance }, 500 );
			$( '#bdownbutton' ).html('see points total');
		} else {
			$( '.slider' ).animate( { 'top': '0' }, 500 );
			$( '#bdownbutton' ).html('see points breakdown');
		}
		bdownVisible = !bdownVisible
	} );

	// ====================== List Sorting Widget ================================

	$(".sort-list dt a").click(function() {
	    $(".sort-list dd ul").toggle();
		return false;
	});
	$(".sort-list dd ul li a").click(function() {
	    $(".sort-list dd ul").hide();
	});

	// ====================== Top Navigation ================================

	$("#top-nav dl dt a").click(function() {
	    $("#top-nav dl dd").toggle();
		$("#top-nav dt").addClass('over');
		return false;
	});
	$("#top-nav dl dd ul li a").click(function() {
	    $("#top-nav dl dd").hide();
		$("#top-nav dt").removeClass('over');
	});

	// ======================= Profile Popup ===============================

	$( '.showpopup' ).hover( function() {
		var popup = getPopup();
		$( this ).append( popup );

		var height = $( this ).children( 'img' ).height();
		var width = $( this ).children( 'img' ).width();

		popup.css( 'width', width );
		popup.css( 'height', height );

		if (!$.browser.msie) popup.fadeIn( 150 );
		else popup.show();
	} );

	$( '.showpopup' ).mouseleave( function() {
		var popupImage = getPopup();
		popupImage.hide();
	} );

	$( '.showpopup' ).click( function() {
		var id = $( this ).attr( 'id' );
		//Get our popup
		var popup = $( '#profilepopup_' + id );

		//Locate the clicked element
		position = new Object();
		position.top = $( this ).offset().top;
		position.left = $( this ).offset().left;

		//Position the popup directly over the clicked element
		popup.css( 'top', position.top );
		popup.css( 'left', position.left );

		//show our popup
		if (!$.browser.msie) popup.fadeIn( 100 );
		else popup.show();
		return false;
	} );

	$( '.profilepopup' ).mouseleave( function() {
		var popup = this;
		if (!$.browser.msie) var fadepopup = function() { $( popup ).fadeOut( 100 ); };
		else var fadepopup = function() { $( popup ).hide(); };
		setTimeout( fadepopup, 500 );
	} );

	/* ======================= Inbox =========================== */

	$( 'table.inbox td' ).css( 'cursor', 'pointer' );
	$( 'table.inbox td:not( .checkbox )' ).click( function() {
		//grab the link to the appropriate view message page
		var subjectcell = ( $( this ).hasClass( 'subject' ) ? $( this ) : $( this ).siblings( '.subject' ) );

		var goto = subjectcell.children( 'a' )[0].href;

		window.location = goto;
	} );

	/* ====================== Message Threads ========================= */

	$( 'div.msgcollapsed' ).click( function() {
		$( this ).parent().removeClass( 'collapsed' ).addClass( 'expanded' );
	} );

	$( 'div.subject' ).click( function() {
		$( this ).parents( 'div.expanded' ).removeClass( 'expanded' ).addClass( 'collapsed' );
	} );

	/* ======================= Forms ======================= */

	$(document).ajaxError(function() {
		if( current_form ){
			fakeSubmitForm( current_form, current_button_id );
			// $(current_form).find('button').removeAttr('disabled');
		}
	});

	$( 'form.form_check' ).submit( function(e) {
		//if a formid has been set, that means we've attempted to submit the form already but had to wait for ajax validation (mb)
		if( formid == "#" + $(this).attr("id") ){
			// Force form submission - this is set in fakeSubmitForm
			if ( forceSubmit ) {
				forceSubmit = false;
				return true;
			}
			// if we've already checked the form, clear the key and submit

			// Comment says to submit but we're doing the opposite here? (mb)
			e.stopImmediatePropagation();
			return false;
		}

		if ($('#jGrowl').data('jGrowl.instance') && $('#jGrowl').data('jGrowl.instance').close) {
			$('#jGrowl').data('jGrowl.instance').close();
		}

		// special handling of login forms
		var formdata = $(this).serialize() + "&formcheck=1";
		var formclass = $(this).hasClass('login-main') ? 'login-main' : ( $(this).hasClass('login-lightbox') ? 'login-lightbox' : '' );
		formselector = formclass ? 'form.' + formclass + ' ' : '';
		var formaction = $(this).action || $(this).attr('action') || window.location.pathname;
		current_form = this;

		// ajax action provided?
		if ($(this).find('input.ajax-action').length > 0) {
			formaction = $(this).find('input.ajax-action').val() || formaction;
		}

		// disable buttons
		// $(this).find('button').attr('disabled', 'disabled');

		$(this).find('label').removeClass( "error" );
		$(formselector).find('span.error').remove();

		//HEY THIS IS IMPORTANT! This is what we use to flag that the first phase of a post has started? (mb)
		formid = "#" + $( this ).attr("id");
		$.post(
			formaction,
			formdata,
			//callback? (mb)
			function(data){

				//if the form had errors (mb)
				if( data && data.form_is_complete == false ){
					// $(current_form).find('button').removeAttr('disabled');
					$( 'form .error' ).remove();
					var error_list = '';
					for ( var key in data['errors'] ) {
						$( formselector + 'label[id=label_' + key + ']' ).addClass( "error" );
						$( formselector + 'label[id=label_' + key + ']' ).after(
							" <span class=\"error\" id=\"error_" + key + "\">" + data['errors'][key] + "</span>"
						);
						error_list = error_list + "<li>" + data['errors'][key] + "</li>"
					}
					$.jGrowl( '<div class="errors"><label class="error">Submission Error</label><ul>' + error_list + '</ul></div>', { sticky: true, animateClose: { opacity: 'show' } } );

					//clear the formid, since there are errors and we want to disallow form submission? (mb)
					formid = '';
				//else we have no files and no errors - let's submit the form (mb)
				} else {
					fakeSubmitForm(current_form, current_button_id);
				}
			},
			"json"
		);
		e.stopImmediatePropagation();
		return false;
	} );

	$('form.form_check button').click(function(e) {
		if (e.currentTarget && $(e.currentTarget).attr) {
			current_button_id = $(e.currentTarget).attr('name');
		} else {
			current_button_id = false;
		}
	});
});

// we need to be able to submit a form without actually clicking the submit button(s)
function fakeSubmitForm(form, button_id) {
	// fake button already exists?
	var _formid = $(form).attr('id');
	var _fake_button_id = '_fake_button_id' + _formid;

	// look for first submit button
	var _fake_button = function (button) {
		// if we already have a fake button for this form, override value
		if ($('#' + _fake_button_id).length) {
			$('#' + _fake_button_id).val($(button).attr('name'));
		} else {
			$(form).prepend( '<input id="' + _fake_button_id + '" type="hidden" value="' + $(button).val() + '" name="' + $(button).attr('name') + '" />');
		}
	};

	// were we passed a button?
	if (button_id) {
		_fake_button($('#' + button_id));
	} else {
		// no button passsed, default to first button
		$(form).children('button').each(function (i, button) {
			if (!$(button).attr('value')) {
				return;
			}
			_fake_button(button);
			return false;
		});
	}
	forceSubmit = true;
	$(form).submit();
}

/*
* Returns an image element singleton for placement on a popup avatar
*/
var _popupImg = null;
function getPopup( width, height) {
	if ( _popupImg == null ) {
		_popupImg = $( '<div style="width: 0; height: 0" class="black50p"><img style="padding: 2px; float:right" src="/assets/img/silk/information.png"/></div>' );
		_popupImg.css( 'position', 'absolute' );
		_popupImg.css( 'top', '1px' );
		_popupImg.css( 'left', '1px' );
		_popupImg.css( 'z-index', '97' );
		_popupImg.hide();
		//_popupImg.insertBefore( document.body.firstChild );
	}
	return _popupImg;
}

/* when you click away from the sort menu it dissapears */
$(document).bind('click', function(e) {
    var $clicked = $(e.target);
    if (! $clicked.parents().hasClass("drop"))
        $("#top-nav dl dd").hide();
		$("#top-nav dt").removeClass('over');
});

/* when you click away from the sort menu it dissapears */
$(document).bind('click', function(e) {
    var $clicked = $(e.target);
    if (! $clicked.parents().hasClass("sort-list"))
        $(".sort-list dd ul").hide();
});

function applyHelpContainerBindings(jq) {
	jq.focus( function() { $(this).parents('div.helpcontainer').find('div.help').fadeIn(300); } ).blur( function() { $(this).parents('div.helpcontainer').find('div.help').fadeOut(300); } );
}

function onItemFollow( container ) {
	var url = $(container).attr('href');

	$.ajax({
		url: url,
		success: function(data) {
			if ( data.result == 'Success' ) {

				var icon = '';

				switch ( data.type ) {
					case 'call':
						icon = '<b></b>';
						break;
					case 'idea':
						icon = '<i></i>';
						break;
					case 'member':
						icon = '<u></u>';
						break;
					case 'yarn':
						icon = '<em></em>';
						break;
				}

				var text = '';

				if ( data.action == 'attach' ) {
					if( data.text != undefined ) {
						text = data.text;
					} else {
						text = 'Unfollow';
					}
					container.setAttribute('href', data.url );
					$( container ).removeClass( 'follow' );
					$( container ).addClass( 'unfollow' );
				} else if ( data.action == 'detach' ) {
					if( data.text != undefined ) {
						text = data.text;
					} else {
						text = 'Follow';
					}

					container.setAttribute('href', data.url );
					$( container ).removeClass( 'unfollow' );
					$( container ).addClass( 'follow' );
				}

				//see if we've got the inner span button
				var innerSpan = $( container ).find('span span')[0];

				var buttonContainer = ( innerSpan == null ) ? container : innerSpan;
				buttonContainer.innerHTML = icon + text;

				if ( typeof data._notice != 'undefined' ) {
					var len = data._notice.length;
					for ( var i = 0; i < len; ++i ) {
						$.jGrowl(data._notice[i]);
					}
				}
			} else {
				$.jGrowl( 'We encountered an error following this. Please refresh and try again.' );
			}
		},
		error: function(obj, error, exception) {
			$.jGrowl( error );
		},
		dataType: 'json'
	});

	return false;
}

// Bit.ly stuff
/*
*	Uses Bit.ly API to return a shortened URL
*	Note: URL encode the longUrl param or very bad things will happen to you.
*/
function replaceLink( longUrl )
{
    // set up default options
    var defaults = {
        login:      'chaordix',
        apiKey:     'R_8aa4b7b20add568736a91d0fee245fd9',
        longUrl:    longUrl
    };

    // Build the URL to query
    var blurl = "http://api.bit.ly/v3/shorten?"
                + "&login=" + defaults.login
                + "&apiKey=" + defaults.apiKey
                + "&longUrl=" + defaults.longUrl
                + "&format=json&callback=?";

    // Hit up bit.ly for shortened URL, and replace the long one if it's successful
    $.getJSON( blurl, function( results ) {
		if ( results.status_txt == 'OK' ) {
			$( 'a.shorten' ).each( function() {
				var shortUrl = results.data.url;
				var oldUrl = $( this ).attr( "href" );
				var newUrl = oldUrl.replace( longUrl, shortUrl );
				$( this ).attr( "href", newUrl );
				$( this ).html( $( this ).html().replace( longUrl, shortUrl ) );
			});
		}
    });
}

function selectUpdate(category,sub_category)
{
	$('#'+sub_category).children().css('display', 'none');
	//remove spaces, and , characters which are valid for text but invalid for class jquery selection etc.
	var selector = '.' + $('#'+category).val().split( ' ' ).join('').split( ',' ).join('');
	$(selector).css('display', 'block');
	//select first sub_category item after parent charge.
	$('#'+sub_category).children(selector).attr('selected','selected');
}


