/*
 * jQuery Bootstrap Pagination v1.4.1
 * https://github.com/esimakin/twbs-pagination
 *
 * Copyright 2014-2016, Eugene Simakin <john-24@list.ru>
 * Released under Apache-2.0 license
 * http://apache.org/licenses/LICENSE-2.0.html
 */
!function(a,b,c,d){"use strict";var e=a.fn.twbsPagination,f=function(b,c){if(this.$element=a(b),this.options=a.extend({},a.fn.twbsPagination.defaults,c),this.options.startPage<1||this.options.startPage>this.options.totalPages)throw new Error("Start page option is incorrect");if(this.options.totalPages=parseInt(this.options.totalPages),isNaN(this.options.totalPages))throw new Error("Total pages option is not correct!");if(this.options.visiblePages=parseInt(this.options.visiblePages),isNaN(this.options.visiblePages))throw new Error("Visible pages option is not correct!");if(this.options.onPageClick instanceof Function&&this.$element.first().on("page",this.options.onPageClick),this.options.hideOnlyOnePage&&1==this.options.totalPages)return this.$element.trigger("page",1),this;this.options.totalPages<this.options.visiblePages&&(this.options.visiblePages=this.options.totalPages),this.options.href&&(this.options.startPage=this.getPageFromQueryString(),this.options.startPage||(this.options.startPage=1));var d="function"==typeof this.$element.prop?this.$element.prop("tagName"):this.$element.attr("tagName");return"UL"===d?this.$listContainer=this.$element:this.$listContainer=a("<ul></ul>"),this.$listContainer.addClass(this.options.paginationClass),"UL"!==d&&this.$element.append(this.$listContainer),this.options.initiateStartPageClick?this.show(this.options.startPage):(this.currentPage=this.options.startPage,this.render(this.getPages(this.options.startPage)),this.setupEvents()),this};f.prototype={constructor:f,destroy:function(){return this.$element.empty(),this.$element.removeData("twbs-pagination"),this.$element.off("page"),this},show:function(a){if(a<1||a>this.options.totalPages)throw new Error("Page is incorrect.");return this.currentPage=a,this.render(this.getPages(a)),this.setupEvents(),this.$element.trigger("page",a),this},enable:function(){this.show(this.currentPage)},disable:function(){var b=this;this.$listContainer.off("click").on("click","li",function(a){a.preventDefault()}),this.$listContainer.children().each(function(){var c=a(this);c.hasClass(b.options.activeClass)||a(this).addClass(b.options.disabledClass)})},buildListItems:function(a){var b=[];if(this.options.first&&b.push(this.buildItem("first",1)),this.options.prev){var c=a.currentPage>1?a.currentPage-1:this.options.loop?this.options.totalPages:1;b.push(this.buildItem("prev",c))}for(var d=0;d<a.numeric.length;d++)b.push(this.buildItem("page",a.numeric[d]));if(this.options.next){var e=a.currentPage<this.options.totalPages?a.currentPage+1:this.options.loop?1:this.options.totalPages;b.push(this.buildItem("next",e))}return this.options.last&&b.push(this.buildItem("last",this.options.totalPages)),b},buildItem:function(b,c){var d=a("<li></li>"),e=a("<a></a>"),f=this.options[b]?this.makeText(this.options[b],c):c;return d.addClass(this.options[b+"Class"]),d.data("page",c),d.data("page-type",b),d.append(e.attr("href",this.makeHref(c)).addClass(this.options.anchorClass).html(f)),d},getPages:function(a){var b=[],c=Math.floor(this.options.visiblePages/2),d=a-c+1-this.options.visiblePages%2,e=a+c;d<=0&&(d=1,e=this.options.visiblePages),e>this.options.totalPages&&(d=this.options.totalPages-this.options.visiblePages+1,e=this.options.totalPages);for(var f=d;f<=e;)b.push(f),f++;return{currentPage:a,numeric:b}},render:function(b){var c=this;this.$listContainer.children().remove();var d=this.buildListItems(b);a.each(d,function(a,b){c.$listContainer.append(b)}),this.$listContainer.children().each(function(){var d=a(this),e=d.data("page-type");switch(e){case"page":d.data("page")===b.currentPage&&d.addClass(c.options.activeClass);break;case"first":d.toggleClass(c.options.disabledClass,1===b.currentPage);break;case"last":d.toggleClass(c.options.disabledClass,b.currentPage===c.options.totalPages);break;case"prev":d.toggleClass(c.options.disabledClass,!c.options.loop&&1===b.currentPage);break;case"next":d.toggleClass(c.options.disabledClass,!c.options.loop&&b.currentPage===c.options.totalPages)}})},setupEvents:function(){var b=this;this.$listContainer.off("click").on("click","li",function(c){var d=a(this);return!d.hasClass(b.options.disabledClass)&&!d.hasClass(b.options.activeClass)&&(!b.options.href&&c.preventDefault(),void b.show(parseInt(d.data("page"))))})},makeHref:function(a){return this.options.href?this.generateQueryString(a):"#"},makeText:function(a,b){return a.replace(this.options.pageVariable,b).replace(this.options.totalPagesVariable,this.options.totalPages)},getPageFromQueryString:function(a){var b=this.getSearchString(a),c=new RegExp(this.options.pageVariable+"(=([^&#]*)|&|#|$)"),d=c.exec(b);return d&&d[2]?(d=decodeURIComponent(d[2]),d=parseInt(d),isNaN(d)?null:d):null},generateQueryString:function(a,b){var c=this.getSearchString(b),d=new RegExp(this.options.pageVariable+"=*[^&#]*");return c?"?"+c.replace(d,this.options.pageVariable+"="+a):""},getSearchString:function(a){var c=a||b.location.search;return""===c?null:(0===c.indexOf("?")&&(c=c.substr(1)),c)},getCurrentPage:function(){return this.currentPage}},a.fn.twbsPagination=function(b){var c,e=Array.prototype.slice.call(arguments,1),g=a(this),h=g.data("twbs-pagination"),i="object"==typeof b?b:{};return h||g.data("twbs-pagination",h=new f(this,i)),"string"==typeof b&&(c=h[b].apply(h,e)),c===d?g:c},a.fn.twbsPagination.defaults={totalPages:1,startPage:1,visiblePages:5,initiateStartPageClick:!0,hideOnlyOnePage:!1,href:!1,pageVariable:"{{page}}",totalPagesVariable:"{{total_pages}}",page:null,first:"First",prev:"Previous",next:"Next",last:"Last",loop:!1,onPageClick:null,paginationClass:"",nextClass:"page-item next",prevClass:"page-item prev",lastClass:"page-item last",firstClass:"page-item first",pageClass:"page-item",activeClass:"active",disabledClass:"disabled",anchorClass:"page-link"},a.fn.twbsPagination.Constructor=f,a.fn.twbsPagination.noConflict=function(){return a.fn.twbsPagination=e,this},a.fn.twbsPagination.version="1.4.1"}(window.jQuery,window,document);
var discourse = discourse || {};
discourse.pagination = discourse.pagination || {};


function discoursePrintPagination(curPage, customTotalPages){
	$('#pagination-discourse').twbsPagination({
	        totalPages: customTotalPages,
	        visiblePages: 4,
	        paginationClass : 'mj-paginator',
			pageClass : 'mj-paginator__item',
			nextClass : 'mj-paginator__item mj-paginator__item--next',
			prevClass : 'mj-paginator__item mj-paginator__item--prev',
			anchorClass : 'mj-paginator__txt',
			prev : ' ',
			next : ' ',
			first : '',
			last : '',
	    	startPage : curPage,
	    	hideOnlyOnePage : true,
	    	initiateStartPageClick : false,
	        onPageClick: function (event, page) {
	    		var searchURL = discourse.searchUrl;
	    		var params = [{
	    			'name' : 'curPage',
	    			'value' : page
	    		}];
	    		
	    		var url = addParameters(searchURL, params, false);
	    		$.ajax({
	    			url : url,
	    			type : 'GET',
	    			cache : false
	    		}).done(function(data, textStatus, jsqXHR) {
	    			$("#resultsDiv").html(data);
	    		});
		    		if(customTotalPages >= 2 ){
			    		if ($("#vertical-tabs").length > 0){				
							$('body,html').stop(true, true).animate({scrollTop: $('#vertical-tabs').offset().top - 
								parseInt($("#banner").height())-parseInt($(".mj-nav").height())}, 300);
						} else {
							$('body,html').stop(true, true).animate({scrollTop: $('#banner').offset().top}, 300);
						}
		    		}
	
	        }
	    });
	 }


function addParameters(url, params, withoutParams) {
	var newUrl = url;
	$.each(params, function(index, param) {
		if (withoutParams && index == 0) {
			newUrl += '?';
		} else {
			newUrl += '&';
		}
		newUrl += discourse.namespace + param.name + "=" + param.value;
	});
	return newUrl;
}


/*
 * jQuery Bootstrap Pagination v1.4.1
 * https://github.com/esimakin/twbs-pagination
 *
 * Copyright 2014-2016, Eugene Simakin <john-24@list.ru>
 * Released under Apache-2.0 license
 * http://apache.org/licenses/LICENSE-2.0.html
 */
!function(a,b,c,d){"use strict";var e=a.fn.twbsPagination,f=function(b,c){if(this.$element=a(b),this.options=a.extend({},a.fn.twbsPagination.defaults,c),this.options.startPage<1||this.options.startPage>this.options.totalPages)throw new Error("Start page option is incorrect");if(this.options.totalPages=parseInt(this.options.totalPages),isNaN(this.options.totalPages))throw new Error("Total pages option is not correct!");if(this.options.visiblePages=parseInt(this.options.visiblePages),isNaN(this.options.visiblePages))throw new Error("Visible pages option is not correct!");if(this.options.onPageClick instanceof Function&&this.$element.first().on("page",this.options.onPageClick),this.options.hideOnlyOnePage&&1==this.options.totalPages)return this.$element.trigger("page",1),this;this.options.totalPages<this.options.visiblePages&&(this.options.visiblePages=this.options.totalPages),this.options.href&&(this.options.startPage=this.getPageFromQueryString(),this.options.startPage||(this.options.startPage=1));var d="function"==typeof this.$element.prop?this.$element.prop("tagName"):this.$element.attr("tagName");return"UL"===d?this.$listContainer=this.$element:this.$listContainer=a("<ul></ul>"),this.$listContainer.addClass(this.options.paginationClass),"UL"!==d&&this.$element.append(this.$listContainer),this.options.initiateStartPageClick?this.show(this.options.startPage):(this.currentPage=this.options.startPage,this.render(this.getPages(this.options.startPage)),this.setupEvents()),this};f.prototype={constructor:f,destroy:function(){return this.$element.empty(),this.$element.removeData("twbs-pagination"),this.$element.off("page"),this},show:function(a){if(a<1||a>this.options.totalPages)throw new Error("Page is incorrect.");return this.currentPage=a,this.render(this.getPages(a)),this.setupEvents(),this.$element.trigger("page",a),this},enable:function(){this.show(this.currentPage)},disable:function(){var b=this;this.$listContainer.off("click").on("click","li",function(a){a.preventDefault()}),this.$listContainer.children().each(function(){var c=a(this);c.hasClass(b.options.activeClass)||a(this).addClass(b.options.disabledClass)})},buildListItems:function(a){var b=[];if(this.options.first&&b.push(this.buildItem("first",1)),this.options.prev){var c=a.currentPage>1?a.currentPage-1:this.options.loop?this.options.totalPages:1;b.push(this.buildItem("prev",c))}for(var d=0;d<a.numeric.length;d++)b.push(this.buildItem("page",a.numeric[d]));if(this.options.next){var e=a.currentPage<this.options.totalPages?a.currentPage+1:this.options.loop?1:this.options.totalPages;b.push(this.buildItem("next",e))}return this.options.last&&b.push(this.buildItem("last",this.options.totalPages)),b},buildItem:function(b,c){var d=a("<li></li>"),e=a("<a></a>"),f=this.options[b]?this.makeText(this.options[b],c):c;return d.addClass(this.options[b+"Class"]),d.data("page",c),d.data("page-type",b),d.append(e.attr("href",this.makeHref(c)).addClass(this.options.anchorClass).html(f)),d},getPages:function(a){var b=[],c=Math.floor(this.options.visiblePages/2),d=a-c+1-this.options.visiblePages%2,e=a+c;d<=0&&(d=1,e=this.options.visiblePages),e>this.options.totalPages&&(d=this.options.totalPages-this.options.visiblePages+1,e=this.options.totalPages);for(var f=d;f<=e;)b.push(f),f++;return{currentPage:a,numeric:b}},render:function(b){var c=this;this.$listContainer.children().remove();var d=this.buildListItems(b);a.each(d,function(a,b){c.$listContainer.append(b)}),this.$listContainer.children().each(function(){var d=a(this),e=d.data("page-type");switch(e){case"page":d.data("page")===b.currentPage&&d.addClass(c.options.activeClass);break;case"first":d.toggleClass(c.options.disabledClass,1===b.currentPage);break;case"last":d.toggleClass(c.options.disabledClass,b.currentPage===c.options.totalPages);break;case"prev":d.toggleClass(c.options.disabledClass,!c.options.loop&&1===b.currentPage);break;case"next":d.toggleClass(c.options.disabledClass,!c.options.loop&&b.currentPage===c.options.totalPages)}})},setupEvents:function(){var b=this;this.$listContainer.off("click").on("click","li",function(c){var d=a(this);return!d.hasClass(b.options.disabledClass)&&!d.hasClass(b.options.activeClass)&&(!b.options.href&&c.preventDefault(),void b.show(parseInt(d.data("page"))))})},makeHref:function(a){return this.options.href?this.generateQueryString(a):"#"},makeText:function(a,b){return a.replace(this.options.pageVariable,b).replace(this.options.totalPagesVariable,this.options.totalPages)},getPageFromQueryString:function(a){var b=this.getSearchString(a),c=new RegExp(this.options.pageVariable+"(=([^&#]*)|&|#|$)"),d=c.exec(b);return d&&d[2]?(d=decodeURIComponent(d[2]),d=parseInt(d),isNaN(d)?null:d):null},generateQueryString:function(a,b){var c=this.getSearchString(b),d=new RegExp(this.options.pageVariable+"=*[^&#]*");return c?"?"+c.replace(d,this.options.pageVariable+"="+a):""},getSearchString:function(a){var c=a||b.location.search;return""===c?null:(0===c.indexOf("?")&&(c=c.substr(1)),c)},getCurrentPage:function(){return this.currentPage}},a.fn.twbsPagination=function(b){var c,e=Array.prototype.slice.call(arguments,1),g=a(this),h=g.data("twbs-pagination"),i="object"==typeof b?b:{};return h||g.data("twbs-pagination",h=new f(this,i)),"string"==typeof b&&(c=h[b].apply(h,e)),c===d?g:c},a.fn.twbsPagination.defaults={totalPages:1,startPage:1,visiblePages:5,initiateStartPageClick:!0,hideOnlyOnePage:!1,href:!1,pageVariable:"{{page}}",totalPagesVariable:"{{total_pages}}",page:null,first:"First",prev:"Previous",next:"Next",last:"Last",loop:!1,onPageClick:null,paginationClass:"",nextClass:"page-item next",prevClass:"page-item prev",lastClass:"page-item last",firstClass:"page-item first",pageClass:"page-item",activeClass:"active",disabledClass:"disabled",anchorClass:"page-link"},a.fn.twbsPagination.Constructor=f,a.fn.twbsPagination.noConflict=function(){return a.fn.twbsPagination=e,this},a.fn.twbsPagination.version="1.4.1"}(window.jQuery,window,document);
/**
 * Version 1.0
 */
var filters = filters || {};
filters.id = filters.id || {};
filters.pagination = filters.pagination || {};
filters.url = filters.url || {};
filters.message = filters.message || {};

filters.init = function() {

	// Metodo que comprueba si esta en modo movil, responsive, que cambie el formulario de fecha al formato correcto
	filters.modifiedTypeFormDate();
	
	// Event handler
	filters.event_handler();

	// filters.initModal();
	var firstDocumentSearch = '';
	if ($(".filter-category")[0] != undefined) {
		// firstDocumentSearch =
		// $(".filter-category").getAttribute("id").substring($(".filter-category")[0].getAttribute("id").lastIndexOf("_")
		// + 1 ,$(".filter-category")[0].getAttribute("id").length);
		firstDocumentSearch = $(".filter-category")[0].getAttribute("data-id");
	}

	var categoryGeneral = filters.categorySearch;
	var categoryRedirect = filters.getUrlParameter("catRed");
	
	if (categoryGeneral == null) {
		categoryGeneral = "";
	}
	
    if (categoryRedirect == null) {
        categoryRedirect = "";
    }
    
	filters.getElement(filters.id.searchButton).trigger('click', {
		resetCur : false,
		firstDocumentSearchParam : firstDocumentSearch,
		categoryGeneralFilter : categoryGeneral,
		categoryRedirect : categoryRedirect
	});
	
	// View state
}

// Event handler
filters.event_handler = function() {
	filters.getElement(filters.id.searchButton).click({
		resetCur : true,
		categoryGeneralFilter : filters.categorySearch
	}, filters.search);

	filters.getElement(filters.id.searchTextInput).keypress(function(event) {
		var key = event.which;
		if (key == 13) { /* the tener key code */
			filters.search(null, {
				resetCur : true,
				categoryGeneralFilter : filters.categorySearch
			});
			return false;
		}
	});

	// filters.getElement(filters.id.searchDateInput).keypress(function(event) {
	// var key = event.which;
	// if(key == 13) { /* the tener key code */
	// filters.search(null, { resetCur : true});
	// return false;
	// }
	// });

	$.each(filters.categories, function(index, element) {
		var category = filters.getElement(filters.id.category + index);
		category.change(function(event) {
			if (filters.categoriesHierarchyEnabled) {
				filters.reloadCategory(index, element);
			}
			filters.search(null, {
				resetCur : true
			});
		});
	});

	filters.getElement(filters.id.resetDateFilter).click(function() {
		filters.getElement(filters.id.searchDateFromInput).val('');
		filters.getElement(filters.id.searchDateToInput).val('');
		filters.getElement(filters.id.searchTextInput).val('');
	});

	// filters.getElement(filters.id.resetTextFilter).click(function(){
	// filters.getElement(filters.id.searchTextInput).val('');
	// filters.search(null, { resetCur : true, textSearchedEvent: ''});
	// });

}



/******************************************************************
 ************ modify date form responsive **************
 ******************************************************************/
//Este metodo cambia el atributo type del formulario para la fecha de busqueda de valor type="date" en type="text"
filters.modifiedTypeFormDate = function (){
	var typeFormInputDate = filters.getElement(filters.id.searchDateFromInput).attr("type");
	
	if(typeFormInputDate == "date"){
		filters.getElement(filters.id.searchDateFromInput).attr("type", "text"); 
		filters.getElement(filters.id.searchDateToInput).attr("type", "text"); 
		//Value de liferay en modo responsive: 11/30/0002, se cambia por vacio
		filters.getElement(filters.id.searchDateFromInput).attr("value", "");
		filters.getElement(filters.id.searchDateToInput).attr("value", "");
		}
	
	filters.getElement(filters.id.searchDateFromInput).attr("placeholder", filters.message.placeHolderDateFrom); 
	filters.getElement(filters.id.searchDateToInput).attr("placeholder", filters.message.placeHolderDateTo); 

	//Este metodo cambia añade el atributo aria-atomic=true por accesibilidad
	filters.getElement(filters.id.searchDateFromInput).attr("aria-atomic", true); 
	filters.getElement(filters.id.searchDateToInput).attr("aria-atomic", true);  
}

/*******************************************************************************
 * *********** SEARCH *********************************************
 ******************************************************************************/

filters.search = function(event, data) {
	
	var dataFunc = "";
	
	if (event!=null){
		dataFunc = data || event.data;
		event.preventDefault();
	} else {
		dataFunc = data;
	}
		
	//var categoriesVal = filters.categoriesValues;
	//var dataFunc = data || event.data;

	var resetCur = dataFunc.resetCur;
	var textSearchedEvent = dataFunc.textSearchedEvent;
	var firstDocumentSearchParam = dataFunc.firstDocumentSearchParam;
	var textSearchedOld = filters.getElement(filters.id.searchTextInput).val();
	var textSearched = encodeURIComponent(textSearchedOld);
	var categoriesSearched = filters.getCategoriesSelectedValues();
	var dates = filters.getDatesValues();
	var categoryDocument = dataFunc.categoryDocumentFilter;
	var categoryGeneral = dataFunc.categoryGeneralFilter;
	var categoryRedirect = dataFunc.categoryRedirect;
//	var anioDocument = $("#"+filters.namespace + "anioDocument").val();
	var isDocumentSearch = false;

	var isDocumentCheck = firstDocumentSearchParam != ''
			|| firstDocumentSearchParam != undefined ? true : false;

	if (isDocumentCheck) {
		isDocumentSearch = true;
		categoryDocument = (categoryDocument == undefined || categoryDocument == '') ? firstDocumentSearchParam
				: categoryDocument;
	} else {
		categoryDocument = categoryDocument == undefined ? ''
				: categoryDocument;
	}

	if (categoryGeneral == null) {
		categoryGeneral = "";
	}
	
	var filterActived = $(".filter-category.active").attr("data-id");
	if (filterActived != null && filterActived != undefined
			&& categoryDocument == undefined) {
		categoryDocument = filterActived;
	}
	
    if (categoryRedirect != '' && categoryRedirect != undefined) {
    	categoryDocument = "";
    }

   	if (dates[0] != "0" && dates[1] != "0") {
		
		filters.getElement(filters.id.resultsDiv)[0].style.minHeight = '600px';
		filters.showLoading();

		if (typeof textSearchedEvent != 'undefined') {
			textSearched = textSearchedEvent;
		}

		if (resetCur) {
			filters.pagination.curPage = 0;
		}

		var curPage = filters.pagination.curPage;

		var params = [ {
			'name' : 'textSearched',
			'value' : textSearched
		}, {
			'name' : 'curPage',
			'value' : curPage
		}, {
			'name' : 'categoriesSearched',
			'value' : categoriesSearched
		}, {
			'name' : 'startDate',
			'value' : dates[0]
		}, {
			'name' : 'endDate',
			'value' : dates[1]
		}, {
			'name' : 'categoryDocument',
			'value' : categoryDocument
		}, {
			'name' : 'categoryGeneral',
			'value' : categoryGeneral
		}, {
            'name' : 'categoryRedirect',
            'value' : categoryRedirect
        }
		];
		var url = filters.addParameters(filters.url.searchUrl, params);

		// LOADING SHOW

		$
				.ajax({
					url : url,
					type : 'GET',
					cache : false
				})
				.done(
						function(dataDone, textStatus, jsqXHR) {
							filters.getElement(filters.id.resultsDiv)[0].removeAttribute("style");
							filters.getElement(filters.id.resultsDiv).html(dataDone);
							filters.getElement(filters.id.formFilter).show();
							filters.getElement(filters.id.newsFilters).show();
							if (isDocumentSearch) {

								var allCategories = filters.getElementsByUniqueClass(filters.id.filtersCategories);
								allCategories.each(function() {
									$(this).parents(".mj-vertical-tabs__list").find(".active").removeClass("active");
									$(this).parent().removeClass("ui-tabs-active ui-state-active");
								});
                                 if (categoryRedirect != '' && categoryRedirect != undefined) {
                                    filters.getElement(categoryRedirect).addClass("active");
                                    $(".mj-vertical-tabs__link.active").parent().addClass("ui-tabs-active ui-state-active");
                                 } else {
								    filters.getElement(categoryDocument).addClass("active");
								    $(".mj-vertical-tabs__link.active").parent().addClass("ui-tabs-active ui-state-active");
								 }
								
//								$('body,html').stop(true, true).animate({scrollTop: $('#banner').offset().top}, 300);

							}

						});
	} else {

		setTimeout(function() {
			filters.hideErrorDate();
		}, 3000);

		var previousFromDate = filters.getElement(
				filters.id.previousSearchDateFromInput).val();
		var previousToDate = filters.getElement(
				filters.id.previousSearchDateToInput).val();

		filters.getElement(filters.id.searchDateFromInput)
				.val(previousFromDate)
		filters.getElement(filters.id.searchDateToInput).val(previousToDate)

	}
}

filters.addParameters = function(url, params, withoutParams) {
	var newUrl = url;
	$.each(params, function(index, param) {
		if (withoutParams && index == 0) {
			newUrl += '?';
		} else {
			newUrl += '&';
		}
		newUrl += filters.namespace + param.name + "=" + param.value;
	});
	return newUrl;
}

filters.showLoading = function() {
	
	filters.getElement(filters.id.resultsDiv).html('<div class="loader"><div class="loadingmask-message"><div class="loadingmask-message-content">'+ filters.message.loading + '</div></div></div>');
}

/*******************************************************************************
 * *********** UTILS **********************************************
 ******************************************************************************/

filters.getElement = function(str) {
	return $('#' + filters.namespace + str);
}

filters.getElementsByClass = function(idStr, classStr) {
	return $('#' + filters.namespace + idStr + " ." + classStr);
}
filters.getElementsByUniqueClass = function(classStr) {
	return $('.' + classStr);
}

filters.getElementByName = function(str) {
	return $('[name=' + filters.namespace + str + ']');
}

filters.getElementSelected = function(str) {
	return $('#' + filters.namespace + str + ' :selected');
}


		
		
/*******************************************************************************
 * *********** CATEGORIES *****************************************
 ******************************************************************************/

filters.getCategoriesSelectedValues = function() {
	var categories = filters.categories;
	var categoriesIdsValues = "";
	for (var index = 0; index < categories.length; index++) {
		var categorySelect = filters.getElement(filters.id.category + index);
		if (categorySelect.val() != "0") {
			categoriesIdsValues += categorySelect.val() + "_";
		}
	}
	if (categoriesIdsValues.length > 0) {
		categoriesIdsValues = categoriesIdsValues.substring(0, categoriesIdsValues.length - 1);
	}
	return categoriesIdsValues;
}

filters.reloadCategory = function(parentIndex, parentCategory) {
	var categories = filters.categories;
	var parentCategorySelected = filters.getElementSelected(filters.id.category
			+ parentIndex);

	/*
	 * for (var indexCategory = parentIndex + 1; indexCategory <
	 * categories.length; indexCategory++) {
	 */
	var indexCategory = parentIndex + 1;
	var category = categories[indexCategory];
	var categorySelect = filters
			.getElement(filters.id.category + indexCategory);
	filters.cleanCategory(indexCategory, category.name);

	var subcategories = category.subcategories;
	for (var indexSubcategory = 0; indexSubcategory < subcategories.length; indexSubcategory++) {
		var subcategory = subcategories[indexSubcategory];
		var propertyFound = false;
		if (parentCategorySelected.val() == 0) {
			propertyFound = true;
		} else {
			var properties = subcategory.properties;
			for (var indexProperty = 0; indexProperty < properties.length
					&& !propertyFound; indexProperty++) {
				var property = properties[indexProperty];
				if (property.name == parentCategory.name) {
					for (var indexValues = 0; indexValues < property.values.length
							&& !propertyFound; indexValues++) {
						var propertyValue = property.values[indexValues];
						if (propertyValue == parentCategorySelected.text()) {
							propertyFound = true;
						}
					}
				}
			}
		}
		if (propertyFound) {
			filters
					.addCategory(indexCategory, subcategory.name,
							subcategory.id);
		}
	}
	categorySelect.selectpicker('refresh');
	/* } */
}

filters.addCategory = function(parentIndex, categoryName, categoryValue) {
	var parentCategory = filters.getElement(filters.id.category + parentIndex);
	parentCategory.append($('<option>', {
		value : categoryValue,
		text : categoryName
	}));
}

filters.cleanCategory = function(parentIndex, parentName) {
	var parentCategory = filters.getElement(filters.id.category + parentIndex);
	parentCategory.html('<option value="0" selected="selected">' + parentName
			+ '</option>');
}

/*******************************************************************************
 * *********** DATES **********************************************
 ******************************************************************************/

// filters.hideResetButton = function(){
// filters.getElement(filters.id.searchDateInput).removeClass('sc-filter-open__date--no-bg');
// $('[data-function="fc-buttonResetCalendar"]').addClass('sc-search__reset--none');
// $('[data-function="fc-buttonResetCalendar"]').removeClass('sc-search__reset--close');
// }
//
// filters.showResetButton = function(){
// filters.getElement(filters.id.searchDateInput).addClass('sc-filter-open__date--no-bg');
// $('[data-function="fc-buttonResetCalendar"]').removeClass('sc-search__reset--none');
// $('[data-function="fc-buttonResetCalendar"]').addClass('sc-search__reset--close');
// }

filters.getDatesValues = function() {
	var dates = [ '', '' ];
	var dateFrom = filters.getElement(filters.id.searchDateFromInput).val();
	var dateTo = filters.getElement(filters.id.searchDateToInput).val();
    var phone = "";

    var today = new Date();
    var day = today.getDate();
   	if(day<10) {
      day = '0'+day;
    }
    var month = today.getMonth() +1;
    if(month<10) {
      month = '0'+month;
    }

    if (dateFrom != "" || dateTo != ""){
        if ((dateFrom.indexOf("/") >= 0 || dateTo.indexOf("/") >= 0) && (dateFrom != "" || dateTo != "")) {
            phone = false;
        } else {
            phone = true;
        }
    }else{
		phone = false;
	}
	if (dateFrom == "" && !phone) {
	    dateFrom = "01/01/1800";
	} else if (dateFrom == "" && phone) {
	    dateFrom = "1800-01-01";
	}
	 if (dateTo == "" && !phone){
	   dateTo = day + "/" + month + "/" + today.getFullYear();
	} else if (dateTo == "" && phone){
	   dateTo =  today.getFullYear() + "-" + month + "-" + day;
	}

	//if (dateFrom != '' && dateTo != '') {
		if (!filters.validateDates(dateFrom, dateTo, phone)) {
			dates[0] = "0";
			dates[1] = "0";
			filters.showErrorDate();
		} else {
			dates[0] = filters.formatDate(dateFrom);
			dates[1] = filters.formatDate(dateTo);
			
			filters.hideErrorDate();
		}
	//}
	return dates;
}

//Return Format String in format locale ES-es "dd/MM/yyyy"
filters.formatDate = function(dateCustom){
	//responsive: 2018-06-30(Format OK with Object Date) normal: 30/06/2018(Format "Invalid Date" with Object Date)
	var dateFormatShort = "";
	
	if (dateCustom.indexOf("/") >= 0){
		//Ventana Escritorio
		dateFormatShort = dateCustom;
	} else{
		//Ventana Responsive
		var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
		dateFormatShort = new Date(dateCustom).toLocaleDateString((themeDisplay.getLanguageId), options);
	}

	return dateFormatShort;
}


filters.validateDates = function(startDate, endDate, isPhone) {
	var startDateDate = "";
	var endDateDate = "";
	//responsive: 2018-06-30(Format OK with Object Date) normal: 30/06/2018(Format "Invalid Date" with Object Date
	if (startDate.indexOf("/") >= 0 && endDate.indexOf("/") >= 0){
		//Ventana Escritorio
		startDateDate = filters.parseDate(startDate);
		endDateDate = filters.parseDate(endDate);
	} else{
		//Ventana Responsive
		startDateDate = new Date(startDate); 
		endDateDate = new Date(endDate);
	}
	
	if (startDateDate && endDateDate && startDateDate <= endDateDate) {
		
		filters.hideErrorDate();
		return true;
	} else {
		filters.showErrorDate();
		return false;
	}
}


filters.parseDate = function(str) {
	var m = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
	return (m) ? new Date(m[3], m[2] - 1, m[1]) : null;
}

filters.showErrorDate = function() {
	filters.getElement(filters.id.errorDates).fadeIn();
}

filters.hideErrorDate = function() {
	filters.getElement(filters.id.errorDates).fadeOut();
}


/*******************************************************************************
 * *********** PAGINATION *****************************************
 ******************************************************************************/

filters.hidePagination = function() {
	filters.getElement(filters.id.pagination).twbsPagination('destroy');
}

filters.printPagination = function() {
	filters.getElement(filters.id.pagination).html('<ul class="mj-paginator" id="<portlet:namespace/>mj-paginator"></ul>');
	
	var currentPage = filters.pagination.curPage;
	var delta = filters.pagination.delta;
	var elementsSize = filters.pagination.size;
	var totalPage = Math.ceil(elementsSize / delta);
	var maxPageNumberShow = 4;
		
	filters.getElement(filters.id.pagination).twbsPagination('destroy');

	filters.getElement(filters.id.pagination).twbsPagination({
		totalPages : totalPage,
		visiblePages : maxPageNumberShow,
		startPage : currentPage + 1,
		hideOnlyOnePage : true,
		initiateStartPageClick : false,
		paginationClass : 'mj-paginator',
		pageClass : 'mj-paginator__item',
		nextClass : 'mj-paginator__item mj-paginator__item--next',
		prevClass : 'mj-paginator__item mj-paginator__item--prev',
		anchorClass : 'mj-paginator__txt',
		prev : ' ',
		next : ' ',
		first : 'Primera',
		last : 'Última',
		onPageClick : function(event, page) {
			filters.pagination.curPage = page - 1;					
			var data = {
				resetCur : false,
				isBase : false,
				categoryGeneralFilter : filters.categorySearch
			};
			
			filters.search(null, data);
			if ($("#vertical-tabs").length > 0){
				$('body,html').stop(true, true).animate({scrollTop: $('#vertical-tabs').offset().top -
						parseInt($("#banner").height())-parseInt($(".mj-nav").height())-50}, 300);
			} else {
				$('body,html').stop(true, true).animate({scrollTop: $('#banner').offset().top}, 300);
			}					
		}
	});

	/* Se añade un titulo al enlace para solucionar problemas de accesibilidad */
	var ariaLabelForPrev = document.querySelector('.mj-paginator__item.mj-paginator__item--prev a'); 
	var ariaLabelForNext = document.querySelector('.mj-paginator__item.mj-paginator__item--next a');
	if(ariaLabelForPrev != null && ariaLabelForNext != null ){
		ariaLabelForPrev.setAttribute("aria-label", "Anterior");
		ariaLabelForNext.setAttribute("aria-label", "Siguiente");
	}
	/* Se añade tabindex=-1 para evitar foco en pagina activa y botones deshabilitados para accesibilidad */
	$(".mj-paginator li.disabled a, .mj-paginator li.active a").attr('tabindex', '-1');
	
}

/*******************************************************************************
 * *********** DETAIL URL *****************************************
 ******************************************************************************/


filters.getUrlParameter = function (sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
    sURLVariables = sPageURL.split('&'),
    sParameterName,
    i;

	for (i = 0; i < sURLVariables.length; i++) {
	    sParameterName = sURLVariables[i].split('=');
	
	    if (sParameterName[0] === sParam) {
	        return sParameterName[1] === undefined ? true : sParameterName[1];
	    }
	}
}

/*******************************************************************************/
/************ ACCESIBILIDAD ****************************************************/

$(document).ready(function () {

	// Boton Buscar en filtro 
	$(".mj-search-adv--filter:not(.mj-search-adv__doc) button").keydown(function (e) {    
		if (e.which == 9) {   
			$('#filterButton').trigger('click');
			$("#vertical-tabs .mj-vertical-tabs__list li:first-child span").focus();
		  	e.preventDefault();
		}
	});

});



// filters.showDetail = function(articleId, groupId) {
//	
// var backUrl = filters.url.backUrl;
//	
// // GETTING ACTUAL SEARCH
// var searchTextVal = filters.getElement(filters.id.searchTextInput).val();
// var searchDateVal = filters.getElement(filters.id.searchDateInput).val();
// var currentPageVal = filters.pagination.curPage;
// var categoriesVal = [];
// filters.categories.forEach(function(element, index){
// var categoryVal = filters.getElement(filters.id.category + index).val();
// categoriesVal[index] = categoryVal;
// });
//	
// var backUrlParams = [{
// 'name' : 'searchTextVal',
// 'value' : searchTextVal
// },{
// 'name' : 'searchDateVal',
// 'value' : searchDateVal
// },{
// 'name' : 'currentPageVal',
// 'value' : currentPageVal
// }];
// categoriesVal.forEach(function(element, index) {
// backUrlParams.push({
// 'name' : 'categoryVal' + index,
// 'value' : element
// });
// })
//	
// backUrl = encodeURIComponent(filters.addParameters(backUrl, backUrlParams));
//	
//	
// var params = [ {
// 'name' : 'articleId',
// 'value' : articleId
// }, {
// 'name' : 'groupId',
// 'value' : groupId
// }, {
// 'name' : 'backUrl',
// 'value' : backUrl
// }];
// var url = filters.addParameters(filters.url.getDetailUrl, params);
//	
//	
// $.ajax({
// url : url,
// type : 'GET',
// cache : false
// }).success(function(data, textStatus, jsqXHR) {
// window.location=data;
// });
//
// }

