/*
 * ThickFaceBox 0.1a - One thick face box to load some content via ajax
 * By Bryan Blakey, adapted from Cody Lindley's thickbox (http://www.codylindley.com) and famspam's facebox (http://www.famspam.com/facebox)
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var fb_pathToImage = "/images/throbber.gif";
var fb_CurRequestObj = null;
var fb_iRequest = 0;
var fb_height = 64;
var fb_width = 64;
var facebox_html = '<div id="facebox" style="display:none; overflow:visible;"> \
			<table> \
			    <tbody> \
				<tr> \
				    <td class="tl"/><td class="b"/><td class="tr"/> \
				</tr> \
				<tr> \
				    <td class="b"/> \
				    <td class="fb_body"> \
					<div class="fb_main"> \
					    <div class="fb_header"> \
						<a href="#" class="fb_close"> \
						    close \
						</a> \
						<span class="fb_title"></span> \
					    </div> \
					    <div class="fb_content"></div> \
					</div> \
				    </td> \
				    <td class="b"/> \
				</tr> \
				<tr> \
				    <td class="bl"/><td class="b"/><td class="br"/> \
				</tr> \
			    </tbody> \
			</table> \
		    </div>';

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){
    tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
    preload = [ new Image() ];
    preload[0].src = fb_pathToImage;

    //preload table borders
    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
	preload.push(new Image());
	preload.slice(-1).src = $(this).css('background-image').replace(/url(.+)/, '$1');
    });
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
    $(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
    });
}

function windowDimensions(){
    if( window.innerHeight !== undefined ){
	var dimensions = [window.innerWidth, window.innerHeight]; // most browsers
    }
    else{ // IE varieties
	var doc = (document.body.clientWidth) ? document.body : document.documentElement;
	var dimensions = [doc.clientWidth, doc.clientHeight];
    }
    return dimensions;
}

function fb_loading() {
    if( $('#facebox .fb_loading').length == 1 ) return true;

    //add the loading div
    $('#facebox .fb_main').hide()
	    .after('<div class="fb_loading" style="height:64px; width:64px; text-align:center;"><img src="'+preload[0].src+'" style="position:relative; top:16px;" /></div>');
    $('#facebox .fb_content').empty();

    //get dimensions for positioning
    var scrolltop = $fb_target.scrollTop();
    var scrollleft = $fb_target.scrollLeft();
    var dimensions = windowDimensions();
    var pageheight = $.browser.msie ? dimensions[1] : $fb_target.height(); //TODO: see if the width/height methods work in jquery 1.2.6 (don't work for IE in 1.2.1)
    var pagewidth = $.browser.msie ? dimensions[0] - 18 : 'auto'; //-18 for IE for the scrollbar

    //position it (parseInt all values to make sure they're intergers and not decimals)
    $('#facebox').css({
	top:    parseInt(scrolltop + (pageheight / 10), 10),
	left:   parseInt(scrollleft, 10),
	width:  parseInt(pagewidth, 10)
    }).show();

    //bind the esc key to close facebox
    document.onkeyup = function(e){
	keycode = e == null ? event.keyCode : keycode = e.which;
	if( keycode == 27 ) tb_remove(); //close on escape
    }
}

function tb_show(caption, url, fb_target, callback) {//function called when the user clicks on a thickbox link

    if( fb_CurRequestObj !== null && fb_CurRequestObj.abort ){
	//Abort the AJAX request
	fb_CurRequestObj.abort();
    }

    //setup callback function
    callback = callback || function(){};

    //if fb_target was provided
    if( fb_target ){
	// If it's a function
	if( $.isFunction( fb_target ) ) {
	    // We assume that it's the callback
	    callback = fb_target;
	    fb_target = null;
	}
    }

    try {
	if( document.getElementById("facebox") === null ){
	    //figure out which div to append the facebox to
	    $fb_target = fb_target ? $(fb_target) : $("#main");
	    $fb_target.append(facebox_html);
	}

	//show the loading image, position facebox
	if( !$('#facebox').is('.fb_visible') ) fb_loading();

	//bind the close function
	$("#facebox .fb_close").click(tb_remove);

	//give it a title if one exists
	if( caption === null ) caption = "";

	//load our ajax content
	fb_CurRequestObj = $.ajax({
	    url: url += "&random=" + (new Date().getTime()),
	    success: function(response){
		$("#facebox .fb_title").html(caption);
		$("#facebox .fb_content").html(response);
		$("#facebox .fb_main").show();
		$('#facebox .fb_loading').css('visibility', 'hidden').hide().remove();

		//hack to focus first input element (autocomplete focus hack included)
		if( $('#facebox :input:not(:hidden)').size() ){
		    var $input = $('#facebox :input:not(:hidden):first'); //Select the first text input in the form
		    $input.focus();
		}

		fb_CurRequestObj = null; //so IE can deal

		//done with everything else, fire the callback function
		callback();
	    }
	});
    }
    catch(e) {
        //nothing here
    }

    return false; //so we can call it in an anchor as return tb_show(); instead of tb_show(); return false;
}

function tb_remove() {
    if( !formIsModified() ){
		resetFormDefaults();
    	$('#facebox .fb_loading').remove(); //so we can load the new one
	    $("#facebox .fb_close").unbind("click");
	    $("#facebox").fadeOut("normal").removeClass('fb_visible');
	    document.onkeydown = "";
	    document.onkeyup = "";
    }
    return false;
}