// plugin linkSubmit: pour qu'au click sur un lien, on soumette le formulaire du bandeau
(function($) {
	var methods = {

		// main function
		init : function(options) {
			$(this).live('click', function(event){
				event.preventDefault ? event.preventDefault() : event.returnValue = false;
				
				if(options.numByPageForm){
					$('#solrForm #numByPageForm').val(options.numByPageForm);
				}
				$('.backUrl').val(window.location.href);
				$('#whatToDisplay').val(options.whatToDisplay);
				
				if($(this).attr('href') == '#'){
					$('#solrForm').attr('action', $("#liste-resultats").attr('href')).submit();
				}else{
					$('#solrForm').attr('action', $(this).attr('href')).submit();
				}
			});
		}		
	};

	$.fn.linkSubmit = function(method) {

		// Method calling logic
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(
					arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist');
		}
	};

})(jQuery);


// plugin pour formulaire de recherche avancée
(function($) {

	var methods = {

		// main function
		init : function(options) {
			
			$(options.clickSelector, $(this)).click(function() {
				$(this).submit();
				return false;
			});
			
			$(this).submit(function() {
				$this = $(this);
				
				solrForm = $('#solrForm');
				
				// remove the relevant checkbox of the solrForm
				$('.multiple_advanced', solrForm).remove();

				$(':input', $this).each(function () {
					var field = $(this);
					var fieldName = field.attr('name');
					targetName = fieldName.replace(/\[advanced\]/i, '');
					target = $('input[name="'+targetName+'"]', solrForm);
					var type = this.type.toUpperCase();
//console.log(targetName);
//console.log(target);
//console.log(type);
					
					switch(type)
					{
						case 'TEXT':
							target.val(field.val());
							break;
							
						case 'CHECKBOX':
							target.attr('checked', field.attr('checked'));
							
							// case audio-video
							if(field.attr('name') == 'tx_cfwbmahefrontend_pi1[advanced][format][0]') {
								$('input[name="tx_cfwbmahefrontend_pi1[format][1]"]', solrForm).attr('checked', field.attr('checked'));
							}
							break;
							
						case 'SELECT-ONE':
							if(field.val()) {
								var newInput = $(document.createElement("input")).attr({
								                	name:  targetName,
								                    value: field.val(),
								                    type:  'text'
								                    //class:  'multiple_advanced'
								                });
								$(newInput).addClass('multiple_advanced');
								
								/*solrForm.append(
										$(document.createElement("input")).attr({
						                	name:  targetName,
						                    value: field.val(),
						                    type:  'text',
						                    class:  'multiple_advanced'
						                })
						        );*/
								solrForm.append(newInput);
							}
							break;
					}
				});				
			
				if(options.callback) options.callback();
				
				return false;
			});
		}		
	};

	$.fn.copyFormFieldToBandeau = function(method) {

		// Method calling logic
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(
					arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist');
		}
	};

})(jQuery);

jQuery(document).ajaxStart(function() {
	
	if($('#whatToDisplay').val() != 'GEOGRAPHIE' ){
		$('#ajaxError').hide();
		//$('#loading').show();
		$.blockUI({ 
	        message: $("#loading").html(), 
	        css: { 
	            /*top:  ($(window).height() - 500) /2 + 'px', 
	            left: ($(window).width() - 500) /2 + 'px', 
	            height: '250px'*/
	             
	        } 
	    });
	}
	 
}).ajaxStop(function() {
	//$.blockUI.remove();
	$('#loading').hide();
	setTimeout($.unblockUI, 1);
	//alert("stop");
})


	
	

$(document).ready(function(){
	
	// remvove click on all link in the bandeau
	$('div.search-toolbar a').click(function(event) {
		event.preventDefault ? event.preventDefault() : event.returnValue = false;
	});

	// Activate ajax submit on solr form
	solrFormoptions = { 
//        target:        '#output1',   // target element(s) to be updated with server response 
//        beforeSubmit:  showRequest,  // pre-submit callback 
//        success:       showResponse  // post-submit callback 
 
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
		data: {
			eID: 'tx_cfwbmahefrontend_pi1'
		},
		
		success: function(data) {
			countByCategories = data.countByCategories; 
			
			
			// update html
			//$('.main-content').html(data.html);
			switch(data.what_to_display){
				
				case 'GEOGRAPHIE':
					//console.debug(data);
					if(!data.reloadCountCat){
						$('#gmapmarker div').html(data.html);
						/*tab = [
						       new GInfoWindowTab('', data.html),
						       ];
						
						map.updateInfoWindow(tab);*/
					}else{
						googleMap(data);
					}
					break;
					
				case 'LIGNE_TEMPS_DETAIL':
					$('.main-content').html(data.html);
					applyTimeline();
					break;
					
				case 'RECHERCHE':
					$('.main-content > div:first').html(data.html);
					break;
					
				default:
					$('.main-content').html(data.html);
					break
		
			}
			if(data.reloadCountCat){
				// update count for each format
				$('#audioVideoCount').html(countByCategories.OBJET_FORMAT_AUDIO_VIDEO);
				$('#objetCount').html(countByCategories.OBJET_FORMAT_OBJET);
				$('#ouvrageCount').html(countByCategories.OBJET_FORMAT_OUVRAGE);
				$('#imageCount').html(countByCategories.OBJET_FORMAT_IMAGE);

			}
			
			initPageBrowser();
		}
    }; 
	
	// soumission du formulaire sur click des "big buttons"
	$('div.search-toolbar a.big-buttons').click(function(event) {
		event.preventDefault ? event.preventDefault() : event.returnValue = false;
		$('#solrForm #whatToDisplay').val('');
		resetSolrForm();
		
		if($(this).attr('id') == 'ligne-du-temps' && $('#periode_map').val()){
			$('#periode').val($('#periode_map').val());
			$('#solrForm #whatToDisplay').val('LIGNE_TEMPS_DETAIL');
			url = $('#ligne-du-temps-detail').val() + '&tx_cfwbmahefrontend_pi1[original_periode]='+$('#periode_map').val();
		}else{
			url = $(this).attr('href');
		}
		
		$('#solrForm').attr('action', url).submit();
	});
	
	//Active recherche simple
	//$('#advanced-search a').click();
	
	// update solr form en fonction du choix de format
	$('div#indications a').click(function() {
		$this = $(this);
		$.blockUI({ 
	        message: $("#loading").html(), 
	    });
		// add actif class
		$this.toggleClass('actif');
		
		// update form element
		if($this.attr('id') == 'audio-video') {
			formElementId = '#audioForm,#videoForm';
		} else {
			formElementId = '#'+$this.attr('id')+'Form'; 
		}
		$(formElementId).attr('checked', $this.hasClass('actif')  ? true : false);
		
		if($('#whatToDisplay').val() == 'BANDEAU'){ //Pour la gestion du bandeau sur toutes les pages
			$('#whatToDisplay').val('LISTE'); 
		}
		
		resetMapXY();
		
		if($('#whatToDisplay').val() == 'LISTE' || $('#solrForm #numByPageForm').val() < 10){
			$('#solrForm #numByPageForm').val(10);
		}
		// submit the form
		$('#solrForm').ajaxSubmit(solrFormoptions);
	});
	
	if($('#whatToDisplay').val() == 'RECHERCHE'){
		$('#form2').copyFormFieldToBandeau({
			clickSelector: '#search_box_simple',
			callback: function(){
				
			}
		});
	}
	
	// on click on search button, update search-word and submit hidden form
	$('div#search-box img').click(function() {
		if($('#whatToDisplay').val() == 'RECHERCHE'){
			$('#form2').submit();
			if(!$('#periode').val()){
				$('#periode_map').val('');
			}
		}
		
		$('#searchWordForm').val($('div#search-box input.search-field').val());
		resetSolrForm();
		$('#solrForm').ajaxSubmit(solrFormoptions);
	});	
	
	
	$('div#search-box input').keypress(function(event){
		if(event.which == 13){
			$('#searchWordForm').val($('div#search-box input.search-field').val());
			
			if($('#whatToDisplay').val() == 'BANDEAU' || $('#whatToDisplay').val() == 'DETAIL'){ //Pour la gestion du bandeau sur toutes les pages
				$('#whatToDisplay').val('LISTE');
				$('#solrForm').attr('action', $("#liste-resultats").attr('href'));
				$('#solrForm').submit();
			}else{
				resetSolrForm();
				$('#solrForm').ajaxSubmit(solrFormoptions);
			}
		}
	});
	
	// lien recherche avancée
	$('#advanced-search a:first').click(function(event) {
		event.preventDefault ? event.preventDefault() : event.returnValue = false;
		if(!$(this).hasClass('simpleSearch')){
			$('#whatToDisplay').val('RECHERCHE');
			resetSolrForm();
			$('#solrForm').attr('action', $(this).attr('href')).submit();
		}
	});
	
	// page browser
	initPageBrowser();
	
	function resetSolrForm()
	{
		//$('#loading').show();
		if($('#whatToDisplay').val()){
			$.blockUI({ 
		        message: $("#loading").html(), 
		    });
		}
		$('#solrForm #pageForm').val(0);
		$('#solrForm #numByPageForm').val(10);
		if($('#whatToDisplay').val() != 'LIGNE_TEMPS_DETAIL'){
			$('#solrForm #periode').val('');
		}		
		resetMapXY();
	}
	
	function resetMapXY(){
		$('#solrForm #latitude').remove();
		$('#solrForm #longitude').remove();
		$('#solrForm #pageForm').val(0);
	}
	
	function googleMap(data){
		map.clearOverlays();
		var infoBulles = [];
//console.log(data);	
		//console.log('length '+data.html.points.length);
		var nbNormPoint = 0;
		for(var i=0;i<data.html.points.length;i++){
			var point = new GLatLng(data.html.points[i]['lat'],data.html.points[i]['lon']);
			infoBulles[i] = data.html.points[i]['html'];
			if(data.html.icons[i]['labelText']!=1){
				var icon = new GIcon();
				icon.image = data.html.icons[i]['image'];
				icon.iconSize = new GSize(44,57);
				icon.iconAnchor = new GPoint(data.html.icons[i]['iconAnchorX'],data.html.icons[i]['iconAnchorY']);
				icon.infoWindowAnchor = new GPoint(data.html.icons[i]['infoWindowAnchorX'],data.html.icons[i]['infoWindowAnchorY']);
				
				var opt = {
						"icon": icon,
						"clickable": true,
						"labelText": data.html.icons[i]['labelText'],
						"labelOffset": new GSize(data.html.icons[i]['labelOffsetX'],data.html.icons[i]['labelOffsetY'])
				};
				/*marker = new LabeledMarker(point,opt);
				
				GEvent.addListener(marker,"click",function(){
					marker.openInfoWindowHtml(infoBulles[i]);
				});*/
				
				createLabelMarker(point,opt,infoBulles[i]);
			}else{
				//console.log('toto');
				/*var marker = createMarker(point,data.html.points[i]['title'],i, "",data.html.points[i]['tooltip']);
				GEvent.addListener(marker,"click",function(){
					marker.openInfoWindowHtml(infoBulles[i]);
				});*/
				var icon = new GIcon();
				icon.image = data.html.icons[i]['image'];
				icon.iconSize = new GSize(20,36);
				icon.iconAnchor = new GPoint(10,18);
				icon.infoWindowAnchor = new GPoint(data.html.icons[i]['infoWindowAnchorX']/5,data.html.icons[i]['infoWindowAnchorY']);
				
				var markerOptions = {
						icon: icon,
				}
				
				createSimpleMarker(point,markerOptions,infoBulles[i]);

				nbNormPoint++;
			}
			
			//map.addOverlay(marker);
		}
		
		var bds = new GLatLngBounds(new GLatLng(data.html.map.minLat, data.html.map.minLon), new GLatLng(data.html.map.maxLat, data.html.map.maxLon));
		var newZoom = map.getBoundsZoomLevel(bds);
		if(newZoom > 11){
			newZoom = 11;
		}
		if(data.html.map.centerLat != null && data.html.map.centerLon != null){
			map.setCenter(new GLatLng(data.html.map.centerLat,data.html.map.centerLon),newZoom);
		}else{
			map.setCenter(new GLatLng(50.5257076,4.0621017),8);
		}
		
	//console.log(data.html.total_count);
		$('#countResult').html(data.html.total_count);
		if($('#critereSearch').html() == ''){
			$('.rslCrit').show();
			$('#critereSearch').html(data.html.critereSearch);
		}else{
			$('#critereSearch').html(data.html.critereSearch);
		}		
	}
	
	function createLabelMarker(point,opt,infoBulle){
		var marker = new LabeledMarker(point,opt);
		
		GEvent.addListener(marker,"click",function(){
			var opts = {
					onOpenFn: function(){
						
						var myInfoWindow = map.getInfoWindow();
						var point = myInfoWindow.getPoint();
						
						
						$("#solrForm #numByPageForm").val(1);
						$("#solrForm #pageForm").val(0);
						$("#solrForm #latitude").remove();
						$("#solrForm #longitude").remove();
						$("#solrForm").append('<input id="latitude" name="tx_cfwbmahefrontend_pi1[latitude]" value="'+point.lat().toFixed(7)+'"/>');
						$("#solrForm").append('<input id="longitude" name="tx_cfwbmahefrontend_pi1[longitude]" value="'+point.lng().toFixed(7)+'"/>');
						
						$("#solrForm").ajaxSubmit(solrFormoptions);
					}
			}
			marker.openInfoWindowHtml(infoBulle,opts);
		});
		
		map.addOverlay(marker);
	}
	
	function createSimpleMarker(point,markerOptions,infoBulle){
		var marker = new GMarker(point,markerOptions);
		
		GEvent.addListener(marker,"click",function(){
			var opts = {
					onOpenFn: function(){
						
						var myInfoWindow = map.getInfoWindow();
						var point = myInfoWindow.getPoint();
						
						
						$("#solrForm #numByPageForm").val(1);
						$("#solrForm #pageForm").val(0);
						$("#solrForm #latitude").remove();
						$("#solrForm #longitude").remove();
						$("#solrForm").append('<input id="latitude" name="tx_cfwbmahefrontend_pi1[latitude]" value="'+point.lat().toFixed(7)+'"/>');
						$("#solrForm").append('<input id="longitude" name="tx_cfwbmahefrontend_pi1[longitude]" value="'+point.lng().toFixed(7)+'"/>');
						
						$("#solrForm").ajaxSubmit(solrFormoptions);
					}
			}
			
			marker.openInfoWindowHtml(infoBulle,opts);
		});
		
		map.addOverlay(marker);
	}
	
	function initPageBrowser()
	{
		//pageBrowser: update the page
		$('.pager a.page').click(function(event) {	
			event.preventDefault ? event.preventDefault() : event.returnValue = false; 
			$('#pageForm').val($(this).attr('href'));
			$('#solrForm').ajaxSubmit(solrFormoptions);
		});
		
		//pageBrowser: update the num by page
		$('.pager a.num_by_page').click(function(event) {	
			event.preventDefault ? event.preventDefault() : event.returnValue = false;
			$('#solrForm #pageForm').val(0);
			$('#numByPageForm').val($(this).attr('href'));
			$('#solrForm').ajaxSubmit(solrFormoptions);
		});
	}
});
