var mobileMsg = '- Mobile Number.';
var mobileMsg2 = '- Do not include 0 as the first digit of cell phone number.';
var operatorMsg = '- Operator.';
var alertMsg1 = 'The following information is missing or invalid:';
var alertMsg2 = 'Please make sure you have provided the above information correctly before submitting the data.';
var pinCodeMsg = 'Please enter the PIN';
var pinLabel = 'PIN';
var leaveMsg = '';

var landingControlHolder = {};

var Owlery = {};
/*
  @param Event e
$(Owlery).bind('repopulate', function(e) {});

  @param Event e
  @param bool with_pre_ent [optional, default false]
$(Owlery).bind('showMin', function(e, with_pre_ent) {});
*/

var Landing = new (function() {
  var Landing = this,

    /**
     * @const string CSS Class name
     */
    INPUTZONE_FIELD_COMPLETED_CLASS_NAME = 'formstate1',

    /**
     * @const string CSS Class name: prefix for indicating operator selected by user
     */
    OPERATOR_CLASS_NAME_PREFIX = 'op_',

    /**
     * @var bool
     */
    _is_ie6 = false;

  /**
   * To be called on ALL pages
   */
  this.initPage = function() {
    _is_ie6 = ($.browser.msie && 6 == parseInt($.browser.version));
  };

  this.initLayout1MINPage = function() {
    this.checkFilledMSISDN();
  };

  this.initLayout1PINPage = function() {
    this.checkFilledPIN();
  };

  /**
   * @param operator_code string
   * @return string to be attached to #docwrapper
   */
  this.getClassForOperator = function(operator_code) {
    return OPERATOR_CLASS_NAME_PREFIX + operator_code;
  };

  /**
   * @param next_field_id string
   * @param char_limit    int
   * @param current_field DOM Element
   */
  this.stepKeyLayout1 = function(next_field_id, char_limit, current_field) {
    if (next_field_id && current_field.value.length >= char_limit) {
      $('#' + next_field_id).focus();
    }
    Landing.checkFilledMSISDN();
  };

  this.stepKeyLayout1SingleMSISDNField = function() {
    Landing.checkFilledMSISDN();
    if ('function' == typeof checkPhoneLength) {
      checkPhoneLength(document.getElementById('msisdn'));
    }
  };

  this.checkFilledMSISDN = function() {
    if (_is_ie6) return; // IE6 not supported

    var $inputzone = $('#inputzone');
    if (checkPhone()) {
      if ($inputzone.hasClass(INPUTZONE_FIELD_COMPLETED_CLASS_NAME))
        $inputzone.removeClass(INPUTZONE_FIELD_COMPLETED_CLASS_NAME);
    }
    else {
      if (! $inputzone.hasClass(INPUTZONE_FIELD_COMPLETED_CLASS_NAME))
        $inputzone.addClass(INPUTZONE_FIELD_COMPLETED_CLASS_NAME);
    }
  };

  this.checkFilledPIN = function() {
    if (_is_ie6) return; // IE6 not supported

    var $inputzone = $('#inputzone');
    var pin_code = $('#pin_code').val();
    if (pin_code != pinLabel && pin_code.length >= 4) {
      if ($inputzone.hasClass(INPUTZONE_FIELD_COMPLETED_CLASS_NAME))
        $inputzone.removeClass(INPUTZONE_FIELD_COMPLETED_CLASS_NAME);
    }
    else {
      if (! $inputzone.hasClass(INPUTZONE_FIELD_COMPLETED_CLASS_NAME))
        $inputzone.addClass(INPUTZONE_FIELD_COMPLETED_CLASS_NAME);
    }
  };

  /**
   * @param $field    DOMElement <input type="text" />
   * @param maxlength int
   * @param position_against DOMElement
   * @param changeCallback function
   */
  this.addVirtualNumPad = function($field, maxlength, position_against, changeCallback) {
    $field.keyboard({
      layout : 'custom',
      customLayout: {
        'default': [
          '1 2 3',
          '4 5 6',
          '7 8 9',
          '0 {accept} {b}'
        ]
      },
      display: { // i18n
        'accept': 'OK:OK'
      },
      maxLength: maxlength,
      restrictInput: true, // Prevent keys not in the displayed keyboard from being typed in
      autoAccept: true,
      usePreview: false,
      position: {
        of: position_against,
        at2: 'left top',
        my: 'right top'
      },
      change: changeCallback || $.noop
    });
  };

  /**
   * Add virtual number-keyboard to Msisdn Field
   */
  this.addVirtualNumPad2MSISDNField = function() {
    if ($('body').hasClass('iphone')) return;

    var $msisdn = $('#msisdn');
    if (! $msisdn.length) return;

    this.addVirtualNumPad(
      $msisdn,
      $msisdn.attr('maxlength'),
      $('#inputphone_button #msisdn').length
        ? '#inputphone' // Layout 1
        : '#msisdn', // Layout 0,
      function(e, keyboard, el) { // callback for keyboard plugins, to fix msisdn maxlength issue:
        Landing.stepKeyLayout1SingleMSISDNField();
        if (keyboard) {
          keyboard.options.maxLength = parseInt($('#msisdn').attr('maxlength'), 10);
        }
      }
    );
  };

  /**
   * Add virtual number-keyboard to PIN Field
   */
  this.addVirtualNumPad2PINField = function() {
    if ($('body').hasClass('iphone')) return;

    var $pin_code = $('#pin_code');
    if (! $pin_code.length) return;

    this.addVirtualNumPad($pin_code, $pin_code.attr('maxlength'), $('#inputpassword_button').length ? '#inputpassword' : '#pin_code');
  };
});

var AnimatedMO = new (function() {
  var AnimatedMO = this;

  this.prepareSWF = function() {
    _prepareDemoSWF();
    _prepareInstructionSWF();
  };

  /**
   * @see localize_all.css for #mo_zone.ended
   */
  this.endAnimation = function() {
    var $mo_zone = $('#mo_zone');
    if ($mo_zone.is(':visible')) {
      $mo_zone.addClass('ended');
    }
  };

  /**
   * For Desktop Landing only. This will MOVE #inputzone to a different level in DOM
   * @require DOM Element div#mo_zone
   * @return bool whether new swf is created
   */
  function _prepareDemoSWF() {
    var $swf_container_mo_demo = $('#inputzone #swf_container_mo_demo');
    if (! $swf_container_mo_demo.length) {
      return false;
    }

    if ($('body').hasClass('iphone')) { // smartphone landing
      $swf_container_mo_demo.css({
        height: 'auto',
        width: 'auto'
      });
      return false;
    }

    // Rearrange certain <div>s
    $('#mo_demo_holder').html('') // useful for second callback
                        .append($swf_container_mo_demo);
    if (! $('#inputzone_holder').find('#inputzone').length) { // if #inputzone has not been moved into #inputzone_holder
      $('#inputzone_holder').append($('#inputzone')); // move #inputzone into #inputzone_holder
    }
    $('#mo_zone').show();

    var $mo_code       = $swf_container_mo_demo.find('.mo_code');
    var $mo_to         = $swf_container_mo_demo.find('.mo_to');
    var $mo_short_code = $swf_container_mo_demo.find('.mo_short_code');
    var params = {};
    params['ln1'] = $.trim($mo_code.text());
    params['c1'] = LandingHelper.color2Hex($mo_code.css('color'), false);
    params['ln2'] = $.trim($mo_short_code.text());
    params['c2'] = LandingHelper.color2Hex($mo_short_code.css('color'), false);
    params['to'] = $.trim($mo_to.text().toUpperCase());
    params['cto'] = LandingHelper.color2Hex($mo_to.css('color'), false);
    params['sendmsg'] = $swf_container_mo_demo.find('.mo_sendmsg').text();
    params['sendbtn'] = $swf_container_mo_demo.find('.mo_sendbtn').text();

    _injectSWF(
      $swf_container_mo_demo.attr('id'),
      215,
      180,
      'flash_mo/mobile_msg.swf',
      $.param(params)
    );

    return true;
  }

  /**
   * @return bool whether new swf is created
   */
  function _prepareInstructionSWF() {
    var $swf_container = null, swf_file = null, params = {};
    if (document.getElementById('swf_container_mo_msg')) {
      // Vertical
      $swf_container = $('#inputzone #swf_container_mo_msg');
      swf_file = 'mo_msg.swf';
    }
    else if (document.getElementById('swf_container_mo_msg_horizontal')) {
      // Horizontal
      $swf_container = $('#inputzone #swf_container_mo_msg_horizontal');
      swf_file = 'mo_msg_horizontal.swf';
      var $mo_send = $swf_container.find('.mo_send');
      params['sms'] = $.trim($mo_send.text());
      params['csms'] = LandingHelper.color2Hex($mo_send.css('color'), false);
    }

    if (! $swf_container || ! $swf_container.length) {
      return false;
    }

    if ($('body').hasClass('iphone')) { // smartphone landing
      $swf_container.css({ height: 'auto', width: 'auto' }); // to suppress inline styles
      return false;
    }

    var $mo_code       = $swf_container.find('.mo_code');
    var $mo_to         = $swf_container.find('.mo_to');
    var $mo_short_code = $swf_container.find('.mo_short_code');

    params['ln1'] = $.trim($mo_code.text());
    params['c1'] = LandingHelper.color2Hex($mo_code.css('color'), false);
    params['to'] = $.trim($mo_to.text());
    params['cto'] = LandingHelper.color2Hex($mo_to.css('color'), false);
    params['ln2'] = $.trim($mo_short_code.text());
    params['c2'] = LandingHelper.color2Hex($mo_short_code.css('color'), false);

    _injectSWF(
      $swf_container.attr('id'),
      parseInt($swf_container.css('width')) || 300,
      parseInt($swf_container.css('height')) || 140,
      swf_file,
      $.param(params)
    );

    return true;
  }

  /**
   * @param swf_container string ID of container of SWF
   * @param swf_width     number width of SWF
   * @param swf_height    number height of SWF
   * @param swf_file      string file name of SWF
   * @param param_string  string parameters to be passed to SWF file (by appending to end of file name)
   */
  function _injectSWF(swf_container, swf_width, swf_height, swf_file, param_string) {
    if (! document.getElementById(swf_container)) return;
    if (! swfobject) return;

    var params = {
      allowScriptAcess: 'sameDomain',
      quality: 'high',
      scale: 'noborder',
      wmode: 'transparent'
    };

    swfobject.embedSWF('/assets/common/' + swf_file + '?' + param_string,
      swf_container, swf_width, swf_height, '9.0.0', false, false, params);
  }
});

var Echo = {
  SHOOT_INTERVAL: 10000, // milliseconds

  shoot_retry: 180,

  form: null,

  /**
   * @param form string jQuery selector of a <form>
   */
  init: function(form) {
    this.form = $(form);
    this.prepare();
  },

  resetTimer: function() {
    this.shoot_retry = 180;
  },

  shoot: function() {
    this.form.ajaxSubmit({
      dataType: 'json',
      success: this.pickSuccess,
      error: this.pickError
    });
    this.shoot_retry--;
  },

  prepare: function() {
    if (this.shoot_retry > 0) {
      setTimeout('Echo.shoot()', this.SHOOT_INTERVAL);
    }
  },

  /**
   * To be overwritten
   */
  pickSuccess: function(data, statusText) {
  },

  /**
   * Safety device
   */
  pickError: function(data, statusText) {
    Echo.prepare();
  }
};

/**
 * Misc Helper
 */
var LandingHelper = new (function() {
  var LandingHelper = this,

    /**
     * @const
     */
    FIELD_EMPTY_CLASS = 'blur',

    /**
     * @var array
     */
    _month_length = [
      [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], // non-leap year
      [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] // leap year
    ];

  /**
   * @param d       integer
   * @param length  integer
   * @return string
   */
  this.padZero = function(d, length) {
    var s = d.toString();
    while (s.length < length) s = '0' + s;
    return s;
  };

  /**
   * @param year numeric to be treated as base 10
   * @return bool
   */
  this.isLeapYear = function(year) {
    var y = parseInt(year, 10);
    if (isNaN(y)) return false;
    return (y % 4 == 0) && (y % 100 != 0 || y % 400 == 0);
  };

  /**
   * @param day    ONE <select>
   * @param month  ONE <select>
   * @param year   ONE <select>
   * @param options object [optional]
   */
  this.buildDateMenu = function(day, month, year, options) {
    var $day = $(day), $month = $(month), $year = $(year),
      _options = $.extend({
          start_year_offset: 80,
          end_year_offset: 18
        }, options || {}),
      html, i;

    for (html = '', i = 1; i <= 31; i++)
      html += '<option value="' + i + '">' + LandingHelper.padZero(i, 2) + '</option>';
    $day.append(html);

    for (html = '', i = 1; i <= 12; i++)
      html += '<option value="' + i + '">' + LandingHelper.padZero(i, 2) + '</option>';
    $month.append(html);

    var current_year = (new Date()).getFullYear(), end_year = current_year - _options.end_year_offset, start_year = current_year - _options.start_year_offset;
    for (html = '', i = end_year; i >= start_year; i--)
      html += '<option value="' + i + '">' + i + '</option>';
    $year.append(html);

    // bind event handler, for showing valid date selection
    $month.add($year).change(function(event) {
      var month_length = 31,
          d = parseInt($day.val()), // 1..31 or NaN
          m = parseInt($month.val()), // 1..12 or NaN
          y = parseInt($year.val());
      if (!isNaN(y) && !isNaN(m))
        month_length = _month_length[LandingHelper.isLeapYear(y) ? 1 : 0][m-1];
      else if (!isNaN(m))
        month_length = _month_length[1][m-1];

      if (!isNaN(d) && d > month_length) d = month_length, $day.val(month_length);

      var last_val;
      while ((last_val = parseInt($day.find('option').last().val())) < month_length)
        $day.append('<option value="' + (++last_val) + '">' + last_val + '</option>'); // add one
      while ((last_val = parseInt($day.find('option').last().val())) > month_length)
        $day.find('option').last().remove(); // remove one

//      if (!isNaN(y) && !isNaN(m) && !isNaN(d)) var date = new Date(y, m-1, d);
    });
  };

  /**
   * @param text_field string selector of a <input type="text" /> or <textarea>...</textarea>
   * @param empty_text string the text to display
   * @param js_initiate bool [optional] whether to let this function initiates the decoration
   */
  this.decorateTextField = function(text_field, empty_text, js_initiate) {
    var $text_field = $(text_field);
    $text_field
      .bind('focus', function(e) {
        var $this = $(this);
        if ($this.hasClass(FIELD_EMPTY_CLASS)) {
          $this.removeClass(FIELD_EMPTY_CLASS).val('');
        }
      })
      .bind('blur', function(e) {
        if (! this.value.length) {
          $(this).addClass(FIELD_EMPTY_CLASS).val(empty_text);
        }
      });

    if (js_initiate) {
      if ($text_field.val().length)
        $text_field.removeClass(FIELD_EMPTY_CLASS);
      else
        $text_field.addClass(FIELD_EMPTY_CLASS).val(empty_text);
    }
  };

  /**
   * Convert color string to color into HEX representation
   * @param color string    It can be "xxx", "#xxx", "xxxxxx", "#xxxxxx", "rgb(d,d,d)", "rgba(d,d,d,d)",
   *                        where d is decimal digit, x is hexadecimal digit
   * @param with_hash bool  [optional, default false] whether to include '#' in return value
   * @return string HEX value if parsing is possible, otherwise the original value of parameter color is returned.
   */
  this.color2Hex = function(color, with_hash) {
    if (typeof with_hash == 'undefined') with_hash = false;

    if ((/^\#?(([0-9a-f]{3})|([0-9a-f]{6}))$/i).test(color)) {
      return (with_hash ? '#' : '') + color.replace('#', '').toUpperCase();
    }
    else {
      var rgba = color.match(/^rgba?\s*\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
      if (rgba) {
        var hex = LandingHelper.dec2hex(rgba[1]) + LandingHelper.dec2hex(rgba[2]) + LandingHelper.dec2hex(rgba[3]);
        return (with_hash ? '#' : '') + hex.toUpperCase();
      }
    }
    return color;
  };

  /**
   * Convert a decimal number into HEX representation
   * @param d string|int a number in decimal digits
   * @return string the return value has at least 2 digits
   */
  this.dec2hex = function(d) {
    return ('0' + parseInt(d, 10).toString(16)).slice(-2);
  };

  this.initializeTooltip = function(selector) {
    // ensure there is ONE instance node
    if (! $('#tooltip_popup').length) $('body').append('<div id="tooltip_popup" style="position:absolute; z-index:9999"></div>');
    if (! selector) return;

    $(selector).find('.tooltip_holder').each(function() {
      var $tooltip_holder = $(this);

      $tooltip_holder.unbind('mouseenter');
      $tooltip_holder.unbind('mouseleave');
      $tooltip_holder.unbind('mousemove');

      if (! $tooltip_holder.children('.tooltip').length) return;

      $tooltip_holder
        .mouseenter(function(event) {
          event.stopPropagation();
          var $tooltip = $(this).children('.tooltip').first();

          if ($tooltip.hasClass('fix_tooltip'))
            $tooltip.show();
          else
            $('#tooltip_popup').empty().append($tooltip.clone().show()).show(); // clone html content
        })
        .mouseleave(function(event) {
          event.stopPropagation();
          var $tooltip = $(this).children('.tooltip').first();

          if ($tooltip.hasClass('fix_tooltip'))
            $tooltip.hide();
          else
            $('#tooltip_popup').empty().hide();
        })
        .mousemove(function(event) {
          event.stopPropagation();
          var $tooltip = $(this).children('.tooltip').first();

          if (! $tooltip.hasClass('fix_tooltip')) {
            var target_x, target_y;
            target_x = ($(document).width() - 55 < event.pageX + 480) ? (event.pageX - 515) : (event.pageX + 15);
            target_y = ($(window).height() - 40 < event.pageY + 370) ? ($(window).height() - 385) : (event.pageY + 15);
            $('#tooltip_popup').css({ left: target_x, top: target_y });
          }
        });
    });
  }
});

/**
 * @param next_field_id string
 * @param char_limit    int
 * @param current_field DOM Element
 */
function stepKey(next_field_id, char_limit, current_field)
{
  if (next_field_id && current_field.value.length >= char_limit) {
    $('#' + next_field_id).focus();
  }
}

/**
 * @return bool
 */
function checkOperator()
{
  if ($('#operatorlist').val() < 4) {
    return false;
  }
  return true;
}

/**
 * @return bool
 */
function checkRegister()
{
  var error = false;
  var msg = '';
  if (! checkPhone()) {
    msg = msg + mobileMsg + '\n';
    error = true;
  }
  if (typeof checkPhone2 == 'function' && ! checkPhone2()) {
    msg = msg + mobileMsg2 + '\n';
    error = true;
  }
  if (! checkOperator()) {
    msg = msg + operatorMsg + '\n';
    error = true;
  }

  if (error) {
    alert(alertMsg1 + '\n\n' + msg + '\n' + alertMsg2);
    return false;
  }
  else {
    $('#submitButton').attr('disabled', true);
    disPopup();
    return true;
  }
}

/**
 * For PIN-in form. Check whether a PIN Code is entered.
 * @return bool whether
 */
function checkActivate()
{
  var $pin_code = $('#pin_code');
  if ($pin_code.val().length == 0 || $pin_code.val() == pinLabel) {
    alert(pinCodeMsg);
    $pin_code.focus();
    return false;
  }
  return true;
}

/**
 * @return bool
 */
function showWarning()
{
  $('#term_warn_box').css('visibility', 'visible');

  // highlight the checkbox
  $('#term_cb_wrap').addClass('term_cb_highlight');

  return false;
}

/**
 * @return bool
 */
function checkTerms()
{
  var $terms = $('#terms');
  if (! $terms.length) return true;
  if ($terms.attr('type') == 'hidden') return true;
  // add event handle
  $terms.click(function() {
    if (this.checked)
      $('#submitButton').attr('disabled', false);
  });

  if (! $terms.attr('checked')) {
    showWarning();
    $terms.focus();
    $('#submitButton').attr('disabled', true);
    return false;
  }

  return true;
}

/* ***** ***** ***** ***** ***** ***** ***** ***** ***** *****
 * BEGIN Pin Form manipulation
 */

var secs;
var timerID = null;
var timerRunning = false;
var delay = 1000;

function InitializeTimer()
{
  // Set the length of the timer, in seconds
  secs = 10;
  StopTheClock();
  StartTheTimer();
}

function StopTheClock()
{
  if (timerRunning) {
    clearTimeout(timerID);
  }
  timerRunning = false;
}

function StartTheTimer()
{
  if (0 == secs) {
    StopTheClock();
    pin_timeout();
  }
  else {
    secs = secs - 1;
    timerRunning = true;
    timerID = self.setTimeout('StartTheTimer()', delay);
    if ('function' == typeof sc_pin_start_timeout) {
      sc_pin_start_timeout();
    }
  }
}

function pin_timeout()
{
  $('#timermsg1').hide();
  $('#timermsg2').show();
  if ('function' == typeof sc_pin_end_timeout) {
    sc_pin_end_timeout();
  }
}

/**
 * Directly-invoked by PIN Form template at page load #####
 */
function pin(time_delay) //function isSecondPage(time_delay)
{
  checkPinMouseOut();
  if (typeof time_delay !== 'number') {
    time_delay = 10;
  }

  time_delay *= 1000;
  window.setTimeout('pin_timeout()', time_delay);
}

/**
 * Directly-invoked by PIN Form template at page load #####
 */
function isSecondPage()
{
  if (document.getElementById('timermsg1') != null) {
    InitializeTimer();
  }
  checkPinMouseOut();
}

/**
 * Event Handler. Invoked at $('#pin_code')->onfocus
 */
function checkPin()
{
  var $pin_code = $('#pin_code');
  if ($pin_code.val() == pinLabel) {
    $pin_code.val('').removeClass('blur');
  }
}

/**
 * Directly-invoked by PIN Form template at page load #####
 * Event Handler. Invoked at $('#pin_code')->onblur
 */
function checkPinMouseOut()
{
  var $pin_code = $('#pin_code');
  if ($pin_code.val() == '') {
    $pin_code.val(pinLabel).addClass('blur');
  }
}
/*
 * END Pin Form manipulation
 * ***** ***** ***** ***** ***** ***** ***** ***** ***** *****/

function handleBeforeUnload()
{
  return leaveMsg;
}

function unloadPopup(link)
{
  var Popup = window.open(link, '', 'height=420,width=760,status=0,toolbar=0,menubar=0,location=0,scrollbars=1');
  Popup.focus();
}

/**
 * Disable popup
 */
function disPopup()
{
  document.body.onunload = '';
  document.body.onbeforeunload = '';
  window.onunload = '';
  window.onbeforeunload = '';
}

function RorC()
{
  var features = '';

  if ((p_height > 0) && (p_width > 0)) {
    features = features + 'height=' + p_height + ',';
    features = features + 'width=' + p_width + ',';
    features = features + 'toolbar=no,menubar=no,location=no,directories=no,status=no';
  }

  var nzzz = window.open(p_url, 'nzzz', features);
  if (nzzz) nzzz.focus();
}
if (typeof p_url == 'string' && p_url.length > 0) {
  window.onunload = RorC;
}

/**
 * @param name          string cookie name
 * @param value         mixed cookie value
 * @param expire_offset int milli seconds
 * @param path
 * @param domain
 * @param secure
 */
function Set_Cookie(name, value, expire_offset, path, domain, secure)
{
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime(today.getTime());

  /*
  if the expires variable is set, make the correct
  expires time, the current script below will set
  it for x number of days, to make it for hours,
  delete * 24, for minutes, delete * 60 * 24
  */
  if (expire_offset) {
    expire_offset = expire_offset * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date(today.getTime() + expire_offset);

  document.cookie = name + '=' + escape(value) +
    ( expire_offset ? ';expires=' + expires_date.toGMTString() : '' ) +
    ( path ? ';path=' + path : '' ) +
    ( domain ? ';domain=' + domain : '' ) +
    ( secure ? ';secure' : '' );
}

/**
 * @param cookie_key string
 * @return string | null
 */
function Get_Cookie(cookie_key)
{
  // first we'll split this cookie up into name/value pairs
  // note: document.cookie only returns name=value, not the other components
  var all_cookies = document.cookie.split(';'),
    segments = '',
    cookie_name = '';

  for (var i = 0; i < all_cookies.length; i++) {
    segments = all_cookies[i].split('='); // split apart each name=value pair

    cookie_name = $.trim(segments[0]);
    if (cookie_name == cookie_key) {
      // we need to handle case where cookie has no value but exists (no = sign, that is):
      return segments.length > 1 ? unescape($.trim(segments[1])) : null;
    }
  }

  return null;
}

/**
 * Fix checkbox message box position
 */
function fix_checkbox_message_box_position()
{
  var $term_warn_box = $('#term_warn_box');
  if ($term_warn_box.length == 0) {
    return;
  }

  if ($('body').hasClass('iphone')) {
    $term_warn_box.addClass('right_align');
  }

  // remove margin first, let the warn box align to most left
  $term_warn_box.css({'margin': 0});
  $('#term_warn_box_arrow').css({'margin-top': 0, 'margin-bottom': 0});

  var left = 0,
    p_offset = 2; // tiny offset

  if ($.browser.msie && 6 == parseInt($.browser.version)) {
    left = $term_warn_box.hasClass('right_align') ?
      ($('#term_cb_wrap').width() + p_offset) :
      (- $term_warn_box.width() - p_offset);
  }
  else {
    left = $term_warn_box.hasClass('right_align') ?
      ($('#term_wrap > table').position().left + $('#term_cb_wrap').width() + p_offset) :
      ($('#term_wrap > table').position().left - $term_warn_box.width() - p_offset);
  }

  $term_warn_box.css({ 'top': - $term_warn_box.height(), 'left': left });
}

/**
 * Grab telco's tnc
 */
function get_telco_tnc(offer_id, locale, operator_code)
{
  $.ajax({
    type: 'POST',
    url:  'get_telco_tnc.php',
    data: {
      a:        offer_id || '',
      locale:   locale || '',
      operator: operator_code || ''
    },
    dataType: 'json',
    success: function(result) {
      if ('SUCCESS' == result['status']) {
        $('#tnc_text_wrapper').html(result['content']);
        decorate_rainbow();
      }
    }
  });
}

function fix_tnc_position()
{
  var $logos = $('#logos');
  if ($logos.length > 0 && $logos.is(':visible')) {
//    alert ($('#logos').css('height')); // '52px' for FF, auto for IE
//    alert ($('#logos').height()); // 52 - preferred
    $('#tnc').css({
      'top':        $logos.css('top'),
      'margin-top': ($logos.height() + 2) + 'px'
    });
  }
}

function decorate_rainbow()
{
  var a = $('input[name=a]').val();
  var s = $('input[name=s]').val();

  if (typeof client_ip == 'string') {
    $('.ip_address').text(client_ip);
    if (client_ip.indexOf('A') == -1)
      $('.ipas_stamp').text(client_ip + '.A' + a + '.S' + s);
    else
      $('.ipas_stamp').text(client_ip);
  }
  $('.as_stamp').text('A' + a + '.S' + s);

  $('img.rainbow').attr('src', 'rainbow.php?a=' + a);
  // for rainbow on very top
  var $rainbow_wrapper = $('#tnc .rainbow_wrapper');
  if ($rainbow_wrapper.hasClass('top') && $rainbow_wrapper.find('img.rainbow').length) {
    $('#rainbow-container').html('').prepend($rainbow_wrapper).show();
  }
}



$(function() {
  Landing.initPage();

  fix_checkbox_message_box_position();
  fix_tnc_position();
  decorate_rainbow();
});



landingControlHolder.calc = function(left, right) {
  if (left == undefined) left = 100;
  if (right == undefined) right = 140;
  var width = right - left + 1,
      pt = 0,
      score = left+1;
  if (this.precontroller && this.precontroller._choice && this.precontroller._choice.length) {
    var choice = this.precontroller._choice;
    with (Math) {
      for (var i=0; i<choice.length; ++i)
        pt += sin(choice[i]+1)+cos(i);
      score = left+abs(round(pt))*103%width;
    }
  }
  else if (null != (score = Get_Cookie('lp_score'))) {
    if (score < left || score > right)
      score = left+Math.round(score)*101%width;
  }
  else {
    pt = Math.floor((new Date()).getTime());
    score = left+Math.round(pt)*97%width;
  }
  Set_Cookie('lp_score', score);
  return score;
}

/* to be overwritten */
function passvar(result) {}

/**
 * @deprecated
 */
function hidediv()
{
  if (document.getElementById) { // DOM3 = IE5, NS6
    document.getElementById('timermsg1').style.display = 'none';
    document.getElementById('timermsg2').style.display = '';
  }
  else {
    if (document.layers) { // Netscape 4
      document.timermsg1.display = 'none';
      document.timermsg2.display = '';
    }
    else { // IE 4
      document.all.timermsg1.style.display = 'none';
      document.all.timermsg2.style.display = '';
    }
  }
}

