/** CUSTOMIZER CLASS **/
/**********************************************************/
// customizer object
cityspk.editor = {};

// current customizer state
cityspk.editor.state = cityspk.states.BKG_DEFAULT;

// current message's letter, indexed
cityspk.editor.glyphList = new Array();

// current message's weighted cities list
cityspk.editor.full_weight_tags = new Array();
// current message's letter, indexed
// cityspk.editor.tagsList = new Array();

// current message's background
cityspk.editor.currentBkgImage = "";
cityspk.editor.currentBkgObj = null;
// current glyph index
cityspk.editor.currentGlyphIndex = 0;
// current glyph match
cityspk.editor.currentGlyphMatch = '';
// current glyph slug
cityspk.editor.currentGlyphSlug = null;
// current glyph context
cityspk.editor.currentGlyphContext = null;
// current glyph obj
cityspk.editor.currentGlyphObj = null;

// selected new background
cityspk.editor.newBkgImage = null;
cityspk.editor.newBkgObj = null;
// selected new glyph slug
cityspk.editor.newGlyphSlug = null;
// selected new glyph context
cityspk.editor.newGlyphContext = null;
// selected new glyph obj
cityspk.editor.newGlyphObj = null;

// current caroussel bkg page
cityspk.editor.currentBckgPage = 1;
cityspk.editor.currentMaxBckgPage = 1;

// current caroussel glyph page
cityspk.editor.currentGlyphPage = 1;
cityspk.editor.currentMaxGlyphPage = 1;

// swf bridge
cityspk.editor.swfbridge = null;

//consts
cityspk.editor.ALPHA_COEFF = /* 0.00378 */ 0.004 ;
cityspk.editor.TINT_COEFF = /* 0.00378*/ 0.0041;
cityspk.editor.BLUR_COEFF = 0.113;

/**
 * (re-)initialize glyph data list
 * @param state
 */
cityspk.editor.setContext = function(post_tags)
{
  var add_bt = false;
  if(post_tags) add_bt = post_tags;
  
  callback = function(response)
	{
		if (response.type != cityspk.SUCCESS)
		{
		  alert(response.msg);
		  return;
		}
		
    // reinit properties
    var html ='';
    cityspk.editor.glyphList = response.data.struct;
    cityspk.editor.setTagsCitiesList(add_bt);
    return false;
  };
    
  cityspk.editor.currentBkgImage = $("#bkg_current_img img").attr("slug");
  cityspk.api.message.loadTmp(callback);
  return;
};


/**
 * set current state and run appropriate inits
 * @param state
 */
cityspk.editor.setState = function(state)
{
  if(!state)
    this.state = cityspk.states.HELP_DEFAULT;
  else
    this.state = state;
  this.setDisplay(this.state);  
  return;
};

/**
 * Write SWFObject to DOM and initialize connection with it
 * @param none
 */
cityspk.editor.initFlash  = function()
{
  if (!cityspk.editor.swfbridge.initialized) {
      try{
          cityspk.editor.swfobj.write("embed_container_swf");
          cityspk.editor.swfbridge.initialized = true;
      }
      catch(e){
          alert("exception caught : "+e);
          return false;
      }
  }
  
  if (!cityspk.editor.swfobj || !cityspk.editor.swfobj.tagName) {
      try{
          var name = "swf_editor";
          var isIE = jQuery.browser.msie;

          //window[name] = document.forms[1].mosaic;

          if(cityspk.editor.swfobj = (isIE) ? window[name] : document[name]){
              return true;
          } else return false;
      }
      catch(e){
          return false;
      }
  } else return true;
};

/**
 * set cities list according to current message data structure
 * @param none
 */
cityspk.editor.setTagsCitiesList = function(add_bt)
{
  
  var tmp_weight_cities = new Array();
  var full_weight_cities = new Array();
  var tmp_weight_tags = new Array();
  cityspk.editor.full_weight_tags = new Array();
  var max_occ_tags = 1;
  var max_occ_cities = 1;
  
  $.each(cityspk.editor.glyphList, function(i, item){
    
    item = item.glyph;
    
    // get cities list
    var found_curr = $.inArray(item.locationId, tmp_weight_cities);
    if (found_curr == -1)
    {
      var tmp_city = {};
      tmp_city.location = item.locationCity;
      tmp_city.nb_occ = 1;
      full_weight_cities.push(tmp_city);
      tmp_weight_cities.push(item.locationId);
    }
    else
    {
      full_weight_cities[found_curr].nb_occ++; 
      if(full_weight_cities[found_curr].nb_occ > max_occ_cities) max_occ_cities++;
    }
    
    // get tags list
    var ttags = explode(",",item.tags);
    $.each(ttags, function(i, ttag){
     
      found_tag = $.inArray(ttag, tmp_weight_tags);
      if (found_tag == -1)
      {
        var tmp_tag = {};
        tmp_tag.tag = ttag;
        tmp_tag.nb_occ = 1;
        cityspk.editor.full_weight_tags.push(tmp_tag);
        tmp_weight_tags.push(ttag);
      }
      else
      {
        cityspk.editor.full_weight_tags[found_tag].nb_occ++;
        if(cityspk.editor.full_weight_tags[found_tag].nb_occ > max_occ_tags) max_occ_tags++;
      }    
    });
    
  });
  
  var html_cities = '';
  var nb_cities = cityspk.editor.full_weight_tags.length;
  //full_weight_cities.sort(function compareOcc(a, b) { return b.nb_occ - a.nb_occ; });
  $.each(full_weight_cities, function(i, item){
    var curr_class = '';
    if( ((item.nb_occ / max_occ_cities)*100) <  20) curr_class = 'small';
    else if( ((item.nb_occ / max_occ_cities)*100) <  40) curr_class = 'med1';
    else if( ((item.nb_occ / max_occ_cities)*100) <  60) curr_class = 'med2';
    else if( ((item.nb_occ / max_occ_cities)*100) <  80) curr_class = 'big1';
    else curr_class = 'big2';
    
    if(i<(full_weight_cities.length - 1)) html_cities += '<span class="'+curr_class+'"><a class="fixed" href="javascript:;">'+item.location+'</a>, </span>';
    else html_cities += '<span class="'+curr_class+'"><a class="fixed" href="javascript:;">'+item.location+'</a></span>';
  });
  $("#cities_list").html(html_cities.substr(0,(html_cities.length - 2)));
  
  cityspk.editor.displayTagsList(add_bt, max_occ_tags);
  return;
};


/**
 * display cities and tags
 * @param add_bt : add hidden input
 * @param max_occ_tags : max occurences
 */
cityspk.editor.displayTagsList = function(add_bt, max_occ_tags)
{
  //display results
  var html_tags = '';
  var nb_tags = cityspk.editor.full_weight_tags.length;

  //cityspk.editor.full_weight_tags.sort(function compareOcc(a, b) { return b.nb_occ - a.nb_occ; });

  $.each(cityspk.editor.full_weight_tags, function(i, item){
    var curr_class = '';
    if(item.nb_occ && (parseInt(item.nb_occ) > 0) && (item.tag) && (item.tag.length > 0))
    {
      if( ((item.nb_occ / max_occ_tags)*100) <  20) curr_class = 'small';
      else if( ((item.nb_occ / max_occ_tags)*100) <  40) curr_class = 'med1';
      else if( ((item.nb_occ / max_occ_tags)*100) <  60) curr_class = 'med2';
      else if( ((item.nb_occ / max_occ_tags)*100) <  80) curr_class = 'big1';
      else curr_class = 'big2';
      
      if(!add_bt)
      {
        html_tags += '<span class="'+curr_class+'"><a class="fixed" href="javascript:;">'+item.tag+'</a>, </span>';
      }
      else if(add_bt == 'fixed')
      {
        if( (curr_class == 'big1') || (curr_class == 'big2'))
        {
          html_tags += '<span class="'+curr_class+'"><a class="fixed" href="javascript:;">'+item.tag+'</a>';
          html_tags += '<input type="hidden" name="message_tags[]" value="' + item.tag + '" />, </span>';
        }
        else
        {
          html_tags += '<span class="'+curr_class+'"><a class="fixed" href="javascript:;">'+item.tag+'</a>';
          html_tags += '<input type="hidden" name="message_tags[]" value="" />, </span>';
        }
      }
      else
      {
        if( (curr_class == 'big1') || (curr_class == 'big2'))
        {
          html_tags += '<span occ="'+item.nb_occ+'" id="tag'+i+'" class="'+curr_class+'">';
          html_tags += '<a rel="tag' + i + '" tag="' + item.tag + '"class="deletable_tag selected" href="javascript:;" title="">' + item.tag + '</a>';
          html_tags += '<input type="hidden" name="message_tags[]" value="' + item.tag + '" />, </span>';
        }
        else
        {
          html_tags += '<span occ="'+item.nb_occ+'" id="tag'+i+'" class="'+curr_class+'">';
          html_tags += '<a rel="tag' + i + '" tag="' + item.tag + '" class="deletable_tag" href="javascript:;" title="">' + item.tag + '</a>';
          html_tags += '<input type="hidden" name="message_tags[]" value="" />, </span>';
        }
      }
    }
  });
  
  $("#tags_list").html(html_tags.substr(0,(html_tags.length - 2)));
  $(".deletable_tag").unbind();
  $(".deletable_tag").bind("click",cityspk.editor.toggleTag);

};

/**
 * set cities list according to current message data structure
 * @param none
 */
cityspk.editor.toggleTag = function(e)
{  
  $("#"+$(this).attr("rel")+" a").toggleClass('selected');
  var curr_input = $("#"+$(this).attr("rel")+" input");
  if(curr_input.val().length > 0) 
    curr_input.val('');
  else
    curr_input.val($(this).attr("tag")); 
  return;
};

/**
 * add tags to list
 * @param none
 */
cityspk.editor.addTagToList = function()
{  
  var html_tags = '';
  var curr_class = 'small';
  var tag = $("#addtag").val();
  if(tag.length > 0)
  {
    html_tags += '<span id="tag' + $(".deletable_tag").length + '" class="'+curr_class+'">';
    html_tags += '<a rel="tag' + $(".deletable_tag").length + '" tag="' + tag + '"class="deletable_tag selected" href="javascript:;" title="">' + tag + '</a>';
    html_tags += '<input type="hidden" name="message_tags[]" value="' + tag + '" />, </span>';
    $("#tags_list").append(html_tags);
    $("#addtag").val("");
  }
  return;
};

/**
 * selectable glyph handler
 * @param none
 */
cityspk.editor.selectableGlyphHandler = function(){
  var urltmp = "/people/"+$(this).attr("username")+"/photos/"+$(this).attr("slug");
  var img_urls_tmp = { mini:$(this).attr("thumb")};
  var params = { 
    title: $(this).attr("title"), 
    tags: $(this).attr("tags"), 
    username: $(this).attr("username"), 
    url: urltmp, 
    img_urls: img_urls_tmp, 
    context: $(this).attr("context"),
    location_url: $(this).attr("location_url"),
    locationCity: $(this).attr("locationCity")
  };
  cityspk.editor.setCurrentGlyph($(this).attr("slug"),$(this).attr("context"),params);
  
	cityspk.editor.changeCurrentGlyph("#customize_glyphe");
  //cityspk.editor.setState(cityspk.states.GLY_DEFAULT);
  cityspk.editor.swfobj.api_changeTile(cityspk.editor.currentGlyphIndex,cityspk.editor.currentGlyphSlug);
	
	//$("#bt_apply_glyph").addClass("bt_active");
};

/**
 * selectable background handler
 * @param none
 */
cityspk.editor.selectableImageHandler = function(){
  var urltmp = "/people/"+$(this).attr("username")+"/photos/"+$(this).attr("slug");
  var img_urls_tmp = { thumb:$(this).attr("thumb")};
  var params = { 
    title:$(this).attr("title"), 
    tags:$(this).attr("tags"), 
    username:$(this).attr("username"), 
    url: urltmp, 
    img_urls: img_urls_tmp ,
    location_url: $(this).attr("location_url"),
    locationCity: $(this).attr("locationCity")
  };
  cityspk.editor.setBkgImage($(this).attr("slug"),params);
  
	if(!cityspk.editor.initFlash()){ 
		alert("cityspk.editor.initFlash() not defined");
		return false;
  } else {
		
		cityspk.editor.changeCurrentBkg("#customize_bckg");
    //cityspk.editor.setState(cityspk.states.BKG_DEFAULT);
    cityspk.editor.swfobj.api_setBackground(cityspk.editor.currentBkgImage);
  }
	
	//$("#bt_apply_bkg").addClass("bt_active");
};

/**
 *  write selected Glyph in SELECTION canvas
 * @param none
 */
cityspk.editor.setCurrentGlyph = function(slug,ctxt,obj)
{
  
  var curr_img = ""; 
  var curr_context = ""; 
  var curr_context_img = ""; 
  var curr_title = "";
  var curr_tags = "";
  var curr_owner = "";
  var curr_thumb = "";
  var curr_location_url = "";
  var curr_location = "";
  var glyph_obj = {};
  var curr_url = "";
  
  if(obj && obj.title) curr_title = obj.title; 
  if(obj && obj.tags) curr_tags = subreplace(obj.tags,",",", ");
  
  if(obj && obj._owner && obj._owner[0].username) curr_owner = obj._owner[0].username;
  else if(obj && obj.username) curr_owner = obj.username;
  
  if(obj && obj._context && obj._context[0] && obj._context[0].img_urls) 
    curr_context = obj._context[0].img_urls.square;
  else if(obj && obj.context) 
    curr_context = obj.context;
  
  if(obj && obj._location && obj._location[0] && obj._location[0].url)
    curr_location_url = obj._location[0].url;
  else if(obj && obj.location_url)
    curr_location_url = obj.location_url;
  
  if(obj && obj.locationCity) curr_location = obj.locationCity;
  
  curr_context_img = "<img src='" + curr_context + "' class='related_context " + cityspk.sizes.THUMB_SQUARE +"' alt='' />";
  if(obj && obj.img_urls && obj.img_urls.mini) curr_img = "<img src='" + obj.img_urls.mini +"' class='selected_glyphe " + cityspk.sizes.THUMB_MINI2 +"' slug='" + slug + "' alt='' />";
  
  if(obj && obj.url) curr_url = obj.url;  
 
  $("#g_current_img").html(curr_img);
  $("#g_current_context").html(curr_context_img);
  $("#g_current_title span").html(curr_title);
  $("#g_current_keywords").html(curr_tags);
	
	//Owner data
	if(curr_owner.length) {
		$("#g_current_owner").css({display: 'block'});
		var ownerLocation = '<a href="' + cityspk.urlmap.app_user + '/' + curr_owner + '">' + curr_owner + '</a>';
	} else $("#g_current_owner").css({display: 'none'});
	ownerLocation ? $("#g_current_owner span").html(ownerLocation) : $("#g_current_owner span").text(curr_owner);
	
	//Location data
	if(curr_location_url.length) {
		var linkLocation = '<a href="' + cityspk.urlmap.root + curr_location_url + '">' + curr_location + '</a>';
		$("#g_current_city").css({display: 'block'});
	} else $("#g_current_city").css({display: 'none'});
	linkLocation ? $("#g_current_city span").html(linkLocation) : $("#g_current_city span").text(curr_location);
	
	
  //$("#g_current_city").attr("href",curr_location_url);
  //$("#g_current_explore_link").attr("href",curr_url);
  
  glyph_obj = { title: curr_title, tags: curr_tags, username: curr_owner, context: curr_context, url: curr_url, location_url: curr_location_url, locationCity: curr_location};
  if(obj && obj.img_urls && obj.img_urls.mini) glyph_obj.img_urls = {mini: obj.img_urls.mini};    
  cityspk.editor.newGlyphSlug = slug;
  cityspk.editor.newGlyphContext = ctxt;
  cityspk.editor.newGlyphObj = glyph_obj;	
  return false;
};

/**
 * write selected Background in SELECTION canvas
 * @param none
 */
cityspk.editor.setBkgImage = function(slug,obj)
{
  var curr_img = "";
  var curr_title = "";
  var curr_tags = "";
  var curr_owner = "";
  var curr_explore_link = "#";
  var curr_img_slug = "";
  var curr_location_url = "";
	var curr_location_id = "";
  var curr_location = "";
  var bckg_obj = {};
  
  if(obj && obj.title) curr_title = obj.title;
  if(obj && obj.url) curr_explore_link = obj.url;
  if(obj && obj.tags) curr_tags = subreplace(obj.tags,",",", ");
  if(obj && obj._owner && obj._owner[0].username) curr_owner = obj._owner[0].username;
  else if(obj && obj.username) curr_owner = obj.username;
  
  if(obj && obj._location && obj._location[0] && obj._location[0].url)
    curr_location_url = obj._location[0].url;
  else if(obj && obj.location_url)
    curr_location_url = obj.location_url;
	
  if(obj && obj.locationCity) curr_location = obj.locationCity;	
	if(obj && obj.locationId) curr_location_id = obj.locationId;
  
  if(obj && obj.img_urls && obj.img_urls.thumb)
		curr_img = "<img src='" + obj.img_urls.thumb +"' class='" + cityspk.sizes.THUMB_THUMB +"' slug='" + slug + "' alt='' title='' />";
		//curr_img = "<div class='vcm'><div class='vci'><img src='" + obj.img_urls.thumb +"' class='" + cityspk.sizes.THUMB_THUMB +"' slug='" + slug + "' alt='' title='' /></div></div>";
 	else
		curr_img = "<img src='" + cityspk.config.relative_root + "/static/images/message/default_photo.gif' class='bckg' slug='' alt='' title='' />";
		//curr_img = "<div class='vcm'><div class='vci'><img src='" + cityspk.config.relative_root + "/static/images/message/default_photo.gif' class='bckg' slug='' alt='' title='' /></div></div>";
  
	$("#bckg_current_title span").html(curr_title);
	
	//Tags
	if(curr_tags.length) $("#bckg_current_keywords").css({display: 'block'});
	else $("#bckg_current_keywords").css({display: 'none'});	
  $("#bckg_current_keywords span").html(curr_tags);
	
	//Owner data
	if(curr_owner.length) {
		$("#bckg_current_owner").css({display: 'block'});
		var ownerLocation = '<a href="' + cityspk.urlmap.app_user + '/' + curr_owner + '">' + curr_owner + '</a>';
	} else $("#bckg_current_owner").css({display: 'none'});
	ownerLocation ? $("#bckg_current_owner span").html(ownerLocation) : $("#bckg_current_owner span").text(curr_owner);

  //$("#bckg_current_explore_link").attr("href",curr_explore_link);
  $("#bckg_current_img").html(curr_img);
	
	//Location data
	if(curr_location_url.length) {
		var linkLocation = '<a href="' + cityspk.urlmap.root + curr_location_url + '">' + curr_location + '</a>';
		$("#bckg_current_city").css({display: 'block'});
	} else $("#bckg_current_city").css({display: 'none'});
	linkLocation ? $("#bckg_current_city span").html(linkLocation) : $("#bckg_current_city span").text(curr_location);
	
  $("#bkg_images").val(slug);
  
  //$("#bkg_current_city").attr("href",curr_location_url);
  bckg_obj = { title: curr_title, tags: curr_tags, username: curr_owner, location_url: curr_location_url, locationCity: curr_location };
  if(obj && obj.img_urls && obj.img_urls.thumb) bckg_obj.img_urls = {thumb: obj.img_urls.thumb};
  if(obj && obj.img_url) bckg_obj.img_url = obj.img_url;
  
  cityspk.editor.newBkgImage = slug;
  cityspk.editor.newBkgObj = bckg_obj;
};

/**
 * set current UI Glyph after applying selection
 * @param none
 */
cityspk.editor.changeCurrentGlyph = function(target)
{
  cityspk.editor.currentGlyphSlug = cityspk.editor.newGlyphSlug;
  cityspk.editor.currentGlyphContext = cityspk.editor.newGlyphContext;
  cityspk.editor.currentGlyphObj = cityspk.editor.newGlyphObj;
  //$(target).empty();
};

/**
 * set current UI Background after applying selection
 * @param none
 */
cityspk.editor.changeCurrentBkg = function(target)
{
  cityspk.editor.currentBkgImage = cityspk.editor.newBkgImage;
  cityspk.editor.currentBkgObj = cityspk.editor.newBkgObj;
  cityspk.editor.newBkgImage = null;
  cityspk.editor.newBkgObj = null;
  //$(target).empty();
};

/**
 * Handle mouseRelease outside of the slider's area
 * @param none
 */
cityspk.editor.handleGlyphEffects = function(evt)
{
  $("body").bind("mouseup",cityspk.editor.getGlyphEffects);
};

/**
 * get current Glyph effect object from sliders combination
 * @param none
 */
cityspk.editor.getGlyphEffects = function()
{
  var effects_params = {};
  
  $("body").unbind('mouseup', cityspk.editor.getGlyphEffects);
 
  var css_blur =  $("#g_effects_blur_slider div.ui-slider-handle").css("left");
  css_blur = css_blur.substr(0,(css_blur.length - 2));
  effects_params.blur = parseInt(css_blur) * cityspk.editor.BLUR_COEFF;
  
  var css_tintamount = $("#g_effects_tint_slider div.ui-slider-handle").css("left");
  css_tintamount = css_tintamount.substr(0,(css_tintamount.length - 2));
  effects_params.tintamount = parseInt(css_tintamount) * cityspk.editor.TINT_COEFF;
  
  var css_tint = $("#g_effects_tint_picker div").css("background-color");
  css_tint = css_tint.substr(4,(css_tint.length - 1));
  var css_tint_tab = explode(",",css_tint);
  effects_params.tint = "0x";
  
  effects_params.tint += rgb2hex(css_tint_tab[0],css_tint_tab[1],css_tint_tab[2]);
      
  var css_alpha = $("#g_effects_alpha_slider div.ui-slider-handle").css("left");
	css_alpha = css_alpha.substr(0,(css_alpha.length - 2));
  effects_params.alpha = parseInt(css_alpha) * cityspk.editor.ALPHA_COEFF;  
  
  effects_params.mode = $("#g_effects_mode_select").val();
  
  var params_str = "effects_params {blur: "+effects_params.blur+", tintamount: "+effects_params.tintamount+", tint: "+effects_params.tint+", alpha: "+effects_params.alpha+", mode: "+effects_params.mode+"}";
  $("#debug_msg_get").html(params_str);
  
    if(!cityspk.editor.initFlash()){
      alert("cityspk.editor.initFlash() not defined getglyphs effects"); return;
    }
    else
    {
      cityspk.editor.swfobj.api_updateSelection(cityspk.editor.currentGlyphIndex, effects_params);
    }
  
  return;
};

/**
 * get current Glyph effect object from sliders combination
 * @param none
 */
cityspk.editor.setGlyphEffects = function(effects_params)
{
  if(effects_params && effects_params.blur >= 0)
  {
    var css_blur = parseInt(parseFloat(effects_params.blur) / cityspk.editor.BLUR_COEFF); //alert(css_blur);
    if(!css_blur) css_blur = 0;
    css_blur = css_blur+"px";
    $("#g_effects_blur_slider div.ui-slider-handle").css("left",css_blur);
  }
  if(effects_params && effects_params.alpha >= 0)
  {
    var css_alpha = parseInt(parseFloat(effects_params.alpha) / cityspk.editor.ALPHA_COEFF);
    if(!css_alpha) css_alpha = 0;
    css_alpha = css_alpha+"px";
    $("#g_effects_alpha_slider div.ui-slider-handle").css("left",css_alpha);
  }

  if(effects_params && effects_params.tintamount >= 0)
  {
    var css_tintamount = parseInt(parseFloat(effects_params.tintamount) / cityspk.editor.TINT_COEFF);
    if(!css_tintamount) css_tintamount = 0;
    css_tintamount = css_tintamount+"px";
    $("#g_effects_tint_slider div.ui-slider-handle").css("left",css_tintamount);
  }
  if(effects_params && effects_params.tint >= 0)
  {
    var css_tint = effects_params.tint;
    css_tint = css_tint.toString(16);
    while(css_tint.length < 6) css_tint = "0"+css_tint;
    $("#g_effects_tint_picker div").css("background-color","#"+css_tint);
  }
  if(effects_params && effects_params.mode)
  {
    $("#fx_"+effects_params.mode).attr("selected","selected");
  }  
  //alert(effects_params.toSource());
 
  //$("#debug_msg_set").html("effects_params {blur: "+effects_params.blur+", css_blur: "+css_blur+", tint: "+effects_params.tint+", css_tint: "+css_tint+", tintamount: "+effects_params.tintamount+", css_tintamount: "+css_tintamount+", alpha: "+effects_params.alpha+",css_alpha: "+css_alpha+", mode: "+$("#g_effects_mode_select").val()+"}");
  return;
};


// ------------------------------------------------------------------------------------------------
// API FLASH -> JS
//invoked by flash when a selection is made
cityspk.editor.updateSelection = function(letter_index, item, extraProperties)
{ 
  var context = null;
  if(!(letter_index >= 0) || !item || !extraProperties || !extraProperties.match) {
    alert("Missing parameter to updateSelection()");
    return;
  }

  var item_decode = decodeFlashString(item);
  
  cityspk.editor.currentGlyphPage = 1;
  cityspk.editor.currentMaxGlyphPage = 1;
  
  cityspk.editor.currentGlyphIndex = letter_index;
  cityspk.editor.currentGlyphSlug  = item_decode._slug;
  cityspk.editor.currentGlyphObj  = item_decode;
  cityspk.editor.currentGlyphMatch = extraProperties.match;
  
  if(item_decode._context && item_decode._context.length > 0)
  {
    context = item_decode._context[0];
    context = context._slug;
  }

  cityspk.editor.setCurrentGlyph(item_decode._slug, context, item_decode);
  cityspk.editor.setState(cityspk.states.GLY_DEFAULT);
  $("#embed_container").removeClass("embed_container_selected");
  //$("#bt_apply_bkg").removeClass("bt_active");
  //$("#bt_apply_glyph").removeClass("bt_active");
	
  cityspk.editor.setGlyphEffects(extraProperties);
	
	/* Update Caroussel Thumbnail */
	try {
		var tmp_params_g = { type: cityspk.types.GLYPH, width: cityspk.customize.CAR_GLY_W, nb_thumbs: cityspk.customize.CAR_GLY_N, match: cityspk.editor.currentGlyphMatch, clear: 0};
  	if(parseInt(cityspk.customize.currentCityGLY) > 0) tmp_params_g.location = cityspk.customize.currentCityGLY;
  	cityspk.editor.writeThumbnailsTo("#customize_glyphe", cityspk.sizes.THUMB_MINI, tmp_params_g, cityspk.editor.carousselGlyph);
	} catch(e) { console.log('Fuck !'); }
};

//invoked by flash when the user deselects everything
cityspk.editor.deselect = function(item)
{
  cityspk.editor.currentBkgObj = decodeFlashString(item);
  
  var curr_bkg_value = (cityspk.editor.currentBkgObj && cityspk.editor.currentBkgObj.img_urls ) ? cityspk.editor.currentBkgObj.img_urls.thumb : "";
  var img_urls_tmp = {thumb: curr_bkg_value};
  cityspk.editor.currentBckgPage = 1;
  cityspk.editor.currentMaxBckgPage = 1;
  cityspk.editor.setBkgImage(cityspk.editor.currentBkgImage, cityspk.editor.currentBkgObj);
  cityspk.editor.setState(cityspk.states.BKG_DEFAULT);
  $("#bt_apply_bkg").removeClass("bt_active");
  $("#bt_apply_glyph").removeClass("bt_active");
  $("#embed_container").addClass("embed_container_selected");
	
	/* Update caroussel background Images */
	try {
		var tmp_params_bckg = { type: cityspk.types.IMAGE, width: cityspk.customize.CAR_BCKG_W, nb_thumbs: cityspk.customize.CAR_BCKG_N, clear: 0};
    if(parseInt(cityspk.customize.currentCityBKG) > 0) tmp_params_bckg.location = cityspk.customize.currentCityBKG;
    cityspk.editor.writeThumbnailsTo("#customize_bckg", cityspk.sizes.THUMB_THUMB, tmp_params_bckg, cityspk.editor.carousselImage);		
	} catch(e) { console.log('sPb Background Loading !'); }
  return;
};


//invoked by flash when the editor is ready (message loaded)
cityspk.editor.loadComplete = function()
{
  return;
};


//invoked by flash when the editor is ready (message saved)
cityspk.editor.saveComplete = function()
{
  if(cityspk.customize.submit_form) $(cityspk.customize.submit_form).submit(); 
  else return; //window.location.replace(cityspk.customize.submit_send)
};


/**
 * prevent user of leaving the page without saving his current message
 * @param event Object
 */
cityspk.editor.preventExitPage = function(evt)
{
  //console.log("click outside area");
  /*if(evt && evt.data && evt.data.url)
    cityspk.customize.submit_send = evt.data.url;*/
  /*var confirm_url = cityspk.urlmap.app_message_customize_exit_confirm; 
  tb_show('',confirm_url,false);*/
  return false;
};


/**
 * redirect user to specified page
 * @param evt eventObject
 * @param evt.data.url eventObject params : return submit url
 */
cityspk.editor.redirectAfterSave = function(evt)
{
  var curr_redirect = $(this).attr("href");
  if(!cityspk.editor.initFlash()){
    alert("cityspk.editor.initFlash() not defined"); return;
  }
  else {
    if(evt && evt.data && evt.data.url)
      cityspk.customize.submit_send = evt.data.url;
    else if(curr_redirect)
      cityspk.customize.submit_send = curr_redirect;
    
    if(evt && evt.data && evt.data.form)
    {
      $(evt.data.form).attr('action', cityspk.customize.submit_send);
      cityspk.customize.submit_form = evt.data.form;
    }
    
    cityspk.editor.swfobj.api_saveStruct();
  }
  return false;
};



/**
 * redirect user to specified page
 * @param evt eventObject
 * @param evt.data.url eventObject params : return submit url
 */
cityspk.editor.performSaveAndRedirect = function(evt)
{
	var curr_redirect = $(this).attr("href");
  if(!cityspk.editor.initFlash()){
    alert("cityspk.editor.initFlash() not defined"); return;
  }
  else {
    if(evt && evt.data && evt.data.url)
      cityspk.customize.submit_send = evt.data.url;
    else if(curr_redirect)
      cityspk.customize.submit_send = curr_redirect;
    
    if(evt && evt.data && evt.data.form)
    {
      $(evt.data.form).attr('action', cityspk.customize.submit_send);
      cityspk.customize.submit_form = evt.data.form;
    }
    cityspk.editor.swfobj.api_save();
  }
  return false;
};

// ------------------------------------------------------------------------------------------------
// JS -> FLASH
//Perform a load of the message identified by slug slug.
//api_LoadMessage(slug) 

/**
 * update Glyphs or Bckg caroussels after completing another search
 * @param target : DOM container
 * @param size : thumb size
 * @param params : params
 * @param ui_callbck
 */
cityspk.editor.writeThumbnailsTo = function(target, size, params, ui_callbck)
{ 
  var callback = function(response)
	{
		if (response.type != cityspk.SUCCESS)
		{
		  alert(response.msg);
		  return;
		}
		
    var curr_page = (page_tmp > 0) ? response.data.page : 0;
    
    // check for adding / removing extra pages OR init caroussel on first selection
    if(params && (params.clear == 0)) 
    {
			$(target).empty();
    }
    else if(params && (params.clear == -1))
    {
			if($(target).find(".c_elt").length > 2) $(target).find(".c_elt:first").remove(); 
    }
    else if(params && (params.clear == 1))
    {
			if($(target).find(".c_elt").length > 2) $(target).find(".c_elt:last").remove();
    } 
    
    if(curr_context  == cityspk.types.IMAGE)    
    { if(response.data.pages >= cityspk.editor.currentMaxBckgPage) cityspk.editor.currentMaxBckgPage = response.data.pages; }
    else
    { if(response.data.pages >= cityspk.editor.currentMaxGlyphPage) cityspk.editor.currentMaxGlyphPage = response.data.pages; }
    
    var html ='';
    var nb_thumbs = 12;
    if(params && params.nb_thumbs) nb_thumbs = params.nb_thumbs;
    
    
    if(curr_page > 0)
    {

			// process data response
    	$.each(response.data.resultset, function(i, item) 
      {
    		var context_img = (item._context && item._context[0] && item._context[0].img_urls) ? item._context[0].img_urls.square : '';      
        var user_img = (item._owner && item._owner[0]) ? item._owner[0].username : '';
        var sizes_img = (item.img_urls) ? eval("item.img_urls." + th_size) : '';
        var sizes_img_mini = ((item.img_urls) && (curr_context  == cityspk.types.IMAGE)) ? item.img_urls.thumb : '';
        var location_url = (item._location && item._location[0] && item._location[0].url) ? item._location[0].url : '';
        var locationCity = (item.locationCity) ? item.locationCity : '';
        sizes_img_mini = ((item.img_urls) && (curr_context  == cityspk.types.GLYPH)) ? item.img_urls.mini : sizes_img_mini;
       
        var photoLink = sizes_img;
        var vcenter_fix = ""; 
    		var img = "<li class='medium'><a href='javascript:;' ";
        img += " slug='"+item._slug+"' context='"+context_img+"' username='"+user_img+"' tags='"+item.tags+"'";
        img += " location_url='"+location_url+"' locationCity='"+locationCity+"' title='"+item.title+"' thumb='"+sizes_img_mini+"'";
        img += " rel='"+item._slug+"' img_url='"+item.img_url+"' class='selectable"+curr_context+"'><span class='vcenter_pict'> <img class='"+ th_size +"' src=" + photoLink + " alt='' />"+vcenter_fix+"</span></a></li>";
							
				if (i % nb_thumbs == 0) html += "<div class='c_elt'><ul>";
        html += img;
        if ( (i % nb_thumbs == (nb_thumbs - 1)) || (i == (response.data.rowcount - 1)) ) 
        {
          curr_page++;
          html += "</ul></div>";
        }
    	});
			
      if(params && (params.clear == -1)) $(target).append(html); 
      else if( params && ((params.clear == 1)||(params.clear == 0)) ) $(target).prepend(html); 
    }
    
    // reinitialize caroussel object after appending new content to it
    if(ui_callbck) 
    {
			var ajax_correction = 1;
      if ((curr_page == 0) && params && (params.clear == 1)) ajax_correction = 0;
      if(params && params.width)
        ui_callbck.reinitialize(params.width, 1, $(target).children(".c_elt").length, ajax_correction, params.clear);
      else  ui_callbck.reinitialize();   
    }
    
    // unbind / rebind all that selectable stuff
    $(".selectableGlyph, .selectableImage").unbind();
    $(".selectableGlyph").bind("click",cityspk.editor.selectableGlyphHandler);
    $(".selectableImage").bind("click", cityspk.editor.selectableImageHandler);
    //$("li.medium").unbind();
    $("li.medium").click(function(){
      $("li.medium").removeClass("selected");
      $(this).addClass("selected");
    });
    return false;    
	};// end callback
      
  var th_size = cityspk.sizes.THUMB_THUMB; 
	if(size) th_size = size;	
  var curr_context = cityspk.types.GLYPH;
  if(params && params.type) curr_context = params.type;
  
  var api_params = {};
  api_params.type = curr_context;
  api_params.privacy = 1;
  
  if(api_params.type == cityspk.types.IMAGE) 
  {
    api_params.contexts = 'none';
    api_params.orientation  = 'landscape';
  }
  if(params && params.location) api_params.locations = [params.location];
  if(params && params.text) api_params.text = params.text;
  if(params && params.match) 
  {
    api_params.match_words = [params.match];
    api_params.match_level = 2;
  }
  
  var pagesize_tmp = 12;
  var page_tmp = 1;
  if(params && params.nb_thumbs) pagesize_tmp = params.nb_thumbs;
  if(params && (params.clear == 0)){
    pagesize_tmp = pagesize_tmp * 2;
  }
  
  if(params && params.user_id) api_params.user_id = 'me';
  
	cityspk.api.photos.search(callback, {pagesize: pagesize_tmp, page: page_tmp, sort : 'random', cache_off : 1}, api_params);
};

/**
 * activate validate button / organizer modal edition
 * @param action
 * @param id DOM element
 */
cityspk.editor.activateSaveBtn = function(action,id_button)
{
	var curr_enabled_class	= 'bt_active';
	var curr_disabled_class	= 'bt_inactive'; 
	$(id_button+" a").removeClass(curr_disabled_class);
	$(id_button+" a").removeClass('sm_button_link');
	$(id_button+" a").addClass(curr_enabled_class);
	$(id_button+" a").bind("click", action);
};

/**
 * desactivate validate button / organizer modal edition
 * @param id DOM element
 */
cityspk.editor.desactivateSaveBtn = function(id_button)
{
	var curr_enabled_class	= 'bt_active';
	var curr_disabled_class	= 'bt_inactive'; 
	$(id_button+" a").addClass(curr_disabled_class);
	$(id_button+" a").addClass('sm_button_link');
	$(id_button+" a").removeClass(curr_enabled_class);
	$(id_button+" a").unbind();
};

/**
 * Customizer controls panels : 
 * includes : caroussel management
 * @param none
 */

var Customize = Customize || {}; //namespace Avatar
Customize.callback = {};
Customize.selected = function(elt, index, carousselID){
	if(!arguments[0] && !carousselID) return;
	var caroussel = $('#' + carousselID)[0];
	if(!caroussel.tagName) return;
	$('.c_elt ul li', caroussel).removeClass('selected');
	var parent = $(elt).parents('li')[0];
	$(parent).addClass('selected');
	return false;
};

Customize.vcentrageImg = function(elt, width, height, sizes){
	var sizes = {width: sizes.width || 0, height: sizes.height || 0};
	var marginTop = (sizes.height > height && height > 0)? parseInt(sizes.height - height) / 2 : 0;
	var marginLeft = (sizes.width > width && width > 0)? parseInt(sizes.width - width) / 2 : 0;
  
	$(elt).css('margin-top',  marginTop + 'px');
	$(elt).css('margin-lef',  marginLeft + 'px');
	return elt;
};

// Obj. CustomizePanel
function CustomizePanel (container, isVisible, isOpen){ 
	this.container = container;
	this.content = $('.c_module_content', this.container)[0];
	this.isVisible = (isVisible) ? true : false; 
	this.isOpen = (isOpen) ? true : false;
	this.btnDisplayContent = new Object();
	this.initialize();
  
};

CustomizePanel.prototype.initialize = function(){
  // set whole panel display
  if(this.isVisible)
    this.showPanel();
  else
    this.hidePanel();
  // bind events
  this.initPanelActions();
  // open or close panel
  if(this.isOpen)
    this.openPanel();
  else
    this.closePanel();
	  
};

CustomizePanel.prototype.initPanelActions = function(){
	this.btnDisplayContent = $('.expand_link', this.container)[0];
	if(!$(this.btnDisplayContent).is('a')) return;
	var that = this;
	$(this.btnDisplayContent).click(function(e){
    if($(this).is(".expand_link_active"))
      that.closePanel();
    else
      that.openPanel();
		return false;
	});	
};

CustomizePanel.prototype.showPanel = function(){
	if(!$(this.container).is('div')) return;
  $(this.container).css('display', 'block');
  this.isVisible = true;
};

CustomizePanel.prototype.hidePanel = function(){
	if(!$(this.container).is('div')) return;
  $(this.container).css('display', 'none');
	this.isVisible = false;
};

CustomizePanel.prototype.openPanel = function(){
	if(!$(this.content).is('div')) return;//if(!this.isOpen) 
  $(this.content).css('display', 'block');
	this.isOpen = true;
	if(!$(this.btnDisplayContent).is('a')) return;
  $(this.btnDisplayContent).addClass('expand_link_active');
};

CustomizePanel.prototype.closePanel = function(){
	if(!$(this.content).is('div')) return;
  $(this.content).css('display', 'none');
	this.isOpen = false;
	if(!$(this.btnDisplayContent).is('a')) return;
  $(this.btnDisplayContent).removeClass('expand_link_active');
};


/**
 * set current state and run appropriate inits
 * @param state
 */
cityspk.editor.createPanels = function()
{
  cityspk.editor.glyphesPanel = new CustomizePanel($('#g_glyphe_action'), true, true);
  cityspk.editor.glyphesActions = new CustomizePanel($('#g_display_manage'), true, true);
	cityspk.editor.glyphesManager = new CustomizePanel($('#g_manage'), true, true);
	cityspk.editor.effectsPanel = new CustomizePanel($('#g_effects_manager'), true, true);  

  cityspk.editor.bckgPanel = new CustomizePanel($('#i_bkg_photo'), true, true);
  cityspk.editor.bckgActions = new CustomizePanel($('#i_bkg_display_manage'), true, true);
	cityspk.editor.bckgManager = new CustomizePanel($('#i_bkg_manage'), true, true);
	cityspk.editor.bckgDownload = new CustomizePanel($('#i_bkg_download'), true, true);
};

/**
 * set current display
 * @param state : current state
 */
cityspk.editor.setDisplay = function(state)
{  
  switch(state)
  { 
    case cityspk.states.BKG_DEFAULT:
      $("#customize_panel").show(); $("#customize_help").hide();
      cityspk.editor.glyphesPanel.hidePanel();
      cityspk.editor.glyphesActions.hidePanel();
      cityspk.editor.glyphesManager.hidePanel();
      cityspk.editor.effectsPanel.hidePanel();
      
      cityspk.editor.bckgPanel.showPanel();
      cityspk.editor.bckgManager.showPanel();
      cityspk.editor.bckgActions.showPanel();
      cityspk.editor.bckgDownload.showPanel(); 
      break;
    case cityspk.states.BKG_LIST:
      $("#customize_panel").show();$("#customize_help").hide();
      cityspk.editor.glyphesPanel.hidePanel();
      cityspk.editor.glyphesActions.hidePanel();
      cityspk.editor.glyphesManager.hidePanel();
      cityspk.editor.effectsPanel.hidePanel();
      
      cityspk.editor.bckgPanel.showPanel();
      cityspk.editor.bckgManager.showPanel();
			cityspk.editor.bckgManager.openPanel();
      cityspk.editor.bckgActions.hidePanel();
      cityspk.editor.bckgDownload.hidePanel();
      break;
    case cityspk.states.GLY_DEFAULT:
      $("#customize_panel").show();$("#customize_help").hide();
      cityspk.editor.glyphesPanel.showPanel();			
      cityspk.editor.glyphesActions.showPanel();			
      cityspk.editor.glyphesManager.showPanel();			
			cityspk.editor.glyphesManager.openPanel();			
      cityspk.editor.effectsPanel.showPanel();
			cityspk.editor.effectsPanel.openPanel();
      
      cityspk.editor.bckgPanel.hidePanel();
      cityspk.editor.bckgManager.hidePanel();
      cityspk.editor.bckgActions.hidePanel();
      cityspk.editor.bckgDownload.hidePanel();
      break;
    case cityspk.states.GLY_LIST:
      $("#customize_panel").show();$("#customize_help").hide();
      cityspk.editor.glyphesPanel.showPanel();
      cityspk.editor.glyphesActions.hidePanel();
      cityspk.editor.glyphesManager.showPanel();cityspk.editor.glyphesManager.openPanel();
      cityspk.editor.effectsPanel.showPanel();cityspk.editor.effectsPanel.closePanel();
      
      cityspk.editor.bckgPanel.hidePanel();
      cityspk.editor.bckgManager.hidePanel();
      cityspk.editor.bckgActions.hidePanel();
      cityspk.editor.bckgDownload.hidePanel();
      break;
    case cityspk.states.HELP_DEFAULT:
      $("#customize_help").show();
      cityspk.editor.glyphesPanel.hidePanel();
      cityspk.editor.glyphesActions.hidePanel();
      cityspk.editor.glyphesManager.hidePanel();
      cityspk.editor.effectsPanel.hidePanel();
      
      cityspk.editor.bckgPanel.hidePanel();
      cityspk.editor.bckgManager.hidePanel();
      cityspk.editor.bckgActions.hidePanel();
      cityspk.editor.bckgDownload.hidePanel();
      break;
    default:
      $("#customize_help").show();
      cityspk.editor.glyphesPanel.hidePanel();
      cityspk.editor.glyphesActions.hidePanel();
      cityspk.editor.glyphesManager.hidePanel();
      cityspk.editor.effectsPanel.hidePanel();
      
      cityspk.editor.bckgPanel.hidePanel();
      cityspk.editor.bckgManager.hidePanel();
      cityspk.editor.bckgActions.hidePanel();
      cityspk.editor.bckgDownload.hidePanel();
  };
  return;
};

