// $Id$


//Global variable, TODO to be deleted during new version refactoring
global_oldRedirectVersion = false;

/**
 * Return the url to redirect to if the country id given in argument is
 * GB, false if not.
 * 
 * @param country_id the country id to test
 * 
 * NB: To be modified when the new redirect java version will be in production
 */
function get_redirect_uk_url(country_id) {
	var result = false;
	if (country_id == 'GB') {
		$.ajax({
			type: "GET",
			async: false,
			url: "/vsc/getRedirectionUKUrl",
			data:"DC=" + country_id,
			success: function(data) {
				if (data != '') {
					result = data;
				} else {
					result = false;
				}
			},
			error: function() {
				//TODO New Java version refactoring: delete next 2 lines and uncomment the other
				global_oldRedirectVersion = true;
				result = 'http://clk.tradedoubler.com/click?p=65194&a=1938736&g=19571098';
				//result =  false;
			}
		});
	}
	return result;
}

/**
 * Check if the user can be redirected and display popup or redirect depending 
 * on the tests.
 * 
 * @param origin Whether we are coming from the map, homepage (onload), or booking form (either express booking or launch train)
 * @param noCloseButton (optional) Option to hide the close button (or not), in case we want to force the user to select a choice (when coming from the booking forms) 
 * @param submitButton (optional) Submit button (jquery object) of the form in case we are coming from the booking forms
 * @param country the user's origin country
 * @return true or false depending if we must display the popup or not
 */
function TGVERedirection(origin, noCloseButton, submitButton, country) {
  //get url to redirect to if necessary
  var redirect_url = get_redirect_uk_url(country);
  
  if (redirect_url) {
	  // Get cookie
	  var cookie = $.cookie("vsct-re-redirect");
	  // Cookie does not exist, display lightbox
	  if (cookie == null) {
			// Only bind the click function for close button if it's not already visible (as in that case it would already be bound)
			if (origin == 'on-booking-submit' && !$('#fancy_close.fancylink-re-redirect-on-booking-submit').is(":visible")) {  				  
				// Call lightbox display		
				showRedirectChoice(origin, noCloseButton, submitButton, country);
				return false;
			} else if (origin == 'on-home-load' || origin == 'on-map-click') {
				showRedirectChoice(origin, noCloseButton, submitButton, country);
				return false;
			}
			return true;
	  } else {
		  // Cookie exists, deal with
		  // Do only something if value is TRUE, meanning user choosed to go to RailEurope
		  if (cookie == 1) {
			  // Cookie is TRUE, meanning user choosed to go to RailEurope
			  window.location = redirect_url;
			  return false;
		  } else {
			  return true;
		  }
	  }
  } else {
	  return true;
  }
}

/**
 * Displaying choice lightbox for RailEurope redirection.
 * 
 * @param origin Whether we are coming from the map, homepage (onload), or booking form (either express booking or launch train)
 * @param noCloseButton (optional) Option to hide the close button (or not), in case we want to force the user to select a choice (when coming from the booking forms) 
 * @param submitButton (optional) Submit button (jquery object) of the form in case we are coming from the booking forms
 * @param country the user's origin country
 *
 * NB: To be modified when the new redirect java version will be in production:
 * remove the if statement
 */
function showRedirectChoice(origin, noCloseButton, submitButton, country) {
  var showCloseButton = true;
  if (noCloseButton) {
    showCloseButton = false;
  }

  // Create the link id/class
  var link_id = 'fancylink-re-redirect-' + origin ;
  // Create link on which a click will be done
  
  //TODO JAVA new version refactoring : remove the if statement
  if (global_oldRedirectVersion) {
	  $("body").after('<a id="' + link_id + '" href="/vsc/train-ticket/enterIntersticeRedirectUK?token='+(new Date()).getTime()+'" class="iframe hidden" style="display: none;">Open fancybox</a>');
  } else {
	  $("body").after('<a id="' + link_id + '" href="/en/redirect/popup-uk?DC='+country+'&token='+(new Date()).getTime()+'" class="iframe hidden" style="display: none;">Open fancybox</a>');
  }
  
  //Instantiate the ligthbox library
  $("a#" + link_id).fancybox({
    "padding"               : 0,
    "overlayShow"           : true,
    "overlayOpacity"        : 0.4,
    "hideOnContentClick"    : false,
    "hideOnOverlayClick"	  : showCloseButton,
    "frameWidth"            : 690,
    "frameHeight"           : 331,
    "centerOnScroll"        : false,
    "showCloseButton"       : true,
    "callbackOnShow": function () {
      var closeTop = $(this).fancybox.i18n[vscLocaleUtil.getLang()].closeTop;
      $("#fancy_close").html("\x3Cdiv class=\x22fermer\x22 id=\x22TB_closeAjaxWindow\x22\x3E\x3Ca id=\x22TB_closeWindowButton\x22 href=\x22#\x22 class=\x22closed\x22\x3E" + closeTop + "\x3C/a\x3E\x3C/div\x3E");

      if (!showCloseButton) {
        $("#fancy_close").hide();
      }
      // Add a class on the close link of the lightbox to know later if we must submit the booking form
      $("#fancy_close").attr('class', link_id);
    },
    // Lightbox close event
    "callbackOnClose": function() {        
      // Check if the close button has the CSS class meanning that the lightbox
      // has been launched after a booking form submit
      if(submitButton && $("#fancy_close").hasClass('fancylink-re-redirect-on-booking-submit')) {
        // Submit the form to resume
        submitButton.click();
      }
      else if ($("#fancy_close").hasClass('fancylink-re-redirect-on-map-click')) {
        // Redirect to TGVE
        var redir = $("#redir-re-TGVE").attr('href');
        window.location.href = redir;
      }
    }
  });
  // Click on the link to launch a lightbox
  $("#" + link_id).click();
  // Remove the link
  $("#" + link_id).remove();
}
