// $Id$

//See with behaviour and parameter context
$(function() {

  // cache variables
  var $text_label = $('#edit-country-wrapper label').text();
  var $block_vsct_i18n_1 = $('#block-vsct_i18n-1');
  var $language_switcher_link = $('#language-switcher a');
  
  // path images
  //we set the path on the correct protocol and correct port
  var base_url = "";
  if (Drupal.settings.base_url == null) { //usual use case
	var a = document.createElement("a");
	a.href = window.location.protocol + "//" + window.location.hostname;
	// Add this condition for Safari, else safari use http://host:0 and not http://host
    if (window.location.port) {
      a.port = window.location.port;
    }
	base_url = a.href;
  }
  else { //use case "export menus"
	base_url = Drupal.settings.base_url;
  }

  var path_img_collapsed = base_url + '/sites/all/modules/custom/vsct_i18n/images/arrow-collapsed.png';
  var path_img_expanded = base_url + '/sites/all/modules/custom/vsct_i18n/images/arrow-expanded.png';

  // Replacement with the new language switcher (list of links)
  $(Drupal.settings.language_switcher_list).insertAfter('#vsct-i18n-language-switcher-form');
	$('#vsct-i18n-language-switcher-form').remove();

	$('#language-switcher').before($('<a href="#" id="country-select"><img src="'+ path_img_collapsed +'" alt="'+ $text_label +'" /></a>'));
  var $country_select_img = $('#country-select img');

	$('#language-switcher li:first, #country-select').click(function() {
		if ($block_vsct_i18n_1.hasClass('expanded')) {
	    $country_select_img.attr({'src':path_img_collapsed});
	    $block_vsct_i18n_1.removeClass('expanded');
		}
		else {
      $country_select_img.attr({'src':path_img_expanded});
      $block_vsct_i18n_1.addClass('expanded');
		}
		return false;
	});

	$(document).bind('click', function(e) {
    var $clicked = $(e.target);
    if (!$clicked.parents().hasClass('expanded')) {
      $block_vsct_i18n_1.removeClass('expanded');
      $country_select_img.attr({'src':path_img_collapsed});
    }
	});

	// tab navigation
	$language_switcher_link.focus(function() {
	  $block_vsct_i18n_1.addClass('expanded');
    $country_select_img.attr({'src':path_img_expanded});
	});
	$language_switcher_link.blur(function() {
	  $block_vsct_i18n_1.removeClass('expanded');
    $country_select_img.attr({'src':path_img_collapsed});
	});
	
});
