var boxes = 0;
var currentBox = 0;
var minLength = 2;
var maxDisplay = 100;
var suggestDelay = 500;
var currentPage = 1;
var totalPages = 1;
var displayBy = 10;
var previewLimit = 10;
var numCloudWords = 20;
var cloudWordsSizeVariance = 5;
var cloudWordsSizeStart = 80;
var separators = new Array(";", ",");
var mask = /^[a-z0-9\-]{2, }(\s+[a-z0-9\-]{2, })*$/gi;
var numeric = /^[0-9\.]*$/gi;

var timer;
var suggestionGroup;
var searchExp;

function search() {
	searchExp = new Object({
		niveau: new Array(),
		filiere: new Array(),
		apprentissage: new Array(),
		specialite: new Array(),
		statut: new Array(),
		etablissement: new Array(),
		region: new Array(),
		academie: new Array(),
		departement: new Array(),
		ville: new Array(),
		autre: new Array()
	});
	$("form#action input").each(function( i ) {
		if ($(this).val() != '') {
			searchExp[$(this).attr('reference')][searchExp[$(this).attr('reference')].length] = $(this).val();
		}
	});
	searchExp = $.toJSON( searchExp );
	getResults( 1 );
	getCloud();
}

function goTo( param ) {
	switch( param ) {
		case "first": 
			if (currentPage != 1) p = 1;
			else p = -1;
			break;
		case "previous": 
			if (currentPage - 1 > 0) p = currentPage - 1;
			else p = -1;
			break;
		case "next": 
			if (currentPage + 1 <= totalPages) p = currentPage + 1; 
			else p = -1;
			break;
		case "last": 
			if (currentPage != totalPages) p = totalPages;
			else p = -1;
			break;
		default: 
			p = Number( param );
			if (p < 1 || p > totalPages) p = -1; 
			break;
	}
	if (p != -1) getResults( p );
}

function getCloud() {
	var container = $("#tagcloud div.block-middle-center");
	container.empty();
	$("#tagcloud").removeClass("hidden");
	clone = $('#loading-blue-template div.loading').clone();
	container.append(clone);
	$.post(
		"/annuaire/getcloud.php", 
		{
			json: searchExp,
			words: numCloudWords
		},
		function(data, textStatus){
			container.empty();
			var randomizer = new Array();
			for (i=0; i<data.cloud.length; i++) {
				t = Math.round(Math.random() * (data.cloud.length - 1) );
				while (inArray(t, randomizer)) {
					t = Math.round(Math.random() * (data.cloud.length - 1) );
				}
				clone = $('#word-template div.word').clone(true);
				clone.html(data.cloud[t].word);
				clone.css("font-size", (cloudWordsSizeStart + -(t - numCloudWords) * cloudWordsSizeVariance)  + "%");
				/*opacity = ( 100 - (Math.floor( 60 / numCloudWords ) * t) ) / 100;
				clone.css("opacity", opacity);*/
				container.append(clone);
				container.append(" ");
				randomizer[i] = t;
			}				
		}, 
		"json"
	);
}

function inArray( value, a ) {
	for (i=0; i<a.length; i++) {
		if (a[i] == value) return true;
	}
	return false;
}

function setNavigation( cp, tp, container ) {
	currentPage = Number(cp);
	totalPages = Number(tp);
	nav = $('#result-navigation-template div.result-navigation').clone(true);
	nav.find("span.numpage").html(currentPage);
	nav.find("span.numpages").html(totalPages);
	if (currentPage == 1) {
		nav.find("img.first").addClass("inactive");
		nav.find("img.previous").addClass("inactive");
	}
	if (currentPage == totalPages) {
		nav.find("img.next").addClass("inactive");
		nav.find("img.last").addClass("inactive");
	}
	$(container).empty().append(nav);
}

function getResults( p ) {
	$("#results").empty();
	clone = $('#loading-template div.loading').clone();
	$("#results").append(clone);
	$.post(
		"/annuaire/search.php", 
		{
			json: searchExp,
			page: p 
		},
		function(data, textStatus){
			$("#results").empty();	
			if (data.etablissements.length > 0) {
				setNavigation( data.page, data.total, "#results-navigation-top" );
				setNavigation( data.page, data.total, "#results-navigation-bottom" );	
				for (i in data.etablissements) {
					clone = $('#result-template div.result').clone(true);
					clone.attr("reference", data.etablissements[i].cle);
					clone.find(".cles-formations").text(data.etablissements[i].cles_formations);
					clone.find(".result-content").html(data.etablissements[i].description);
					var statut = "";
					switch (data.etablissements[i].statut) {
						case "Pu":
							statut = "Public";
							break;
						case "Pr":
							statut = "Priv&eacute;";
							break;
						case "Prc":
							statut = "Priv&eacute; sous contrat";
							break;
						case "Co":
							statut = "Consulaire";
							break;
					}
					clone.find(".result-status-statut span").html(statut);
					clone.find(".result-status-academie span").html(data.etablissements[i].academie);
					clone.find(".result-status-formations span").html(data.etablissements[i].total);
					clone.find(".matching-text span.match").html(data.etablissements[i].formations);
					var diff = Number(data.etablissements[i].total) - Number(data.etablissements[i].formations);
					if (diff > 0) {
						clone.find(".not-matching-text span.not-match").html(diff);
					}
					else {
						clone.find(".not-matching").addClass("hidden");
					}
					$("#results").append(clone);
					getFormations(data.etablissements[i].cle, true);
				}
			} else {
				setNavigation( 1, 1, "#results-navigation-top" );
				setNavigation( 1, 1, "#results-navigation-bottom" );
				clone = $('#no-result-template div.no-result').clone(true);
				$("#results").append(clone);	
			}			
		}, 
		"json"
	);
}

function getFormations( etb, inc ) {
	var path = inc ? "" : "not-";
	$("#results div.result[reference='" + etb + "'] div." + path + "matching-results-content").empty();
	clone = $('#loading-template div.loading').clone();
	$("#results div.result[reference='" + etb + "'] div." + path + "matching-results-content").append(clone);
	$.post(
		"/annuaire/getlist.php", 
		{
			etb: etb,
			cles: $("#results div.result[reference='" + etb + "'] div.cles-formations").text(),
			include: inc 
		},
		function(data, textStatus){
			var currentNiveau = "";
			var niv = "";
			var container = $("#results div.result[reference='" + etb + "'] div." + path + "matching-results-content");
			container.empty();		
			for(i in data.formations) {
				if (currentNiveau != data.formations[i].niveau) {
					if (currentNiveau != "") container.append(niv);
					niv = $('#formation-niveau-template div.formation-niveau').clone(true);
					niv.find(".niveau-title").html(data.formations[i].niveau);
					currentNiveau = data.formations[i].niveau;
				}
				clone = $('#formation-template div.formation').clone(true);
				clone.find(".title").attr("reference", data.formations[i].cle).html(data.formations[i].titre);
				clone.find(".content").html(data.formations[i].description).hide();
				clone.find(".addtocart").hide();
				niv.find(".niveau-content").append(clone);
			}
			container.append(niv);
		}, 
		"json"
	);	
}

function getCart( reference, action ) {
	$.post(
		"/annuaire/getcart.php", 
		{
			add: (action == 'add') ? reference : null,
			remove: (action == 'remove') ? reference : null
		},
		function(data, textStatus){
			container = $("#mycart div.cart-selection");
			container.empty();
			if (data.cart.length > 0) {
				for(i in data.cart) {
					if (data.cart[i] != "") {
						clone = $("#cart-item-template div.cart-item").clone(true);
						clone.find(".cart-item-content").html(data.cart[i]);
						container.append(clone);						
					}
				}
			}
		}, 
		"json"
	);
}

function suggest( b ) {
	var input = $('#qs-' + b);
	if ( input.val().length >= minLength) {
		$.post(	'/annuaire/suggest.php', 
			{ q: input.val() },
			function( data ) {
				$('#suggestions').empty().slideUp('fast');
				clone = $('#suggestion-close-template div.suggestion-close').clone();
				$('#suggestions').append(clone);
				if (data.count < maxDisplay && data.count != 0) {
					suggestionGroup = '';
					var g = 0;
					for(var i in data.results) {
						if ( suggestionGroup != data.results[i].source ) {
							g++;
							parity = (g % 2 == 1) ? 'odd' : 'even';
							suggestionGroup = data.results[i].source;
							group = $('#suggestion-group-template div.suggestion-group').clone();
							group.addClass(data.results[i].source + ' ' + parity);
							$('#suggestions').append(group);
						}						
						clone = $('#suggestion-template div.suggestion').clone();
						clone.find('.keyword').html(highlightWords(data.results[i].libelle, data.words));
						clone.find('.source').html(data.results[i].source);
						clone.attr('reference', data.results[i].id);
						setResultListeners(clone);
						group.append(clone);
					}				
				} else {
					clone = $('#count-template div.error').clone();
					$('#suggestions').append(clone);
				}
				$('#suggestions').slideDown('fast');
			},
			'json'
		);
	} else {
		$('#suggestions').empty().addClass('hidden');
	}
}

function createFilter( value ) {
	clone = $("#smart-search-filter-template div.smart-search-filter").clone();
	boxes++;
	currentbox = boxes;
	clone.find("input")
		.attr("id", "qs-" + boxes)
		.attr("name", "qs-" + boxes)
		.attr("value", value)
		.attr("reference", "autre" )
		.addClass("active")
		.bind("keyup", function( e ) { keyUp( $(this), e ); });
	$("#smart-search-box").append( clone );
	$("#qs-" + boxes)
		.trigger("focus")
		.bind('keyup', function( e ) {
			if (e.keyCode != 13) {
				if ( $(this).val().length >= minLength ) {
					window.clearTimeout(timer);
					timer = setTimeout("suggest('" + boxes + "')", suggestDelay);
				} else {
					$('#suggestions').empty().hide();
				}
			}
		});
	}

function lockFilter( o ) {
	p = o.parents(".smart-search-filter");
	p.find("input").removeClass("active");
	p.find("div.input").html( o.val() );
	p.bind("mouseover", function( e ) { mouseOver( $(this), e ); });
	p.bind("mouseout", function( e ) { mouseOut( $(this), e ); });
	p.find("div.editable").addClass("hidden");
	p.find("div.locked").removeClass("hidden");
	p.find(".remove-filter").bind("click", function( e ) { removeFilter( $(this) ); });
}

function removeFilter( o ) {
	p = o.parents(".smart-search-filter");
	p.remove();
	$("input.active").trigger("focus");
}

function keyUp( o, e ) {
	switch( e.keyCode ) {
		case 13:
			
			break;
		case 188:
		case 190:
			if ( o.val().length > 1 ) {	
				o.val( o.val().replace(/[;,]+/, "") );
				lockFilter( o );
				createFilter( "" );
			}
			break;
		default:
			if ( $(this).val().length >= minLength ) {
				window.clearTimeout(timer);
				timer = setTimeout("suggest('" + boxes + "')", suggestDelay);
			} else {
				$('#suggestions').empty().hide();
			}
			break;
	}
}

function mouseOver( o, e ) {
	o.addClass("highlight");
	o.find(".functions").removeClass("hidden");
}

function mouseOut( o, e ) {
	o.removeClass("highlight");
	o.find(".functions").addClass("hidden");
}

function setResultListeners( e ) {
	e.bind('mouseover', function() { 
		e.addClass('highlight'); 
	});
	e.bind('mouseout', function() { 
		e.removeClass('highlight'); 
	});
	e.bind('click', function() { 
		source = e.find(".source").html();
		if (source != "autre") {
			$("input.active").attr("value",  e.find(".keyword").text() );
			$("input.active").attr("reference", source );			
			lockFilter( $("input.active") );
			createFilter( "" );
			autoSuggestClose();
		} else {
			
		}
	});
}

function autoSuggestClose() {
	$('#suggestions').slideUp('fast');
}

function highlightWords(input, words) {
	var buffer = '';
	for( i=0; i<words.length; i++) {
		buffer += words[i];
		if (i < words.length - 1) buffer += ')|(';
	}
	var reg = new RegExp('((' + buffer + '))', 'gi');
	var output = input.replace( reg, '<span class="highlight-word">$1</span>')	
	return output;
}


$(document).ready(function(){
	$("form#action").bind("submit", function() {
		return false;
    });
	
	$("#smart-search-box").bind("click", function() {
		$("form#action input.active").trigger("focus");
    });
	
	$("#smart-search-validation").bind("click", function() {
		search( $(this).attr("reference") );
    });
	
	$(".result .display").bind("click", function() {
		var o = $(this);
		if (o.hasClass("expanded")) {
			o.removeClass("expanded");
			$(this).parents("div.result").find(".not-matching-results-content").empty();			
		}  else {
			o.addClass("expanded");	
			getFormations( $(this).parents("div.result").attr("reference"), false );		
		}
    });
	
	$(".formation div.title").bind("click", function() {
		var o = $(this).siblings(".content");
		if (o.hasClass("expanded")) {
			o.fadeOut("fast").removeClass("expanded");			
		}  else {
			o.fadeIn("fast").addClass("expanded");			
		}
		var o = $(this).siblings(".addtocart");
		if (o.hasClass("expanded")) {
			o.fadeOut("fast").removeClass("expanded");			
		}  else {
			o.fadeIn("fast").addClass("expanded");			
		}
    });
	
	$(".formation div.addtocart").bind("click", function() {
		var ref = $(this).siblings(".title").attr("reference");
		getCart( ref, 'add' );
    });
	
	$("div.word").bind("click", function() {
		var t = $(this).text();
		$("input.active").attr("value",  t );
		$("input.active").attr("reference", "autre" );			
		lockFilter( $("input.active") );
		createFilter( "" );
		autoSuggestClose();
		search();
    });
	
	$("img.first")
		.bind("click", function() { if ( !$(this).hasClass("inactive") ) goTo("first"); })
		.bind("mouseover", function(){ if ( !$(this).hasClass("inactive") ) $(this).attr("src", "/extension/ezwebin/design/ezwebin/images/v2/fleche-gauche-fast.gif"); })
		.bind("mouseout", function(){ if ( !$(this).hasClass("inactive") ) $(this).attr("src", "/extension/ezwebin/design/ezwebin/images/v2/fleche-gauche-fast.gif"); });
	$("img.previous")
		.bind("click", function() { if ( !$(this).hasClass("inactive") ) goTo("previous"); })
		.bind("mouseover", function(){ if ( !$(this).hasClass("inactive") ) $(this).attr("src", "/extension/ezwebin/design/ezwebin/images/v2/fleche-gauche.gif"); })
		.bind("mouseout", function(){ if ( !$(this).hasClass("inactive") ) $(this).attr("src", "/extension/ezwebin/design/ezwebin/images/v2/fleche-gauche.gif"); });
	$("img.next")
		.bind("click", function() { if ( !$(this).hasClass("inactive") ) goTo("next"); })
		.bind("mouseover", function(){ if ( !$(this).hasClass("inactive") ) $(this).attr("src", "/extension/ezwebin/design/ezwebin/images/v2/fleche-droite.gif"); })
		.bind("mouseout", function(){ if ( !$(this).hasClass("inactive") ) $(this).attr("src", "/extension/ezwebin/design/ezwebin/images/v2/fleche-droite.gif"); });
	$("img.last")
		.bind("click", function() { if ( !$(this).hasClass("inactive") ) goTo("last"); })
		.bind("mouseover", function(){ if ( !$(this).hasClass("inactive") ) $(this).attr("src", "/extension/ezwebin/design/ezwebin/images/v2/fleche-droite-fas.gift"); })
		.bind("mouseout", function(){ if ( !$(this).hasClass("inactive") ) $(this).attr("src", "/extension/ezwebin/design/ezwebin/images/v2/fleche-droite-fast.gif"); });		
				
	$("#suggestions").hide();
	createFilter( "" );
	getCart();
	
	$("#printme").bind("click", function() {
		$("#printselection").removeClass("hidden");
		$("#printiframe").attr("src", "/annuaire/print.php");
	});
});
