/** 
 * @projectDescription	RTVV. Utilities
 *
 */


/**
 * Namespace Register Helper. Allows to Register a namespace
 * @param {Object} _Name	namespace name
 * @return	{string} NE		namespaced element
 * @constructor
 * 
 */

var Namespace = {
    Register : function(_Name)
    {
        var chk = false;
        var cob = "";
        var spc = _Name.split(".");
        for(var i = 0; i<spc.length; i++)
        {
            if(cob!=""){cob+=".";}
            cob+=spc[i];
            chk = this.Exists(cob);
            if(!chk){this.Create(cob);}
        }
        if(chk){ throw "Namespace: " + _Name + " is already defined."; }
    },

    Create : function(_Src)
    {
        eval("window." + _Src + " = new Object();");
    },

    Exists : function(_Src)
    {
        eval("var NE = false; try{if(" + _Src + "){NE = true;}else{NE = false;}}catch(err){NE=false;}");
        return NE;
    }
};


/**
 * Set global namespace
 * RTV = Radio Televisión Valenciana
 */
	Namespace.Register("RTV");



/**
 * get property helper
 * @author J.Serrano - Bitban Technologies
 * @param {Object} jObj, type
 * @constructor
 */

RTV.getProperty = function (jObj, type) {
	var isJQuery = jObj instanceof jQuery;
	
	if(!isJQuery) { return false; }
	
	if (!jObj.attr("class")) { return false; }
	
	var values = jObj.attr("class").split(" ");
	var ret = null;
	var _regexp = new RegExp("^" + type + "_");
	jQuery.each(values, function(i,data) {  if(data.match(_regexp)) ret = data.replace(_regexp, ""); });	
	return ret;
};



/**
 * Main Navigation
 * @author F.S.Encinas - Bitban Technologies
 * @param {Object} jObj
 * @constructor
 */

RTV.tabbedNavigation = function (jObj) {

	var $navObj = jObj;

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

	var dropNav = jQuery("#nav-b").find(".drop-nav-item");

	_hideSubMenu = function(rel) {
		clearTimeout(menuTime);
	    tabNav.parent("li.tabnav").removeClass("highlight");
		dropNav.css('display', 'none');
	    current_submenu_tab.addClass("selected");
	}

	loadSubMenu = function() {

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

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

	    // parent menu event actions (complex / tricky)
	    tabNav.mouseenter(function(i) {

	    	rel = jQuery(this.rel);

			_hideSubMenu(rel);
            jQuery(this).parent("li.tabnav").addClass("highlight");
            rel.show();

			jQuery(this).mouseleave(function(e){
				menuTime = setTimeout(function(){
					_hideSubMenu(rel)
				}, 2000);
				rel.data('menuTime', menuTime);
				jQuery(this).unbind(e);					
			});

			// drop-featured menu (outside DOM context of parent menu)
			rel.mouseover(function(e){
				e.stopImmediatePropagation();
				clearTimeout(jQuery(this).data('menuTime'));
			}).mouseleave(function(e){
				e.stopImmediatePropagation();
				menuTime = setTimeout(function(){
					_hideSubMenu(rel)
				}, 1000);
				rel.data('menuTime', menuTime);
			});
		});
	};
	// navigation submenu init
	loadSubMenu();
};



/**
 * Mini select
 * @author F.S.Encinas - Bitban Technologies
 * @param {Object} jObj
 * @constructor
 */

RTV.miniSelect = function (jObj) {

	// "la del copón" for this... 

	var obj = jObj;
	var lnk = obj.find(".event-grp .lnk");

	function _destroy(dropdown, t){
		destroyIn = setTimeout(function(){
			releaser(dropdown, 0);
			dropdown.parent().find(".lnk").removeClass("fold");
		}, t);
		dropdown.data('destroyTime', destroyIn);
	}

	function releaser(tobj, st) {
		if(st == 1){
			tobj.show();
		} else if(st == 0){
			tobj.css("display", "none");
		}
	}

	lnk.click(function(e){

		var dropdown = jQuery(this).parent().find(".dropdown");
		var eGrp = jQuery(this).parent();

		if(dropdown.is(":visible")){
			releaser(dropdown, 0);
			jQuery(this).removeClass("fold");
			clearTimeout(dropdown.data('destroyTime'));
		} else {
			releaser(dropdown, 1);
			jQuery(this).addClass("fold");
		}
		eGrp.mouseenter(function(e){
			e.stopImmediatePropagation();
			clearTimeout(dropdown.data('destroyTime'));
		}).mouseleave(function(e){
			e.stopImmediatePropagation();
			_destroy(dropdown, 1500);
		});
	});
};



/**
 * Simple Search Form Text Hint
 * @author F.S.Encinas - Bitban Technologies
 * @param {Object} jObj
 * @arguments {arg} text
 * @constructor
 */
RTV.simpleSearchForm = function (jObj, arg) {

	arg = arg || {};

	//args
	arg = jQuery.extend({
		hint : "Texto de la búsqueda",
		searchField : "#mainSearchField",
		submit : true,
		submitButton : ".bt-submit"
	}, arg);

	searchForm = jQuery(jObj);
	searchFormId = searchForm.attr("id");
	searchField = searchForm.find(arg.searchField);

	searchField.val(arg.hint);
	searchField.focus(function(){if(jQuery(this).val() == arg.hint) jQuery(this).val("");});
	searchField.blur(function(){if(jQuery(this).val() == "") jQuery(this).val(arg.hint);});

	if(arg.submit == true){
		searchForm.find(arg.submitButton).click(function() {
			document.forms[searchFormId].submit();
			return false;
		});		
	} else {
		searchForm.attr("onsubmit", "return false");
	}
};



/**
 * Get Scrollable Sizes fn
 * @author F.S.Encinas - Bitban Technologies
 * @param {Object} jObj, type (string): "horizontal", "vertical"
 * @constructor
 */
RTV.getScrollableSizes = function (jObj, type) {

	var $scrollContainer = jObj;

	var $scrollable = $scrollContainer.find('.bh-scrollable');
	var $wrapper = $scrollContainer.find('.scr-wrapper');

	var item = jObj.find('.scr-item');
	var numItems = item.length;

	if(type == "horizontal") {

		var scrollableSize = $scrollable.width();
		$scrollable.css('width', scrollableSize);

		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');

	} else if(type == "vertical") {

		var scrollableHeight = $scrollable.height();
		$scrollable.css('height', scrollableHeight);

		jQuery.each(item, function(index, obj) {
			var itemHg = jQuery(this).height();
			jQuery(this).css('height', itemHg);
		});

		var wrapperHeight = numItems * item.height();
		$wrapper.css('height', wrapperHeight);
		$wrapper.css('position', 'absolute');
	}

};



/**
 * fn Equalize Block/Columns Heights
 * @author F.S.Encinas - Bitban Technologies
 * @param {Object} jObj, {arguments} args
 * @constructor
 * 
 * @usage RTV.equalizeBlocks(jObj, {column: ['selector', 'selector2', ...]});
 */

RTV.equalizeBlocks = function (jObj, args) {

	args = args || {};

	//args
	args = jQuery.extend({
		column : [".eqBlock", ".foo"], // you could pass an array of different object for stacking
	//	column : ".eqBlock",           // or a single string (automatic type casting)
		attr : 'min-height'
	}, args);

	var eqContainer = jQuery(jObj);

	function equalize(col) {
		var largestHeight = 0;
		var largestNetHeight = 0;
		var highestElem = null;

		var parsep = function parsep(obj, val) {
			return parseInt(obj.css(val), 10);
		}

		// IE, reset and other
		col.each(function() {
			obj = jQuery(this);

			if (jQuery.browser.msie && jQuery.browser.version < '7') {
				args.attr = 'height';
			}

			if (args.attr == 'min-height') {
				jQuery(this).css('cssText', 'min-height:inherit');
			} else if (args.attr == 'height' && !obj.css('height')) {
				jQuery(this).css('cssText', 'height:auto');
			}

			jQuery(this).addClass("eqCalc"); // used to keep elements visible if hidden while calculation occurs
		});

	 	col.each(function(i) {
	 		var obj = jQuery(this);

	 		var elHeight = jQuery(this).height();
	 		var elPadding = parsep(obj, 'padding-top') + parsep(obj, 'padding-bottom');
	 		var elMargin  = parsep(obj, 'margin-top')  + parsep(obj, 'margin-bottom');

	 		var elBorders = obj.outerHeight(true) - (elHeight + elPadding + elMargin);

	      	if((elHeight + (elPadding + elBorders)) > largestHeight) {
	      		largestHeight = elHeight + elPadding + elBorders;
				largestNetHeight = elHeight;
	      		highestElem = this;
	      	}
		});

		// col.not($(highestElem)).each(function() { // due to quantization errors in browsers better apply to all elements
		col.each(function(i) {
	 		var obj = jQuery(this);

	 		var elHeight = jQuery(this).height();
	 		var elPadding = parsep(obj, 'padding-top') + parsep(obj, 'padding-bottom');
	 		var elMargin  = parsep(obj, 'margin-top')  + parsep(obj, 'margin-bottom');

	 		var elBorders = obj.outerHeight(true) - (elHeight + elPadding + elMargin);

			jQuery(this).css('cssText', args.attr + ':' + (largestHeight - (elPadding + elBorders)) + 'px !important');
			jQuery(highestElem).css('cssText', 'height:' + largestNetHeight + 'px !important');

			jQuery(this).removeClass("eqCalc"); // revert the keep visible calculation class
		});
	}

	eqContainer.each(function(i, el){

		el = jQuery(this);

		// scope
		var _col = args.column;
		var col = _col;

		// if not array (type cast)
		if (!jQuery.isArray(col)) {
			col = [_col];
		}

		$.each(col, function(index, value) {
			colObj = el.find(value); 
			equalize(colObj);
		});

	});

};



// jPlayer Tools ->

  /**
   * jPlayer Instance grabber
   * 
   */
  RTV.jplayerInstanceGrab = function(obj){

	// grab this object parent instance
	var thisPlayerInstance = obj.parents(".jplayer-instance");

	return thisPlayerInstance;

  };


  /**
   * jPlayer Sizer
   * 
   */
  RTV.jplayerSizer = function(obj, width){

  	var thisPlayerInstance = RTV.jplayerInstanceGrab(obj);

	if(width && width != 'auto') {
		thisPlayerInstance.find('.cp-jplayer').css({
			'width': width,
			'margin': '0 auto'
		});
	}

  };


  /**
   * jPlayer crossover instances Pause
   * 
   */
  RTV.jplayerCrossoverPause = function (e, obj, thisPlayerInstance) {

	if(!thisPlayerInstance) {
		var thisPlayerInstance = RTV.jplayerInstanceGrab(obj);
	}

	var thisPlayer = thisPlayerInstance.find(".jplayer-obj");

	thisPlayerInstance.addClass("jp-status-active");

	var playerInstances = jQuery(".jplayer-instance");
	var players = playerInstances.find(".jplayer-obj");

	players.not(thisPlayer).each(function() {
		jQuery(this).parent(".jplayer-instance").removeClass("jp-status-active");
		jQuery(this).jPlayer("pause");
	});
  };



/**
 * fn FONT SIZER
 * @author F.S.Encinas - Bitban Technologies
 * @param {Object} jObj, {Objects} target, {arguments} settings
 * @constructor
 */

RTV.fontSizer = function (jObj, target, settings) {

	settings = settings || {};

	// settings (defaults)
	settings = jQuery.extend({
		buttonIncrease : ".tx-increase",
		buttonDecrease : ".tx-decrease",
		maxFontSize : 24,
		minFontSize : 10
	}, settings);

	var increaser = jObj.find(settings.buttonIncrease);
	var decreaser = jObj.find(settings.buttonDecrease);

	// resize text action (params)
	function resizeText(target, currentFontSizeNum, factor) {

		var currentFontSize = target.css('font-size');
		currentFontSizeNum = parseFloat(currentFontSize, 10);

		if (isNaN(currentFontSizeNum)) {
			currentFontSizeNum = 10;
		}

		var newFontSize = currentFontSizeNum * factor;

		// if sizes are in range 
		if (newFontSize <= settings.maxFontSize && newFontSize >= settings.minFontSize) {
			target.css('font-size', newFontSize);
		}
	}

	// increase font size
	increaser.click(function() {
		resizeText(target, 0, 1.2);
		return false;
	});

	// decrease font-size
	decreaser.click(function() {
		resizeText(target, null, 0.8);
		return false;
	});
};



/**
 * fn ADDTHIS INSERT APIS (FB/TWEETER)
 * 
 * @author F.S.Encinas - Bitban Technologies
 * @param {Object} jObj, {arguments} selectors
 * @constructor 
 * @see http://www.addthis.com/help/client-api
 */

RTV.addThisInsertApis = function (jObj, selectors) {

	selector = selectors || {};

	//args selectors
	selectors = jQuery.extend({
		fbLikeA : ".fbLikeA",
		fbLikeB : ".fbLikeB",
		twTweet : ".twTweet"
	}, selectors);

	var itemHt = [
			'<a class="addthis_button_facebook_like" fb:like:layout="button_count" fb:like:width="100" fb:like:height="20" fb:like:locale="es_ES">'+'</a>',
			'<a class="addthis_button_facebook_like" fb:like:layout="standard" fb:like:width="340" fb:like:height="23" fb:like:show_faces=false fb:like:locale="es_ES">'+'</a>',
			'<a class="addthis_button_tweet" tw:via="RTVV">'+'</a>'
		];

	var idx = 0;

	jQuery.each(selectors, function(prop, value) {
		idx++;		
		if (prop != "none" || prop != "") {
			jObj.find(value).html(itemHt[idx-1]);
		}
	});
};



// OTHER STUFF ->


/**
 * fn Disable Text Selection
 * Perfect usage for clickable widgets to avoid all wrapper text selection ...
 * ... when user fire a quick or double mouse click onto sliders
 * 
 * @param {Object} jObj
 * @constructor
 */
jQuery(function(){
	jQuery.fn.disableTextSelect = function() {
		return this.each(function(){
			if(jQuery.browser.mozilla){ //Firefox
				jQuery(this).css('MozUserSelect','none');
			}else if(jQuery.browser.msie){ //IE
				jQuery(this).bind('selectstart',function(){return false;});
			}else{ //Opera, other...
				jQuery(this).mousedown(function(){return false;});
			}
		});
	};
});






/**
 * INITS
 * Place here general inits only if JS file is loaded at end
 * Don't use document ready unless strongly needed (Whether it is inline as if it is defined here) 
 * Use inline/embeded script initializations for better performance
 * ... and within enclosed modules (wich need an contentId or moduleId for instantiation) 
 */

/**
 *  BE CAREFUL: this is buggy in editors if empty or not initilaziations are placed here
 *  if you dont't plan include here inits, remove it!
 */
$(function(){

	// disable text selection PRELOAD INIT LISTENING FOR CLASS 'noSelect'
	jQuery('.noSelect').disableTextSelect();

});


RTV.addFavorites = function () {
	var value = jQuery.cookie('52f83fff0ce7872c90f157dbbd7d145d');
	if (value != ""  && value != null) {
		var url = location.href;
		jQuery.post('/participa/addFavorites.json', {"url" : url,} ,function (_response) {
				var response = BBT.fixJson(_response);
				if(response["error"] == "0") {
					alert("Afegit a favorits");
				} else if(response["error"] == "4") {
					alert("Ja està afegit a favorits");
				}
			});
	}
};
