text:
var scroll_position = false;
var return_position = false;
var not_scroll = false;
$(document).ready(function(){
	// calculate contest start/expiring date
	manageContestTimedelta();

	// write bootstrap modal inside body tag
	bootstrapModalsObect.writeModalInsideBodyTag();

	// show fucking cookie bar (W EU)
	lawCookieCompliance.createDivOnLoad();

	// toggle navigation
	$(document).on("click",".navbar-toggle", function(){
		$(".toggle_navigation").toggle();
	});

	// modal in fase di apertura ma non ancora aperta
	$(document).on('show.bs.modal', ".modal", function () {
		if ($(".modal").css('position') === 'absolute' && !not_scroll) {
			/* We will need to return to where we were.*/
			// return_position = true;
			// saving position
			scroll_position = $(window).scrollTop(); // Where did we start in the window.
			not_scroll = true;
		}
	});

	// modal apertura completata
	$(document).on('shown.bs.modal', ".modal", function () {
		if ($(".modal").css('position') === 'absolute') {
			// scroll top page top
			$(window).scrollTop(0);
		}
	});

	// modal in fase di chiusura ma non ancora chiusa
	$(document).on('hide.bs.modal', ".modal", function (e) {
		if ($(".modal").css('position') === 'absolute') {
			/* Return to where we were.*/
			$(window).scrollTop(scroll_position);
			not_scroll = false;
		}
	});

	/* open modal to resend email confirmation */
	$(document).on("click",".openResendConfirmationModalClickAction", function(){
		bootstrapModalsObect.showSendValidationEmail();

		return false;
	});

	/* function to resend a confirmation email */
	$(document).on("click",".resendConfirmationEmailClickAction", function(){
		resendConfirmationEmail();

		return false;
	});

	/* Function to manage toggle block like FAQ questions */
	$(".toggle_block").on("click",".toggle_block_action", function(){
		$(this).siblings(".toggle_block_content").toggle();

		return false;
	});

	// hide law cookie bar on window scroll event
	// per ora lo commento
	/*$(document).on('scroll', window, function() {
		// lawCookieCompliance.removeMe();
	});*/
});

/**
 * 	Author: Entpy Software <developer at entpy dot com>
 * 	Version: 0.1.0
 * 	- wrapper for ajax call
 *  	- require jquery
 */
var loadDataWrapper = {

	__idPage : "",
	htmlLoaded : "",

	setIdPage : function(pageId){
		this.__idPage = pageId;
		return this.__idPage;
	},

	getIdPage : function(){
		return this.__idPage;
	},

	performAjaxCall : function(ajaxCallData){

		// setting ajax call data
		ajaxCallObj.setAjaxData(ajaxCallData);

		// performing ajax call
		ajaxCallObj.doAjaxCall();
	},
};

// wrapper to save page data
var saveDataWrapper = {

	__idPage: "",

	__setIdPage : function(pageId){
		this.__idPage = pageId;
		return this.__idPage;
	},

	getIdPage : function(){
		return this.__idPage;
	},

};

var ajaxCallObj = {

	__url : "",
	__type : "",
	__data : "",
	__cache : "",
	__success : "",
	__error : "",
	__async: "",
	__headers: "",

	// common wrappers params
	setAjaxDataEasy : function(){

		this.__type = "POST";
		this.__cache = false;
		this.__async = true;

		return true;
	},

	// setting ajax call params
	setAjaxData : function(dataToSet){

		// loading common wrappers params
		this.setAjaxDataEasy();

		if(dataToSet.url){
			this.__url = dataToSet.url;
		}

		if(dataToSet.type){
			this.__type = dataToSet.type;
		}

		if(dataToSet.data){
			this.__data = dataToSet.data;
		}

		if(dataToSet.cache){
			this.__cache = dataToSet.cache;
		}

		if(dataToSet.async === true || dataToSet.async === false){
			this.__async = dataToSet.async;
		}

		if(dataToSet.success){
			this.__success = dataToSet.success;
		}

		if(dataToSet.error){
			this.__error = dataToSet.error;
		}

		if(dataToSet.headers){
			this.__headers = dataToSet.headers;
		}

		return true;
	},

	// loading ajax call params
	getAjaxData : function(){

		return {
			"url" : this.__url,
			"type" : this.__type,
			"async" : this.__async,
			"data" : this.__data,
			"cache" : this.__cache,
			"success" : this.__success,
			"error" : this.__error,
			"headers" : this.__headers
		};
	},

	// performing ajax call with previously data
	doAjaxCall : function(){

		$.ajax({
			url: this.getAjaxData().url,
			type: this.getAjaxData().type,
			data: this.getAjaxData().data,
			async: this.getAjaxData().async,
			cache: this.getAjaxData().cache,
			success: this.getAjaxData().success,
			error: this.getAjaxData().error,
			headers: this.getAjaxData().headers
		});
	}
};

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

/* Function to read csrftoken from cookie */
function readCsrftokenFromCookie() {
	return $.cookie('csrftoken');
}

/* Function to generate a random number */
function randomInt(min, max) {
	return Math.floor(Math.random() * max + min);
}

function getImageTemplateHtml(imageUrl) {
	var imageTemplate = false;
	if (imageUrl) {
		imageTemplate = '';
	}

	return imageTemplate
}

/* Function to retrieve current timestamp in seconds */
function getCurrentTimestamp() {
	var dateObj = new Date();
	// retrieve timestam in microseconds
	var current_timestamp = dateObj.getTime();

	// return timestam in seconds
	return Math.floor(current_timestamp / 1000);
}

/* Function to manage contest timedelta (run this function every second)*/
function manageContestTimedelta() {
	if ($(".contest_info_block").length) {
		// buld and write timedelta string inside container
		buildAndWriteContestTimedeltaString();
	}
}

/* Function to build contest expiring/start date string */
function buildAndWriteContestTimedeltaString() {
	var contestStatus = $(".contest_info_block").data("contestStatus");
	var timedelta = $(".contest_info_block").data("contestTimeDelta");

	countdown.setLabels(
		' millisecondo| secondo| minuto| ora| giorno| settimana| mese| anno| decennio| secolo| millennio',
		' millisecondi| secondi| minuti| ore| giorni| settimane| mesi| anni| decenni| secoli| millenni',
		' e ',
		'  '
	);

	// countdown launch
	runCountdown(timedelta, contestStatus)

	// print contest status string
	writeCountdownContestStatusString(contestStatus);
}

/* Function to launch a countdown */
function runCountdown(timedelta, contestStatus) {
	if (timedelta && contestStatus) {
		var timerId = countdown(timedelta * 1, function(ts) {
			if (!ts.days && !ts.hours && !ts.minutes && !ts.seconds) {
				// countdown finish
				window.clearInterval(timerId);
				setTimeout(function() { writeCountdownEndString(contestStatus); }, 1100);
			}
			$('.contest_timedelta_string_container').html(ts.toHTML());
		}, countdown.DAYS|countdown.HOURS|countdown.MINUTES|countdown.SECONDS).toString();
	}
}

/* Function to write contest status string */
function writeCountdownContestStatusString(contestStatus) {
	if (contestStatus == "active") {
		$('.contest_status_container').html("alla chiusura del concorso");
	} else if (contestStatus == "opening") {
		$('.contest_status_container').html("all'apertura del concorso");
	}
}

/* Function to retrieve info about user (name, points, ranking) */
function retrieveUserInfo(userId) {
	if (userId) {
		// save image id
		var retrieveUserInfoAjaxAction = customAjaxAction;
		// serialize form
		retrieveUserInfoAjaxAction.setAjaxCallParams("user_id=" + userId + "&");
		// setting action name
		retrieveUserInfoAjaxAction.setActionName("get_user_info");
		// success callback function
		var successCallback = function(jsonResponse) {
			// open bootstrap modal
			user_data = jsonResponse.user_info
			bootstrapModalsObect.showFavoriteUserModal(user_data.user_id, user_data.user_first_name, user_data.user_last_name, user_data.user_ranking, user_data.user_points, user_data.user_profile_image_url);
		};
		retrieveUserInfoAjaxAction.setAjaxSuccessCallbackFunction(successCallback);
		// perform ajax call to save a new profile image
		retrieveUserInfoAjaxAction.performAjaxAction();
	}
}

/* Function to write string at the countdown finish */
function writeCountdownEndString(contestStatus) {
	if (contestStatus == "active") {
		$('.contest_timedelta_string_container').html("Il contest è stato appena chiuso!");
		$('.contest_status_container').html("");
	} else if (contestStatus == "opening") {
		$('.contest_timedelta_string_container').html("Il contest è stato appena aperto!");
		$('.contest_status_container').html("");
	}
}

/* Function to resend a confirmation email */
function resendConfirmationEmail() {
	var resendConfirmationEmailAjaxAction = customAjaxAction;
	// set async to false
	resendConfirmationEmailAjaxAction.setAsyncFlag(false);
	// setting action name
	resendConfirmationEmailAjaxAction.setActionName("resend_confirmation_email");
	// success callback function
	var successCallback = function(jsonResponse) {
	    // hide resend button and show alert
	    var htmlSuccessBlock = '
';
	    htmlSuccessBlock += '
Una nuova email di verifica ti è stata appena inviata, clicca il link al suo interno per confermare il tuo account.
';
	    htmlSuccessBlock += '
';
	    $(".resendEmailConfirmationContainerAction").html(htmlSuccessBlock);
	};
	resendConfirmationEmailAjaxAction.setAjaxSuccessCallbackFunction(successCallback);
	// perform ajax call to add favorite
	resendConfirmationEmailAjaxAction.performAjaxAction();

	return true;
}

/* Object to manage bootstrap modals */
var bootstrapModalsObect = {

	// popup message tags
	simple_message_tags : "popup_simple_message",
	success_message_tags : "popup_success",
	alert_message_tags : "popup_alert",
	error_message_tags : "popup_error",

	/* Function to write bootstrap modal inside body tag, only if not already exists */
	writeModalInsideBodyTag: function() {
		if (!$(".bootstrap_modal").length) {
			var bootstrapModal = '';
			bootstrapModal += '
';
			bootstrapModal += this.getBootstrapModalHtmlTemplate();
			bootstrapModal += '
';
			$("body").prepend(bootstrapModal);
		}

		return true;
	},

	/* Function to retrieve bootstrap modal html template */
	getBootstrapModalHtmlTemplate: function() {
		var bootstrapModal = '';
		bootstrapModal += '
';
		bootstrapModal += '
';
		bootstrapModal += '
';
		bootstrapModal += '<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>';
		bootstrapModal += '

';
		bootstrapModal += '
';
		bootstrapModal += '
';
		bootstrapModal += '
';
		bootstrapModal += '

';
		bootstrapModal += '
';
		bootstrapModal += '
';

		return bootstrapModal;
	},

	/* Function to reset bootstrap modal */
	resetBootstrapModal: function() {
		// questo è un layer che non scompare se vengono aperte
		// modal in modo consecutivo, quindi lo nascondo io forzatamente
		$('.modal-backdrop').remove();
		$('body').attr("style", "padding-right: 0px;");
		$(".bootstrap_modal").removeData();
		$(".bootstrap_modal").remove();
		this.writeModalInsideBodyTag();

		return true;
	},

	/* Function to show bootstrap modal */
	showBootstrapModal: function() {
		$(".bootstrap_modal").modal('show');

		return true;
	},

	/* Function to hide bootstrap modal */
	/*hideBootstrapModal: function() {
		// close previously opened bootstrap modal
		$('.bootstrap_modal').modal('hide');
		// fix per aprire modal in modo consecutivo
		$('.modal-backdrop').hide();

		return true;
	},*/

	/* Function to show popup message with bootstrap modal */
	showPopupMessage : function(message, message_tags){
		if (message_tags == this.success_message_tags) {
			// show a success modal popup
			this.showSuccessModal(message);
		} else if (message_tags == this.alert_message_tags) {
			// show an alert modal popup
			this.showAlertModal(message);
		} else if (message_tags == this.error_message_tags) {
			// show an error modal popup
			this.showErrorModal(message);
		} else if (message_tags == this.simple_message_tags) {
			// show a simple message popup without style
			this.showMessageModal(message);
		}
	},

	/* custom bootstrap modal functions {{{ */
	/* Function to build and show image zoom bootstrap modal */
	showZoomImageModal: function(imageUrl) {
		if (imageUrl) {
			this.resetBootstrapModal();
			$(".bootstrap_modal").find('.modal-header').remove();
			$(".bootstrap_modal").find('.modal-body').html(this.getImageHtmlBlock(imageUrl));
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>');
			this.showBootstrapModal();
		}

		return false;
	},

	/* Function to build and show delete image bootstrap modal */
	showDeleteImageModal: function(imageUrl, imageId) {
		if (imageUrl && imageId) {
			this.resetBootstrapModal();
			$(".bootstrap_modal").find('.modal-header').remove();
			$(".bootstrap_modal").find('.modal-body').html(this.getImageHtmlBlock(imageUrl));
			$(".bootstrap_modal").find('.modal-footer').html(this.deleteImageButtonHtmlBlock(imageId));
			this.showBootstrapModal();
		}

		return false;
	},

	/* Function to build and show perform login bootstrap modal */
	showPerformLoginModal: function() {
		this.resetBootstrapModal();
		performLoginTemplate = "";
		performLoginTemplate += '
';
		performLoginTemplate += '
';
		performLoginTemplate += '
';
		performLoginTemplate += '
Per poter continuare è necessario accedere.
';
		performLoginTemplate += '
';
		performLoginTemplate += '
';
		performLoginTemplate += 'Accedi';
		performLoginTemplate += '
';
		performLoginTemplate += '
';
		performLoginTemplate += '
';
		performLoginTemplate += '
';
		performLoginTemplate += 'Non sei ancora registrato? Registrati e partecipa al concorso, la prossima star di Beauty & Pics potresti essere tu!
';
		performLoginTemplate += '
';
		performLoginTemplate += '
';
		performLoginTemplate += '
';
		$(".bootstrap_modal").find('.modal-title').html("Aggiungi preferito");
		$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>');
		$(".bootstrap_modal").find('.modal-body').html(performLoginTemplate);
		this.showBootstrapModal();

		return false;
	},

	/* Function to build and show a success bootstrap modal */
	showSuccessModal: function(message, popup_title) {
		if (message) {
			this.resetBootstrapModal();
			var messageBlockTemplate = '';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += message;
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			$(".bootstrap_modal").find('.modal-title').html("Ottimo");
			if (popup_title) {
				$(".bootstrap_modal").find('.modal-title').html(popup_title);
			}
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>');
			$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
			this.showBootstrapModal();
		}

		return false;
	},

	/* Function to build and show a message bootstrap modal */
	showMessageModal: function(message, popup_title) {
		if (message) {
			this.resetBootstrapModal();
			var messageBlockTemplate = '';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += message;
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			$(".bootstrap_modal").find('.modal-title').html("Ottimo");
			if (popup_title) {
				$(".bootstrap_modal").find('.modal-title').html(popup_title);
			}
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>');
			$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
			this.showBootstrapModal();
		}

		return false;
	},

	/* Function to build and show an alert bootstrap modal */
	showAlertModal: function(message) {
		if (message) {
			this.resetBootstrapModal();
			var messageBlockTemplate = '';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += message;
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			$(".bootstrap_modal").find('.modal-title').html("Gulp!");
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>');
			$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
			this.showBootstrapModal();
		}

		return false;
	},

	/* Function to build and show an error bootstrap modal */
	showErrorModal: function(message) {
		if (message) {
			this.resetBootstrapModal();
			var messageBlockTemplate = '';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += message;
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			$(".bootstrap_modal").find('.modal-title').html("Ops...");
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>');
			$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
			this.showBootstrapModal();
		}

		return false;
	},

	/* Function to build and show favorite user bootstrap modal */
	showFavoriteUserModal: function(userId, userFirstName, userLastName, userRanking, userPoints, userProfileImageUrl) {
		this.resetBootstrapModal();
		var messageBlockTemplate = '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		if (userRanking) {
		    messageBlockTemplate += '
' + userRanking + 'a posizione
';
		}
		messageBlockTemplate += '
' + userPoints + ' punti
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '<img class="favorite_profile_image" alt="Immagine profilo" src="' + userProfileImageUrl + '"';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		$(".bootstrap_modal").find('.modal-title').html(userFirstName + ' ' + userLastName);
		$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>Vai al profilo');
		$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
		this.showBootstrapModal();

		return false;
	},

	/* Function to build and show welcome bootstrap modal */
	showWelcomeModal: function(userFirstName) {
		this.resetBootstrapModal();
		var messageBlockTemplate = '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
Ciao ' + userFirstName + ',
';
		messageBlockTemplate += 'questo è Beauty and Pics, il concorso più fico dell\'universo!
'
		messageBlockTemplate += 'Ecco qualche dritta per iniziare:

Carica un\'immagine profilo.

Carica almeno 5/6 immagini del book.

Chiedi ai tuoi amici e parenti di votarti.

';
		messageBlockTemplate += 'Quindi aspetta i primi voti e tieni d\'occhio la classifica...pronta/o per diventare una star del web?';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		$(".bootstrap_modal").find('.modal-title').html("Benvenuta/o al concorso!");
		$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-success" data-dismiss="modal">Si, iniziamo!</button>');
		$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
		this.showBootstrapModal();

		return false;
	},

	/* Function to build and show system notify modal */
	showSystemNotifyModal: function(userFirstName, notifyToRead) {
		this.resetBootstrapModal();
		var messageBlockTemplate = '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
' + userFirstName + ',
';
		if (notifyToRead == 1) {
			messageBlockTemplate += 'hai ' + notifyToRead + ' nuova notifica ';
		} else {
			messageBlockTemplate += 'hai ' + notifyToRead + ' nuove notifiche ';
		}
		messageBlockTemplate += 'di Beauty and Pics da leggere.
'
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		$(".bootstrap_modal").find('.modal-title').html("Sistema di notifiche");
		$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Ricorda in seguito</button>Leggi ora');
		$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
		this.showBootstrapModal();

		return false;
	},

	/* Function to build and show send validation email bootstrap modal */
	showSendValidationEmail: function() {
		this.resetBootstrapModal();
		var messageBlockTemplate = '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += 'Una email di verifica ti è stata inviata in fase di registrazione, tuttavia puoi riceverne un\'altra premendo il pulsante "Inviami email di verifica".
Infine, per confermare il tuo account, clicca sul link ricevuto via email.';
		messageBlockTemplate += '
';
		messageBlockTemplate += '

<button type="button" class="btn btn-success resendConfirmationEmailClickAction">Inviami email di verifica</button>

';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		$(".bootstrap_modal").find('.modal-title').html("Conferma il tuo account");
		$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>');
		$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
		this.showBootstrapModal();

		return false;
	},

	/* Function to build and show vote user bootstrap modal */
	showVoteUserModal: function(userId, userFirstName, howItWorksImageUrl, selectionImageUrl, contestOpen, userRegistered, emailVerified) {
		this.resetBootstrapModal();
		var descriptionMessageBlock = "";
		var enableVoteButton = false;
		// debug var {{{
		/*contestOpen = true;
		userRegistered = true;
		emailVerified = true;*/
		// debug var }}}
		if (contestOpen && emailVerified && userRegistered) {
			descriptionMessageBlock = '

Seleziona quale voto vuoi assegnare all\'utente. In base al voto scelto i punti verranno ripartiti su ogni metrica di valutazione.

';
			enableVoteButton = true;
		} else if (!contestOpen) {
			msg_text = 'Fino all\'apertura del concorso non sarà possibile votare';
			descriptionMessageBlock = '

Ci spiace, fino all\'apertura del concorso non sarà possibile votare.

';
		} else if (!userRegistered) {
			msg_text = 'Per votare devi prima registrarti';
			descriptionMessageBlock = '

Per votare devi prima registrarti, fallo ora per dare il tuo primo voto. Registrazione rapida

';
		} else if (!emailVerified) {
			msg_text = 'Verifica il tuo indirizzo email per votare';
			descriptionMessageBlock = '

Attenzione per votare devi prima verificare il tuo indirizzo email.
Clicca qui per verificarlo ora.

';
		}

		var messageBlockTemplate = '';
		messageBlockTemplate += '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += descriptionMessageBlock;
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '';
		messageBlockTemplate += '
';
		messageBlockTemplate += 'Sguardo ammaliante';
		messageBlockTemplate += 'Persona solare';
		messageBlockTemplate += 'Troppo stile';
		messageBlockTemplate += 'Che classe';
		messageBlockTemplate += 'Impeccabile';
		messageBlockTemplate += 'Notevole';
		messageBlockTemplate += '
';
		messageBlockTemplate += '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '';
		messageBlockTemplate += 'Seleziona voto ';
		messageBlockTemplate += '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
Sguardo ammaliante';
		messageBlockTemplate += '
Persona solare';
		messageBlockTemplate += '
Troppo stile';
		messageBlockTemplate += '
Che classe';
		messageBlockTemplate += '
Impeccabile';
		messageBlockTemplate += '
Notevole';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '

Ripartizione punti

';
		messageBlockTemplate += '
Come funziona?
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
Sorriso +0
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '

';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
Sguardo +0
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '

';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
Globale +0
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '

';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
Stile +0
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '

';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		messageBlockTemplate += '
';
		// modal title
		$(".bootstrap_modal").find('.modal-title').html("Dai il tuo voto a " + userFirstName + "");
		// modal footer
		if (enableVoteButton) {
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button><button type="button" class="btn btn-success confirmVoteButtonAction">Conferma il voto</button>');
		} else {
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button><button type="button" class="btn btn-default disabled-only-graphics alertVoteButtonAction" data-alert-text="' + msg_text + '">Conferma il voto</button>');
		}
		// modal content
		$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
		this.showBootstrapModal();

		return false;
	},

	/* Function to build and show a generic text modal with close button */
	showGenericTextModal: function(title, content) {
		if (title && content) {
			this.resetBootstrapModal();
			var messageBlockTemplate = '';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
' + content + '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			$(".bootstrap_modal").find('.modal-title').html(title);
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>');
			$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
			this.showBootstrapModal();
		}

		return false;
	},

	/* Function to build and show a publish survey modal */
	showPublishSurveyModal: function(content) {
		if (content) {
			this.resetBootstrapModal();
			var messageBlockTemplate = '';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
' + content + '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '

<button type="button" class="btn btn-success publishSurveyClickAction">Pubblica adesso</button>

';
			$(".bootstrap_modal").find('.modal-title').html("Pubblica la tua intervista");
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>');
			$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
			this.showBootstrapModal();
		}

		return false;
	},

	/* Function to build and show photocontest info modal bootstrap modal */
	showPhotocontestInfoModal: function(photocontestCode, photocontestName, photocontestDescription, photocontestLikeLimit, photocontestImageUrl, questionPointImageUrl) {
		if (photocontestCode && photocontestName && photocontestDescription && photocontestLikeLimit) {
			this.resetBootstrapModal();
			var messageBlockTemplate = '';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '';
			messageBlockTemplate += '
';
			messageBlockTemplate += '

' + photocontestDescription + '

"Mi piace" richiesti: ' + photocontestLikeLimit + '

';
			messageBlockTemplate += '
';
			$(".bootstrap_modal").find('.modal-title').html(photocontestName);
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Annulla</button><button type="button" class="btn btn-success photocontestEnterClickAction" data-photocontest-code="' + photocontestCode + '" data-dismiss="modal">Partecipa</button>');
			$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
			this.showBootstrapModal();
			// mostro la tooltip nella modal
			$('[data-toggle="tooltip"]').tooltip();
		}

		return false;
	},

	/* Function to build and show add image to photocontest bootstrap modal */
	showAddImageToPhotocontest: function(imageUrl, imageId, photocontestName) {
		if (imageUrl && imageId) {
			this.resetBootstrapModal();
			var messageBlockTemplate = '';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += 'Stai per inserire la seguente immagine nel concorso a tema ' + photocontestName + '.
(Potrai comunque rimuoverla e caricarne un\'altra successivamente).
Confermi l\'immagine?'
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '
';
			messageBlockTemplate += '

' + this.getImageHtmlBlock(imageUrl) + '

';
			$(".bootstrap_modal").find('.modal-title').html("Conferma");
			$(".bootstrap_modal").find('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">Annulla</button><button type="button" class="btn btn-success addImageToPhotocontestClickAction" data-image-id="' + imageId + '" data-dismiss="modal">Conferma</button>');
			$(".bootstrap_modal").find('.modal-body').html(messageBlockTemplate);
			this.showBootstrapModal();
		}

		return false;
	},

	/* custom bootstrap modal functions }}} */

	/* modal image block, with must be a size: eg. '100%' or '129px' or '12em' ecc... */
	getImageHtmlBlock: function(imageUrl, width) {
		var templateBlock = false;
		var imageWidth = "100%";
		if (width) {
			imageWidth = width;
		}
		if (imageUrl) {
			templateBlock = '';
		}

		return templateBlock;
	},

	deleteImageButtonHtmlBlock: function(imageId) {
		var templateBlock = false;
		if (imageId) {
			templateBlock = '<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button><button type="button" data-image-id="' + imageId + '" class="btn btn-success deleteProfileImageClickAction">Cancella immagine</button>';
		}

		return templateBlock;
	}
};

/* Object to perform custom ajax action */
var customAjaxAction = {
	__ajaxCallParams : false,
	__ajaxCallActionName : false,
	__ajaxCallAsync : true,
	__ajaxSuccessCallbackFunction : function() { },
	__ajaxErrorCallbackFunction : function() { },
	ajaxCallUrl : "/ajax/", // the ajax call url

	/* Function to set action name */
	setActionName : function(actionName) {
		if (actionName) {
			this.__ajaxCallActionName = actionName;
		}
	},

	/* Function to retrieve action name */
	getActionName : function() {
		return this.__ajaxCallActionName;
	},

	/* Function to set async flag */
	setAsyncFlag : function(asyncFlag) {
		this.__ajaxCallAsync = asyncFlag;
	},

	/* Function to retrieve async flag */
	getAsyncFlag : function() {
		return this.__ajaxCallAsync;
	},

	/* Function to set a success callback function */
	setAjaxSuccessCallbackFunction : function(callbackFunction) {
		if (callbackFunction) {
			this.__ajaxSuccessCallbackFunction = callbackFunction;
		}
	},

	/* Function to retrieve a success callback function */
	getAjaxSuccessCallbackFunction : function(jsonResponse) {
		return this.__ajaxSuccessCallbackFunction(jsonResponse);
	},

	/* Function to set an error callback function */
	setAjaxErrorCallbackFunction : function(callbackFunction) {
		if (callbackFunction) {
			this.__ajaxErrorCallbackFunction = callbackFunction;
		}
	},

	/* Function to retrieve an error callback function */
	getAjaxErrorCallbackFunction : function(jsonResponse) {
		return this.__ajaxErrorCallbackFunction(jsonResponse);
	},

	/* Function to set ajax call params */
	setAjaxCallParams : function(paramsList) {
		if (paramsList) {
			this.__ajaxCallParams = paramsList;
		}
	},

	/* Function to retrieve ajax call params */
	getAjaxCallParams : function() {
		return this.__ajaxCallParams;
	},

	/* Function to perform an action */
	performAjaxAction : function() {
		// reading csrfmiddlewaretoken from cookie
		var csrftoken = readCsrftokenFromCookie();
		var ajaxCallData = {
			url : this.ajaxCallUrl,
			data : this.getAjaxCallParams() + "&ajax_action=" + this.getActionName(),
			async : this.getAsyncFlag(),
			headers: { "X-CSRFToken": csrftoken },
			success : function(jsonResponse) {
				// functions to manage JSON response
				console.log("==========risultato chiamata==========");
				console.log(jsonResponse);
				if (jsonResponse.success) {
					customAjaxAction.getAjaxSuccessCallbackFunction(jsonResponse);
				} else if (jsonResponse.error) {
					customAjaxAction.getAjaxErrorCallbackFunction(jsonResponse);
				}
			},
			error : function(jsonResponse) {
				// ...fuck
				// console.log(jsonResponse);
			}
		}
		// performing ajax call
		loadDataWrapper.performAjaxCall(ajaxCallData);

		return true;
	},
};

/* Object to perform votes */
var voteUserObject = {
	__maxPoints : 8,
	__metrics_list : {
		'smile_metric' : 'smile_metric',
		'look_metric' : 'look_metric',
		'global_metric' : 'global_metric',
		'style_metric' : 'style_metric'
	},
	selectedVoteCode : false,
	votationIsValid : false,
	selectedVoteCodeClass : "selected_vote",
	voteUserId : false,
	ajaxCallUrl : "/ajax/",

	/* Function to calculate points percentage */
	getPointPercentage : function(points) {
		return pointPercentage = parseInt((points / this.__maxPoints) * 100);
	},

	/* Function called on vote_code selection */
	manageVoteCodeSelected : function(voteCode, userId) {
		if (voteCode && userId) {
			// setting points bar
			var singleVoteCodeData = this.getSingleVoteCodeData(voteCode);
			// show metric info on html
			this.showMetricInfo(this.__metrics_list["smile_metric"], singleVoteCodeData[this.__metrics_list["smile_metric"]])
			this.showMetricInfo(this.__metrics_list["look_metric"], singleVoteCodeData[this.__metrics_list["look_metric"]])
			this.showMetricInfo(this.__metrics_list["global_metric"], singleVoteCodeData[this.__metrics_list["global_metric"]])
			this.showMetricInfo(this.__metrics_list["style_metric"], singleVoteCodeData[this.__metrics_list["style_metric"]])

			// setto la classe selected_vote al vote_code cliccato
			this.setActiveVoteCodeSelected(voteCode);

			// setto la label corretta alla dropdown di bootstrap
			this.setDropdownText();

			// setto il vote code e abilito la votazione
			this.enableVotation(voteCode, userId);
		}

		return false;
	},

	/* setto la classe selected_vote al vote_code cliccato*/
	setActiveVoteCodeSelected : function(voteCode) {
		$(".voteItemAction").removeClass(this.selectedVoteCodeClass);
		$(".voteItem_" + voteCode).addClass(this.selectedVoteCodeClass);

		return true;
	},

	/* Function to enable votation */
	enableVotation : function(voteCode, userId) {
		this.selectedVoteCode = voteCode;
		this.voteUserId = userId;
		this.votationIsValid = true;

		return true;
	},

	/* Function to reset votation data */
	resetVotation : function() {
		this.selectedVoteCode = false;
		this.voteUserId = false;
		this.votationIsValid = false;

		return true;
	},

	/* Function to check if votation is enabled */
	getVotationIsEnabled : function() {
		var returnVar = false;
		if (this.selectedVoteCode && this.votationIsValid && this.voteUserId) {
			returnVar = true;
		}

		return returnVar;
	},

	/* Function to set dropdown text */
	setDropdownText : function() {
		// retrieve active element text
		var selectedText = $(".vote_type_dropdown").find("." + this.selectedVoteCodeClass).html();
		$(".vote_type_dropdown").find('.dropdown-toggle').html(selectedText+' ');

		return true;
	},

	/* Function to show metric info about a vote_code on html */
	showMetricInfo : function(metricCode, metricPoints) {
		// setting point into label
		$("." + metricCode + " .metric_points").html(metricPoints);
		// setting bar width
		$("." + metricCode + " .progress-bar").css("width", this.getPointPercentage(metricPoints) + "%");

		return true;
	},

	/* Function to retrieve info about all vote_codes */
	getAllVoteCodesData : function() {
		return {
			'sguardo_ammaliante' : {
				'smile_metric' : '2',
				'look_metric' : '8',
				'global_metric' : '3',
				'style_metric' : '2'
			},
			'persona_solare' : {
				'smile_metric' : '8',
				'look_metric' : '2',
				'global_metric' : '2',
				'style_metric' : '3'
			},
			'troppo_stile' : {
				'smile_metric' : '3',
				'look_metric' : '2',
				'global_metric' : '3',
				'style_metric' : '7'
			},
			'che_classe' : {
				'smile_metric' : '2',
				'look_metric' : '2',
				'global_metric' : '8',
				'style_metric' : '3'
			},
			'impeccabile' : {
				'smile_metric' : '4',
				'look_metric' : '4',
				'global_metric' : '3',
				'style_metric' : '4'
			},
			'notevole' : {
				'smile_metric' : '4',
				'look_metric' : '4',
				'global_metric' : '4',
				'style_metric' : '3'
			}
		}
	},

	/* Function to retrieve info about a single vote_code */
	getSingleVoteCodeData : function(voteCode) {
		var return_var = false;
		if (voteCode) {
			var allVoteCodesData = this.getAllVoteCodesData();
			/*console.log("all vote_codes");
			console.log(allVoteCodesData[voteCode]);*/
			return_var = allVoteCodesData[voteCode];
		}

		return return_var;
	},

	/* Function to perform an action after confirm vote button click */
	confirmVoteButtonClickAction : function() {
		if (!this.getVotationIsEnabled()) {
			alert("Devi prima selezionare un voto.");
		} else {
			if (confirm("Confermi il voto? Potrai votare nuovamente questo partecipante tra 7 giorni.")) {
				this.performVoteAction();
			}
		}

		return false;
	},

	/* Function to perform a vote action */
	performVoteAction : function() {
		if (this.getVotationIsEnabled()) {
			// reading csrfmiddlewaretoken from cookie
			var csrftoken = readCsrftokenFromCookie();
			var ajaxCallData = {
				url : this.ajaxCallUrl,
				data : "user_id=" + this.voteUserId + "&vote_code=" + this.selectedVoteCode + "&ajax_action=perform_voting",
				async : false,
				headers: { "X-CSRFToken": csrftoken },
				success : function(jsonResponse) {
					// functions to manage JSON response
					console.log("==========risultato chiamata==========");
					console.log(jsonResponse);
					if (jsonResponse.success) {
						voteUserObject.performVoteSuccessCallback(jsonResponse.message)
					} else if (jsonResponse.error) {
						voteUserObject.performVoteErrorCallback(jsonResponse.message)
					}
				},
				error : function(jsonResponse) {
					// ...fuck
					// console.log(jsonResponse);
				}
			}
			// performing ajax call
			loadDataWrapper.performAjaxCall(ajaxCallData);
		}

		return true;
	},

	/* Function to close bootstrap vote modal */
	closeVoteBootstrapModal : function() {
		$('.bootstrap_modal').modal('hide');
	},

	/* Success callback function  */
	performVoteSuccessCallback : function(message) {
		// show success message
                alert(message);
                $(".successVoteMessageAction").removeClass("hide");
		// hide default info text
                $(".voteInfoMessageAction").addClass("hide");
                // hide vote form
                $(".voteFormContainerAction").addClass("hide");
		// closing bootstrap modal
		this.closeVoteBootstrapModal();

		return true;
	},

	/* Error callback function  */
	performVoteErrorCallback : function(message) {
		// show error message
                alert(message);

		return true;
	}
};

/* Object to retrieve a filtered list of elements (user, photo book, favorites, notify, photocontest) */
var elementsListObject = {
	__elementsListFilters : {
		"user_id" : null, // required in "favorites" and "book" elementsListType
		"elements_list_type" : null, // catwalker, favorite, photobook, notify, photocontest
		"start_limit" : 0, // element retrieving start limit
		"show_limit" : 1, // element retrieving stop limit
		"elements_per_call" : 1, // number of element retrieved per call
		"filter_name" : null, // main filter (Es. latest_registered, classification, ecc...)
	}, // list of AND filters */
	ajaxCallUrl : "/ajax/", // the ajax call url
	bootstrapBlockSize : null, // the bootstrap block size for display
	blocksContainerClassName : ".image_grid_container", // the block container class inside html page
	tableBlocksContainerClassName : ".table_body_block_container", // the block container class inside html page
	actionButtonClassName : ".loadMoreElementsAction", // load more button class name

	/* Function to reset all filters */
	__resetFilters : function() {
		this.__elementsListFilters["user_id"] = null;
		this.__elementsListFilters["elements_list_type"] = null;
		this.__elementsListFilters["start_limit"] = 0;
		this.__elementsListFilters["show_limit"] = 1;
		this.__elementsListFilters["elements_per_call"] = 1;
		this.__elementsListFilters["filter_name"] = null;
	},

	/* Function to clear current loaded elements inside html */
	__clearHtml : function() {
		$(this.blocksContainerClassName).html("");
	},

	/* Function to clear current element list */
	newElementList : function() {
		this.__resetFilters();
		this.__clearHtml();
		this.showActionButton();
	},

	/* Function to add a new AND filter */
	addFilter : function(filterName, filterValue) {
		if (filterName) {
			if (!filterValue) filterValue = null
			// retrieve previously added filters
			var existing_filters = this.getElementsListFilters();
			// override or add new filter
			existing_filters[filterName] = filterValue;
			// setting new filters object
			this.setElementsListFilters(existing_filters);
		}

		return true;
	},

	/* Function to set list of AND filters */
	setElementsListFilters : function(elementsListFilters) {
		if (elementsListFilters) {
			this.__elementsListFilters = elementsListFilters
		}

		return true;
	},

	/* Function to retrieve list of AND filters */
	getElementsListFilters : function() { return this.__elementsListFilters; },

	/* Function to set element show limit */
	setElementsPerCall : function(elementsPerCall) {
		if (elementsPerCall) {
			// retrieve previously added filters
			var existing_filters = this.getElementsListFilters();
			existing_filters["elements_per_call"] = elementsPerCall;
			existing_filters["show_limit"] = elementsPerCall;
			// setting new filters object
			this.setElementsListFilters(existing_filters);
		}

		return true;
	},

	/* Function to set element start limit */
	/*setStartLimit : function(startLimit) {
		if (startLimit) {
			// retrieve previously added filters
			var existing_filters = this.getElementsListFilters();
			existing_filters["start_limit"] = showLimit;
			// setting new filters object
			this.setElementsListFilters(existing_filters);
		}

		return true;
	},

	/* Function to set element show limit */
	/*setShowLimit : function(showLimit) {
		if (showLimit) {
			// retrieve previously added filters
			var existing_filters = this.getElementsListFilters();
			existing_filters["show_limit"] = showLimit;
			// setting new filters object
			this.setElementsListFilters(existing_filters);
		}

		return true;
	},*/

	/* Function to set user id */
	setUserId : function(userId) {
		if (userId) {
			// retrieve previously added filters
			var existing_filters = this.getElementsListFilters();
			existing_filters["user_id"] = userId;
			// setting new filters object
			this.setElementsListFilters(existing_filters);
		}

		return true;
	},

	/* Function to set elements list type */
	setElementsListType : function(elementsListType) {
		if (elementsListType) {
			// retrieve previously added filters
			var existing_filters = this.getElementsListFilters();
			existing_filters["elements_list_type"] = elementsListType;
			// setting new filters object
			this.setElementsListFilters(existing_filters);
		}

		return true;
	},

	getElementsList : function() {
		// hide "load more" button
		elementsListObject.hideActionButton();
		// reading csrfmiddlewaretoken from cookie
		var csrftoken = readCsrftokenFromCookie();
		var ajaxCallData = {
			url : this.ajaxCallUrl,
			data : $.param(this.getElementsListFilters()) + "&ajax_action=elements_list",
			async : true,
			headers: { "X-CSRFToken": csrftoken },
			success : function(jsonResponse) {
				// functions to manage JSON response
				console.log("==========risultato chiamata==========");
				console.log(jsonResponse);

				// show or hide "load more" button
				if (jsonResponse.show_load_button) {
				    elementsListObject.showActionButton();
				} else {
				    elementsListObject.hideActionButton();
				}

				if (jsonResponse.elements_list_type == "catwalker") {
					// build and write block into html
					elementsListObject.writeHtmlBlock(elementsListObject.manageCatwalkerList(jsonResponse.elements_list));
				} else if (jsonResponse.elements_list_type == "favorite") {
					// build and write block into html
					elementsListObject.writeHtmlBlock(elementsListObject.manageFavoriteList(jsonResponse.elements_list));
				} else if (jsonResponse.elements_list_type == "photobook") {
					// build and write block into html
					elementsListObject.writeHtmlBlock(elementsListObject.managePhotobookList(jsonResponse.elements_list));
				} else if (jsonResponse.elements_list_type == "last_upload") {
					// build and write block into html
					elementsListObject.writeHtmlBlock(elementsListObject.manageFavoriteList(jsonResponse.elements_list));
				} else if (jsonResponse.elements_list_type == "notify") {
					// build and write table blocks into html
					elementsListObject.writeTableHtmlBlock(elementsListObject.manageTableElementsList(jsonResponse.elements_list));
				} else if (jsonResponse.elements_list_type == "photocontest") {
					// build and write block into html
					elementsListObject.writeHtmlBlock(elementsListObject.managePhotocontestList(jsonResponse.elements_list));
				}

				// set blocks number limit
				elementsListObject.setBlocksNumberLimit();
			},
			error : function(jsonResponse) {
				// ...fuck
				// console.log(jsonResponse);
			}
		}

		// performing ajax call
		loadDataWrapper.performAjaxCall(ajaxCallData);

		return true;
	},

	hideActionButton : function() {
	/* Function to hide action button */
		$(this.actionButtonClassName).addClass("display_none");
	},

	showActionButton : function() {
	/* Function to show action button */
		$(this.actionButtonClassName).removeClass("display_none");
	},

	setBlocksNumberLimit : function() {
	/* Function to set block number limit */
	/*
	3....8
	9....14
	15....20
	*/

		// retrieve previously added filters
		var existing_filters = this.getElementsListFilters();
		var limit_metric = existing_filters["show_limit"] - existing_filters["start_limit"]
		existing_filters["start_limit"] = existing_filters["show_limit"];
		existing_filters["show_limit"] = existing_filters["start_limit"] + limit_metric;
		// setting new filters object
		this.setElementsListFilters(existing_filters);
	},

	manageCatwalkerList : function(elementsList) {
	/* Function to retrieve an html blocks list, this must be appended to html page */
		var items = "";
		$.each(elementsList, function(index, singleElement) {
			blockUrl = "/passerella/dettaglio-utente/" + singleElement.user_id;
			blockThumbnailImageUrl = singleElement.thumbnail_image_url;
			items += elementsListObject.getSingleHtmlBlock(blockUrl, blockThumbnailImageUrl, false, "hvr-grow-rotate", false);
		});
		// return jQuery object
		return $(items);
	},

	manageFavoriteList : function(elementsList) {
	/* Function to retrieve an html blocks list, this must be appended to html page */
		var items = "";
		$.each(elementsList, function(index, singleElement) {
			blockUrl = "#";
			blockThumbnailImageUrl = singleElement.thumbnail_image_url;
			items += elementsListObject.getSingleHtmlBlock(blockUrl, blockThumbnailImageUrl, false, "hvr-grow-rotate zoom-image", singleElement.user_id);
		});

		// return jQuery object
		return $(items);
	},

	manageTableElementsList : function(elementsList) {
	/* Function to retrieve an html blocks list, this must be appended to html page */
		var items = "";
		$.each(elementsList, function(index, singleElement) {
			items += elementsListObject.getSingleHtmlNotifyTableBlock(singleElement.notify_id, singleElement.title, singleElement.creation_date, singleElement.already_read);
		});

		// return jQuery object
		return $(items);
	},

	managePhotobookList : function(elementsList) {
	/* Function to retrieve an html blocks list, this must be appended to html page */
		var items = "";
		$.each(elementsList, function(index, singleElement) {
			blockUrl = "#";
			// alert(singleElement.image_url);
			blockThumbnailImageUrl = singleElement.thumbnail_image_url;
			blockImageUrl = singleElement.image_url;
			blockImageId = singleElement.image_id;
			items += elementsListObject.getSingleHtmlBlock(blockUrl, blockThumbnailImageUrl, blockImageUrl, "hvr-grow-rotate zoom-image", blockImageId);
		});

		// return jQuery object
		return $(items);
	},

	managePhotocontestList : function(elementsList) {
	/* Function to retrieve an html blocks list, this must be appended to html page */
		var items = "";
		$.each(elementsList, function(index, singleElement) {
			photocontestCode = singleElement.photo_contest_code
			blockUrl = "/concorsi-a-tema/" + photocontestCode + "/" + singleElement.user_id;
			blockThumbnailImageUrl = singleElement.thumbnail_image_url;
			items += elementsListObject.getSingleHtmlBlock(blockUrl, blockThumbnailImageUrl, false, "hvr-grow-rotate");
		});

		// return jQuery object
		return $(items);
	},

	getSingleHtmlBlock : function(blockUrl, blockThumbnailImageUrl, blockImageUrl, imgTagClass, imgId, imgAlt) {

		returnVar = "";
		if (!imgTagClass) {
			imgTagClass = "";
		}

		if (!imgId) {
			imgId = "";
		}

		if (!imgAlt) {
			imgAlt = "Immagine del book";
		}

		if (blockUrl && blockThumbnailImageUrl) {
			// setting bootstrap block size
			if (!this.bootstrapBlockSize) {
				this.bootstrapBlockSize = true;
			}

			// retrieve bootstrap block size
			var blockSize = this.getBlockSize();
			// build html block with link and image
			var returnVar = '

'
		}

		return returnVar;
	},

	getSingleHtmlNotifyTableBlock : function(notifyId, notifyTitle, notifyCreationDate, notifyAlreadyRead) {
	/* Function to build notify table html blocks */

		returnVar = "";

		if (notifyTitle && notifyId) {
			// action to read notify
			var actionLink = '/profilo/notifiche/' + notifyId;
			if (notifyAlreadyRead) {
				returnVar = '
' + notifyTitle + '	' + notifyCreationDate + '	letta
';
			} else {
				returnVar = '
' + notifyTitle + '	' + notifyCreationDate + '	da leggere
';
			}
		}

		return returnVar;
	},

	getBlockSize : function() {
	/* Function to retrieve bootstrap block size */
		// setting bootstrap block size
		if (!this.bootstrapBlockSize) {
			this.bootstrapBlockSize = true;
		}
		var blockSize = Array();
		blockSize["lg_size"] = (this.bootstrapBlockSize["lg_size"] ? this.bootstrapBlockSize["lg_size"] : "15");
		blockSize["md_size"] = (this.bootstrapBlockSize["md_size"] ? this.bootstrapBlockSize["md_size"] : "3");
		blockSize["sm_size"] = (this.bootstrapBlockSize["sm_size"] ? this.bootstrapBlockSize["sm_size"] : "3");
		blockSize["xs_size"] = (this.bootstrapBlockSize["xs_size"] ? this.bootstrapBlockSize["xs_size"] : "6");

		return blockSize;
	},

	writeHtmlBlock : function(htmlBlocksList) {
	/* function to append blocks into html container */
		// console.log(htmlBlocksList);
		// alert("blocchi 'scritti' con successo" + this.blocksContainerClassName);
		$(this.blocksContainerClassName).append(htmlBlocksList);
	},

	writeTableHtmlBlock : function(htmlBlocksList) {
	/* function to append blocks into html container */
		// console.log(htmlBlocksList);
		// alert("blocchi 'scritti' con successo" + this.blocksContainerClassName);
		$(this.tableBlocksContainerClassName).append(htmlBlocksList);
	},
};

/* Object to manage form errors and success redirect */
var ajaxFormValidation = {

	formClassName : 'ajax_form', // Default "ajax_form"
	errorMessageBoxClassName : 'error_container', // Default "error_container"
	serverMsgContainer : 'server_msg_container', // Server side message container class name
	errorClassName : 'has-error', // Default "has-error"
	formGroupClassName : 'form-group', // Default "form-group"
	// redirectUrl : '', // Es . "/registrati/" Default None
	ajaxCallUrl : "/ajax/", // the ajax call url
	callData : Array(),

	/* Function to manage Ajax form response */
	manageFormResponse : function(jsonResponse) {
		try {
			if (!$.isEmptyObject(jsonResponse)) {
				JSONResult = $.parseJSON(JSON.stringify(jsonResponse));
				if (JSONResult["error"]) {
					this.removeFormErrors();
					this.showFormErrorMessages(JSONResult);
				} else if (JSONResult["success"]) {
					// console.log("Form salvato con successo");
					// submit current form after successfully validation
					this.submitForm();
				}
			}
		} catch(Exception) {
		    // ops...ajax resonse may be corrupted
		    console.log("manageFormErrorResponse error: " + Exception);
		}
		return true;
	},

	/* Function to submit current form after successfully validation */
	submitForm : function() {
		$("." + this.formClassName).submit();
		return true;
	},

	/* Function to remove all previously errors messagges */
	removeFormErrors : function() {
		$("." + this.formGroupClassName).removeClass(this.errorClassName);
		$("." + this.errorMessageBoxClassName).html("");
		$("." + this.serverMsgContainer).html("");
		return true;
	},

	/* Function to show form error message after Ajax call */
	showFormErrorMessages : function(jsonResponse) {
		if (!$.isEmptyObject(jsonResponse) && !$.isEmptyObject(jsonResponse["form_data"])) {
			$.each(jsonResponse["form_data"], function(fieldName, errorList) {
				if (fieldName == "__all__") {
					ajaxFormValidation.showAllFieldErrorsBox(errorList);
				} else {
					ajaxFormValidation.addSingleFieldErrorClass(fieldName);
				}
			});
		}
		return true;
	},

	/* Function to show a box with main form validation error */
	showAllFieldErrorsBox : function(errorListJson) {
		var errorList = '';
		var htmlErrorBoxTemplate = '';

		$.each(errorListJson, function(field_name, field_errors) {
			errorList += "
" + field_errors["message"] + "
";
		});

		if (errorList) {
			htmlErrorBoxTemplate += '
';
			htmlErrorBoxTemplate += '
';
			htmlErrorBoxTemplate += '
';
			htmlErrorBoxTemplate += '
Uhm qualcosa non va!
';
			htmlErrorBoxTemplate += '
';
			htmlErrorBoxTemplate += errorList;
			htmlErrorBoxTemplate += '
';
			htmlErrorBoxTemplate += '
';
			htmlErrorBoxTemplate += '
';
			htmlErrorBoxTemplate += '
';

			$("." + this.errorMessageBoxClassName).html(htmlErrorBoxTemplate);
		}
		return true;
	},

	/* Function to show error on single fields */
	addSingleFieldErrorClass : function(fieldName) {
		$("#id_" + fieldName).parents("." + this.formGroupClassName).addClass(this.errorClassName);
		return true;
	},

	/* Function to check if ajax call can be performed */
	ajaxCallCanBePerformed : function() {
		var returnVar = false;
		if (typeof this.callData !== 'undefined') {
			if (this.ajaxCallUrl && this.callData["data"]) {
				returnVar = true;
			}
		}
		return returnVar;
	},

	/* Function to send form data via Ajax */
	validateForm : function(){
		// check if ajax call can be performed
		if (this.ajaxCallCanBePerformed()) {
			// reading csrfmiddlewaretoken from cookie
			var csrftoken = readCsrftokenFromCookie();
			var ajaxCallData = {
				url : this.ajaxCallUrl,
				data : this.callData["data"] + "&ajax_action=form_validation",
				async : true,
				headers: { "X-CSRFToken": csrftoken },
				success : function(jsonResponse) {
					// function to manage JSON response
					// console.log(result);
					ajaxFormValidation.manageFormResponse(jsonResponse);
				},
				error : function(jsonResponse) {
					// ...fuck
					// console.log(jsonResponse);
				}
			}

			// performing ajax call
			loadDataWrapper.performAjaxCall(ajaxCallData);
		}
		return true;
	},
};

/* Object to manage law cookie div */
// Creare's 'Implied Consent' EU Cookie Law Banner v:2.4
// Conceived by Robert Kent, James Bavington & Tom Foyster
var lawCookieCompliance = {
	dropCookie : true, // false disables the Cookie, allowing you to style the banner
	cookieDuration : 60, // Number of days before the cookie expires, and the banner reappears
	cookieName : 'complianceCookie', // Name of our cookie
	cookieValue : 'on', // Value of cookie

	createDiv : function() {
		var bodytag = document.getElementsByTagName('body')[0];
		var div = document.createElement('div');
		div.setAttribute('id', 'cookie-law');
		div.innerHTML = '
Su questo sito utilizziamo i cookie. Per saperne di più clicca qui. Continuando la navigazione acconsenti al loro utilizzo.  X
';
		// bodytag.appendChild(div); // Adds the Cookie Law Banner just before the closing  tag
		// or
		bodytag.insertBefore(div, bodytag.firstChild); // Adds the Cookie Law Banner just after the opening  tag
		document.getElementsByTagName('body')[0].className += ' cookiebanner'; //Adds a class tothe  tag when the banner is visible
		this.createCookie(lawCookieCompliance.cookieName, lawCookieCompliance.cookieValue, lawCookieCompliance.cookieDuration); // Create the cookie
	},

	createCookie : function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		} else var expires = "";
		if(lawCookieCompliance.dropCookie) {
			document.cookie = name+"="+value+expires+"; path=/";
		}
	},

	checkCookie : function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},

	eraseCookie : function(name) {
		this.createCookie(name,"",-1);
	},

	removeMe : function() {
		var element = document.getElementById('cookie-law');
		if(element) element.parentNode.removeChild(element);
	},

	createDivOnLoad : function() {
		if(this.checkCookie(lawCookieCompliance.cookieName) != lawCookieCompliance.cookieValue){
			this.createDiv();
		}
	},
};

// Facebook JavaScript SDK
window.fbAsyncInit = function() {
	FB.init({
		appId : '932261456835509',
		xfbml : true,
		version : 'v2.4'
	});
};


text:
package com.samsung.surc.swtest;

public interface User {
    public String getMySingleId();

    public String getName();

    public String getSurname();
}

redpajama_set_name: RedPajamaGithub


text:
shared_examples_for 'defining a method double that sets the implementation of that method' do
  include DoubleDefinitionCreatorHelpers

  it "works when not given a block" do
    expect_that_double_can_be_defined_without_block
  end

  context 'by giving a block' do
    it "replaces the implementation with the block" do
      expect_that_double_sets_implementation do |double_creator, method_name, block|
        double_creator.__send__(method_name, &block)
      end
    end

    it "resets the double correctly" do
      expect_that_double_sets_implementation_and_resets do |double_creator, method_name, block|
        double_creator.__send__(method_name, &block)
      end
    end
  end

  context 'by using #returns' do
    context 'with a block' do
      it "replaces the implementation with the block" do
        expect_that_double_sets_implementation do |double_creator, method_name, block|
          double_creator.__send__(method_name).returns(&block)
        end
      end

      it "resets the double correctly" do
        expect_that_double_sets_implementation_and_resets do |double_creator, method_name, block|
          double_creator.__send__(method_name).returns(&block)
        end
      end
    end

    context 'with a straight argument' do
      it "makes the method return the argument" do
        expect_that_double_sets_value do |double_creator, method_name, value|
          double_creator.__send__(method_name).returns(value)
        end
      end

      it "resets the double correctly" do
        expect_that_double_sets_value_and_resets do |double, method_name, value|
          double_creator.__send__(method_name).returns(value)
        end
      end
    end
  end
end


text:
from leonardo_api.base import routers

router = routers.DefaultRouter(trailing_slash=True)


text:
var Item = require('../../lib/item');
var Directory = require('../../lib/directory');
var File = require('../../lib/file');
var assert = require('../helper').assert;

describe('Directory', function() {

  describe('constructor', function() {

    it('creates a named directory', function() {
      var dir = new Directory();
      assert.instanceOf(dir, Directory);
      assert.instanceOf(dir, Item);
    });

  });

  describe('#addItem()', function() {

    it('allows a directory to be added', function() {
      var parent = new Directory();
      var child = new Directory();
      parent.addItem('child', child);
      assert.equal(parent.getItem('child'), child);
    });

    it('allows a file to be added', function() {
      var parent = new Directory();
      var child = new File();
      parent.addItem('child', child);
      assert.equal(parent.getItem('child'), child);
    });

    it('returns the added item', function() {
      var parent = new Directory();
      var child = new File();
      var got = parent.addItem('child', child);
      assert.equal(got, child);
    });

  });

  describe('#getItem()', function() {

    it('retrieves a named directory', function() {
      var parent = new Directory();
      var child = new Directory();
      parent.addItem('child', child);
      assert.equal(parent.getItem('child'), child);
    });

    it('retrieves a named file', function() {
      var parent = new Directory();
      var child = new File();
      parent.addItem('child', child);
      assert.equal(parent.getItem('child'), child);
    });

    it('returns null for missing item', function() {
      var parent = new Directory();
      var child = new File();
      parent.addItem('child', child);
      assert.isNull(parent.getItem('kid'));
    });

  });

  describe('#removeItem()', function() {

    it('allows a directory to be removed', function() {
      var parent = new Directory();
      var child = new Directory();
      parent.addItem('child', child);
      var removed = parent.removeItem('child');
      assert.equal(removed, child);
      assert.isNull(parent.getItem('child'));
    });

    it('allows a file to be removed', function() {
      var parent = new Directory();
      var child = new File();
      parent.addItem('child', child);
      var removed = parent.removeItem('child');
      assert.equal(removed, child);
      assert.isNull(parent.getItem('child'));
    });

    it('throws if item is not a child', function() {
      var parent = new Directory();
      parent.addItem('one', new Directory());
      parent.addItem('two', new File());
      assert.throws(function() {
        parent.removeItem('three');
      });
    });

  });

  describe('#list()', function() {

    it('lists all items in a directory', function() {
      var dir = new Directory();
      dir.addItem('one file', new File());
      dir.addItem('another file', new File());
      dir.addItem('a directory', new Directory());
      dir.addItem('another directory', new Directory());
      var list = dir.list();
      assert.deepEqual(list.sort(), [
        'a directory',
        'another directory',
        'another file',
        'one file'
      ]);
    });

    it('works for empty dir', function() {
      var dir = new Directory();
      assert.deepEqual(dir.list(), []);
    });

    it('lists one level deep', function() {
      var d0 = new Directory();
      var d1 = new Directory();
      var d2 = new Directory();
      d1.addItem('d2', d2);
      d0.addItem('d1', d1);
      assert.deepEqual(d0.list(), ['d1']);
    });

  });

});


text:
var p = Proxy.create({
  has : function(id) {}
});
Object.prototype.__proto__ = p;
function f() {
  if (/a/.exec("a"))
    return 1;
  return 0;
}
delete RegExp.prototype.test;
f();


text:
namespace Paramore.Brighter
{
    ///
    /// Interface IAmAnOutbox
    /// In order to provide reliability for messages sent over a Task Queue we
    /// store the message into an OutBox to allow later replay of those messages in the event of failure. We automatically copy any posted message into the store
    /// We provide implementations of <see cref="IAmAnOutboxSync{T}"/> for various databases. Users using other databases should consider a Pull Request
    ///
    /// <typeparam name="T"></typeparam>
    public interface IAmAnOutbox<in T> where T : Message
    {

    }
}


text:
import unittest

# External library imports
import vtk

# Enthought library imports
from mayavi.sources.vtk_file_reader import VTKFileReader

# Local imports.
from .common import get_example_data

vtk_major_version = vtk.vtkVersion.GetVTKMajorVersion()
vtk_minor_version = vtk.vtkVersion.GetVTKMinorVersion()

class TestVTKFileReader(unittest.TestCase):
    def setUp(self):
        # Read a VTK data file.
        self.src = VTKFileReader()

    def tearDown(self):
        """For necessary clean up, automatically called by TestCase
           after the test methods have been invoked"""
        self.src = None
        return

    def check(self, n_points, n_cells):
        """Do the actual testing."""
        output = self.src.outputs[0]
        self.assertEqual(output.number_of_points, n_points)
        self.assertEqual(output.number_of_cells, n_cells)

    def test_structured_points_file(self):
        self.src.initialize(get_example_data('texThres2.vtk'))
        self.check(128, 127)

    def test_rectiliner_grid_file(self):
        self.src.initialize(get_example_data('RectGrid2.vtk'))
        self.check(17061, 14720)

    def test_polydata_file(self):
        self.src.initialize(get_example_data('polyEx.vtk'))
        self.check(8, 6)

    def test_structured_grid_file(self):
        self.src.initialize(get_example_data('SampleStructGrid.vtk'))
        self.check(24000, 21489)

    @unittest.skipIf(vtk_major_version == 5 and vtk_minor_version < 10,
                    "This test is probably broken in VTK < 5.10")
    def test_unstructured_grid_file(self):
        self.src.initialize(get_example_data('UGridEx.vtk'))
        self.check(27, 12)

    def test_field_file(self):
        self.src.initialize(get_example_data('fieldfile.vtk'))
        self.check(18, 3)

if __name__ == '__main__':
    unittest.main()


text:
The Wrap database is a web service that provides Meson build definitions to projects that do not have it natively. Using it is simple. The service can be found [here](https://wrapdb.mesonbuild.com).

The front page lists all projects that are on the service. Select the one you want and click it. The detail page lists available versions by branch and revision id. The branch names come from upstream releases and revision ids are version numbers internal to the database. Whenever the packaging is updated a new revision is released to the service a new revision with a bigger revision id is added. Usually you want to select the newest branch with the highest revision id.

You can get the actual wrap file which tells Meson how to fetch the project by clicking on the download link on the page. As an example, the wrap file for [zlib-1.2.8, revision 4](https://wrapdb.mesonbuild.com/v1/projects/zlib/1.2.8/4/get_wrap) looks like this. You can find detailed documentation about it in [the Wrap manual](Wrap-dependency-system-manual.md).

    [wrap-file]
    directory = zlib-1.2.8

    source_url = http://zlib.net/zlib-1.2.8.tar.gz
    source_filename = zlib-1.2.8.tar.gz
    source_hash = 36658cb768a54c1d4dec43c3116c27ed893e88b02ecfcb44f2166f9c0b7f2a0d

    patch_url = https://wrapdb.mesonbuild.com/v1/projects/zlib/1.2.8/4/get_zip
    patch_filename = zlib-1.2.8-4-wrap.zip
    patch_hash = 2327a42c8f73a4289ee8c9cd4abc43b324d0decc28d6e609e927f0a50321af4a

Add this file to your project with the name `subprojects/zlib.wrap`. Then you can use it in your `meson.build` file with this directive:

    zproj = subproject('zlib')

When Meson encounters this it will automatically download, unpack and patch the source files.

## Contributing build definitions

The contents of the Wrap database are tracked in git repos of the [Mesonbuild project](https://github.com/mesonbuild). The actual process is simple and described in [submission documentation](https://github.com/mesonbuild/wrapweb/wiki).


text:
'use strict';
((rb, document) => {
  const aria = rb.aria;
  const DESCRIBED_BY_ERROR_ID_ATTR = 'data-rb-describedbyerrorid';

  function onClassMutation(mutations) {
    const mutationsLen = mutations.length;

    for (let k = 0; k < mutationsLen; k++) {
      const mutation = mutations[k];
      const el = mutation.target;
      const message = el.parentNode.querySelector('.validation-message');

      let describedByErrorId = '';
      let describedByIds = [];
      let i = -1;

      if (mutation.oldValue !== 'invalid' && mutation.target && mutation.target.classList.contains('invalid')) {
        // If "invalid" was added, do the decoratin'
        el.setAttribute(aria.invalid, 'true');
        describedByErrorId = el.getAttribute(DESCRIBED_BY_ERROR_ID_ATTR);
        describedByIds = el.getAttribute(aria.describedby).split(' ');
        i = describedByIds.indexOf(describedByErrorId);

        if (message) {
          message.setAttribute(aria.role, 'alert');
          message.setAttribute(aria.live, 'polite');

          // If a validation message exists && the related element is newly invalid,
          // add message id to described-by
          if (i === -1) {
            describedByIds.push(describedByErrorId);
            el.setAttribute(aria.describedby, describedByIds.join(' '));
          }
        }
      } else if (mutation.oldValue === 'invalid' && el && !el.classList.contains('invalid')) {
        // If "invalid" was removed
        el.setAttribute(aria.invalid, 'false');
        describedByErrorId = el.getAttribute(DESCRIBED_BY_ERROR_ID_ATTR);
        describedByIds = el.getAttribute(aria.describedby).split(' ');
        i = describedByIds.indexOf(describedByErrorId);

        if (message) {
          message.removeAttribute('role');
          message.removeAttribute(aria.live);

          // If a validation message exists && the related element longer invalid,
          // remove message id from described-by
          if (i > -1) {
            describedByIds.splice(i, 1);
            el.setAttribute(aria.describedby, describedByIds.join(' '));
          }
        }
      }
    }
  }

  function affixInputs() {
    const $affixedInputs = $('input.affixed');

    $affixedInputs.each(function () {
      const $input = $(this);
      const $affixment = $input.siblings('.affixment');

      const top = $input.position().top;

      $affixment.css('top', top);
      $affixment.addClass('affixed');
    });
  }

  function decorateInputs() {
    const formEls = document.querySelectorAll(
      '.form-group input, .form-group select, .form-group textarea, .form-group fieldset'
    );
    const formElsLen = formEls.length;

    for (let i = 0; i < formElsLen; i++) {
      const el = formEls[i];

      // "invalid" will be raised by the checkValidity() call below.
      // .invalid is added and will be handled by the MutationObserver
      // created by this function.
      // https://daverupert.com/2017/11/happier-html5-forms/
      el.addEventListener('invalid', () => {
        if (el && el.classList) {
          el.classList.add('invalid');
        }
      }, false);

      // Set an observer to listen for .invalid.
      const observer = new MutationObserver(mutations => { onClassMutation(mutations); });
      observer.observe(el, {
        subtree: false,
        attributes: true,
        attributeOldValue: true,
        attributeFilter: ['class']
      });

      const messages = el.parentNode.querySelectorAll('.validation-message, .helper-text');
      const msgLen = messages.length;

      if (msgLen > 0) {
        let describedByIds = '';

        if (el.hasAttribute(aria.describedby)) {
          describedByIds = `${el.getAttribute(aria.describedby)} `;
        }

        for (let j = 0; j < msgLen; j++) {
          const thisMsg = messages[j];
          const id = thisMsg.id ? thisMsg.id : `rb-a11y_${rb.getShortId()}`;
          describedByIds += `${id} `;

          if (thisMsg.classList.contains('validation-message')) {
            el.setAttribute(DESCRIBED_BY_ERROR_ID_ATTR, id);
          }

          // Don't clobber any existing attributes!
          if (!thisMsg.id) {
            thisMsg.id = id;
          }
        }

        if (!el.hasAttribute(aria.describedby)) {
          el.setAttribute(aria.describedby, describedByIds.trim());
        }
      }
    }

    const formsAndGroups =
      document.querySelectorAll('form.validate-on-blur, .form-group.validate-on-blur');
    for (const el of formsAndGroups) {
      el.addEventListener('blur', () => {
        el.checkValidity();
      });
    }
  }

  rb.onDocumentReady(decorateInputs);
  rb.onDocumentReady(affixInputs);
  rb.forms = rb.forms || {};
  rb.forms.decorateInputs = decorateInputs;
  rb.forms.affixInputs = affixInputs;
})(window.rb, document);


text:
package lifecycle

import (
	"fmt"
	"io"
	"math/rand"
	"strings"
	"time"

	"github.com/golang/glog"

	"k8s.io/kubernetes/pkg/admission"
	kapi "k8s.io/kubernetes/pkg/api"
	apierrors "k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/meta"
	"k8s.io/kubernetes/pkg/apimachinery/registered"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	"k8s.io/kubernetes/pkg/util/sets"

	"github.com/openshift/origin/pkg/api"
	oadmission "github.com/openshift/origin/pkg/cmd/server/admission"
	"github.com/openshift/origin/pkg/project/cache"
	projectutil "github.com/openshift/origin/pkg/project/util"
)

// TODO: modify the upstream plug-in so this can be collapsed
// need ability to specify a RESTMapper on upstream version
func init() {
	admission.RegisterPlugin("OriginNamespaceLifecycle", func(client clientset.Interface, config io.Reader) (admission.Interface, error) {
		return NewLifecycle(client, recommendedCreatableResources)
	})
}

type lifecycle struct {
	client clientset.Interface
	cache  *cache.ProjectCache

	// creatableResources is a set of resources that can be created even if the namespace is terminating
	creatableResources sets.String
}

var recommendedCreatableResources = sets.NewString("resourceaccessreviews", "localresourceaccessreviews")
var _ = oadmission.WantsProjectCache(&lifecycle{})
var _ = oadmission.Validator(&lifecycle{})

// Admit enforces that a namespace must exist in order to associate content with it.
// Admit enforces that a namespace that is terminating cannot accept new content being associated with it.
func (e *lifecycle) Admit(a admission.Attributes) (err error) {
	if len(a.GetNamespace()) == 0 {
		return nil
	}
	// always allow a SAR request through, the SAR will return information about
	// the ability to take action on the object, no need to verify it here.
	if isSubjectAccessReview(a) {
		return nil
	}

	groupMeta, err := registered.Group(a.GetKind().Group)
	if err != nil {
		return err
	}
	mapping, err := groupMeta.RESTMapper.RESTMapping(a.GetKind())
	if err != nil {
		glog.V(4).Infof("Ignoring life-cycle enforcement for resource %v; no associated default version and kind could be found.", a.GetResource())
		return nil
	}
	if mapping.Scope.Name() != meta.RESTScopeNameNamespace {
		return nil
	}

	// we want to allow someone to delete something in case it was phantom created somehow
	if a.GetOperation() == "DELETE" {
		return nil
	}

	name := "Unknown"
	obj := a.GetObject()
	if obj != nil {
		name, _ = meta.NewAccessor().Name(obj)
	}

	if !e.cache.Running() {
		return admission.NewForbidden(a, err)
	}

	namespace, err := e.cache.GetNamespace(a.GetNamespace())
	if err != nil {
		return admission.NewForbidden(a, err)
	}

	if a.GetOperation() != "CREATE" {
		return nil
	}

	if namespace.Status.Phase == kapi.NamespaceTerminating && !e.creatableResources.Has(strings.ToLower(a.GetResource().Resource)) {
		return apierrors.NewForbidden(a.GetResource(), name, fmt.Errorf("Namespace %s is terminating", a.GetNamespace()))
	}

	// in case of concurrency issues, we will retry this logic
	numRetries := 10
	interval := time.Duration(rand.Int63n(90)+int64(10)) * time.Millisecond
	for retry := 1; retry <= numRetries; retry++ {

		// associate this namespace with openshift
		_, err = projectutil.Associate(e.client, namespace)
		if err == nil {
			break
		}

		// we have exhausted all reasonable efforts to retry so give up now
		if retry == numRetries {
			return admission.NewForbidden(a, err)
		}

		// get the latest namespace for the next pass in case of resource version updates
		time.Sleep(interval)

		// it's possible the namespace actually was deleted, so just forbid if this occurs
		namespace, err = e.client.Core().Namespaces().Get(a.GetNamespace())
		if err != nil {
			return admission.NewForbidden(a, err)
		}
	}
	return nil
}

func (e *lifecycle) Handles(operation admission.Operation) bool {
	return true
}

func (e *lifecycle) SetProjectCache(c *cache.ProjectCache) {
	e.cache = c
}

func (e *lifecycle) Validate() error {
	if e.cache == nil {
		return fmt.Errorf("project lifecycle plugin needs a project cache")
	}
	return nil
}

func NewLifecycle(client clientset.Interface, creatableResources sets.String) (admission.Interface, error) {
	return &lifecycle{
		client:             client,
		creatableResources: creatableResources,
	}, nil
}

var (
	sar  = api.Kind("SubjectAccessReview")
	lsar = api.Kind("LocalSubjectAccessReview")
)

func isSubjectAccessReview(a admission.Attributes) bool {
	return a.GetKind() == sar || a.GetKind() == lsar
}


text:
html {
  background: #e9e9e9;
}
.readonly, .readonly:hover, .readonly:focus {
  border: 1px solid transparent;
  text-overflow: ellipsis;
}
.editable {
  resize: none;
}


text:
<?php

namespace PanicHD\PanicHD\Traits;

use PanicHD\PanicHD\Helpers\LaravelVersion;

trait MemberTrait
{
    /**
     * list of all agents and returning collection.
     *
     * @param $query
     * @param bool $paginate
     *
     * @return bool
     *
     * @internal param int $cat_id
     */
    public function scopeAgents($query, $paginate = false)
    {
        if ($paginate) {
            return $query->where('panichd_agent', '1')->paginate($paginate, ['*'], 'agents_page');
        } else {
            return $query->where('panichd_agent', '1');
        }
    }

    /**
     * list of all admins and returning collection.
     *
     * @param $query
     * @param bool $paginate
     *
     * @return bool
     *
     * @internal param int $cat_id
     */
    public function scopeAdmins($query, $paginate = false)
    {
        if ($paginate) {
            return $query->where('panichd_admin', '1')->paginate($paginate, ['*'], 'admins_page');
        } else {
            return $query->where('panichd_admin', '1')->get();
        }
    }

    /**
     * list of all agents and returning collection.
     *
     * @param $query
     * @param bool $paginate
     *
     * @return bool
     *
     * @internal param int $cat_id
     */
    public function scopeUsers($query, $paginate = false)
    {
        if ($paginate) {
            return $query->where('panichd_agent', '0')->paginate($paginate, ['*'], 'users_page');
        } else {
            return $query->where('panichd_agent', '0')->get();
        }
    }

    /**
     * list of all agents and returning lists array of id and name.
     *
     * @param $query
     *
     * @return bool
     *
     * @internal param int $cat_id
     */
    public function scopeAgentsLists($query)
    {
        if (version_compare(app()->version(), '5.2.0', '>=')) {
            return $query->where('panichd_agent', '1')->pluck('name', 'id')->toArray();
        } else { // if Laravel 5.1
            return $query->where('panichd_agent', '1')->lists('name', 'id')->toArray();
        }
    }

    /**
     * Check if auth() member is agent.
     *
     * @return bool
     */
    public function isAgent()
    {
        return $this->panichd_agent;
    }

    /**
     * Check if auth() member is admin.
     *
     * @return bool
     */
    public function isAdmin()
    {
        return $this->panichd_admin;
    }

    /**
     * Check if user is the assigned agent for a ticket.
     *
     * @param int $id ticket id
     *
     * @return bool
     */
    public function isAssignedAgent($id)
    {
        if ($this->panichd_agent) {
            if ($this->id == \PanicHD\PanicHD\Models\Ticket::find($id)->agent->id) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if user is the owner for a ticket.
     *
     * @param int $id ticket id
     *
     * @return bool
     */
    public function isTicketOwner($id)
    {
        if ($this->id == \PanicHD\PanicHD\Models\Ticket::find($id)->user_id) {
            return true;
        }

        return false;
    }

    /**
     * Get general maximum permission level for current user.
     *
     * @param int $id category id
     *
     * @return int
     */
    public function maxLevel()
    {
        if ($this->isAdmin()) {
            return 3;
        } elseif ($this->isAgent()) {
            return 2;
        } else {
            return 1;
        }
    }

    /**
     * Get current permission level for user.
     *
     * @param int $id category id
     *
     * @return int
     */
    public function currentLevel()
    {
        if ($this->isAdmin()) {
            return 3;
        } elseif ($this->isAgent()) {
            if (session()->exists('panichd_filter_currentLevel') and session('panichd_filter_currentLevel') == 1) {
                return 1;
            } else {
                return 2;
            }
        } else {
            return 1;
        }
    }

    /**
     * Get permission level for specified category.
     *
     * @param int $id category id
     *
     * @return int
     */
    public function levelInCategory($id = false)
    {
        if ($this->panichd_admin) { // avoiding ->isAdmin()
            return 3;
        } elseif (!$this->panichd_agent) { // avoiding ->isAgent()
            return 1;
        } else {
            if ($id == false) {
                return 1; // user level by default
            } else {
                if ($this->categories()->where('id', $id)->count() == 1) {
                    return 2;
                } else {
                    return 1;
                }
            }
        }
    }

    /**
     * Check if user has close permissions on a ticket.
     *
     * @param int $id ticket id
     *
     * @return bool
     */
    public function canCloseTicket($id)
    {
        $a_perm = \PanicHD\PanicHD\Models\Setting::grab('close_ticket_perm');

        if ($this->isAdmin() && $a_perm['admin'] == 'yes') {
            return true;
        }
        if ($ticket = \PanicHD\PanicHD\Models\Ticket::find($id)) {
            if ($this->id == $ticket->agent_id or \PanicHD\PanicHD\Models\Setting::grab('agent_restrict') == 0 and $this->categories()->where('id', $ticket->category_id)->count() == 1) {
                return true;
            }
        }

        if ($this->isTicketOwner($id) && $a_perm['owner'] == 'yes') {
            return true;
        }

        return false;
    }

    /**
     * Check if user can make a comment on a ticket.
     *
     * @param $ticket instance of \PanicHD\PanicHD\Models\Ticket
     *
     * @return bool
     */
    public function canCommentTicket($ticket)
    {
        if ($this->canManageTicket($ticket->id)
            or $this->isTicketOwner($ticket->id)
            or $ticket->commentNotifications()->where('member_id', $this->id)->count() > 0) {
            return true;
        }

        return false;
    }

    /**
     * Check if user has manage permissions on a ticket.
     *
     * @param int $id ticket id
     *
     * @return bool
     */
    public function canManageTicket($id)
    {
        if ($this->isAdmin()) {
            return true;
        } elseif ($ticket = \PanicHD\PanicHD\Models\Ticket::find($id)) {
            if ($this->id == $ticket->agent_id or \PanicHD\PanicHD\Models\Setting::grab('agent_restrict') == 0 and $this->categories()->where('id', $ticket->category_id)->count() == 1) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if user can view new tickets button.
     *
     * @param int $id ticket id
     *
     * @return bool
     */
    public function canViewNewTickets()
    {
        if ($this->isAdmin()) {
            return true;
        } elseif ($this->isAgent() and $this->currentLevel() == 2) {
            if (\PanicHD\PanicHD\Models\Setting::grab('agent_restrict') == 1) {
                return $this->categories()->wherePivot('autoassign', '1')->count() == 0 ? false : true;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * Get directly associated department (ticketit_department).
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function userDepartment()
    {
        return $this->belongsTo('PanicHD\PanicHD\Models\Department', 'ticketit_department', 'id');
    }

    /**
     * Get associated department list through person_id.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function department()
    {
        return $this->belongsTo('PanicHD\PanicHD\Models\Department');
    }

    /**
     * Get related categories.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function categories()
    {
        return $this->belongsToMany('PanicHD\PanicHD\Models\Category', 'panichd_categories_users', 'user_id', 'category_id')->withPivot('autoassign')->orderBy('name');
    }

    /**
     * Get categories where user has permission to create new tickets.
     *
     * @return array
     */
    public function getNewTicketCategories()
    {
        if ($this->isAdmin()) {
            $categories = \PanicHD\PanicHD\Models\Category::orderBy('name');
        } else {
            $categories = \PanicHD\PanicHD\Models\Category::where('create_level', '1')->orderBy('name')->get();

            if ($this->isAgent() and $this->currentLevel() == 2) {
                $create_level_2 = $this->categories()->where('create_level', '2')->get();

                $categories = $categories->merge($create_level_2)->sortBy('name');
            }
        }

        if (LaravelVersion::min('5.3.0')) {
            return $categories->pluck('name', 'id');
        } else {
            return $categories->lists('name', 'id');
        }
    }

    /**
     * Get categories where user has permission to edit tickets.
     *
     * @return array
     */
    public function getEditTicketCategories()
    {
        if ($this->isAdmin()) {
            $categories = \PanicHD\PanicHD\Models\Category::orderBy('name');
        } elseif ($this->isAgent() and $this->currentLevel() == 2) {
            $categories = $this->categories()->where('create_level', '<=', '2')->orderBy('name');
        } else {
            return [];
        }

        if (LaravelVersion::min('5.3.0')) {
            return $categories->pluck('name', 'id');
        } else {
            return $categories->lists('name', 'id');
        }
    }

    /**
     * Get related tickets as agent.
     */
    public function ticketsAsAgent()
    {
        return $this->hasMany('PanicHD\PanicHD\Models\Ticket', 'agent_id');
    }

    /**
     * Get related owner tickets.
     */
    public function ticketsAsOwner()
    {
        return $this->hasMany('PanicHD\PanicHD\Models\Ticket', 'user_id');
    }

    /**
     * Get all Visible agents for current user.
     *
     * @param $query
     * @param $id
     *
     * @return mixed
     */
    public function scopeVisible($query)
    {
        $query = $query->agents();

        $member = \PanicHDMember::findOrFail(auth()->user()->id);

        if ($member->panichd_admin) {
            return $query->orderBy('name', 'ASC');
        } elseif ($member->panichd_agent) {
            return $query->VisibleForAgent($member->id);
        } else {
            return $query->where('id', '0');
        }
    }

    /**
     * Get all agents from the categories where Agent $id belongs to.
     *
     * @param $query
     * @param $id
     *
     * @return mixed
     */
    public function scopeVisibleForAgent($query, $id)
    {
        $member = \PanicHDMember::findOrFail(auth()->user()->id);

        if ($member->currentLevel() == 2) {
            // Depends on agent_restrict
            if (\PanicHD\PanicHD\Models\Setting::grab('agent_restrict') == 0) {
                return $query->whereHas('categories', function ($q1) use ($id) {
                    $q1->whereHas('agents', function ($q2) use ($id) {
                        $q2->where('id', $id);
                    });
                })->orderBy('name', 'ASC');
            } else {
                return $query->where('id', $id);
            }
        } else {
            return false;
        }
    }

    /**
     * Get array with all user id's from the departments where current user belongs and users that have ticketit_department = 0.
     *
     * @return array
     */
    public function getMyNoticesUsers()
    {
        // Get my related departments
        $related_departments = [];

        $c_related = $this->getRelatedDepartments();

        if (!$c_related) {
            return [];
        }

        foreach ($c_related as $rel) {
            $related_departments[] = $rel->id;
        }

        /*
         *	Get related Departamental users from my related departments
         *
         * Conditions:
         *    - agent ticketit_department in related_departments
         *    - agent person in related_departments
        */
        $related_users = \PanicHDMember::where('id', '!=', $this->id)
            ->whereIn('ticketit_department', $related_departments);

        // Get users that are visible by all departments
        $all_dept_users = \PanicHDMember::where('ticketit_department', '0');

        if (version_compare(app()->version(), '5.3.0', '>=')) {
            $related_users = $related_users->pluck('id')->toArray();
            $related_users = array_unique(array_merge($related_users, $all_dept_users->pluck('id')->toArray()));
        } else {
            $related_users = $related_users->lists('id')->toArray();
            $related_users = array_unique(array_merge($related_users, $all_dept_users->lists('id')->toArray()));
        }

        return $related_users;
    }

    /*
     * Get member related departments in Department hierarchy
     *
     * For a main department: Returns self + all descendants
     * For descendant: Returns self + ancestor
     *
     * @Return collection
    */
    public function getRelatedDepartments()
    {
        if (is_null($this->department)) {
            return [];
        }

        $member_department = $this->department()->first();

        if ($member_department->is_main()) {
            return $member_department->get()->merge($member_department->descendants()->get());
        } else {
            return $member_department->get()->merge($member_department->ancestor()->get());
        }
    }

}


text:
import sys

from oslo_config import cfg
from oslo_log import log
from oslo_policy import opts as policy_opts

from monasca_log_api import conf
from monasca_log_api import version

CONF = conf.CONF
LOG = log.getLogger(__name__)

_CONF_LOADED = False
_GUNICORN_MARKER = 'gunicorn'

def _is_running_under_gunicorn():
    """Evaluates if api runs under gunicorn"""
    content = filter(lambda x: x != sys.executable and _GUNICORN_MARKER in x,
                     sys.argv or [])
    return len(list(content) if not isinstance(content, list) else content) > 0

def get_config_files():
    """Get the possible configuration files accepted by oslo.config

    This also includes the deprecated ones
    """
    # default files
    conf_files = cfg.find_config_files(project='monasca',
                                       prog='monasca-log-api')
    # deprecated config files (only used if standard config files are not there)
    if len(conf_files) == 0:
        old_conf_files = cfg.find_config_files(project='monasca',
                                               prog='log-api')
        if len(old_conf_files) > 0:
            LOG.warning('Found deprecated old location "{}" '
                        'of main configuration file'.format(old_conf_files))
            conf_files += old_conf_files
    return conf_files

def parse_args(argv=None):
    global _CONF_LOADED
    if _CONF_LOADED:
        LOG.debug('Configuration has been already loaded')
        return

    log.set_defaults()
    log.register_options(CONF)

    argv = (argv if argv is not None else sys.argv[1:])
    args = ([] if _is_running_under_gunicorn() else argv or [])

    CONF(args=args,
         prog=sys.argv[1:],
         project='monasca',
         version=version.version_str,
         default_config_files=get_config_files(),
         description='RESTful API to collect log files')

    log.setup(CONF,
              product_name='monasca-log-api',
              version=version.version_str)

    conf.register_opts()
    policy_opts.set_defaults(CONF)

    _CONF_LOADED = True