/**
 * + mmEdit is a wrapper object :
 *   it acts as a singleton ( http://www.dustindiaz.com/add-remove-elements-reprise/ )
 * 	 and gives namespaces   ( http://www.dustindiaz.com/namespace-your-javascript/ )
 *   it brings few globals vars and methods too.
 *
 * + the edition workflow process is divided into steps :
 *   - each steps corresponds to a panel that we have to hide/show
 *   - we also need to init events in each panels
 *
 * + mmEdit core object is divided into 3 objects (each is a singleton ) :
 *   - "step" manages the edition steps ( going from a step to another step)
 *
 * 			- each workflow step correponds to a method of this object, for example :
 * 				- the startEdition step corresponds to the step.startEdition method
 *        - the stopEdition step corresponds to the step.stopEdition method
 *        - endMarkerEdit step corresponds to the step.endmarkerEdit method
 * 				- ...
 *
 *   - "display" manages the show/hide of each panel and events init
 *
 * 			- each workflow step corresponds 2 methods : show and hide.
 * 				these methods name is set like this : 'show + StepName + 'Bloc' and 'hide' + StepName + 'Bloc'
 * 				so the 'startEdition' step have a 'showStartEditionBloc' and a 'hideStartEditonBloc' methods
 * 				and the 'endmarkerEdit' step have a 'showEndMarkerEditBloc' method a 'hideEndMarkerEditBloc' method
 *
 * 	 - "utils" contains some methods mostly used by the 'display' object
 *
 *
 * + We have to specify 3 types/mode of workflow
 *   - "normal" : when we access workflow from the 'lieu' button
 *   - "extra"  : when we access workflow from the "contenu" button
 *   - "consult": when we access workflow from the marker pan
 *
 * + public / private vars and methods inside mmEdit :
 *   - all mmEdit globals properties are publics ( those defined directly in mmEdit )
 *   - for each object/subclass (step, display, utils):
 * 	   - publics properties (vars and methods) are prefixed with the 'this' keyword'
 *     - private properties (vars and methods) are prefixed with the 'var' keyword.
 *
 * + 'self = this' when calling 'this' inside a closure
 *
 *  hope it's clear enough...
 */


var mmEdit = window.mmEdit = {

	//namespaces
	step    : {},
	utils   : {},
	display : {},

	//other globals properties
	displayed: false,              // is edition pan displayed ?
	currentStep: null,             //current workflow step
	lastStep: null,                // last workflow step
	storage: $('#bt-create'),      // element where to store edition data
	consultationBlocs: [$("#pan-pub"), $("#pan-sel")],


  /**
   * set workflow mode
   */

  setWorkflow : function(mode){
		this.storage.data('workflow', mode);
  },


  /**
   * get workflow mode
   */

  getWorkflow : function(){
  	return this.storage.data('workflow');
  },


	/**
   * set lastStep and currentStep
   */

  setEditionStep : function(step){
    if(this.currentStep){
    	this.lastStep = this.currentStep;
    }
    this.currentStep = step;
  }

}; //mmEdit ends here



/**
 * mmEdit.step
 */

mmEdit.step = new function step(){

	var self = this;

	/**
	 *  startEdition
	 *  show first step edition bloc
	 *  used for all worklow (normal, extra, consult)
	 */

	this.startEdition = function(blocs){

      // close all other pans
      $pan2nd.hide();
      $panMar.hide();
      $panMar.data('marId', '0');
      $panMed.hide();
      $('a', $mainMenu).toggleClass('active', false);

      // we have to check we are not already in edition ( from the 'consult' mode)
      if(mmEdit.getWorkflow() == 'consult'){
      	 this.stopEdition();
      }

      // checkAuth
		  $.post('private2/checkAuth', function(response){
	     response = eval("(" + response + ")");
		    switch(response.status){
		     case "success":
            // hide pan-sel if needed, we may access this bloc from endMapEdit or EndMarkerEdit
		        if(blocs){
		          $.each(blocs, function(i, bloc){bloc.hide();});
		        }
			      // display first step edition bloc
			      mmEdit.setWorkflow(null); //reset workflow
						mmEdit.setEditionStep('startEdition');
			      self.changeStep();
			      mmEdit.displayed = true;

			      // mmGeo.desactivateConsultation();

			   break;
			   case "failure":
				   showMsgBox('notauth');
				   return false;
			   break;
		    }

      },'json');
	};


	/**
	 * stopEdition
	 * cancel edition process
	 * used for all workflow mode
	 */

	this.stopEdition = function(blocs){

		  //clear session data
		  $.post('private2/clearSessionData');

		  //clear DOM data
		  mmEdit.utils.clearStoredData();

      //check for binded events
      if(mmEdit.currentStep != null){
      	mmEdit.display['hide' + mmEdit.utils.capitalize(mmEdit.currentStep) + 'Bloc']();
      }

			//remove geolocatemarker if needed
      mmEdit.utils.removeGeolocateMarker();

      //clear edition steps values
      mmEdit.currentStep = null;
      mmEdit.lastStep = null;
      mmEdit.displayed = false;

      //hide editin bloc and display selected map bloc
      $('#pan-create').hide();
      $.each(mmEdit.consultationBlocs, function(i, bloc){bloc.show();});

//      mmGeo.activateConsultation();
	};


	/**
	 * first step of map edition
	 * used for the map creation workflow
	 */

	this.mapEdit = function(){
	 mmEdit.lastStep = (mmEdit.getWorkflow() == "extra")? 'mapChoice' : 'startEdition';
	 mmEdit.currentStep = 'mapEdit';
   this.changeStep();
	};


	/**
	 * user have to select a map to put a marker/media inside
	 * used for normal and extra
	 */

	this.mapSelect = function(){
	 mmEdit.setEditionStep("mapSelect");
	 this.changeStep();
	};


	/**
	 *  geolocate a marker/media
	 *  used fo normal and extra
	 */

	this.geolocate = function(){
	  if(mmEdit.getWorkflow() == 'normal'){
	  	mmEdit.lastStep = 'mapSelect';
	  }
	  else if(mmEdit.getWorkflow() == 'extra'){
	  	mmEdit.lastStep = 'markerChoice';
	  }
	  mmEdit.setEditionStep("geolocate");
		this.changeStep();

	};


	/**
	 * a user have to choose for a type of media
	 * used in all workflow
	 */

	this.contentSelect = function(){
	  if(mmEdit.getWorkflow() == 'consult') mmEdit.lastStep = 'endMarkerEdit';
	 	mmEdit.setEditionStep("contentSelect");
		this.changeStep();
	};


	/**
	 * user edit a media
	 * used in all workflow
	 */

	this.contentEdit = function(response){
    mmEdit.setEditionStep("contentEdit");
		this.changeStep(escape(response));
	};


	/**
	 *  user choose if media will be add in existing marker of new marker
	 *  used for extra
	 */
	this.markerChoice = function(){
		mmEdit.lastStep = "contentEdit";
		mmEdit.setEditionStep("markerChoice");
		this.changeStep();
	};

	/**
	 * user choose an existing marker in a list to put the media inside
	 * used for extra
	 */
	this.markerSelect = function(){
		mmEdit.lastStep = "markerChoice";
		mmEdit.setEditionStep("markerSelect");
		this.changeStep();
	};


	/**
	 * user choose if a marker should be insert in existing map or new map
	 * used for extra
	 */

	this.mapChoice = function(){
		mmEdit.setEditionStep('mapChoice');
		this.changeStep();
	};


	/**
	 * last map edition step
	 */

	this.endMapEdit = function(response){
    mmEdit.setEditionStep("endMapEdit");
		this.changeStep(escape(response));
	};


	/**
	 * last marker edition step
	 * used for all workflow
	 */

	this.endMarkerEdit = function(marker){
		mmEdit.setEditionStep('endMarkerEdit');
		this.changeStep(marker);
	};


  /**
   *  addMediaFromConsultation
   *  add a media in existing marker from the consultation panel
   */

  this.addMediaFromConsultation = function(marId) {

  	//first we stop a current edition process if needed
    if(mmEdit.displayed) {
    	this.stopEdition();
    }

    //store current marker infos and display contentSelect bloc
    $.post('private2/storeMarkerInfosFromConsultation', {markerId: marId}, function(response){
      var response = eval("(" + response + ")");
      if(response.status == "success"){

        //store marker infos in dom
        var markerInfos = {};
        markerInfos.markerTitle = response.message.markerTitle;
        $('#bt-create').data('markerInfos', markerInfos);
        //set workflow mode
        mmEdit.setWorkflow('consult');

        //hide consultation panels and show required edition bloc
        $.each(mmEdit.consultationBlocs, function(i, bloc){bloc.hide();});
        $("#pan-create").show();
        mmEdit.displayed = true;
        //go to contentSelect step
        mmEdit.step.contentSelect();

        //mmGeo.desactivateConsultation(true);

      }else if(response.status == "authFailure"){
      	showMsgBox(response.message);
      	return false;
      }
      else { return false; } // do nothing
    });
  };


  /**
   * changeStep
   * hide lastStep panel
   * show currentStep panel
   */

  this.changeStep = function(prm){
 		if(mmEdit.lastStep) mmEdit.display['hide' + mmEdit.utils.capitalize(mmEdit.lastStep) + 'Bloc']();
    mmEdit.display['show' + mmEdit.utils.capitalize(mmEdit.currentStep) + 'Bloc'](prm);
  };

}; //mmEdit.step ends here



/**
 * mmEdit.utils
 */

mmEdit.utils = new function utils () {
	//private
  var step = mmEdit.step;
  var contentInfos = {};         //media data
  var self = this;

  //publics
  this.geolocateEvent = null;    //event
  this.geolocateMarker = null;     //the marker that will be dragged on the map for geolocation step
  this.mapEvent= null;           //event


  /**
   * set media title and desc.
   */

  this.contentPreValidation = function(){
    contentInfos.title = $('#title').val();
    contentInfos.description = $('#description').val();
  };


  /**
   *  media pre-insertion action
   *  get the type of media
   *  set action according to the media type
   */

	this.prepareInsertContent = function(){
		//get the contentType
		var contentType = parseInt($('#bt-create').data('contentType'));
		//forward to corresponding action
		switch(contentType){
			case 1:
			 this.prepareInsertFile(contentType);
			break;
			case 2:
			 this.prepareInsertEmbedVideo();
			break;
			case 3:
			 this.prepareInsertFile(contentType);
			break;
			case 4:
			 this.prepareInsertText();
			break;
			case 5:
			 this.prepareInsertRSS();
			break;
		}
	};


  /**
   * prepareInsertEmbedVideo
   */

	this.prepareInsertEmbedVideo = function(){

		this.contentPreValidation();

		var code = $('#code').val();
		var licence = $('#licence').val();

		//set content infos and send them
		var data = {
			           title : contentInfos.title,
			           description: contentInfos.description,
			           code: code,
			           licence: licence,
			           workflow: mmEdit.getWorkflow()
			         };

		$.post('private2/insertEmbedVideo', data, function(response){
  			switch(response.status){
  				case "success":
				 	 if(mmEdit.getWorkflow() == 'extra'){
				 	 		step.markerChoice();
				 	 }else{
				   		step.endMarkerEdit(response.message);
				 	 }
  			  break;
  			  case "failure":
  			   self.setFormError(response.message, '#embed-video-form-error');
  			  break;
  			  case "authFailure":
  			   showMsgBox(response.message);
  			   return false;
  			  break;
  			}
			}, 'json');

	};


 /**
  * prepareInsertFile
  * @see private2/_initAjaxUpload for client validation
  *
  */

	this.prepareInsertFile = function(contentType){
		this.contentPreValidation();
		//get post vars
		var el = contentType == 1 ? "#import-photo-file" : contentType == 3 ? '#import-audio-file' : null;
		$(el).uploadifySettings('scriptData', {'title' : $('#title').val(), 'description': $('#description').val(), 'licence': $('#licence').val(), 'workflow': mmEdit.getWorkflow()});
  		$(el).uploadifyUpload();

	};


 /**
  * prepareInsertText
  */

	this.prepareInsertText = function(){

		this.contentPreValidation();

		var data = {
			title: contentInfos.title,
			description: contentInfos.description,
			workflow: mmEdit.getWorkflow()};

		$.post('private2/insertText', data, function(response){
			 switch(response.status){
			 	case "success":
			 	 if(mmEdit.getWorkflow() == 'extra'){
			 	 		step.markerChoice();
			 	 }else{
			   		step.endMarkerEdit(response.message);
			 	 }
			  break;
			  case  "failure":
			   self.setFormError(response.message, '#text-form-error');
			  break;
        case "authFailure":
         showMsgBox(response.message);
         return false;
        break;
			 }
			}, 'json');

	};


  /**
  * prepareInsertRSS
  */

	this.prepareInsertRSS = function(){

		this.contentPreValidation();

		var data = {title: contentInfos.title, description: contentInfos.description, workflow: mmEdit.getWorkflow()};

		$.post('private2/insertRSS', data, function(response){
	   	 response = eval("(" + response + ")");
			 switch(response.status){
			 	case "success":
			 	 if(mmEdit.getWorkflow() == 'extra'){
			 	 		step.markerChoice();
			 	 }else{
			   		step.endMarkerEdit(response.message);
			 	 }
			  break;
			  case  "failure":
			   self.setFormError(response.message, '#rss-form-error');
			  break;
        case "authFailure":
         showMsgBox(response.message);
         return false;
        break;
			 }
		});

	};


 /**
  * prepareMarkerEditGeolocate
  */

	this.prepareStoreMapInfos = function(){
		var id = $('#user-map-list :selected').val();
		var title = $('#user-map-list :selected').text();
		var workflow = mmEdit.getWorkflow();
		//client validation
		if(id == "" || title == ""){
			return false;
		}

		//store mapId && mapTitle for next step
		mmEdit.storage.data('mapInfos', {mapId: id, mapTitle: title});
		
		// store map ID for reloading content when back to selection pan
		$panSel.data('mapReload', id);

		//store mapInfos in session
		$.post('private2/storeMapInfos', {mapId:id, mapTitle:title, workflow:workflow}, function(response){
			switch(response.status){
			  case 'success':
				  if(workflow == "extra"){
				  	//show endMarkerEdit bloc
				  	step.endMarkerEdit(response.message);
				  }else{
				  	//show geolocate bloc
				  	step.geolocate();
				  }
				break;
				case "failure":
				  self.setFormError(response.message, '#map-form-error');
				break;
				case "authFailure":
			    showMsgBox('vous devez vous (re)connecter');
			    return false;
				break;
			}
		}, 'json');
	};


	/**
	 * prepareMarkerEditContentType
	 */

	this.prepareContentSelect = function(markerTitle){
		//get marker and map infos
		var workflow = mmEdit.getWorkflow();

		var markerInfos = {};
//		if(workflow != "extra") markerInfos.mapTitle = $('#bt-create').data('mapInfos').mapTitle;
//		markerInfos.mapId = $('#bt-create').data('mapInfos').mapId;
		markerInfos.markerTitle = markerTitle;
		markerInfos.markerLat = $('#marker-lat').val();
		markerInfos.markerLon = $('#marker-lon').val();

		//store marker infos in DOM
		$('#bt-create').data('markerInfos', markerInfos);

		//store markerInfos in session
		$.post('private2/storeMarkerInfos', markerInfos, function(response){
		    switch(response.status){
		      case 'success':
		        //next step : show contentntype bloc
						if(workflow == "extra"){
							step.mapChoice();
						}
						else{
		        	step.contentSelect();
						}
		      break;
		      case "failure":
		        self.setFormError(response.message, '#marker-form-error');
		      break;
		      case "authFailure":
	          showMsgBox(response.message);
	          return false;
		      break;
		    }
		}, 'json');

	};


	/**
	 *
	 */

	this.checkLicence = function(){
		alert('test');
	};

	/**
	 * clear all data stored via JQuery.data()
	 */

	this.clearStoredData = function(){
    mmEdit.storage.removeData('mapInfos');
    mmEdit.storage.removeData('markerInfos');
    mmEdit.storage.removeData('contentType');
    mmEdit.storage.removeData('workflow');
	};


	/**
	 * add the marker that will be dragged for geolocation step
	 */

	this.createGeolocateMarker = function(){

   //removemarker if previous needed
   if(this.geolocateMarker)
      this.removeGeolocateMarker();

   this.geolocateMarker = new GMarker(map.getCenter(), {draggable:true});
   this.geolocateEvent = GEvent.addListener(this.geolocateMarker, 'dragend', function(latlng){
      $('#marker-lat').val(latlng.lat());
      $('#marker-lon').val(latlng.lng());
   });

	 this.mapEvent = GEvent.addListener(map, "moveend", function() {
	  var center = map.getCenter();
	  if(self.geolocateMarker){ self.geolocateMarker.setLatLng(center);}
	 });

	 map.addOverlay(this.geolocateMarker);

	};


  /**
   * remove the marker that have been add for geolocation step
   */

  this.removeGeolocateMarker = function(){
  	if(this.geolocateEvent && this.geolocateMarker){
	  	if(this.geolocateEvent) GEvent.removeListener(this.geolocateEvent);
	    map.removeOverlay(this.geolocateMarker);
	    this.geolocateMarker = null;
  	}
  };


  /**
   * tinyMCE init
   */

  this.tinyInit = function(){
    $('#description', $panCreate).tinymce({
    // Location of TinyMCE script
    script_url : '/js/tinymce/tiny_mce.js',
    // General options
    theme : "advanced",
    plugins : "safari",
    theme_advanced_buttons1 : "formatselect,bold,italic,bullist,link,unlink,|,removeformat,undo",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_blockformats : "p,h4,h5,h6,blockquote"
    });
  };


  /**
   * create a list of user's marker (to be selected during the extra)
   */

	this.createMarkersList = function(markers){
		var options = "";
		$.each(markers, function(k,v){
			options += '<option value="'+k+'">'+v+'</option>\n';
		});
		$('#marker-form-select').append(options);
	};


	/**
	 * tigger a clik on the last created marker
	 */

	this.triggerMarker = function(marker){
		var delay = 1200;
		if(!mmGeo.isOverlayed(marker.marId)){ // last edited marker may not be on map
			mmGeo.addTempMarker(marker);
			setTimeout(function(){GEvent.trigger(mmGeo.temp_overlay, 'click');}, delay);
		}else{
			setTimeout(function(){GEvent.trigger(mmGeo.overlayed['marker_'+marker.marId], 'click');}, delay);
		}
	};


	/**
	 * set error message
	 */

  this.setFormError =  function(message, element){
  	if(typeof element != 'undefined')
  	   $(element).html(message);
  	else
      $(".form-error").html(message);
  };


  /**
   * clear errors that would have benn displayed
   */

  this.clearFormError = function(){
    $('.form-error').html('');
  };


  /**
   * capitalize
   */

  this.capitalize = function (string){
		return string.charAt(0).toUpperCase()+string.substr(1);
	};

}; //mmEdit.utils ends here



/**
 * mmEdit.display
 */

mmEdit.display = new function display() {

	 //alias ( we can use alias here as these two subclasses have been already init )
	 var step = mmEdit.step;
	 var utils = mmEdit.utils;
	 var self = this;

	 /**
   * display firt step bloc of the edition process
   * user have to choose between map creation or markaer creation
   */

  this.showStartEditionBloc = function(){

  	$("#pan-create").show();
    $("#create").show();

    //map edition event
    $("#bt-create-map a").bind("click", function(e){
    	  e.preventDefault();
        step.mapEdit();
    });

    //marker edition event
    $("#bt-create-marker a").bind("click", function(e){
        e.preventDefault(e);
        mmEdit.setWorkflow('normal');
        step.mapSelect();
    });

    //media edition event
    $("#bt-create-media a").bind("click", function(e){
        e.preventDefault(e);
        //set default wkf mode and go to next step
        $('#bt-create').data('workflow', 'extra');
        step.contentSelect();
    });

    //cancel event
    $('#cancel-start-edition').bind('click', function(e){
    	e.preventDefault();
    	step.stopEdition();
    });

  };


  /**
   * hide the fisrt step edition bloc
   */

  this.hideStartEditionBloc = function(){
    $("#bt-create-map a").unbind("click");
    $("#bt-create-marker a").unbind("click");
    $("#bt-create-media a").unbind("click");
    $('#cancel-start-edition').unbind('click');
    $("#create").hide();
  };


  /**
    * display the map edition bloc
    * user has selected the map creation step
    * fisrt step of a map edition
   */

  this.showMapEditBloc = function(){

  	  //display a new map edition bloc ( map form )
      $.get('private2/editMap', function(response){

      	  //we may access this bloc from the endMapEditBloc, so we need to clear it
          if($('#create-map-end').is (':visible')){
            self.hideEndMapEditBloc();
          }

		      //put a map form
		      $("#create-map").html(response).show();

		      //cancel map edit event
          $('#bt-form-cancel').bind('click',function(e){
            e.preventDefault();
//            mmInterface.hideMapEditBloc();
            if(mmEdit.getWorkflow() == "extra")
            	step.mapChoice();
            else
            	step.startEdition();
          });

      	}, 'html');
  };


  /**
   * hide the map edition bloc
   */

  this.hideMapEditBloc = function(){
  	  $('#bt-form-cancel').unbind('click');
      $("#create-map").html("");
  };


	/**
	 * display user's map list bloc
	 * fisrt step of a marker edition
	 */

	this.showMapSelectBloc = function(response){
 	 	var extra =  mmEdit.getWorkflow() == "extra" ? true : false;
    $.get('private2/getUserMapList', function(response){
	      $("#create-marker-1").html(response).show();
	      //event back button
	      $('#bt-cancel-map-select').bind('click', function(){
	        //mmInterface.hideMapSelectBloc();
	      	if(extra)
	      		step.mapChoice();
	      	else
	      		step.startEdition();
	      });
	      // event for next step button
	      $('#bt-validate-map-select').click(function(){
           utils.prepareStoreMapInfos();
	      });

    }, 'html');

	};


 /**
  * hide user's map list bloc
  */

 this.hideMapSelectBloc = function(){
	   $('#create-marker-1').html('').hide();
	   $('#bt-cancel-map-select').unbind('click');
     $('#bt-validate-map-select').unbind('click');
 };


 /**
  * show the geolocate step bloc when editing a marker
  * second step of marker edition
  */

 this.showGeolocateBloc = function(){
 	 var extra =  mmEdit.getWorkflow() == "extra" ? true : false;
 	 // create a marker for geolocation and show bloc
 	 utils.createGeolocateMarker();
 	 $('#create-marker').show();

 	 //display map title if needed
 	 if(!extra){
 	 	$('#create-marker').children('p.create-infos').show(); //may be have been hide by a previous extra edition
 	 	$('#map-title-span').html(mmEdit.storage.data('mapInfos').mapTitle);
 	 }else{
 	 		$('#create-marker').children('p.create-infos').hide();
 	 }

 	 //event on cancel button
 	 $('#bt-cancel-geolocate').bind('click', function(e){
	 	 	e.preventDefault();
			utils.removeGeolocateMarker();
			if(extra){
				step.markerChoice();
			}else{
				step.mapSelect();
			}
 	 });

 	 //event on 'next' button
 	 $('#bt-validate-geolocate').bind('click',function(e){
 	 	  e.preventDefault();
	 	 	var markerTitle = $('#marker-title').val();
	 	 	var markerLat = $('#marker-lat').val();
	 	 	var markerLon = $('#marker-lon').val();

	 	 	//check if marker name is empty || client validation
	 	 	if(markerTitle == ""){
	 	 		utils.setFormError('veuillez saisir un titre');
	 	 		return false;
	 	  }else if(markerLat == "" || markerLon ==""){
        utils.setFormError('Il faut déplacer la marque sur la carte.');
        return false;
	 	  }

	 	 	utils.prepareContentSelect(markerTitle);

   });

 };


 /**
  * hide the geolocate step bloc when editing a marker
  */

 this.hideGeolocateBloc = function(){
 	//empty form fieds
	utils.clearFormError();
	$('#create-marker input').val('');
	$('#create-marker').hide();
	$('#bt-cancel-geolocate').unbind('click');
	$('#bt-validate-geolocate').unbind('click');

	if(utils.geolocateMarker){
		utils.geolocateMarker.disableDragging();
		GEvent.removeListener(utils.mapEvent);
	}

 };


 /**
  * show the selection content type bloc when editing a marker
  * user have to select the content type that is going to be insert in the marker
  * third step of marker edition
  */

 this.showContentSelectBloc = function(){
 	var workflow = mmEdit.getWorkflow();

 	$('#create-content-type').show();
 	if(mmEdit.storage.data('markerInfos') && workflow == 'extra'){
 		//fill marker title field
 		$('#create-marker').children('p.create-infos').show(); //may have been hide by a previous extra edition
 		var markerTitle = mmEdit.storage.data('markerInfos').markerTitle;
 		$('#stored-marker-title').html(markerTitle);
 	}else{ //hide marker title
 		$('#create-content-type').children('p.create-infos').hide();
 	}

 	//fix cancel button value if needed
 	if(workflow == 'consult'){
 		$('span','#bt-cancel-content-type').html('annuler');
 	}

	//data source selector event
	var contentTypes = $('.med-src', '#create-content-type').children();

	$(contentTypes).bind('click', function(e, t){
    e.preventDefault();
    //get selected content type and store the value
	  var data = { "contentType": parseInt($(this).text())};
    mmEdit.storage.data('contentType', data.contentType);
    //get media form
    $.post("/private2/getContentType", data, function(response){
    	//showMsgBox("msglic");
    	mmEdit.step.contentEdit(response);
    	}, "html");

	});

	$('#bt-cancel-content-type').bind('click', function(){
		var workflow = mmEdit.getWorkflow();

    if (workflow == 'consult'){
	      step.stopEdition();
		}else if (mmEdit.lastStep == "endMarkerEdit"){
//    	mmInterface.hideContentSelectBloc();
    	step.endMarkerEdit();
    }else if(workflow == 'normal'){
//	  	mmInterface.hideContentSelectBloc();
			step.geolocate();
	  }else if(workflow == 'extra'){
//	  	mmInterface.hideContentSelectBloc();
			step.startEdition();
	  }

	});

 };


 /**
  * hide the selection content type bloc when editing a marker
  */

 this.hideContentSelectBloc = function(){
 	$('.med-src', '#create-content-type').children().unbind('click');
 	$('#bt-cancel-content-type').unbind('click');
  $('#create-content-type').hide();
 };


 /**
  * show content edit bloc when editing marker
  * fourth step of marker edition
  * user have to fill a form correposnding of the type of content
  * that will be inserted with the marker
  */

  this.showContentEditBloc = function(response){

  	var response = unescape(response);
  	$('#create-content').html(response).show();

  	if(mmEdit.getWorkflow() == 'normal'){
  		$('#title').val(mmEdit.storage.data('markerInfos').markerTitle);
  	}

  	$('#bt-cancel-content-edit').bind('click', function(){
  		step.contentSelect();
  	});

  	//now we init event for next step action
  	$('#bt-validate-content-edit').bind('click', function(){
  			$('.uploadifyProgress').css('display', 'block');
    		$('.uploadifyProgressBar').css('display', 'block');
  		  utils.prepareInsertContent();
  	});

  	//init Textarea
  	if($('#bt-create').data('contentType') == 4) utils.tinyInit();

  };

  /**
   *  hide the 'media' edition
   */

  this.hideContentEditBloc = function(){
  	$('#bt-cancel-content-edit').unbind('click');
  	$('#bt-validate-content-edit').unbind('click');
  	//clear content edition bloc
  	$('#create-content').html('').hide();
  };

  /**
   * show last step of map edition
   */

  this.showEndMapEditBloc = function(response){
  	var response = unescape(response);
    $('#create-map-end').html(response).show();

    //create new marker event
    $("#bt-new-marker a").bind("click", function(e){
      e.preventDefault();
      mmEdit.setWorkflow('normal');
      step.mapSelect();
    });

  	//create another map event
    $("#bt-create-another-map a").bind("click", function(e){
    	e.preventDefault();
      step.mapEdit();
    });

    //cancel edition event
    $("#bt-back-to-selected-map a").bind("click", function(e){
    	e.preventDefault();
      step.stopEdition();
    });

  };

  /**
   * hideEndMapEditBloc
   */

  this.hideEndMapEditBloc = function(){
  	$("#bt-new-marker a").unbind("click");
  	$("#bt-create-another-map a").unbind("click");
  	$("#bt-back-to-selected-map a").unbind("click");

 	  $('#create-map-end').html('');
  };

  /**
   * showEndMarkerEditBloc
   */

  this.showEndMarkerEditBloc = function(marker){
  	$('#create-content-end').show();
  	if(mmEdit.getWorkflow() != 'normal'){$('#bt-add-marker').hide();}

  	//events
  	//add new media to current marker
  	$('#bt-add-new-media').bind('click', function(e){
  		  e.preventDefault();
  		  //simulate a consult mode
  		  mmEdit.setWorkflow('consult');
  		  step.contentSelect();
  	});

//  	//add new marker in current map
//  	$('#bt-add-new-marker').bind('click', function(e){
//  		  e.preventDefault();
//  		  mmEdit.setWorkflow('normal');
//  		  self.hideEndMarkerEditBloc();
//  		  step.geolocate();
//  	});


  	//create new marker
  	$('#bt-create-new-marker').bind('click', function(e){
        e.preventDefault();
  		  mmEdit.setWorkflow('normal');
//  		  mmInterface.hideEndMarkerEditBloc();
        step.startEdition();
  	});


  	//create new map
  	$('#bt-create-new-map').bind('click', function(e){
       e.preventDefault();
  	   mmEdit.storage.removeData('workflow');
  	   step.mapEdit();
  	});

  	//back to consultation
  	$('#bt-map-selection').bind('click', function(e){
       e.preventDefault();
//       mmInterface.hideEndMarkerEditBloc();
       step.stopEdition();
  	});


  	utils.removeGeolocateMarker();

  	//refresh place publique
  	$(".order-list option:first").attr('selected', true);
  	$('#pub-reload', $panPub).trigger('click');
  	if(mmEdit.getWorkflow() != 'consult' && marker){
			utils.triggerMarker(marker);
  	}
  };

  /**
   * hideEndMarkerEditBloc
   */

  this.hideEndMarkerEditBloc = function(){
  	$('#create-content-end').hide();
  	$('#bt-add-new-media').unbind('click');
//  	$('#bt-add-new-marker').unbind('click');
  	$('#bt-create-new-marker').unbind('click');
  	$('#bt-create-new-map').unbind('click');
    $('#bt-map-selection').unbind('click');
  };

	/**
	 * showMarkerChoiceBloc
	 */

	this.showMarkerChoiceBloc = function(){
		$('#marker-choice').show();

		$('#bt-existing-marker a').bind('click',function(e){
      e.preventDefault();
			step.markerSelect();
		});

		$('#bt-new-marker a').bind('click',function(e){
      e.preventDefault();
			step.geolocate();
		});

		$('#cancel-marker-choice').bind('click',function(e){
			e.preventDefault();
			confirm('Etes vous sûr de vouloir quitter le processus d\'ajout de contenu ?', step.stopEdition);
			return false;
		});

	};


	/**
	 * hideMarkerChoiceBloc
	 */

	this.hideMarkerChoiceBloc = function(){
		$('#marker-choice').hide();
		$('#bt-existing-marker a').unbind('click');
		$('#bt-new-marker a').unbind('click');
		$('#cancel-marker-choice').unbind('click');
	};

	/**
	 * showMarkerSelectBloc
	 */

	this.showMarkerSelectBloc = function(){

		//get user's markers
		$.post('private2/getUserMarkers', function(response){
	    response = eval("(" + response + ")");
			switch(response.status){
				case "success":
					utils.createMarkersList(response.message);
				break;

				case "failure":
					if(response.message == "empty") step.geolocate();
				break;

			}
		}, 'json');

		$('#marker-select').show();

		$('#bt-validate-marker-select').bind('click', function(e){
			e.preventDefault();
			var data = {'markerId': $('#marker-form-select :selected').val()};
			$.post('private2/prepareAddMedia', data, function(response){
	   	  response = eval("(" + response + ")");
				switch(response.status){
					case "success":
						step.endMarkerEdit(response.message);
					break;
					case "failure":
					//@todo
					break;
				}
			});
		});

		$('#bt-cancel-marker-select').bind('click', function(e){
			e.preventDefault();
//			mmInterface.hideMarkerSelectBloc();
			step.markerChoice();
		});

	};


	/**
	 * hideMarkerSelectBloc
	 */

	this.hideMarkerSelectBloc = function(){
		$('#marker-form-select').html('');
		$('#marker-select').hide();
		$('#bt-validate-marker-select').unbind('click');
		$('#bt-cancel-marker-select').unbind('click');
	};


	/**
	 * showMapChoiceBloc
	 */

	this.showMapChoiceBloc = function(){
		$('#map-choice').show();
		$('#bt-existing-map a').unbind().bind('click', function(e){
			e.preventDefault();
			step.mapSelect();
		});

		$('#bt-new-map a').unbind().bind('click', function(e){
			e.preventDefault();
			step.mapEdit();
		});


		$('#bt-cancel-map-choice').bind('click', function(e){
			e.preventDefault();
			step.geolocate();
		});

	};

	/**
	 * hideMapChoiceBloc
	 */

	this.hideMapChoiceBloc = function(){
		$('#map-choice').hide();
		$('#bt-validate-map-choice').unbind('click');
		$('#bt-cancel-map-choice').unbind('click');
	};

}; //display ends here

