/// <reference path="/scripts/jquery-1.3.2-vsdoc.js" />

//create main utility class
function fbisGuiInternal(opts){
	//if its not a jquery object then create one using paramter as a selector
	this.tojq = function(p){
		if(p!=undefined && !(p instanceof jQuery)){
			//not a jQuery object so must be a string
			p = jQuery(p);
		};
	
	return p;
	};
	
	return this;
}

//create global instance
var fbisGui = new fbisGuiInternal();

(function($) {
	$.fn.fbisGui = fbisGui;
	
})(jQuery);

//extend with public methods

/****************************************/
/* Movement and animation related utils */
/****************************************/

//makes an object absolute and appends to the body if rebase is true
fbisGuiInternal.prototype.makeAbsolute = function(jQ, rebase) {
	jQ = fbisGui.tojq(jQ); //ensure its a jquery collection
	return jQ.each(function() {
		var el = $(this);
		var pos = el.position();
		el.css({ position: "absolute",
			marginLeft: 0, marginTop: 0,
			top: pos.top, left: pos.left });
		if (rebase)
			el.remove().appendTo("body");
	});
}

fbisGuiInternal.prototype.slideOver = function(obj, target) {
	//get the position of the placeholder element  
	var pos = $(target).offset();
	var eWidth = $(target).outerWidth();
	var mWidth = $(obj).outerWidth();
	var left = (pos.left + eWidth - mWidth) + "px";
	var top = pos.top + "px";
	//show the menu directly over the placeholder  
	$(obj).css({
		position: 'absolute',
		zIndex: 5000,
		left: left,
		top: top
	});

	$(obj).slideToggle();
}

fbisGuiInternal.prototype.center = function(obj, absolute) {
	var t = jQuery(obj);

	t.css("position", "absolute");
	t.css("top", ($(window).height() - t.height()) / 2 + $(window).scrollTop() + "px");
	t.css("left", ($(window).width() - t.width()) / 2 + $(window).scrollLeft() + "px");

	/* The code below is more advanced and works best in all browsers except IE! 
	In IE sortables do not behave correctly when set this way for some reason.
	Reverted to simpler version above which works better with sortable but still not 100%
	 */
//	t.css({
//		position: absolute ? 'absolute' : 'fixed',
//		left: '50%',
//		top: '50%',
//		zIndex: '99'
//	}).css({
//		marginLeft: '-' + (t.outerWidth() / 2) + 'px',
//		marginTop: '-' + (t.outerHeight() / 2) + 'px'
//	});

//	if (absolute) {
//		t.css({
//			marginTop: parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(),
//			marginLeft: parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
//		});
//	}
	return t;
};

//jQuery.fn.center = function() {
//	this.css("position", "absolute");
//	this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
//	this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
//	return this;
//}
	
fbisGuiInternal.prototype.ajaxInsert = function(obj, url) {
	var load = $(obj).append('<span class="loading">loading...</span>');
	$(obj).load(url);
	load.remove();
	load = null;
}

/*******************************************/
/* Component behavior - actions/operations */
/*******************************************/

//Collapsable looks in item for div.wrap where the icon is then binds to .minmaxContent
fbisGuiInternal.prototype.Collapsable = function(jQ){
	jQ = fbisGui.tojq(jQ); //ensure its a jquery collection
	
	return jQ.each(function() {
		console.log($(this));
		//add handler
		$(this).click(function(e) {
			$(e.target).toggleClass('open')
				.parents('div.wrap')
				.find('.minmaxContent').slideToggle('fast');
			console.log($(e.target).parents());
		});
	});
};
//Notify just pops up a notification and fades it out
fbisGuiInternal.prototype.Notify = function(msg, duration, markup) {
	if (markup == undefined) markup = '<div class="notify">' + msg + '</div>';
	if (duration == undefined) duration = 3000;
	var $$note = $(markup);
	$$note.css('display', 'none');
	$('body').append($$note);
	fbisGui.center($$note)
	$$note.show(100).animate({ 'opacity': '1' }, duration)
				.animate({ 'opacity': 'toggle' }, 1000, function() { $$note.remove(); }); //fade out again
};
/****************************************/
/* Controls/plugins						*/
/****************************************/

fbisGuiInternal.prototype.EditLabel = function(item) {
	var $$item = $(item);
	if (!$$item.hasClass('editing')) {
		$$item.addClass('editing'); 								// add class because we only want to start editing on the first click
		$$item.attr('title', $$item.text()); 						// save the current label value so we can undo on escape
		$("input.IPE").blur();                                      // clear any other IPE editors
		//create an input that we can use and copy the labels value into it
		var edit = $('<input class="IPE" type="text" value="' + $$item.text() + '"/>"');
		edit.width = item.width; 								//match the width
		edit.blur(function(e) {
			$$item.html($(e.target).val()); 					//set label text to the edited value
			$(e.target).remove();
			$$item.removeClass('editing');
		}).keydown(function(e) {
			switch (e.keyCode) {
				case 13: 										//on enter save changes
					edit.blur();
					break;
				case 27: 										//on escape exit editing and restore value
					edit.unbind('blur');
					$$item.html('<label>' + $$item.attr('title') + '</label>');
					$$item.removeClass('editing');
					break;
			}
		});

		$$item.html(edit).focus().select(); 						//give it focus and select the value
	}
}
fbisGuiInternal.prototype.EditText = function(item, callback) {
	var $$item = $(item);
	if (!$$item.hasClass('editing')) {
		$$item.addClass('editing'); 								// add class because we only want to start editing on the first click
		$$item.attr('title', $$item.text()); 						// save the current label value so we can undo on escape
		$("input.IPE").blur();                                      // clear any other IPE editors
		//create an input that we can use and copy the labels value into it
		var edit = $('<input class="IPE" type="text" value="' + $$item.text() + '"/>"');
		edit.width = item.width; 								//match the width
		edit.blur(function(e) {
			$$item.html($(e.target).val()); 					//set label text to the edited value
			$(e.target).remove();
			$$item.removeClass('editing');
			callback($$item);
		}).keydown(function(e) {
			switch (e.keyCode) {
				case 13: 										//on enter save changes
					edit.blur();
					break;
				case 27: 										//on escape exit editing and restore value
					edit.unbind('blur');
					$$item.html('<label>' + $$item.attr('title') + '</label>');
					$$item.removeClass('editing');
					break;
			}
		});

		$$item.html(edit).focus().select(); 						//give it focus and select the value
	}
}

fbisGuiInternal.prototype.msgBox = function(content, buttons, options) {
	//just a wrapper to expose msgBox plugin through fbisGui
	return $().fbisGui.msgBox(content, buttons, options);
}
fbisGuiInternal.prototype.calendar = function(jQ, options)
{
	jQ = fbisGui.tojq(jQ); //ensure its a jquery collection
	jQ = $(jQ[0]); //only get the first one
	
	return $(jQ).fbisCalendar(options);
}
fbisGuiInternal.prototype.toolbar = function(jQ, handler, options) {
	j2= fbisGui.tojq(jQ); //ensure its a jquery collection
	console.log(jQ, handler);
	return $().fbisGui.toolbar(j2, handler, options);
}
fbisGuiInternal.prototype.fileExplorer = function(jQ, handler, options) {
	j2 = fbisGui.tojq(jQ); //ensure its a jquery collection
	//console.log(jQ, handler);
	return $().fbisGui.fileExplorer(j2, handler, options);
}
fbisGuiInternal.prototype.overlay = function() {
	var size = viewport();
	var mask = $('<div class="pagemask"/>').css({
		position: 'absolute',
		top: 0,
		left: 0,
		opacity: 0.5,
		width: size[0],
		height: size[1],
		display: 'block',
		zIndex: 1999
	});
	$('body').append(mask);
	
	return mask;
}
/* one of the greatest headaches in the tool. finally made it */
/* From jQuery Tools - http://flowplayer.org/tools/index.html */
function viewport() {
	// the horror case
	if ($.browser.msie) {

		// if there are no scrollbars then use window.height
		var d = $(document).height(), w = $(window).height();

		return [
				window.innerWidth || 							// ie7+
				document.documentElement.clientWidth || 	// ie6  
				document.body.clientWidth, 					// ie6 quirks mode
				d - w < 20 ? w : d
			];
	}

	// other well behaving browsers
	return [$(window).width(), $(document).height()];
} 
/* Utility functions */
/* Disable text-select plugin*/
$(function() {
	$.extend($.fn.disableTextSelect = function() {
		return this.each(function() {
			if ($.browser.mozilla) {//Firefox
				$(this).css('MozUserSelect', 'none');
			} else if ($.browser.msie) {//IE
				$(this).bind('selectstart', function() { return false; });
			} else {//Opera, etc.
				$(this).mousedown(function() { return false; });
			}
		});
	});
});