  var current_step = 0;
  var global_data;

  var buyer_flow_ajax_wrapper = function(data, callback){

    if( self.Ajax ){
      // Ajax object is loaded by freewebs
      // (http://images.freewebs.com/Platform/JS/Ajax.js)
      var ajax = new Ajax();
      ajax.responseType   = Ajax.RAW;
      ajax.ondone         = callback;
      ajax.post( url, data );
      return;
    }

    $.ajax({
      type    : 'POST',
      url     : url,
      data    : data,
      success : function(msg){
        callback(msg);
      },
      cache   : false,
      error   : function(XMLHttpRequest, textStatus, errorThrown) {
        var _responseText = eval("(" + XMLHttpRequest.responseText + ")");
        var _status       = eval("(" + XMLHttpRequest.responseText + ")");
        var _statusText   = eval("(" + XMLHttpRequest.responseText + ")");
        $("<img>").attr("src", '/images/ajax_logger.gif?m=' + textStatus + '&r=' + _responseText + '&s=' + _status + '&st=' + _statusText + '&a=' + data.xaction);
      }
    });
  }

  var location_preload = function(){

  }

  var waiting_preload = function(){
    if (done_redirect_url.length > 10){
      if (done_redirect_url.match("\\?")){
        done_redirect_url += '&';
      } else {
        done_redirect_url += '?';
      }
      for(i in this_reservation){
        done_redirect_url += i + '=' + this_reservation[i] + '&';
      }
      document.location.href = done_redirect_url;
    }
  }

  var done_preload = function(){
    if(typeof do_optimizer_conversion == 'function') {
      do_optimizer_conversion();
    }
    $('#buyer_flow_cart_content').html('Booking request submitted. <a href="javascript:window.location.reload();" class="buyer_flow_cart_link">Book another</a>');
  }

  var get_staff_for_sub_service = function(sub_service_id){
    var rv = new Array;
    $(".staff_member" ).each(
      function(i){
        if ( staff_sub_service[ sub_service_id ][ $(this)[0].id ]){
          rv.push($(this)[0].id);
        }
      }
    );
    return rv;
  }

  var staff_preload = function(){
    $(".staff_member" ).each(
      function(i){
        $(this).css({'display' : 'none'});
        var _s_id = $(this)[0].id.replace('staff_member_', '');
        if (typeof(staff_sub_service[ this_reservation.sub_service_id ][ _s_id ] ) != 'undefined'){
          $(this).show();
        }
      }
    );
  }

  var datetime_preload = function(){
    fetch_time_bubbles(false, 10);
  }

  var show_zoofade = function(){
    offset =  $('#buyer_flow_body').offset();
    $('#zoofade').css({
      'top'     : offset.top,
      'left'    : offset.left,
      'width'   : $('#buyer_flow').width(),
      'height'  : $(document).height() - offset.top,
      'opacity' : 0.7}).fadeIn();
    return false;
  }

  var hide_zoofade = function(){
    $('#zoofade').fadeOut();
    return false;
  }

  var NIXED_contact_preload = function(){
    $('#contact_phone_type').hide();
    show_more_info_popup('review_details');
    return false;
  }

  var show_step = function(step){
    set_cart();
    if (typeof(pageTracker) != 'undefined'){
      pageTracker._trackEvent('buyer_flow', 'show_step', step);
    } else {
      if (typeof(console) != 'undefined'){
        console.log("pageTracker is undefined");
      }
    }

    hide_more_info_popup();
    $('.buyer_flow_step:eq(' + current_step + ')').fadeOut('def',
      function(){
        current_step = 0;
        for(s in steps){
          if(step == steps[s]){
            current_step = parseInt(s, 10);
          }
        }
        _next = $('.buyer_flow_step:eq(' + (current_step) + ')');
        _next.fadeIn('def',
          function(){
            preload_function = steps[ current_step ] + '_preload';
            if (typeof (window[preload_function]) == 'function'){
              window[preload_function]();
            }
          }
        );
      }
    );
  }

  var flow_next = function(){
    $('.buyer_flow_step:eq(' + current_step + ')').fadeOut('def',
      function(){
        _next = $('.buyer_flow_step:eq(' + (current_step + 1) + ')');
        if ( _next.length == 0){
          alert('form is done (step ' + (current_step + 1) + ') ... moving on');
        } else {
          current_step = current_step + 1;
          current_step_name = steps[ current_step ];
          if (typeof(pageTracker) != 'undefined'){
            pageTracker._trackEvent('buyer_flow', 'flow_next', current_step_name);
          }

          if (current_step_name != 'waiting' && current_step_name != 'done'){
             set_cart();
          }
          if (current_step_name == 'staff'){
            staff_array = get_staff_for_sub_service( this_reservation.sub_service_id );
            if (staff_array.length == 1){
              set_staff_id( staff_array[0] );
              return;
            }
          }

          preload_check_function = steps[ current_step ] + '_preload_check';
          if (typeof (window[preload_check_function]) == 'function'){
            var next_step = window[preload_check_function]();
            if (typeof(next_step) != 'undefined'){
              window.setTimeout("show_step('" + next_step + "');", 0);
              return;
            }
          }

          preload_function = steps[ current_step ] + '_preload';
          _next.fadeIn('def',
            function(){
              // webs hack //
              if (current_step > 0){
                $('.buyer_flow_step:first').css({'display' : 'none'});
              }
              if (typeof (window[preload_function]) == 'function'){
                window[preload_function]();
              }
            }
          );
        }
      }
    );
  }

  var flow_prev = function(){
    _next = $('.buyer_flow_step:eq(' + (current_step - 1) + ')');
    if ( _next.length == 0){
      return;
    }
    $('.buyer_flow_step:eq(' + current_step + ')').fadeOut('def',
      function(){
        current_step = current_step - 1;
        
        if (typeof(pageTracker) != 'undefined'){
          pageTracker._trackEvent('buyer_flow', 'flow_prev', steps[ current_step ]);
        }
        _next.fadeIn();
      }
    );
  }

  var this_reservation = {
    id                  : false,
    temp_reservation_id : false,
    deal_id             : false,

    // step 0 //
    sub_service_id  : false,
    duration_id     : false,

    // step 1 //
    location        : false, // 'premises' or 'customer' //

    // step 2 //
    staff_user_id   : false,

    // step 3 //
    datetime        : false,
    date            : false,
    time            : false,

    // step 4 //
    first_name      : false,
    last_name       : false,
    email           : false,
    phone           : false,
    status          : false,
    comments        : false,
    address         : false,
    zipcode         : false
  }
  this_reservation.service_id = this_service.id;

  var show_more_info_popup = function(div_id){        
    if (typeof(pageTracker) != 'undefined'){
      pageTracker._trackEvent('buyer_flow', 'show_more_info_popup', div_id);
    }

    offset = $('#buyer_flow_body').offset();
    show_zoofade();
    $('#' + div_id).css({
      'position' : 'absolute',
      'top' : offset.top + 20,
      'left' : offset.left + 20}).fadeIn();
  }

  var hide_more_info_popup = function(){
    if (typeof(pageTracker) != 'undefined'){
      pageTracker._trackEvent('buyer_flow', 'hide_more_info_popup');
    }
        
    $('#error_message').dialog('destroy');
    $('#contact_phone_type').show();
    hide_zoofade();
    $('#submit_flow').removeAttr("disabled");
    $(".more_info_popup" ).each(
      function(i){
        $(this).fadeOut();
      }
    );
  }

  var show_datepicker = function(){
    if (typeof(pageTracker) != 'undefined'){
      pageTracker._trackEvent('buyer_flow', 'show_datepicker');
    }
        
    $('#datepicker_container').datepicker( 'show' );  
  }

  var show_sub_service_description = function(element){
    $('#' + element).slideToggle();
  }

  var show_cart = function(){
    _top = $('#buyer_flow_body')[0]['offsetTop'];
    $('#contact_phone_type').hide();
    show_more_info_popup('shopping_cart');
  }

  var get_duration = function(duration_id){
    var _dur;
    for(_d in distinct_sub_services){
      if (distinct_sub_services[_d].duration && distinct_sub_services[_d].duration.id == duration_id){
        _dur = distinct_sub_services[_d].duration;
      }
    }
    return _dur;
  }

  var format_service_title = function(_dur, _sub_service){
    return _dur.time + ' ' + _dur.unit + ' ' + _sub_service.name;
  }

  var set_cart = function(){
    _sub_service = this_service.services[ this_reservation.sub_service_id ];
    if (typeof(_sub_service) == 'undefined'){
      return false;
    }
    _dur = get_duration(this_reservation.duration_id);
    _s = format_service_title(_dur, _sub_service);
    $('#buyer_flow_cart_content').html(_s + ' <a href="javascript:show_cart();" class="buyer_flow_cart_link">view / change</a>')
    $('#buyer_flow_cart').slideDown();
    $('.cart_service').html(_s);
    if (this_reservation.location){
      $('.cart_location').html(this_reservation.location);
      $('#cart_location_edit').show();
    } else {
      $('#cart_location_edit').hide();
    }
    if (this_reservation.location == 'customer'){
      $('.address_cart_line_item').show();
      if (this_reservation.address){
        $('.cart_address').html(this_reservation.address + ' ' + this_reservation.address2 + ', ' + this_reservation.city + ', ' + this_reservation.state + ', ' + this_reservation.zipcode);
        $('#cart_address_edit').show();
      } else {
        $('#cart_address_edit').hide();
      }
    } else {
      $('.address_cart_line_item').hide();
    }
    if (this_reservation.staff_user_id){
      staff = staff_members[ this_reservation.staff_user_id ];
      $('.cart_staff').html( staff.first_name + ' ' + staff.last_name );
      $('#cart_staff_edit').show();
    } else {
      $('#cart_staff_edit').hide();
    }
    if (this_reservation.date){
      $('.cart_datetime').html( this_reservation.date + ' at ' + this_reservation.time );
      $('#cart_datetime_edit').show();
    } else {
      $('#cart_datetime_edit').hide();
    }
    if (show_payments){
      $('.cart_contact').html( (this_reservation.first_name ? this_reservation.first_name  + ' ' : '') + (this_reservation.last_name ? this_reservation.last_name : '') );
      $('#cart_contact_edit').show();
    } else {
      $('#cart_contact_edit').hide();
    }
  }

  var set_sub_service_and_duration = function(sub_service_id, duration_id){
    this_reservation.sub_service_id = sub_service_id;
    this_reservation.duration_id = duration_id;
    
    //The current step might not be the services step
    if (steps[current_step] == 'service'){
      flow_next();
    }
  }
  
  var set_location = function(location){
    if (location != 'customer'){
      location = 'premises';
    }
    this_reservation.location = location;
    flow_next();
  }

  var show_about_me = function(user_id){
    if (typeof(pageTracker) != 'undefined'){
      pageTracker._trackEvent('buyer_flow', 'show_about_me', user_id);
    }

    user = staff_members[user_id];
    if (!user){
      return false;
    }

    $('#staff_bio_name').html( user.first_name + ' ' + user.last_name );
    blobs = ['bio', 'education', 'awards', 'interests', 'associations']
    for (_b in blobs){
      _blob = blobs[_b];
      if ( user_blobs[ user.id ] && user_blobs[ user.id ][_blob] ){
        $('#blob_' + _blob).show();
        $('#user_blob_' + _blob).html( user_blobs[ user.id ][_blob] );
      } else {
        $('#blob_' + _blob).hide();
      }
    }

    $('#staff_bio_img > img')[0].src = user.thumbnail;
    show_more_info_popup('staff_bio');
  }

  var set_staff_id = function(user_id){
    if (!user_id){
      for(_s in staff_members){
        if(staff_sub_service[ this_reservation.sub_service_id ][_s] != undefined){
          if (!user_id){
            user_id = _s;
          }
        }
      }
    }
    this_reservation.staff_user_id = user_id;
    if (steps[current_step] == 'staff'){
      flow_next();
    }
  }

  var set_start_time = function (time, user_id){
    if (user_id){
      this_reservation.staff_user_id = user_id;
    }

    var _date_obj = $('#datepicker_container').datepicker('getDate');
    var _year   = _date_obj.getFullYear();
    var _month  = _date_obj.getMonth() + 1;
    var _date   = _date_obj.getDate();

    this_reservation.date = _year.toString() + '-' + _month.toString() + '-' + _date.toString();
    this_reservation.time = time;
    set_temporary_reservation( get_temporary_reservation );
  }

  var get_temporary_reservation = function( msg ){
    rv = $.evalJSON(msg);
    if(rv.temp_reservation_id.length > 0){
      this_reservation.temp_reservation_id = rv.temp_reservation_id;
      if(this_reservation.location == 'customer'){
        show_step('address');
      } else {
        show_step('contact');
      }
    } else {
      show_error_message('Please select an alternate time for your appointment');
    }
  }

  var set_temporary_reservation = function(callback){
    data = {
      view            : 'ajax',
      xaction         : 'set_temporary_reservation'
    }
    for(_i in this_reservation){
      data[_i] = this_reservation[_i];
    }
    buyer_flow_ajax_wrapper( data, callback );
  }

  var draw_availability_bubble = function( bubble, append_to ){
    _available_class = 'available_no';
    if(bubble.available){
      _available_class = 'available_yes';
    }
    append_to.append('<div id="' + bubble.staff_user_id + '_'
        + bubble.start_time + '" class="availability_bubble ' + _available_class
        + '"><div class="' + _available_class + '_content">'
        + bubble.start_time + '</div></div>');
  }

  var check_prev_date = function(){
    if(datepicker_date.getDate() == start_datepicker_date.getDate() && datepicker_date.getMonth() == start_datepicker_date.getMonth() && datepicker_date.getYear() == start_datepicker_date.getYear()){
      $('#datepicker_prev').hide();
    } else {
      $('#datepicker_prev').show();
    }
  }

  var fetch_time_bubbles = function(new_date, initial_load){
    $("#datetime_bubbles").hide();
    $("#datetime_bubbles_no_availability").hide();
    $("#datetime_bubbles_msg").show();
    if (!is_date_available(datepicker_date)[0]){
      if(initial_load){
        if (initial_load == 1){
          alert('No availability for this staff member');
          return;
        } else {
          return increment_date_picker(1, initial_load - 1);
        }
      } else {
        return increment_date_picker();
      }
    }

    if (new_date){
      datepicker_date = new_date;
      check_prev_date();
    }

    $('#datepicker_value').html( d_names[ datepicker_date.getDay() ] + ', ' +
        m_names[ datepicker_date.getMonth() ] + ' ' + datepicker_date.getDate() +
        ', ' + datepicker_date.getFullYear() );

    var _date_obj = $('#datepicker_container').datepicker('getDate');
    var _year   = _date_obj.getFullYear();
    var _month  = _date_obj.getMonth() + 1;
    var _date   = _date_obj.getDate();

    data = {
      view                : 'ajax',
      xaction             : 'get_availability_for_service',
      service_id          : this_reservation.service_id,
      sub_service_id      : this_reservation.sub_service_id,
      duration_id         : this_reservation.duration_id,
      location            : this_reservation.location,
      staff_user_id       : this_reservation.staff_user_id,
      temp_reservation_id : this_reservation.temp_reservation_id
    }

    data.date =  _year.toString() + '-' + _month.toString() + '-' + _date.toString();

    var callback = function(msg){
      rv = $.evalJSON(msg);
      if (rv.availability_message.length > 0){
        $('#datetime_bubbles').html(rv.availability_message);
        return false;
      }
      $("#datetime_bubbles").html('').css({'height' : 'auto'});
      slots_available = 0;
      $("#datetime_bubbles_msg").hide();
      $("#datetime_bubbles_no_availability").hide();
      $("#datetime_bubbles").append('<table cellpadding="0" cellspacing="0"><tr><td id="bubbles_left" valign="top"></td><td style="display: block; width: 12px;">&nbsp;</td><td id="bubbles_right" valign="top"></td></tr></table>');
      var i = 0;
      for(_b = 0; _b < rv.availability.length; _b++ ){
        if (rv.availability[_b].available ){
          slots_available++;
        }
        if (i < (rv.availability.length / 2)){
          var append_to = $('#bubbles_left');
        } else {
          var append_to = $('#bubbles_right');
        }
        draw_availability_bubble( rv.availability[_b], append_to );
        i++;
      }

      if (slots_available == 1){
        $('#appointment_count').html(slots_available + ' appointment available');
      } else {
        $('#appointment_count').html(slots_available + ' appointments available');
      }

      if (slots_available == 0){
        if (initial_load && initial_load > 0){
          return increment_date_picker(1, initial_load - 1);
        } else {
          $('#datetime_bubbles').hide();
          $('#datetime_bubbles_no_availability').show();
          return;
        }
      }

      $("#datetime_bubbles").fadeIn();
      $(".available_yes").bind("click",
        function(e){
          if ( $(e.target).hasClass('availability_bubble') ){
            bubble = $(e.target);
          } else {
            bubble =  $(e.target).parents('.availability_bubble');
          }
          pieces = bubble[0].id.split('_');
          set_start_time(pieces[1], pieces[0]);
        }
      );
      $(".available_yes").bind("mouseover",
        function(e){
          $(this).addClass('available_yes_hover');
        }
      );
      $(".available_yes").bind("mouseout",
        function(e){
          $(this).removeClass('available_yes_hover');
        }
      );
    }
    buyer_flow_ajax_wrapper( data, callback );
  }

  var show_error_message = function(copy){
    $('#error_message_copy').html(copy);
    $('#error_message').dialog({
      width: 450,
      height: 175,
      autoOpen: true,
      modal: true,
      closeOnEscape: true,
      resizable: false,
      draggable: false
    });
    // show_more_info_popup('error_message');
  }

  var set_address_info = function(){

    this_reservation.address  = $('#address_address').val();
    this_reservation.address2 = $('#address_address2').val();
    this_reservation.city     = $('#address_city').val();
    this_reservation.state    = $('#address_state').val();
    this_reservation.zipcode  = $('#address_zipcode').val();

    var _err_msg = '';
    if (this_reservation.address.length < 1){
      _err_msg += 'Missing Address<br />\n';
    }
    if (this_reservation.city.length < 1){
      _err_msg += 'Missing City<br />\n';
    }
    if (this_reservation.state.length < 1){
      _err_msg += 'Missing State<br />\n';
    }
    if (this_reservation.zipcode.length < 1){
      _err_msg += 'Missing Zipcode<br />\n';
    }
    if (_err_msg.length > 0){
      show_error_message(_err_msg);
      return false;
    }


    flow_next();
  }

  var set_user_info = function(){
    $('#submit_flow').attr("disabled", "true"); 
    _err_msg = '';
    this_reservation.first_name   = $('#contact_first_name').val();
    this_reservation.last_name    = $('#contact_last_name').val();
    this_reservation.email        = $('#contact_email').val();
    this_reservation.phone        = $('#contact_phone').val();
    this_reservation.phone_type   = $('#contact_phone_type').val();
    this_reservation.comments     = $('#contact_comments').val();

    if (this_reservation.first_name.length < 1){
      _err_msg += 'Missing First Name<br />\n';
    }
    if (this_reservation.last_name.length < 1){
      _err_msg += 'Missing Last Name<br />\n';
    }
    if (this_reservation.email.length < 1){
      _err_msg += 'Missing Email<br />\n';
    }
    if (this_reservation.phone.length < 1){
      _err_msg += 'Missing Phone<br />\n';
    }
    if (_err_msg.length > 0){
      show_error_message(_err_msg);
      return false;
    }

    data = {
      view            : 'ajax',
      xaction         : 'create_new_reservation'
    }

    for(_i in this_reservation){
      data[_i] = this_reservation[_i];
    }

    if (show_payments){
      data['payment_status'] = 'pending';
    }
    
    data['deal_id'] = deal_id;

    if(this_reservation.id){
      data['xaction'] = 'update_reservation';
    }
    create_reservation(data, this_reservation);
    return false;
  }

  var create_reservation = function(data){
    if (typeof(pageTracker) != 'undefined'){
      pageTracker._trackEvent('buyer_flow', 'create_reservation');
    }
    if (persist.length > 0){
      data['persist'] = persist;
    }
    var callback = function(msg){
      rv = $.evalJSON(msg);
      if(rv.is_error == 1){
        $('#submit_flow').attr("disabled", "false");
        show_error_message(rv.reservation_message);
      } else {
        _dur = get_duration(this_reservation.duration_id);
        _sub_service = this_service.services[ this_reservation.sub_service_id ];
        _s = format_service_title(_dur, _sub_service);
        _staff = staff_members[ this_reservation.staff_user_id ];

        $('#reservation_sub_service').html( _s );
        $('#reservation_cost').html( format_price(_dur.price) );
        $('#reservation_date').html( $('#datepicker_value').html() );
        $('#reservation_time').html( this_reservation.time );
        $('#reservation_staff').html( _staff.first_name + ' ' + _staff.last_name );

        this_reservation.id = rv.reservation_id;
        if (!show_payments){
          setTimeout("flow_next();", 3000);
        }
        flow_next();
      }
    }
    buyer_flow_ajax_wrapper( data, callback );
  }

  var increment_date_picker = function(date_step, initial_load){
    if (!date_step){
      date_step = 1;
    }
    i = 0;
    while(i<=6){
      datepicker_date.setDate(datepicker_date.getDate() + date_step);
      _rv = is_date_available(datepicker_date);
      if (_rv[0]){
        i = 100;
      }
      i = i + 1;
    }
    $('#datepicker_container').datepicker('disable');
    $('#datepicker_container').datepicker('setDate', datepicker_date);
    check_prev_date();
    $('#datepicker_container').datepicker('enable');
    fetch_time_bubbles(false, initial_load);
  }

  var now = new Date();
  now.setHours(0);
  now.setMinutes(0);
  now.setSeconds(0);
  now.setMilliseconds(0);
  var is_date_available = function(date) {
    if (now.getTime() > date.getTime()){
      return false;
    }
    _key =  'start_dow' + date.getDay();
    if (!this_reservation.staff_user_id){
      return [true, 'ui-datepicker-available'];
    }
    if( staff_hours[this_reservation.staff_user_id][_key] < 0){
      return [false, 'ui-datepicker-unavailable'];
    }
    return [true, 'ui-datepicker-available'];
  }

  var splash_click = function(){
    $('#splash_img').animate({'width':0,'height':0}, 3).fadeOut('fast', function(e){
      $('.buyer_flow_header').fadeIn(1, function(e){
        $('#buyer_flow_cart').show();
        set_buyer_flow_body_height();
      });
      flow_next();
    });
  }

  var m_names = new Array("January", "February", "March",
    "April", "May", "June", "July", "August", "September",
    "October", "November", "December");

  var d_names = new Array("Sunday", "Monday", "Tuesday",
    "Wednesday", "Thursday", "Friday", "Saturday");

  $(document).ready(function(){
    _set_sub_service_id = false;
    _set_duration_id    = false;
    _set_staff_user_id  = false;

    // preloader //
    $("<img>").attr("src", '/images/glass_button_green.gif');

    $('#splash_img').bind('click', function(e){
      splash_click();
    }).css({'backgroundColor' : $('#buyer_flow_body').css('backgroundColor')}).animate({
      'width'     : $(document).width() - (2 * _border_width),
      'height'    : $(document).height() - (2 * _border_width)
    }, 3).mouseover(function(e){
      document.body.style.cursor = "pointer";
    }).mouseout(function(e){
      document.body.style.cursor = "auto";
    });

    $(".more_info_popup").draggable({
      appendTo:'body',
      opacity: 0.5
    });

    if (sub_service_id.length > 0 && duration_id.length > 0){
      for(s in distinct_sub_services){
        if( distinct_sub_services[s].id == sub_service_id && distinct_sub_services[s].duration.id == duration_id){
          _set_sub_service_id = sub_service_id;
          _set_duration_id    = duration_id;
        }
      }
    }

    _staff_count = 0;
    for(_u in staff_members){
      _staff_id = _u;
      _staff_count = _staff_count + 1;
    }
    if (_staff_count == 1){
      this_reservation.staff_user_id = _staff_id;
      $('.staff_cart_line_item').css('display', 'none');
    }
    
    if (staff_user_id.length > 0){
      set_staff_id(staff_user_id);
    }
    if (rez_date.length > 0){
      this_reservation.date = rez_date;
    }
    if (rez_time.length > 0){
      this_reservation.time = rez_time;
    }
    if (deal_id.length > 0){
      this_reservation.deal_id = deal_id;
    }
    if (temp_reservation_id.length > 0){
      this_reservation.temp_reservation_id = temp_reservation_id;
    }

    i = 0;
    while(i<=6){
      _rv = is_date_available(datepicker_date);
      if (_rv[0]){
        i = 100;
      } else {
        datepicker_date.setDate(datepicker_date.getDate() + 1);
      }
      i = i + 1;
    }

    $('#datepicker_container').datepicker({
      beforeShowDay: is_date_available,
      changeMonth: false,
      changeYear: false,
      closeText: 'X',
      dateFormat: "DD, M d, yy",
      dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
      defaultDate: datepicker_date,
      mandatory: true,
      maxDate: '+12m',
      minDate: '+0',
      monthNames: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
      numberOfMonths: 1,
      onSelect: function(new_date, inst) {
        var _new_date = new Date();
        _new_date.setFullYear(inst.selectedYear, inst.selectedMonth, inst.selectedDay);
        _new_date.setHours(0);
        _new_date.setMinutes(0);
        _new_date.setSeconds(0);
        fetch_time_bubbles(_new_date);
      },
      prevText: '&lt;&lt;',
      nextText: '&gt;&gt;',
      showAnim: 'fadeIn'
    });

    if (this_service.location_type == 'premises' || this_service.location_type == 'customer' || this_service.location_type == 'phone'){
      this_reservation.location = this_service.location_type;
      $('.location_cart_line_item').css('display', 'none');
    }
    do_once_on_load();
  });

  var onload_interval = false;
  var do_once_on_load = function(){
    $('body').css({'backgroundColor' : $('#buyer_flow_body').css('backgroundColor') });
    if (steps[ current_step ] != 'splash'){
      $('.buyer_flow_header').show();
    }

    $('#buyer_flow_body').fadeIn(200, function(e){
      set_buyer_flow_body_height();
      if ( $(this).height() == 0 && !onload_interval){
        // iframe is not visible on the page, cant init some stuff //
        onload_interval = setInterval ( "do_once_on_load();", 200 );
        return false;
      }

      if ($(this).height() > 0 && onload_interval){
        clearInterval( onload_interval );
      }
      $('.buyer_flow_step:first').show();
      if (_set_sub_service_id && _set_duration_id) {
        set_sub_service_and_duration(sub_service_id, duration_id);
        _set_sub_service_id = false;
        _set_duration_id = false;
      } else {
        $('#splash_img').css({'width': $(document).width(), 'height':$(document).height(), 'overflow' : 'hidden'});
        if (steps[ current_step ] == 'splash'){
          $(this).css({'overflow' : 'hidden'});
        } else {
          $('#buyer_flow_cart').show();
          $(this).css({'overflow' : 'auto'});
        }
//        $('.buyer_flow_step:first').show();
      }
    });
  }


  var set_buyer_flow_body_height = function(){
    var bfb = $('#buyer_flow_body');
    if (set_buyer_flow_body_height_to){
      _new_height = 'auto';
    } else {
      _new_height = $(document).height() - Math.floor(bfb.offset().top) - parseInt(bfb.css('paddingTop'), 10) - parseInt(bfb.css('paddingBottom'), 10) - _border_width - $('#buyer_flow_cart').height();
      if (_new_height < 0){
        _new_height = 0;
      }
    }
    bfb.css({'height' : _new_height, 'overflow' : 'auto' });
  }

  var payments_preload_check = function(){
    _dur = get_duration(this_reservation.duration_id);
    if (_dur.price == 0){
      return 'done';
    }
  }

  var payments_preload = function(){
    var price = 0;
    if (deal_price.length == 0){
      _sub_service = this_service.services[ this_reservation.sub_service_id ];
      _dur = get_duration(this_reservation.duration_id);
      price = _dur.price;
    }
    else {
      price = deal_price;
    }
    if (price != 0){
      if (deal_name.length == 0){
        _s = format_service_title(_dur, _sub_service);
      } else {
        _s = deal_name;
      }
      $('#payment_service_label').text(_s);
      if (price > 0){
        $('#payment_price_label').text(currency_symbol + price);
        $('#payment_amount').hide();
      }
      else {
        $('#payment_price_label').text(currency_symbol);
        var amt = $('#payment_amount');
        amt.show();
      }
    }
    else {
      pay_later();
    }
    return;
  }
  
  var pay_later = function(){
    if (typeof(pageTracker) != 'undefined'){
      pageTracker._trackEvent('buyer_flow', 'pay_later');
    }
        
    show_step('done');
//Sending communication for optional payments when reservation is created.
//    send_communications();
  }
  
  var set_payment_info = function(){
    var price = 0;
    if (deal_price.length == 0){
      _dur = get_duration(this_reservation.duration_id);
      price = _dur.price;
    }
    else {
      price = deal_price;
    }
    var show_payment_input = (price < 0);
    
    var tip;
    if (tipping_enabled){
      tip = $('#payment_tip').val();
      if (tip != '' && tip.length > 0){
        if (isNaN(tip) || (tip < 0)){
          show_error_message("The Tip must be a positive number, or left blank");
          return;
        }
      }
    }
    var payment;
    if (show_payment_input){
      payment = $('#payment_amount').val();
      if (payment != '' && payment.length > 0){
        if (isNaN(payment) || (payment < 0)){
          show_error_message("The Payment amount must be a positive number");
          return;
        }
      }
    }
    
    var pp_url = site_url + "index.html?view=paypal_autopost";
    pp_url += "&rid=" + this_reservation.id;
    if (tipping_enabled){
      pp_url += "&t=" + tip;
    }
    if (show_payment_input){
      pp_url += "&p=" + payment;
    }
    if (deal_id.length > 0){
      pp_url += "&did=" + deal_id;
    }
    pp_win = window.open(pp_url, "_blank");
    flow_next();
    check_payment_results();
    return false;
  }
  
  var cancel_payment = function(){
    if (typeof(pageTracker) != 'undefined'){
      pageTracker._trackEvent('buyer_flow', 'cancel_payment');
    }
        
    //cancel_check_payments_results = true;
    data = {
      view            : 'ajax',
      xaction         : 'cancel_payment',
      reservation_id  : this_reservation.id
    }

    var callback = function(msg){
      rv = $.evalJSON(msg);
      if(rv.is_error == 1){
        $('#submit_flow').attr("disabled", "false");
        show_error_message(rv.reservation_message);
      } else {
        //Do nothing. Let the polling take care of the transitions
      }
    }

    buyer_flow_ajax_wrapper( data, callback );
  }
  
  var send_communications = function(){
    if (typeof(pageTracker) != 'undefined'){
      pageTracker._trackEvent('buyer_flow', 'send_communications');
    }
        
    data = {
      view            : 'ajax',
      xaction         : 'send_reservation_emails',
      reservation_id  : this_reservation.id
    }

    var callback = function(msg){
      rv = $.evalJSON(msg);
      if(rv.is_error == 1){
        $('#submit_flow').attr("disabled", "false"); 
        show_error_message(rv.reservation_message);
      } else {
        setTimeout("show_step('done');", 1000);
      }
    }

    buyer_flow_ajax_wrapper( data, callback );
  }
  
  var cancel_check_payments_results = false;
  var check_payment_results = function(){
    if (cancel_check_payments_results){
      return;
    }
    
    data = {
      view            : 'ajax',
      xaction         : 'check_payment_results',
      reservation_id  : this_reservation.id
    }

    var callback = function(msg){
      rv = $.evalJSON(msg);
      if(rv.is_error == 1){
        $('#submit_flow2').attr("disabled", "false"); 
        show_error_message(rv.reservation_message);
      } else {
        if (rv.payment_status == 'pending'){
          setTimeout("check_payment_results();", 1000);
        }
        else if (rv.payment_status == 'paid'){
          show_step('done');
        }
        else if (rv.payment_status == 'none'){
          show_step('payments');
          show_error_message("An error has occurred processing the result of your payment. Please contact support@hourtown.com for assistance.");
        }
        else if (rv.payment_status == 'failed'){
          if (payments_req){
            show_step('payments');
            show_error_message("We have recorded that your payment transaction failed. Payments are required for this service. Please try your payment again.");
          }
          else {
            show_step('done');
            show_error_message("We recorded that your payment transaction failed. However, we have continued with your appointment request.");
          }
        }
        else if (rv.payment_status == 'cancelled'){
          if (payments_req){
            show_step('payments');
            show_error_message("We recorded that your payment transaction was cancelled. Payments are required for this service. Please try your payment again.");
          }
          else {
            //handled by action_buyer_request
            //setTimeout("send_communications();", 1000);
            show_step('done');
            show_error_message("We recorded that your payment transaction was cancelled. However, we have continued with your appointment request.");
          }
        }
        else {
          show_step('payments');
          show_error_message("An error has occurred processing the result of your payment. Please contact support@hourtown.com for assistance.");
        }
      }
    }

    buyer_flow_ajax_wrapper( data, callback );
  }

  var format_price = function(price){
    if (price == '-1'){
      return 'Price varies';
    }
    if (price == '-2'){
      return 'Included';
    }
    if (price == '0'){
      return 'Free';
    }
    _currency_unit = '$';
    return _currency_unit + price;
  }
