(function ($) {

/**
 * A progressbar object. Initialized with the given id. Must be inserted into
 * the DOM afterwards through progressBar.element.
 *
 * method is the function which will perform the HTTP request to get the
 * progress bar state. Either "GET" or "POST".
 *
 * e.g. pb = new progressBar('myProgressBar');
 *      some_element.appendChild(pb.element);
 */
Drupal.progressBar = function (id, updateCallback, method, errorCallback) {
  var pb = this;
  this.id = id;
  this.method = method || 'GET';
  this.updateCallback = updateCallback;
  this.errorCallback = errorCallback;

  // The WAI-ARIA setting aria-live="polite" will announce changes after users
  // have completed their current activity and not interrupt the screen reader.
  this.element = $('<div class="progress" aria-live="polite"></div>').attr('id', id);
  this.element.html('<div class="bar"><div class="filled"></div></div>' +
                    '<div class="percentage"></div>' +
                    '<div class="message">&nbsp;</div>');
};

/**
 * Set the percentage and status message for the progressbar.
 */
Drupal.progressBar.prototype.setProgress = function (percentage, message) {
  if (percentage >= 0 && percentage <= 100) {
    $('div.filled', this.element).css('width', percentage + '%');
    $('div.percentage', this.element).html(percentage + '%');
  }
  $('div.message', this.element).html(message);
  if (this.updateCallback) {
    this.updateCallback(percentage, message, this);
  }
};

/**
 * Start monitoring progress via Ajax.
 */
Drupal.progressBar.prototype.startMonitoring = function (uri, delay) {
  this.delay = delay;
  this.uri = uri;
  this.sendPing();
};

/**
 * Stop monitoring progress via Ajax.
 */
Drupal.progressBar.prototype.stopMonitoring = function () {
  clearTimeout(this.timer);
  // This allows monitoring to be stopped from within the callback.
  this.uri = null;
};

/**
 * Request progress data from server.
 */
Drupal.progressBar.prototype.sendPing = function () {
  if (this.timer) {
    clearTimeout(this.timer);
  }
  if (this.uri) {
    var pb = this;
    // When doing a post request, you need non-null data. Otherwise a
    // HTTP 411 or HTTP 406 (with Apache mod_security) error may result.
    $.ajax({
      type: this.method,
      url: this.uri,
      data: '',
      dataType: 'json',
      success: function (progress) {
        // Display errors.
        if (progress.status == 0) {
          pb.displayError(progress.data);
          return;
        }
        // Update display.
        pb.setProgress(progress.percentage, progress.message);
        // Schedule next timer.
        pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay);
      },
      error: function (xmlhttp) {
        pb.displayError(Drupal.ajaxError(xmlhttp, pb.uri));
      }
    });
  }
};

/**
 * Display errors on the page.
 */
Drupal.progressBar.prototype.displayError = function (string) {
  var error = $('<div class="messages error"></div>').html(string);
  $(this.element).before(error).hide();

  if (this.errorCallback) {
    this.errorCallback(this);
  }
};

})(jQuery);
;
Drupal.locale = { 'pluralFormula': function ($n) { return Number(($n!=1)); }, 'strings': {"":{"An AJAX HTTP error occurred.":"Hubo un error HTTP AJAX.","HTTP Result Code: !status":"C\u00f3digo de Resultado HTTP: !status","An AJAX HTTP request terminated abnormally.":"Una solicitud HTTP de AJAX termin\u00f3 de manera anormal.","Debugging information follows.":"A continuaci\u00f3n se detalla la informaci\u00f3n de depuraci\u00f3n.","Path: !uri":"Ruta: !uri","StatusText: !statusText":"StatusText: !statusText","ResponseText: !responseText":"ResponseText: !responseText","ReadyState: !readyState":"ReadyState: !readyState","Hide":"Ocultar","Show":"Mostrar","Show shortcuts":"Mostrar atajos","Hide shortcuts":"Ocultar atajos","Edit":"Editar","Re-order rows by numerical weight instead of dragging.":"Reordenar las filas por peso num\u00e9rico en lugar de arrastrar.","Show row weights":"Mostrar pesos de la fila","Hide row weights":"Ocultar pesos de la fila","Drag to re-order":"Arrastre para reordenar","Changes made in this table will not be saved until the form is submitted.":"Los cambios realizados en esta tabla no se guardar\u00e1n hasta que se env\u00ede el formulario","Configure":"Configurar","Loading":"Cargando","(active tab)":"(solapa activa)","This permission is inherited from the authenticated user role.":"Este permiso se hereda del rol de usuario registrado.","Not restricted":"Sin restricci\u00f3n","Restricted to certain pages":"Restringido a algunas p\u00e1ginas","Not customizable":"No personalizable","The changes to these blocks will not be saved until the \u003Cem\u003ESave blocks\u003C\/em\u003E button is clicked.":"Los cambios sobre estos bloques no se guardar\u00e1n hasta que no pulse el bot\u00f3n \u003Cem\u003EGuardar bloques\u003C\/em\u003E.","The block cannot be placed in this region.":"El bloque no se puede colocar en esta regi\u00f3n.","This field is required.":"Este campo es obligatorio.","Disabled":"Desactivado","Settings":"Ajustes","Select all rows in this table":"Seleccionar todas las filas de esta tabla","Deselect all rows in this table":"Quitar la selecci\u00f3n a todas las filas de esta tabla","Please wait...":"Espere, por favor...","Other":"Otro(s)","@count year from now":"@count a\u00f1os desde ahora","@count years from now":"@count a\u00f1os desde ahora.","Hide summary":"Ocultar resumen","Edit summary":"Editar resumen","Not in menu":"No est\u00e1 en un men\u00fa","New revision":"Nueva revisi\u00f3n","No revision":"Sin revisi\u00f3n","By @name on @date":"Por @name en @date","By @name":"Por @name","Not published":"No publicado","Alias: @alias":"Alias: @alias","No alias":"Sin alias","@number comments per page":"@number comentarios por p\u00e1gina","Autocomplete popup":"Ventana emergente con autocompletado","Searching for matches...":"Buscando coincidencias","Done":"Hecho","Prev":"Previo","Next":"Siguiente","Today":"Hoy","January":"Enero","February":"Febrero","March":"Marzo","April":"Abril","May":"Mayo","June":"Junio","July":"Julio","August":"Agosto","September":"Septiembre","October":"Octubre","November":"Noviembre","December":"Diciembre","Jan":"Ene","Feb":"Feb","Mar":"Mar","Apr":"Abr","Jun":"Junio","Jul":"Jul","Aug":"Ago","Sep":"Sep","Oct":"Oct","Nov":"Nov","Dec":"Dic","Sunday":"Domingo","Monday":"Lunes","Tuesday":"Martes","Wednesday":"Mi\u00e9rcoles","Thursday":"Jueves","Friday":"Viernes","Saturday":"S\u00e1bado","Sun":"Dom","Mon":"Lun","Tue":"Mar","Wed":"Mi\u00e9","Thu":"Jue","Fri":"Vie","Sat":"S\u00e1b","Su":"Do","Mo":"Lu","Tu":"Ma","We":"Mi","Th":"Ju","Fr":"Vi","Sa":"Sa","mm\/dd\/yy":"mm\/dd\/yy","Requires a title":"Necesita un t\u00edtulo","Don\u0027t display post information":"No mostrar informaci\u00f3n del env\u00edo","Customize dashboard":"Personalizar panel de control","The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.":"El archivo seleccionado %filename no puede ser subido. Solo se permiten archivos con las siguientes extensiones: %extensions.","Close":"Cerrar","Maximize":"Maximizar","Minimize":"Minimizar","Collapse":"Plegar","Expand":"Desplegar","Translatable":"Traducible","Not translatable":"No traducible","Restricted to certain languages":"Limitado a ciertos idiomas","Published":"Publicado","Flag translations as outdated":"Marcar traducciones como desactualizadas","Content can only be inserted into CKEditor in the WYSIWYG mode.":"Contenido s\u00f3lo se puede insertar en CKEditor en el modo WYSIWYG.","None":"Ninguno","Add":"Agregar","Remove group":"Eliminar grupo","Apply (all displays)":"Aplicar (todas las presentaciones)","Revert to default":"Volver al valor inicial","Apply (this display)":"Aplicar (esta presentaci\u00f3n)","Minimum":"M\u00ednimo","Maximum":"M\u00e1ximo","Resume":"Curriculum","Pause":"Pausa","There was no action specified.":"No hubo acci\u00f3n especificada.","This slideshow is forced paused.":"Esta presentaci\u00f3n es forzada pausa.","An invalid integer was specified for slideNum.":"Un entero no v\u00e1lido se especific\u00f3 para slideNum.","An invalid action \u0022!action\u0022 was specified.":"Se ha especificado una acci\u00f3n no v\u00e1lida \u0022!action\u0022","No flags":"Sin marcas","Loading token browser...":"Cargando navegador de comodines...","Available tokens":"Comodines disponibles","Insert this token into your form":"Inserte este comod\u00edn en su formulario","First click a text field to insert your tokens into.":"En primer lugar, haga clic en un campo de texto para insertar sus fichas en.","Automatic alias":"Alias autom\u00e1tico","This extension is currently disabled":"Esta extensi\u00f3n est\u00e1 actualmente desactivado","All unsaved changed has been reseted!":"Todos los cambios que no se han guardado, se revertir\u00e1n. ","Saved config sucessfully!":"Guardado config con \u00e9xito!","Remove this block":"Eliminar este bloque","Update Advanced Option":"Actualizaci\u00f3n Opciones avanzadas","Applied Options":"Opciones Aplicadas","Select":"Seleccionar","Select all":"Seleccionar todo","Max.":"M\u00e1x.","Min.":"M\u00edn.","all":"todo","Deselect all":"Deseleccionar todo","Received an invalid response from the server.":"Recibi\u00f3 una respuesta no v\u00e1lida desde el servidor.","Internal server error. Please see server or PHP logs for error information.":"Error interno del servidor. Por favor, consulte los registros de informaci\u00f3n de error del servidor o PHP.","An error occurred at @path.\\n\\nError Description: @error":"Se produjo un error al @path. \\ n \\ nError Descripci\u00f3n:@error","Cancel button":"Mostrar bot\u00f3n Cancelar","Save and continue button":"Guardar y continuar bot\u00f3n","Create new tab":"Crear una nueva pesta\u00f1a","No tab":"A\u00f1adir pesta\u00f1a","Allowed HTML tags":"Etiquetas HTML permitidas","@count items added to @container":"@count elementos adicionados a @container","Extend":"Ampliar","@label":"@label","Horizontal orientation":"La orientaci\u00f3n horizontal","Vertical orientation":"Orientaci\u00f3n vertical","The navbar cannot be set to a horizontal orientation when it is locked.":"La barra de navegaci\u00f3n no se puede ajustar a una orientaci\u00f3n horizontal cuando est\u00e1 bloqueado.","Tray orientation changed to @orientation.":"La orientaci\u00f3n de la bandeja cambi\u00f3 a @orientation.","Tray \u0022@tray\u0022 closed.":"Bandeja \u0022@tray\u0022 cerrado.","Tray \u0022@tray\u0022 opened.":"Bandeja \u0022@tray\u0022 abierto.","Also allow !name role to !permission?":"\u00bfDesea tambi\u00e9n permitir el rol !name a !permission?","Breadcrumbs":"Rutas","Inverse":"Inverso","Anchors":"Puntos de ancla","Popovers":"Ventanas emergentes","Tooltips":"Ventanas de ayuda emergente","Rebuild Registry":"Reconstruir Registro","Votes remaining: ":"Votos restantes:","Saving vote...":"Guardando voto...","@count new":"@count nuevos","1 new comment":"1 comentario nuevo","@count new comments":"@count comentarios nuevos","Add file":"Agregar archivo","No style":"Sin estilo","No title":"Sin t\u00edtulo","No name":"Sin nombre","return to the same page":"volver a la misma p\u00e1gina","Contacting":"Contactando","This username is available.":"Este nombre de usuario esta disponible","This username is not available.":"Este nombre de usuario no esta disponible","This email address has not been used.":"Esta direcci\u00f3n de correo esta disponible","This email address is already in use, please \u003Ca href=\u0022@login\u0022\u003Etry logging in\u003C\/a\u003E with that email address or \u003Ca href=\u0022@reset\u0022\u003Eresetting your password\u003C\/a\u003E.":"Esta direcci\u00f3n de correo ya esta en uso, por favor \u003Ca href=\u0022@login\u0022\u003EInicie sesion\u003C\/a\u003E con dicha cuenta de correo o \u003Ca href=\u0022@reset\u0022\u003Erestablezca su contrase\u00f1a\u003C\/a\u003E","Automatic (hide title field)":"Automatico (esconder campo del t\u00edtulo)","Automatic (if title empty)":"Automatico (si el t\u00edtulo esta vac\u00edo)","Scheduled for publishing":"Estilo de panel para \u0022!pane\u0022","Scheduled for unpublishing":"Exigen anular la publicaci\u00f3n programada","Not scheduled":"No programado","Publishing enabled":"Editorial habilitado","Unpublishing enabled":"Anular la publicaci\u00f3n habilitado","Enabled: !networks !num":"Enabled: !networks !num","\u003Cbr \/\u003E(1 social network)":"\u003Cbr\u003E(1 red social)","\u003Cbr \/\u003E(@count social networks)":"\u003Cbr\u003E(@count redes sociales )","Translation published":"Traducci\u00f3n Publicada","Translation not published":"Traducci\u00f3n no publicado","Do not flag translations as outdated":"La bandera no traducidas como anticuado","Needs to be updated":"Necesita ser actualizado","Does not need to be updated":"No necesita ser actualizada","The selected text format will not allow it to display images. The text format will need to be changed for this image to display properly when saved.":"El formato del texto seleccionado no le permitir\u00e1 visualizar im\u00e1genes. El formato de texto tendr\u00e1 que ser cambiado para que esta imagen que se mostrar\u00e1 correctamente cuando salv\u00f3.","Set blocks as default":"Predeterminar bloques","Any content type":"Cualquier tipo de contenido","Any page":"una p\u00e1gina.","Any user role":"Cualquier rol de usuario","Taxonomy: %term":"Taxonom\u00eda: %term","Vocabulary: %vocab":"Vocabulario: %vocab","Any vocabulary or taxonomy":"Cualquier vocabulario o taxonom\u00eda","Select All":"Seleccionar Todo","Select None":"No seleccionar ninguno","IFrame URL is not from the same domain - autoresize not working.":"IFrame URL no es del mismo dominio - autoresize no funciona.","Content limited to @limit characters, remaining: \u003Cstrong\u003E@remaining\u003C\/strong\u003E":"Contenido limitada a  @limit characters, restante: \u003Cstrong\u003E@remaining\u003C\/strong\u003E","My Location":"Mi ubicaci\u00f3n","Geocoder failed due to: ":"Geocoder fall\u00f3 debido a: ","Geocode was not successful for the following reason: ":"Geocode no fue satisfactorio por la siguiente raz\u00f3n: ",", or use your browser geolocation system by clicking this link":", o use su sistema de geolocalizaci\u00f3n del navegador pulsando este enlace",", or use the IP-based location by clicking this link":", o use la localizaci\u00f3n basada en IP pulsando en este enlace","Geolocation service failed. We\u0027ve placed you in NewYork.":"El servicio de Geolocation fall\u00f3. Te hemos colocado en Nueva York.","Your browser doesn\u0027t support geolocation. We\u0027ve placed you in Siberia.":"Su navegador no soporta geolocalizaci\u00f3n. Le hemos situado en Siberia.","No ID":"No ID","No relationship":"Relaci\u00f3n","No classes":"No hay clases","No access key":"Clave de Acceso","Contacting @title...":"Contactando @title...","Show layout designer":"Mostrar maquetador de dise\u00f1o.","Hide layout designer":"Ocultar el maquetador de dise\u00f1o","Remove this pane?":"\u00bfEliminar este panel?"},"shs":{"\u003CAdd new item\u003E":"\u003C Agregar nuevo item \u003E"}} };;
/**
 * 
 * Documentation
 * https://github.com/mattkersley/Responsive-Menu
 *
 */
(function($){
	
	//plugin's default options
	var settings = {
		combine: true,					//combine multiple menus into a single select
		groupPageText: 'Main',			//optgroup's aren't selectable, make an option for it
		nested: true,					//create optgroups by default
		prependTo: 'body',				//insert at top of page by default
		switchWidth: 480,				//width at which to switch to select, and back again
		topOptionText: 'Select a page'	//default "unselected" state
	},
	
	//used to store original matched menus
	$menus,
	
	//used as a unique index for each menu if no ID exists
	menuCount = 0,
	
	//used to store unique list items for combining lists
	uniqueLinks = [];


	//go to page
	function goTo(url){
		document.location.href = url;
	}
	
	//does menu exist?
	function menuExists(){
		return ($('.mnav').length) ? true : false;
	}

	//validate selector's matched list(s)
	function isList($this){
		var pass = true;
		$this.each(function(){
			if(!$(this).is('ul') && !$(this).is('ol')){
				pass=false;
			}
		});
		return pass;
	}//isList()


	//function to decide if mobile or not
	function isMobile(){
		return ($(window).width() < settings.switchWidth);
	}
	
	
	//function to get text value of element, but not it's children
	function getText($item){
		return $.trim($item.clone().children('ul, ol').remove().end().text());
	}
	
	//function to check if URL is unique
	function isUrlUnique(url){
		return ($.inArray(url, uniqueLinks) === -1) ? true : false;
	}
	
	
	//function to do duplicate checking for combined list
	function checkForDuplicates($menu){
		
		$menu.find(' > li').each(function(){
		
			var $li = $(this),
				link = $li.find('a').attr('href'),
				parentLink = function(){
					if($li.parent().parent().is('li')){
						return $li.parent().parent().find('a').attr('href');
					} else {
						return null;
					}
				};
						
			//check nested <li>s before checking current one
			if($li.find(' ul, ol').length){
				checkForDuplicates($li.find('> ul, > ol'));
			}
		
			//remove empty UL's if any are left by LI removals
			if(!$li.find(' > ul li, > ol li').length){
				$li.find('ul, ol').remove();
			}
		
			//if parent <li> has a link, and it's not unique, append current <li> to the "unique parent" detected earlier
			if(!isUrlUnique(parentLink(), uniqueLinks) && isUrlUnique(link, uniqueLinks)){
				$li.appendTo(
					$menu.closest('ul#mmnav').find('li:has(a[href='+parentLink()+']):first ul')
				);
			}
			
			//otherwise, check if the current <li> is unique, if it is, add it to the unique list
			else if(isUrlUnique(link)){
				uniqueLinks.push(link);
			}
			
			//if it isn't, remove it. Simples.
			else{
				$li.remove();
			}
		
		});
	}
	
	
	//function to combine lists into one
	function combineLists(){
		
		//create a new list
		var $menu = $('<ul id="mmnav" />');
		
		//loop through each menu and extract the list's child items
		//then append them to the new list
		$menus.each(function(){
			$(this).children().clone().appendTo($menu);
		});
		
		//de-duplicate any repeated items
		checkForDuplicates($menu);
				
		//return new combined list
		return $menu;
		
	}//combineLists()
	
	
	
	//function to create options in the select menu
	function createOption($item, $container, text){
		
		//if no text param is passed, use list item's text, otherwise use settings.groupPageText
		if(!text){
			$('<option value="'+$item.find('a:first').attr('href')+'">'+$.trim(getText($item))+'</option>').appendTo($container);
		} else {
			$('<option value="'+$item.find('a:first').attr('href')+'">'+text+'</option>').appendTo($container);
		}
	
	}//createOption()
	
	
	
	//function to create option groups
	function createOptionGroup($group, $container){
		
		//create <optgroup> for sub-nav items
		var $optgroup = $('<optgroup label="'+$.trim(getText($group))+'" />');
		
		//append top option to it (current list item's text)
		createOption($group,$optgroup, settings.groupPageText);
	
		//loop through each sub-nav list
		$group.children('ul, ol').each(function(){
		
			//loop through each list item and create an <option> for it
			$(this).children('li').each(function(){
				createOption($(this), $optgroup);
			});
		});
		
		//append to select element
		$optgroup.appendTo($container);
		
	}//createOptionGroup()

	
	
	//function to create <select> menu
	function createSelect($menu){
	
		//create <select> to insert into the page
		var $select = $('<select id="mm'+menuCount+'" class="mnav" />');
		menuCount++;
		
		//create default option if the text is set (set to null for no option)
		if(settings.topOptionText){
			createOption($('<li>'+settings.topOptionText+'</li>'), $select);
		}
		
		//loop through first list items
		$menu.children('li').each(function(){
		
			var $li = $(this);

			//if nested select is wanted, and has sub-nav, add optgroup element with child options
			if($li.children('ul, ol').length && settings.nested){
				createOptionGroup($li, $select);
			}
			
			//otherwise it's a single level select menu, so build option
			else {
				createOption($li, $select);			
			}
						
		});
		
		//add change event and prepend menu to set element
		$select
			.change(function(){goTo($(this).val());})
			.prependTo(settings.prependTo);
	
	}//createSelect()

	
	//function to run plugin functionality
	function runPlugin(){
	
		//menu doesn't exist
		if(isMobile() && !menuExists()){
			
			//if user wants to combine menus, create a single <select>
			if(settings.combine){
				var $menu = combineLists();
				createSelect($menu);
			}
			
			//otherwise, create a select for each matched list
			else{
				$menus.each(function(){
					createSelect($(this));
				});
			}
		}
		
		//menu exists, and browser is mobile width
		if(isMobile() && menuExists()){
			$('.mnav').show();
			$menus.hide();
		}
			
		//otherwise, hide the mobile menu
		if(!isMobile() && menuExists()){
			$('.mnav').hide();
			$menus.show();
		}
		
	}//runPlugin()

	
	
	//plugin definition
	$.fn.mobileMenu = function(options){

		//override the default settings if user provides some
		if(options){$.extend(settings, options);}
		
		//check if user has run the plugin against list element(s)
		if(isList($(this))){
			$menus = $(this);
			runPlugin();
			$(window).resize(function(){runPlugin();});
		} else {
			alert('mobileMenu only works with <ul>/<ol>');
		}
				
	};//mobileMenu()
	
})(jQuery);;
