var originalCardList;

// Flash map global variables
var from_station_element;
var to_station_element;

var active_station_element;
var active_type;
var active_retval;
var active_value;

var stationobjectsearch_url;
var selectedFromStation;
var selectedToStation;
var unknownStationUnknownText;
var unknownStationMissingText;
var unknownStationImageHtml;

var CSSHelper ={
  createStyleRule: function(selector, declaration)
  {
    // We can't manipulate the document like we want, so don't try
    if (!document.getElementsByTagName || !(document.createElement || document.createElementNS)) {
        return;
    }

    // This is incompatible with IE Mac
    if (Environment.browser_is_ie() && Environment.platform_is_mac()) {
        return;
    }

    var head = document.getElementsByTagName('head')[0];
    var style = (typeof document.createElementNS != 'undefined') ?
      document.createElementNS('http://www.w3.org/1999/xhtml', 'style') : document.createElement('style');

    var is_iewin = (Environment.browser_is_ie() && Environment.platform_is_win());
    if (!is_iewin) {
      var style_rule = document.createTextNode(selector + ' {' + declaration + '}');
      style.appendChild(style_rule);
    }
    style.setAttribute('type', 'text/css');
    style.setAttribute('media', 'screen');
    head.appendChild(style);

    if (is_iewin && document.styleSheets && (document.styleSheets.length > 0)) {
      var last_style = document.styleSheets[document.styleSheets.length - 1];
      if (typeof last_style.addRule == 'object') {
        last_style.addRule(selector, declaration);
      }
    }
  }
};

var Environment = {
  browser: function() { return navigator; },
  browser_is_ie: function() { return (Environment.browser().appName == "Microsoft Internet Explorer"); },
  browser_is_ie_6: function() { return (Environment.browser_is_ie() && (Environment.browser().userAgent.toLowerCase().indexOf('msie 6.') != -1)); },
  browser_is_ie_7: function() { return (Environment.browser_is_ie() && (Environment.browser().userAgent.toLowerCase().indexOf('msie 7.') != -1)); },
  browser_is_opera: function() { return Environment.browser().appName == "Opera"; },
  browser_is_moz: function() { return (Environment.browser().appName == "Netscape"); },
  browser_is_safari: function() { return (Environment.browser().userAgent.toLowerCase().indexOf("applewebkit") != -1); },
  platform_is_win: function() { return (Environment.browser().userAgent.toLowerCase().indexOf("win") != -1); },
  platform_is_mac: function() { return (Environment.browser().userAgent.toLowerCase().indexOf("mac") != -1); },
  platform_is_linux: function() { return (Environment.browser().userAgent.toLowerCase().indexOf("linux") != -1); },
  getDocumentWidth: function()
  {
    if (window.innerWidth != null) {
      return window.innerWidth;
    } else if (document.body.clientWidth != null) {
      return document.body.clientWidth;
    } else {
      return null;
    }
  },
  getDocumentHeight: function()
  {
    if (window.innerHeight != null) {
      return window.innerHeight;
    } else if (document.body.clientHeight != null) {
      return document.body.clientHeight;
    } else {
      return null;
    }
  },
  getUrlParameter: function(param)
  {
    var url = window.location.href;
    var start_of_parameters = url.indexOf('?');
    if (start_of_parameters > -1) {
      var parameter_str = url.substr(start_of_parameters).toLowerCase();
      var parameters = parameter_str.split('&');
      for (var i = 0; i < parameters.length; i++) {
        if (parameters[i].indexOf(param + '=') > -1) {
          return parameters[i].split('=');
        }
      }
    }
    return null;
  }
};

var Cookie = {
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? decodeURIComponent(cookie[2]) : null);
  }
};

var FormPropertiesFromCookie = {
    setFormValue : function(formId, propertyId) {
        var formElementId = formId + '-' + propertyId;
        // Check if the URL contains a value for the property
        var urlValue = Environment.getUrlParameter(formElementId);
        if(urlValue == null) {
            var formElement = $(formElementId);
            var valueInCookie = Cookie.get(formId + '-' + propertyId);
            if(valueInCookie != null && formElement != null) {
                formElement.value = valueInCookie.replace(/\+/g, ' ');
            }
        }
    }
};

var Purchase1ProgressUtil = {
  gotoStep2: function(infoText, animationUrl, cancelUrl, cancelText)
  {
      // Modalbox does not work on opera
      if(!Environment.browser_is_opera()) {
        var header = '<div class="header" style="height: 65px;">&nbsp;</div>';
        var info = '<div class="info">' + infoText + '</div>';
        var animation = '<div class="animation"><img src="' + animationUrl + '"/></div>';
        var close_button= '<div class="close_button"><a href="' + cancelUrl + '"><span class="button"><span class="inner_border"><span>' + cancelText + '</span></span></span></a></div>';
        var footer = '<div class="footer" style="height: 60px;">' + close_button + '</div>';

        // Construct the content
        var content = '<div class="content">' + info + animation + '</div>';
        var outer_div = '<div class="purchase1_progress">' + header + content + footer + '</div>';
        // Show the actual dialog
        Modalbox.show(outer_div, {width: 400, displayLeft: 225, displayTop: 146, title: this.title, inactiveFade: false, transitions: false });
        Modalbox.deactivate();
      }
  }
};

var smsStopInfo = {
	stopService: function(infoText, buttonUrl, buttonText)
	{
		var header = '<div class="header" style="height: 65px;">&nbsp;</div>';
		var info = '<div class="info">' + infoText + '</div>';
		var close_button= '<div class="close_button"><a href="' + buttonUrl + '"><span class="button"><span class="inner_border"><span>' + buttonText + '</span></span></span></a></div>';
        var footer = '<div class="footer" style="height: 60px;">' + close_button + '</div>';

        // Construct the content
        var content = '<div class="content">' + info + '</div>';
        var outer_div = '<div class="purchase1_progress">' + header + content + footer + '</div>';
        // Show the actual dialog
        Modalbox.show(outer_div, {width: 400, displayLeft: 225, displayTop: 146, title: this.title, inactiveFade: false, transitions: false });
        Modalbox.deactivate();
        
	}
};

var AjaxHelper = {
  autocomplete: function(elem_id, result_div_id, url)
  {
    completer = new Ajax.Autocompleter(elem_id, result_div_id, url,
                                {paramName: 'input', minChars: 1, method: 'get', frequency: 0.3});
  },
  get_station_id: function(station_name)
  {
    if(station_name) {
      result = new Ajax.Request(stationobjectsearch_url + '&input=' + encodeURIComponent(station_name), {asynchronous:false, method:'get'});
      response = result.transport.responseText;
      station_array = response.split(':');

      station_name = station_array[1];
      station_id = station_array[2];
      return station_id;
    }
    else {
      return;
    }
  },
  set_stationobjectsearch_url: function(url) { stationobjectsearch_url = url; },
  getCalendar: function(elem_id, current_date, url)
  {
    var ajaxUpdater = new Ajax.Updater(elem_id, url + '?date=' + current_date, {method:'get'});
  },
  selectDate: function(calendar_id, result_elem_id, selected_date, element_hide)
  {
    var calendar = $(calendar_id);

    if (Environment.browser_is_ie_6() && ($(element_hide) != null)) {
      $(element_hide).style.visibility = 'visible';
    }

    if ((selected_date != null) && (selected_date != 0)) {
      // Only set new value if one is given
      element = $(result_elem_id);
      element.value = selected_date;
    }
    // Hide calendar again
    calendar.style.display = 'none';
  }
};

var FormHelper = {
  setupPurchaseForm: function()
  {
    // Setup for step 1
    var purchase_form_element = $('purchase_form');
    if (purchase_form_element) {
      // Only perform these actions on the front page
      var checked_value = null;
      // Next element refers to the 'return' radio button and must be changed if the form changes
      if (purchase_form_element.elements[3].checked) {
        FormHelper.toggleReturn();
      }
      if ($('purchase_form-num_adults')) {
          FormHelper.updateLoyaltyCard($('purchase_form-num_adults').value);
      }
    }
    // Setup for step 3
    var services_form_element = $('services_form');
    if (services_form_element) {
        // Check if sleep is selected, and if so, make extra selection visible
        var trip_types = ['departure', 'return'];
        for(var j = 0; j < trip_types.length; j++) {
            var trip_type = trip_types[j];
            for(var i = 0; i < 8; i++) {
                var radio_element = $('services_form-' + trip_type + '-' + i + '-sove1000');
                if(radio_element) {
                    var extra_element = $('extra-selection-' + trip_type + '-' + i + '-ex-sove1000');
                    if(extra_element) {
                        var styleForExtraElement = 'block';
                        if(!radio_element.checked) {
                            // Hide the extra element
                            styleForExtraElement = 'none';
                        }
                        CSSHelper.createStyleRule('#' + 'extra-selection-' + trip_type + '-' + i + '-ex-sove1000', 'display: ' + styleForExtraElement + ';');
                    }
                }
            }
        }
    }
    // Setup for seasonticket step 4
    var seasonticket_customer_form_element = $('seasonticket_customerdetails_form');
    if (seasonticket_customer_form_element) {
      Cvc2Enabling.showOrHideCvc2Element('seasonticket_customerdetails_form-card_type', 'seasonticket_customerdetails_form-card_cvc2');
    }    
  },
  toggleReturn: function()
  {
    var purchase_form_element = $('purchase_form');
    var period_purchase_form_element = $('seasonticket_trip_form');
    if (purchase_form_element) {
      // Next element refers to the 'departure' radio button and must be changed if the form changes. 2=Roundtrip, 3=single, 4=period.
      if (purchase_form_element.elements[2].checked) {
        $('purchase_form-time_return').style.display = 'block';
        if (Environment.browser_is_ie()) {
          $('cal_end').style.display = 'block';
        }
        else {
          $('cal_end').style.display = 'table';
        }
        $('return_date_label').style.display = 'block';
        $('return_time_label').style.display = 'block';
        $('calendar_spacer_return').style.display = 'none';
        $('time_spacer_return').style.display = 'none';
        $('frontpage_seasonticket').style.display='none';
        $('purchase_form').style.display='block';
      } else if (purchase_form_element.elements[3].checked) {
        $('purchase_form-time_return').style.display = 'none';
        $('cal_end').style.display = 'none';
        $('return_date_label').style.display = 'none';
        $('return_time_label').style.display = 'none';
        $('calendar_spacer_return').style.display = 'block';
        $('time_spacer_return').style.display = 'block';
        $('frontpage_seasonticket').style.display='none';
        $('purchase_form').style.display='block';
      } else if (purchase_form_element.elements[4].checked) {

        $('seasonticket_trip_form-from_station').value=$('purchase_form-from_station').value;
        $('seasonticket_trip_form-to_station').value=$('purchase_form-to_station').value;
        
        $('frontpage_seasonticket').style.display='block';
        $('purchase_form').style.display='none';
        if (period_purchase_form_element) {
            period_purchase_form_element.elements[4].checked = true;
        }
      }
    }
  },
  toggleReturn2: function()
  {
      var purchase_form_element = $('purchase_form')  ;
      var period_purchase_form_element = $('seasonticket_trip_form');
      if (purchase_form_element && period_purchase_form_element) {
          if (period_purchase_form_element.elements[2].checked) {
              purchase_form_element.elements[2].checked=true;
              $('purchase_form-time_return').style.display = 'block';
              if (Environment.browser_is_ie()) {
                  $('cal_end').style.display = 'block';
              }
              else {
                  $('cal_end').style.display = 'table';
              }
              $('return_date_label').style.display = 'block';
              $('return_time_label').style.display = 'block';
              $('calendar_spacer_return').style.display = 'none';
              $('time_spacer_return').style.display = 'none';
              $('purchase_form-from_station').value=$('seasonticket_trip_form-from_station').value;
              $('purchase_form-to_station').value=$('seasonticket_trip_form-to_station').value;
              $('frontpage_seasonticket').style.display='none';
              $('purchase_form').style.display='block';
          } else if (period_purchase_form_element.elements[3].checked) {
              purchase_form_element.elements[3].checked=true;
              $('purchase_form-time_return').style.display = 'none';
              $('cal_end').style.display = 'none';
              $('return_date_label').style.display = 'none';
              $('return_time_label').style.display = 'none';
              $('calendar_spacer_return').style.display = 'block';
              $('time_spacer_return').style.display = 'block';
              $('purchase_form-from_station').value=$('seasonticket_trip_form-from_station').value;
              $('purchase_form-to_station').value=$('seasonticket_trip_form-to_station').value;
              $('frontpage_seasonticket').style.display='none';
              $('purchase_form').style.display='block';
          }
      }
  },
  turnOffSeasonTicket: function() {
      $('frontpage_seasonticket').style.display='none';
      $('purchase_form').style.display='block';
      $('purchase_form-ticket_typeperiod_label').style.display='inline';
  },
  getCheckedValue: function(radioObj)
  {
    if(!radioObj) {
      return "";
    }
    var radioLength = radioObj.length;
    if(radioLength == undefined) {
      //console.log(radioObj);
      if(radioObj.checked) {
        return radioObj.value;
      }
      else {
        return "";
      }
    }
    for(var i = 0; i < radioLength; i++) {
      if(radioObj[i].checked) {
        return radioObj[i].value;
      }
    }
    return "";
  },
  updateLoyaltyCard: function(count)
  {
    var element = $('purchase_form-num_card');
    if (element) {
      var originalSelection = element.value;
      if (!originalCardList) {
        originalCardList = [];
        for (var i = 0; i < element.options.length; i++) {
          originalCardList[i] = element.options[i].firstChild.data;
        }
      }

      newCardList = [];

      element.options.length = 0;
      for (i = 0; i <= count; i++) {
        element.options[i] = new Option(originalCardList[i], i);
      }
      if (originalSelection <= count) {
        element.value = originalSelection;
      }
    }
  },
  setupTimeTableSearchForm: function()
  {
    var formElement = $('timetablesearch');
    if (formElement) {
      // Set the enabling of time period elements
      FormHelper.setEnablingPeriodsInTimeTable();
    }
  },
  setEnablingPeriodsInTimeTable: function()
  {
    var checkBoxElement = $('timetablesearch-view_all_day');
    var depStartTimeElement = $('timetablesearch-depart_start_time');
    var depEndTimeElement = $('timetablesearch-depart_end_time');
    var arrStartTimeElement = $('timetablesearch-arrive_start_time');
    var arrEndTimeElement = $('timetablesearch-arrive_end_time');
    var disable = false;
    if(checkBoxElement.checked) {
      disable = true;
    }
    depStartTimeElement.disabled = disable;
    depEndTimeElement.disabled = disable;
    arrStartTimeElement.disabled = disable;
    arrEndTimeElement.disabled = disable;
  },
  clearDefaultText: function(text, element)
  {
    if (element) {
      if (element.value == text) {
        element.value = '';
        // Make sure cursor is shown in IE
        if (Environment.browser_is_ie()) {
          var range = element.createTextRange();
          range.moveStart('character', element.value.length);
          if (range.select) {
              range.select();
          }
        }
      }
      // Make sure element retains focus
      element.focus();
    }
  },
  restoreDefaultText: function(text, element)
  {
    if (element) {
      if (element.value == '') {
        element.value = text;
      }
    }
  },
  setupTrainOnTimeResult: function()
  {
    var formElement1 = $('trainontimeresult');
    var formElement2 = $('mypagetrainontimeresult');
    if (formElement1 || formElement2) {
        // Hide all  long messages initially
        for(var i = 0; i < 50; i++) {
            var readMoreLinkId = 'readmorelink_' + i;
            var readMoreLink = $(readMoreLinkId);
            // Hide the message if we found it, otherwise abort, since
            // there is no more messages then
            if(readMoreLink != null) {
                FormHelper.toggleLongTrainOnTimeMessage(i, false);
            }
            else {
                break;
            }
        }
    }
  },
  toggleLongTrainOnTimeMessage: function(messageNumber, show)
  {
    var readMoreLinkId = 'readmorelink_' + messageNumber;
    var longMessageId = 'restofmessage_' + messageNumber;
    var hideMessageId = 'hidelink_' + messageNumber;
    var trafficInformationId = 'trafficInformationLink_' + messageNumber;
    var readMoreLink = $(readMoreLinkId);
    if(readMoreLink != null) {
        if(show) {
            CSSHelper.createStyleRule('#' + readMoreLinkId, 'display: none;');
            CSSHelper.createStyleRule('#' + longMessageId, 'display: block;');
            CSSHelper.createStyleRule('#' + hideMessageId, 'display: block;');
            CSSHelper.createStyleRule('#' + trafficInformationId, 'display: inline;');
        }
        else {
            CSSHelper.createStyleRule('#' + readMoreLinkId, 'display: inline;');
            CSSHelper.createStyleRule('#' + longMessageId, 'display: none;');
            CSSHelper.createStyleRule('#' + hideMessageId, 'display: none;');
            CSSHelper.createStyleRule('#' + trafficInformationId, 'display: none;');
        }
    }      
  },
  includePickupLocationInSubmit: function(sourceId, targetId)
  {
      var sourceElement = $(sourceId);
      if(sourceElement != null) {
          var targetElement = $(targetId);
          if(targetElement != null) {
              targetElement.value = sourceElement.value;
          }
      }
      return true;
  },
  toggleElements: function(elements, states)
  {
    if (elements) {
      elements.each ( function(element) {
        $(element).style.display = ($(element).getStyle('display') == states.first()) ? states.last() : states.first();
      });
    }
  },
  toggleSMSShowDetails: function(show)
  {
      if(show) {
          CSSHelper.createStyleRule('div.mypage-smsalerts div.mypage-smstable table.smsinfotable tbody tr td.more span.smsshow', 'display: none;');
          CSSHelper.createStyleRule('div.mypage-smsalerts div.mypage-smstable table.smsinfotable tbody tr td.more span.smshide', 'display: inline;');
          CSSHelper.createStyleRule('div.mypage-smsalerts div.mypage-smstable div.smshidden', 'display: block;');
          CSSHelper.createStyleRule('div.mypage-smsalerts div.mypage-smstable table tbody tr.smsinforow', 'background-color: #CDC2BB;');
          
      } else {
          CSSHelper.createStyleRule('div.mypage-smsalerts div.mypage-smstable table.smsinfotable tbody tr td.more span.smsshow', 'display: inline;');
          CSSHelper.createStyleRule('div.mypage-smsalerts div.mypage-smstable table.smsinfotable tbody tr td.more span.smshide', 'display: none;');
          CSSHelper.createStyleRule('div.mypage-smsalerts div.mypage-smstable div.smshidden', 'display: none;');
          CSSHelper.createStyleRule('div.mypage-smsalerts div.mypage-smstable table tbody tr.smsinforow', 'background-color: #FFFFFF;');

      }
  },
  cleanupGoogleMapForStationArticle: function()
  {
    var formElement = $('station_google_map');
    if (formElement) {
        GUnload();
    }
    else {
        formElement = $('stationanddistance-article-destination');
        if (formElement) {
            GUnload();
        }
    }
  }  
};

var WindowHelper = {
  elementPosition: function(element)
  {
    var curleft = 0;
    var curtop = 0;
    if (element.offsetParent) {
      curleft = element.offsetLeft;
      curtop = element.offsetTop;
      while ((element = element.offsetParent)) {
        curleft += element.offsetLeft;
        curtop += element.offsetTop;
      }
    }
    return [curleft,curtop];
  },
  openWindow: function(url, w, h, options, parent_elem, title)
  {
    var x, y;

    if (parent_elem != null) {
      // Open window next to parent element if one is given
      var pos = WindowHelper.elementPosition(parent_elem);
      x = pos[0];
      y = pos[1];
    } else {
      // Open window in the middle of the screen
      x = (640 - w)/2;
      y = (480 - h)/2;
      if (screen) {
        x = (screen.availWidth - w)/2;
        y = (screen.availHeight - h)/2;
      }
    }
    // Append window position to options
    options = options + ',screenX=' + x + ',screenY=' + y + ',left=' + x + ',top=' + y + ',height=' + h + ',width=' + w;

    var win;
    if (title != null) {
      // Open the window with the provided title
      win = window.open(url, title, options);
    } else {
      // Open the window with a 'random' title to make sure we actually open a new window
      win = window.open(url, new Date().getTime(), options);
    }
    win.focus();
    return win;
  },
  openClean: function(url, w, h, parent_elem, title)
  {
    var options = "status=no,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes";
    return WindowHelper.openWindow(url, w, h, options, parent_elem, title);
  },
  openVeryClean: function(url, w, h, parent_elem, title)
  {
    var options = "status=no,toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no";
    return WindowHelper.openWindow(url, w, h, options, parent_elem, title);
  },
  showElement: function(element, displaystyle)
  {
    element.style.display =  displaystyle;
  }
  ,showCalendar: function(element, displaystyle, element_hide)
  {
    if (Environment.browser_is_ie_6()) {
      $(element_hide).style.visibility = 'hidden';
    }
    element.style.display =  displaystyle;
  }
};

function siteSetup()
{
  FormHelper.setupPurchaseForm();
}
function siteCleanup()
{
  FormHelper.cleanupGoogleMapForStationArticle();
}

if (document.getElementById) {
  var url_param = Environment.getUrlParameter('purchase_form-ticket_type');
  if (url_param && (Environment.getUrlParameter('purchase_form-ticket_type')[1] == 'single')) {
    CSSHelper.createStyleRule('#cal_end', 'display: none;');
    CSSHelper.createStyleRule('#purchase_form-time_return', 'display: none;');
    CSSHelper.createStyleRule('#return_date_label', 'display: none;');
    CSSHelper.createStyleRule('#return_time_label', 'display: none;');
    CSSHelper.createStyleRule('#calendar_spacer_return', 'display: block;');
    CSSHelper.createStyleRule('#time_spacer_return', 'display: block;');
  }
  CSSHelper.createStyleRule('.autocomplete_choices', 'display: block;');
}

// Functions for intefacing with the Flash map
var MapHelper = {
    getMapElement : function() {
        return $('flash_map_nsb');
    },
    closeArticleWindow : function() {
        Element.hide('stationanddistance-article-destination');
        Element.hide('stationanddistance-article-closewindow');
    },
    setUnknownStationInfo: function(aUnknownText, aMissingText, aImageHtml)
    {
        unknownStationUnknownText = aUnknownText;
        unknownStationMissingText = aMissingText;
        unknownStationImageHtml = aImageHtml;
    },    
    selectStationInMap : function(formId, elementId)
    {
      // Clear any error messages for form
      var formErrorSection = $(formId + '-error_section');
      if(formErrorSection != null) {
          formErrorSection.innerHTML = '';
      }
      
      // Find the station id for the station name typed by the user
      var station_name = $(elementId).value;
      var station_id = AjaxHelper.get_station_id(station_name);
      if(station_id) {
          // Select the station in the map if it was found
          var mapElement = MapHelper.getMapElement();
          if(mapElement != null) {
              mapElement.showObject(1, station_id);
          }
      }
      else {
          if(formErrorSection != null) {
              var message = null;
              if((fromStationName != null && fromStationName.length > 0) || (toStationName != null && toStationName.length > 0)) {
                  message = unknownStationUnknownText;
              }
              else {
                  message = unknownStationMissingText;
              }
              formErrorSection.innerHTML = '<div class="content"><div class="general_messages"><ul><li>' + unknownStationImageHtml + message +  '</li></ul></div></div><div class="footer">&nbsp;</div>';
          }
      }
    },
    selectDistanceInMap : function(formId, fromElementId, toElementId) {
        // Find the station id for the station name typed by the user
        var fromElement = $(fromElementId);
        var toElement = $(toElementId);
        var fromStationName = null;
        var toStationName = null;
        var fromStationId = null;
        var toStationId = null;        
        var stationsEventObject = new Object();

        if(fromElement != null) {
            fromStationName = fromElement.value;
            if(fromStationName != null) {
                fromStationId = AjaxHelper.get_station_id(fromStationName);
                stationsEventObject.fromId = fromStationId;
                stationsEventObject.fromName = fromStationId;
            }
        }
        if(toElement != null) {
            toStationName = toElement.value;
            if(toStationName != null) {
                toStationId = AjaxHelper.get_station_id(toStationName);
                stationsEventObject.toName = toStationName;
                stationsEventObject.toId = toStationId;
            }
        }
        // Select the distance in the map
        var mapElement = MapHelper.getMapElement();
        if(mapElement != null) {
            mapElement.setRoute(fromStationId, toStationId, null);
            // Manually send the event, since the map does not send it
            ReceiveMapEventHelper.tripSelected(stationsEventObject);
        }
    },
    showMap: function(container, input_element_id)
    {
      $(container).style.visibility = 'visible';
    },
    gotoFrontpage: function(fromElementId, toElementId, frontpageFromStationId, frontpageToStationId, baseUrl, linkId)
    {
        var fromStationElement = $(fromElementId);
        var toStationElement = $(toElementId);
        var linkElement = $(linkId);
        var fromStation = null;
        var toStation = null;
        if(linkElement) {
            if(fromStationElement != null && fromStationElement.value.length > 0 ) {
                fromStation = fromStationElement.value;
            }
            if(toStationElement != null && toStationElement.value.length > 0) {
                toStation = toStationElement.value;
            }
           
            if(fromStation != null || toStation != null) {
                var completeUrl = null;
                if(baseUrl.indexOf('?') >= 0) {
                    completeUrl = baseUrl + '&';
                }
                else {
                    completeUrl = baseUrl + '?';
                }
                var addedFromParam = false;
                if(fromStation != null) {
                    completeUrl = completeUrl + frontpageFromStationId + '=' + fromStationElement.value;
                    addedFromParam = true;
                }
                if(toStation != null) {
                    if(addedFromParam) {
                        completeUrl = completeUrl + '&';
                    }
                    completeUrl = completeUrl + frontpageToStationId + '=' + toStationElement.value;
                }

                // Update the link element
                linkElement.href = completeUrl;
            }
        }
        return true;
    },
    showArticleOnMap: function(type, id, elementId)
    {
        var articleUrl = getAjaxArticleOnMapUrl(type, id);
        MapHelper.showArticleUrlOnMap(articleUrl, elementId);
    },
    showArticleIdOnMap: function(type, articleId, elementId)
    {
        var articleUrl = getAjaxArticleOnMapUrl(type, articleId);
        // Don't try to show info article on linux, wmode=transparent doesn't work
        if (Environment.platform_is_linux()) {
          WindowHelper.openClean(articleUrl, 400, 500);
        } else {
          MapHelper.showArticleUrlOnMap(articleUrl, elementId);
        }
    },
    showArticleUrlOnMap: function(articleUrl, elementId)
    {
        element = $(elementId);
        // Retrieve new content
        if(articleUrl != null && element != null) {
            var showContent = function(t, o) {
                if(t.status != 404 && t.status != 500 && t.responseText.indexOf("<div class=\"article-display\">") >= 0) {
                    Element.show(element.id);
                    Element.show('stationanddistance-article-closewindow');
                    Element.show('ajax_closebutton_for_map');
                }
            };
            var ajaxUpdater = new Ajax.Updater(element.id, articleUrl, {method:'get', asynchronous:true, onComplete: showContent, evalScripts: true});
        }
    }
};

var StationMapHelper = {
  openMap: function(url, type, retval, element, other_element_id)
  {
    if (retval == 'fromId') {
      to_station_element = $(other_element_id);
      from_station_element = $(element);
    } else {
      to_station_element = $(element);
      from_station_element = $(other_element_id);
    }

    map_window = WindowHelper.openVeryClean(url, 583, 403, $(element), 'Map');
    active_type = type;
    active_retval = retval;
    active_station_element = element;
    active_value = $(element).value;
  }
};

var ReceiveMapEventHelper = {
    // Functions for receiving messages from the Flash map
    destinationArticleDisplay : function (destination) {
        if(destination.type == 2) {
            var articleDisplayDiv = $('stationanddistance-article-destination');
            if(articleDisplayDiv != null) {
                // Remove any existing content
                articleDisplayDiv.innerHTML = '';
                // Retrieve new content
                MapHelper.showArticleOnMap('2', destination.id, articleDisplayDiv.id);
            }
        }
    },
    tripSelected : function (stations) {
        // Remove any content for the image in the margin
        var imageDiv = $('stationanddistance-image-display');
        if(imageDiv != null) {
           imageDiv.innerHTML = ''; 
        }
        
        // Display links for selected station in the tile to the right of the map
        var articleDisplayDiv = $('stationanddistance-articlelinks');
        if(articleDisplayDiv != null) {
            // Remove any existing content
            articleDisplayDiv.innerHTML = '';
            // Retrieve new content
            if(stations.toId != null) {
                var articleUrl = getAjaxArticleStationLinksUrl(stations.toId);
                if(articleUrl != null) {
                    var showContent = function(t, o) {
                        if(t.status != 404 && t.status != 500 && t.responseText.indexOf("<div class=\"article-content\">") >= 0) {
                            Element.show(articleDisplayDiv.id);

                            // Check if the station has an image2, which should be displayed
                            // in the imageDiv
                            var stationImage2Div = $('station_image2_hidden');
                            if(stationImage2Div != null) {
                                imageDiv.innerHTML = stationImage2Div.innerHTML;
                            }
                        }
                        else {
                            Element.hide(articleDisplayDiv.id);
                        }
                    };
                    var ajaxUpdater = new Ajax.Updater(articleDisplayDiv.id, articleUrl, {method:'get', asynchronous:true, onComplete: showContent});
                }
            }
        }
        // Set the to station for the to fields in both tabs
        // Check which tab is active
        var destinationToElement = $('stationanddistancesearchdistance-destination_to_station');
        if(destinationToElement != null) {
            destinationToElement.value = stations.toName;
        }
        destinationToElement = $('stationanddistancesearchdistance-to_station');
        if(destinationToElement != null) {
            destinationToElement.value = stations.toName;
        }
        // Zoom to the select stations
        // Select the distance in the map
        var mapElement = MapHelper.getMapElement();
        if(mapElement != null) {
            mapElement.setRoute(stations.fromId, stations.toId, null);
        }        
    }
};
/**
 *  These methods and variables is copied from Coretreks cplib.js
 *  cpNavigatorUserAgent, cpNavigatorUserAgentInfo, 
 *  cpWriteMediaObject(...), cpReadCookie(...), getQueryParamsFromObject(...)
 */
var cpNavigatorUserAgent = navigator.userAgent.toLowerCase() ;
var cpNavigatorUserAgentInfo = {
    isIE     : (cpNavigatorUserAgent.indexOf('msie')>-1),
    isIE7    : (cpNavigatorUserAgent.indexOf('msie 7')>-1),
    isGecko  : (cpNavigatorUserAgent.indexOf('gecko/')>-1),
    isSafari : (cpNavigatorUserAgent.indexOf('safari')>-1),
    isOpera  : (cpNavigatorUserAgent.indexOf('opera')>-1),
    isMac    : (cpNavigatorUserAgent.indexOf('macintosh')>-1)
};

/**
 *  Function used to print flash and movies inline
 *
 *  *) These settings might not work in all browser plugins
 *
 *  @src         string The full URL to the video
 *  @sessionName string The session name where users sessionid is stored (used for IE)
 *  @width       int The width
 *  @height      int The height
 *  @mimetype    string The files mimetype
 *  @loop        boolean Whether or not to loop the video *
 *  @autoplay    boolean Whether or not to start the video when it's loaded *
 *  @controller  boolean Whether or not to include plugin controllers *
 */
function cpWriteMediaObject(src, sessionName, width, height, mimeType, loop, autoplay, controller, objId){
    var objectSettings = '';

    // Detect protocol for codebase
    var codebaseProtocol = (src.substr(0,5)=='https'?'https':'http');

    // Check if this is a flash movie
    var isFlashMovie = new Object();
    
    isFlashMovie['video/x-flv'] = true;
    isFlashMovie['application/x-flash-video'] = true;
    isFlashMovie['video/x-flv'] = true;

    if (isFlashMovie[mimeType] != null){    
        var flashVars = new Object();         
        flashVars["file"] = encodeURIComponent(src);
        flashVars["width"] = width;
        flashVars["height"] = height;       
        //flashVars["displayheight"] = height+; // set to same as height for floating controls
        flashVars["overstrech"] = 'true';
        flashVars["frontcolor"] = '0xFFFFFF';
        flashVars["backcolor"] = '0x000000';
        flashVars["lightcolor"] = '0xFFFFFF';
        flashVars["autostart"] = autoplay?'true':'false';
        flashVars["repeat"] = loop?'true':'false';
        flashVars["usefullscreen"] = 'true';

        // Add flash movie parameters
        objectSettings += '<param name="allowscriptaccess" value="always" />';
        objectSettings += '<param name="allowfullscreen" value="true" />';
        objectSettings += '<param name="flashvars" value="' + getQueryParamsFromObject(flashVars) + '" />';

        mimeType = 'application/x-shockwave-flash';
        src = CPLIBHTMLROOT +'/mediaplayer.swf';
    }

    // Handling IE specialties
    var rewriteMimeType = new Object();
    if (cpNavigatorUserAgentInfo.isIE){
    
        rewriteMimeType['audio/mpeg'] = 'application/x-mplayer2';
        rewriteMimeType['video/mpeg'] = 'application/x-mplayer2';
        rewriteMimeType['video/x-msvideo'] = 'video/x-ms-wmv';
    }
    // In some cases we must change the mimetype for IE :/
    if (rewriteMimeType[mimeType] != null){
        mimeType = rewriteMimeType[mimeType];
    }

    // Add object parameters
    if (mimeType != 'application/x-shockwave-flash') {    
        objectSettings += '<param name="loop" value="' +(loop?'true':'false') +'" />';
        objectSettings += '<param name="autostart" value="' +(autoplay?'true':'false') +'" />';
        objectSettings += '<param name="controller" value="' +(controller?'true':'false') +'" />';
    } else {
        objectSettings += '<param name="wmode" value="opaque" />';
    }

    // IE: We need to add sessionid to the URL in order for the video plugin to use the same session
    //     as IE. If sessionid is not sent, the video plugin will try to load the URL without a valid
    //     session causing the session to be destoyed.
    //     -----------------------------
    //     NOTE from Kurt: The session id broke together with the new JW FLV player. I first tried removing
    //     this alltogether, and it seem to work, event with user protected files. I can't get it
    //     to break whatever I do. To be sure not to reintroduce old bugs, I move this session stuff
    //     down here. This way it will be added for the non JW FLV players.
    if (cpNavigatorUserAgentInfo.isIE){    
        var sep = (src.indexOf('?') > -1?'&':'?');     
        var sessionID = cpReadCookie(sessionName);           
        if (sessionID != null && sessionID.length > 0){
            var src = src +sep +sessionName +'=' +sessionID;
        }
    }

    // Build object tag and content
    var objectString = '';
    var objectStringStart = '<object type="' +mimeType +'" data="' +src +'" width="' +width +'" height="' +height +'">';
    var objectStringName = '<param name="movie" value="' +src +'" />';
    var objectStringFallback = '<p>(No plugin detected for your OS/browser)</p>';
    var objectStringEnd = '</object>';
    switch (mimeType) {
        case 'application/x-shockwave-flash':
            if (cpNavigatorUserAgentInfo.isIE){            
                var objectStringStart = '<object codebase="'+codebaseProtocol+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' +width +'" height="' +height +'">';
            }
            break;
        case 'application/x-mplayer2':
        case 'video/x-ms-wmv':
        case 'video/x-msvideo':
            // WMV, MPEG
            objectStringName = '<param name="src" value="' +src +'" />';
            break;

        case 'video/quicktime':
            // Quicktime in IE
            if (cpNavigatorUserAgentInfo.isIE){
                objectStringStart = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="'+codebaseProtocol+'://www.apple.com/qtactivex/qtplugin.cab" width="' +width +'" height="' +height +'">';
                objectStringName  = '<param name="src" value="' +src +'" />';
                break;
            }
            break;

        case 'video/x-ms-asf':
            // ASF in IE
            if (cpNavigatorUserAgentInfo.isIE){
                objectStringName = '<param name="FileName" value="' +src +'" />';
                break;
            }
            break;

        default:
            break;
    }

    objectString += objectStringStart;
    objectString += objectStringName;
    objectString += objectSettings;
    objectString += objectStringFallback;
    objectString += objectStringEnd;

    try {
        document.getElementById(objId).innerHTML = objectString;
    } catch(e){
        document.write(objectString);
    }
}

/**
 *  Function that reads a cookies value. Returns null if the requested cookie is not found
 */
function cpReadCookie(cookieName){
    cookieName += '=';
    var cookies = document.cookie.split(';');
    for (var i=0; i<cookies.length; i++){
        var cookie = cookies[i];
        while (cookie.charAt(0)==' ') cookie = cookie.substr(1);
        if (cookie.indexOf(cookieName) == 0) return cookie.substr(cookieName.length);
    }
    return null;
}

/**
 *  Returns a query string (useful as flashvars) from a object and its
 *  attributes.
 *
 *  Example:
 *
 *  obj = new Object();
 *  obj["file"] = "testfile";
 *  obj["showControls"] = "true";
 *
 *  getQueryParamsFromObjectAttributes(obj) ==>
 *  file=testfile&showControls=true
 */
function getQueryParamsFromObject(object) {
    var query = "";
    for(var attr in object) {
        if(query.length > 0) {
            query += "&";
        }
        query += attr +"=" + encodeURIComponent(object[attr]);
    }
    return query;
}

/** End Coretreks cplib.js code */

