
/* BBT UTILS
 * @name			bbt utils
 * @namespace:		EDE
 * @namespacedFile	ede.utils.js
 * @dependencies:	bbt.js
 *
 */

	// NAMESPACE REGISTERING (bbt.js dependant)
	Namespace.Register("EDE");



/* fn TABBED MAIN NAVIGATION
 * 
 * TODO: optimize, extend and refactorize in an elegant way.
 *       Arguments passing.
 * 
 * @namespace:	EDE
 * @usage:		jObj.EDE.tabbedNavigation();
 * @apply:		Any properly formed Tabbed Navigation element
 * 
 */

EDE.tabbedNavigation = function (jObj) {

	var $navObj = jObj;

	var current_submenu_tab = "";
	var menuTime = null;
	var tabNav = $navObj.find(".parent-nav > li.tabnav");
	var tabSelected = $navObj.find(".parent-nav > li.tabnav.selected");
	var childNav = $navObj.find(".child-nav");

	_hideSubMenu = function() {
	    tabNav.removeClass("highlight");
	    childNav.css('display', 'none');
	    current_submenu_tab.find(".child-nav").show();
	    current_submenu_tab.addClass("selected");
		checkChild();
	}

	checkChild = function() {
		if (current_submenu_tab.find(".child-nav").length == 0) {
			jQuery("#nav").addClass("noChildNav");
		} else {
			jQuery("#nav").removeClass("noChildNav");
		}
	}

	loadSubMenu = function() {

	    $navObj.find("a.no-link").click(function() {
	        return false;
	    });

	    if (current_submenu_tab == "") {
	        current_submenu_tab = tabSelected;
			checkChild();
	    }

	    tabNav.mouseover(function() {

	    	clearTimeout(menuTime);

	        _hideSubMenu();

	        if (jQuery(this).find(".child-nav").length > 0) {
	            jQuery(this).not('.selected').addClass("highlight");
	            childNav.css('display', 'none');
	            jQuery(this).find(".child-nav").show();
				jQuery("#nav").removeClass("noChildNav");
	        } else {
	            jQuery(this).not('.selected').addClass("highlight");
	            childNav.css('display', 'none');
				jQuery("#nav").addClass("noChildNav");
	        }
	    });

	    tabNav.mouseout(function() {
	        menuTime = setTimeout("_hideSubMenu()", 600);
	    });
	};

	// navigation submenu load
	loadSubMenu();

};




// FUNCTION COLLAPSIBLE ITEMS
// ------------------------------
// TRIGGER USAGE:
//	jQuery('elem').collapsibleTable();
//  or passing arguments
//  jQuery('elem').collapsibleTable({ args });
//
// TODO: refactor and parametrize
//       text, effect, buttons and scrollTo - moveTo trigger
//       performance enhancement
//       Scrollmove:
//                  http://plugins.jquery.com/project/ScrollTo
//                  http://demos.flesler.com/jquery/scrollTo/
//

EDE.collapsibleItems = function(jObj, args) {
	
	args = args || {};

	//arguments
	args = jQuery.extend({
		toggleTrigger : ".toggler",     // element who fires the event (tag, class or id)
		toggleButton: "bt-toggle",
		tgCollapse: "toggle-collapse",
		tgText: "mostrar",
		tgTextCollapse: "ocultar",
		tgBrackets: true,
		accordion: true
	}, args);

	var subHead = jQuery(jObj).find(args.toggleTrigger);

	// brackets
	var brackets = ["", ""];
	if (args.tgBrackets == true) {
		var brackets = ['[ ', ' ]'];
	}

	jQuery(jObj).find('.vpane').hide();
	jQuery(jObj).find('.vpane:first').hide(); // TODO: parametrizar si el primero está abierto o no

	subHead.prepend('<span class="iblk ' + args.toggleButton + '" title=""></span>');
	subHead.append('<span class="inf-toggle iblk">' + brackets[0] + '<span class="lk-toggle">' + args.tgText + '</span>' + brackets[1] + '</span>');


	var accordion = function (checkButton, checkMsg) {
		jQuery(jObj).find('.vpane:visible').css('display', 'none');
		checkButton.removeClass(args.tgCollapse).attr('title', 'desplegar');
		checkMsg.text(args.tgText);
	}

	var scrollToPos = function (csItem) {
		var doc	= (window.opera)? (document.compatMode=="CSS1Compat"? $('html') : $('body')) : $('html,body')
		var ypos = csItem.offset().top;
		doc.stop().animate( { scrollTop: ypos }, 250);
	}


	jQuery(subHead)
		.bind("click", function(e) {

			var eTrigger = e.target;

			$eTrigger = jQuery(eTrigger);  // node wrap in a jQuery object

			var csItem = jQuery(this).closest(".cs-item");

			var checkElement = $eTrigger.parents('.collapsible').find('.vpane');
			var checkButton = $eTrigger.parents('.cs-item').siblings().find("."+args.tgCollapse);
			var checkMsg = $eTrigger.parents('.cs-item').siblings().find(".lk-toggle");

			if (checkElement.is(':visible')) {

				checkElement.css('display', 'none');
				jQuery(this).removeClass(args.tgCollapse).attr('title', 'desplegar');

				jQuery(this).find(".lk-toggle").text(args.tgText);
				//scrollToPos(csItem);

			} else {

				if (args.accordion != false) {
					accordion(checkButton, checkMsg);
					scrollToPos(csItem);
				}

				checkElement.show();
				jQuery(this).addClass(args.tgCollapse).attr('title', 'plegar');
				jQuery(this).find(".lk-toggle").text(args.tgTextCollapse);
			}
			return false;
		});
	return this;
};



/* fn Drop Shadow Skin
 * 
 * @namespace:	EDE
 * @usage:		jObj.EDE.dropShadow();
 * @apply:		mostly component inset elements (.cp-inset) with skin-dropshadow skin class attached
 * 
 */

EDE.dropShadow = function (jObj) {
	if (jQuery.browser.msie && jQuery.browser.version < '7') {
		return "";
	} else {
		var $insetContainer = jObj;
		var dropshadowHtml = '<span class="layer-sh"><span class="layer-l"></span><span class="layer-r"></span><span class="layer-lt"></span><span class="layer-rt"></span><span class="layer-bl"></span><span class="layer-br"></span></span>';
		$insetContainer.prepend(dropshadowHtml);
	}
}



/* fn GET SCROLLABLE SIZES
 * Calculate sizes of scrollable and slider wrapper, items and containers
 * 
 * TODO: optimize, extend and refactorize in an elegant way.
 *       Arguments passing.
 * 
 * @namespace:	EDE
 * @usage:		$('[selector]').getScrollableSizes();
 *        		or $("[selector]").aniyPluginCall({arg1: x, arg2: x, etc }).getScrollableSizes();
 *       		or 
 *
 * @apply:		scrollable modules
 * 
 */


EDE.getScrollableSizes = function (jObj) {

	var $scrollContainer = jObj;

	var $scrollable = $scrollContainer.find('.bh-scrollable');
	var $wrapper = $scrollContainer.find('.scr-wrapper');
	
	var scrollableSize = $scrollable.width();
	$scrollable.css('width', scrollableSize);
	
	var item = jObj.find('.scr-item');
	var numItems = item.length;
	
	jQuery.each(item, function(index, obj) {
		var itemWd = jQuery(this).width();
		jQuery(this).css('width', itemWd);
	});
	
	var wrapperSize = numItems * item.width();
	$wrapper.css('width', wrapperSize);
	$wrapper.css('position', 'absolute');

};



/* fn EXPOSED ITEMS
 * 
 * @namespace:	EDE
 * @usage:		EDE.exposed(jObj);
 * 
 */

EDE.exposed = function (jObj) {

	jQuery(document).ready(function() { // Doc ready (ie KB927917 bug)

		var mask = '<div id="expose" class="exposed-mask"></div>';
		jQuery('body').append(mask);
		var expose = jQuery("#expose");

		function viewport() {
			if ($.browser.msie) {
				// if no scrollbars then use window.height
				var docH = jQuery(document).height(), winH = jQuery(window).height();
				return [
					window.innerWidth || 						// ie7+
					document.documentElement.clientWidth || 	// ie6  
					document.body.clientWidth, 					// ie6 quirks mode
					docH - winH < 20 ? winH : docH
				];
			} 
			// compliant browsers
			return [jQuery(document).width(), jQuery(document).height()]; 
		} 

		function constrain() {
			var dimensions = viewport();				
			expose.css({width: dimensions[0], height: dimensions[1]});
		}

		// mask resize when window is resized
		jQuery(window).bind("resize.expose", function() {
			constrain();
		});

		jQuery(jObj).bind('mousedown', function(e){
			var $trigger = jQuery(this);

			$trigger.addClass("exposed");

			// reveal mask
			expose.show();
			constrain();

			expose.bind("click", function(e){
				jQuery(this).css('display', 'none');
				$trigger.removeClass("exposed");
				expose.unbind("click");
			});
		// $trigger.unbind("mousedown");
		});
	});
}



/* fn Release Password Hint
 *
 * @namespace:	EDE
 * @usage:		EDE.releasePassword(jObj);
 * @author:		Pacote
 */

EDE.releasePassword = function (jObj) {

	var form = jObj;
	var elems = form.find('.bb-field[title!=""]');

	elems.each(function (i) {
		var el = jQuery(this);

		var id = el.attr('id');
		var $id = jQuery('#'+id);
		var itype = $id.attr('type');

		if (itype == 'password') {
			var name = $id.attr('name');
			var title = $id.attr('title');
			iSwapHt = '<input class="bb-field-liveswap tx-field id-'+ id +'" type="text" name="'+ name +'_replaced" value="'+title+'" />';
			$id.before(iSwapHt).hide();
			
		} else {
			jQuery(this).hint();
		}
	});

	form.find('input').focus(function() {
		if(jQuery(this).hasClass('bb-field-liveswap')) {
			var nid = jQuery(this).attr("class").split('id-')[1].split(' ')[0];
			jQuery(this).hide();
			jQuery('#'+nid).show().focus();
		}
		// On Blur
		jQuery(this).blur(function(){
			if(jQuery(this).val() == '') {
				if(jQuery(this).attr('type') == 'password') {
					jQuery(this).prev('.bb-field-liveswap').show();
					jQuery(this).hide();
				}
			}
		});
	});
}




/* 
 * INITIALIZATIONS
 * @note	place here general inits
 */


$(function(){

	// INSET DROP SHADOWS
	var jObj = jQuery(".cp-inset.skin-dropshadow");
	EDE.dropShadow(jObj);

	// Textual Tooltips
	var jObj = jQuery(".tx-tooltip");
	jObj.tooltip({
		tipClass: 'cp-tooltip',
		effect: 'slide',
		delay: 1500
	}).dynamic({
		bottom: {
			direction: 'down',
			bounce: true
			}
		});
	
});


// transformar peticiones get a post
var __bbt_force_post = function (jObj) {
	if (jObj == null) {
		jObj = jQuery("body");
	}

	// Evitamos que se registre dos veces
	jObj.find("a.bbt-force-post").unbind("click");

	jObj.find("a.bbt-force-post").click(function () {
				var vars = [], hash;
				var url = jQuery(this).attr("href");
				hashes = url.slice(url.indexOf('?') + 1).split('&');

			for(var i = 0; i < hashes.length; i++) {
				hash = hashes[i].split('=');
				vars.push(hash[0]);
				vars[hash[0]] = hash[1];
			}
			
			var form_id = parseInt(Math.random() * 10000,10);
			jQuery("body").append("<form action='" + (url.split("?").slice(0,1)) + "' method='POST' id='form_" + form_id+ "'></form>");
			jQuery.each(vars, function (i, data) {
			var _input = jQuery("<input type='hidden' name='" + data + "' value='" + vars[data] + "'>");
			jQuery("#form_" + form_id).append(_input);
				});
                        jQuery("#form_" + form_id).submit();
			return false;
			});
};
jQuery(document).ready(function() { __bbt_force_post(); });

