(function() {
  $(document).ready(function() {
    var Attendees, Countdown, RegisterDelegateForm, RegisterForm, Schedule, Slideshow;
    Slideshow = {
      el: $('#slideshow'),
      activeIndex: 1,
      oneliners: ['A record 1 million Chinese have applied for visas to the US already this year... will you be ready for them?', 'Inbound tourism from China to North America is forecast to increase 274% by 2016...will you get your share?', 'The average Chinese visitor spends $6,000 shopping during their vacation... will they spend it with you?', 'Chinese tour operators are hungry for new itinerary ideas... will your products be included?', 'The total number of outbound tourists from China will reach 100 million by 2020... how many will you see?'],
      options: {
        interval: 5
      },
      init: function() {
        var self;
        self = this;
        if (!this.el.length) {
          return;
        }
        setInterval((function() {
          return self.gotoIndex(self.activeIndex + 1);
        }), this.options.interval * 2000);
      },
      gotoIndex: function(index) {
        var $oneliner, $targetImg, sec, self;
        self = this;
        $targetImg = $('img:nth-child(' + index + ')', this.el);
        $oneliner = $('.oneliner', this.el);
        if (index < this.el.find('img').length + 1) {
          self.activeIndex = index;
          sec = 1000;
        } else {
          self.activeIndex = 0;
          sec = 0;
        }
        $targetImg.siblings('img').fadeOut(1500, function() {
          $targetImg.hide().fadeIn(1500);
          $oneliner.hide().text(self.oneliners[3]).fadeIn(1500);
        });
      }
    };
    Countdown = {
      el: $('#countdown'),
      options: {
        date: Date.parse('5/22/2012', 'M/d/yyyy')
      },
      init: function() {
        var self;
        self = this;
        if (!this.el.length) {
          return;
        }
        setInterval((function() {
          return self.refresh();
        }), 1000);
      },
      refresh: function() {
        var day, hours, mins, secs, timediff;
        timediff = this.options.date - new Date();
        day = Math.floor(timediff / (24 * 60 * 60 * 1000));
        hours = Math.floor((timediff - (day * 24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
        mins = Math.floor((timediff - (day * 24 * 60 * 60 * 1000) - (hours * 60 * 60 * 1000)) / (60 * 1000));
        secs = Math.floor((timediff - (day * 24 * 60 * 60 * 1000) - (hours * 60 * 60 * 1000) - (mins * 60 * 1000)) / 1000);
        this.el.find('.day var').text(day);
        this.el.find('.hour var').text(hours);
        this.el.find('.min var').text(mins);
        this.el.find('.sec var').text(secs);
      }
    };
    RegisterForm = {
      el: $('#register-dmo-form'),
      steps: ['intro', 'basic-info', 'payment-info', 'confirm'],
      currstep: 'intro',
      items: {
        admission: {
          price: parseFloat(G.site.data.global.confPrice)
        },
        present: {
          price: parseFloat(G.site.data.global.presentPrice)
        },
        followup: {
          price: parseFloat(G.site.data.global.followUpPrice)
        }
      },
      total: parseFloat(G.site.data.global.confPrice),
      templates: {
        presentItem: '<input name="item_name_2" type="hidden" value="Destination Presentation to Chinese Tour Operators" />\
				<input name="item_description_2" type="hidden" value="an opportunity to make a 10-minute presentation to the entire Chinese delegation. Limited availability - first come, first serve." />\
				<input name="item_quantity_2" type="hidden" value="1" />\
				<input name="item_price_2" type="hidden" value="995.0" />\
				<input name="item_currency_2" type="hidden" value="USD" />',
        followupItem: '<input name="item_name_3" type="hidden" value="In-Country Follow Up" />\
				<input name="item_description_3" type="hidden" value="We will make available through our partner in Bejing - the i2i Group - the option of signing up for Active America post-conference follow up services in China. The goal of this service is to maximize relationship building and sales from the contacts you make at Active America-China. This service is available for six weeks after Active America." />\
				<input name="item_quantity_3" type="hidden" value="1" />\
				<input name="item_price_3" type="hidden" value="695.0" />\
				<input name="item_currency_3" type="hidden" value="USD" />'
      },
      init: function() {
        var self;
        self = this;
        if (!this.el.length) {
          return;
        }
        this._render();
      },
      loadStep: function(step) {
        var $currstep, $step, forward, gotoNext, self;
        self = this;
        $step = this.el.find('.step-' + step);
        $currstep = this.el.find('.step-' + this.currstep);
        forward = this.steps.indexOf(this.currstep) + 1 === this.steps.indexOf(step);
        gotoNext = function() {
          $('.tipsy').remove();
          self.el.find('[class*="step-"].active', self.el).hide().removeClass('active');
          $step.addClass('active').hide().fadeIn();
          if (forward) {
            $('.progress [rel="' + step + '"]', self.el).addClass('active');
          } else {
            $('.progress [rel="' + self.currstep + '"]', self.el).removeClass('active');
          }
          self.currstep = step;
        };
        if ($step.length) {
          if (forward) {
            $currstep.validate('validate', function(err) {
              var $agree, $email;
              if (err && self.currstep === 'basic-info') {
                $(window).scrollTo($('.tipsy'), 'slow');
              }
              if (!err) {
                switch (self.currstep) {
                  case 'intro':
                    $agree = $currstep.find('[name="agree"]');
                    if (!$agree.attr('checked')) {
                      $.validate.error($agree, 'Need to agree in order to continue', {
                        gravity: 's'
                      });
                      return false;
                    }
                    gotoNext();
                    break;
                  case 'basic-info':
                    if (G.attendee) {
                      gotoNext();
                      return;
                    }
                    $email = $currstep.find('[name="email"]');
                    if ($email.val() === 'sofia@visitnaj.com') {
                      gotoNext();
                      return;
                    }
                    self.validateEmail($email.val(), function(err, r) {
                      if (!_.isEmpty(r)) {
                        $.validate.error($email, 'This email is already registered.');
                        return false;
                      }
                      gotoNext();
                    });
                    return;
                  default:
                    gotoNext();
                }
              }
            });
          } else {
            gotoNext();
          }
        }
      },
      _render: function() {
        var self;
        self = this;
        this._renderPickType();
        this._renderUSForm();
      },
      _renderPickType: function() {
        var $pick, self;
        self = this;
        $pick = $('#pick-register-type');
        $('.us-vendor-btn', $pick).click(function() {
          window.location.hash = 'us-vendors';
          $pick.hide();
          $('#us-register').show().fadeIn();
        });
        $('.china-delegate-btn', $pick).click(function() {
          window.location.hash = 'china-delegates';
          $pick.hide();
          $('#china-register').show().fadeIn();
        });
        switch (window.location.hash) {
          case '#us-vendors':
            $('.us-vendor-btn', $pick).trigger('click');
            break;
          case '#china-delegates':
            $('.china-delegate-btn', $pick).trigger('click');
        }
      },
      _renderUSForm: function() {
        var $creditForm, $form, self;
        self = this;
        $form = $('#us-register', this.el);
        $creditForm = $('#credit-card-form', $form);
        $('[name="payment-method"]', $form).change(function(e) {
          var $t;
          $t = $(this);
          $t.closest('.pay-method').siblings('.pay-method').find('[type="checkbox"]:checked').attr('checked', false);
          if ($t.val() === 'credit') {
            $creditForm.show();
          } else {
            $creditForm.hide();
            $creditForm[0].reset();
          }
        });
        $('.pay-method', $form).click(function(e) {
          var $check, _ref;
          $check = $(this).find('[name="payment-method"]');
          $check.attr('checked', (_ref = $check.attr('checked')) != null ? _ref : {
            "false": true
          });
          $check.trigger('change');
        });
        $('[name="present"]', $form).change(function() {
          var $t;
          $t = $(this);
          if ($t.attr('checked')) {
            $('<div class="item" rel="present"><label>Destination Presentation to Chinese Tour Operator</label><var>$' + G.site.data.global.presentPrice + '</var></div>').insertBefore($('.items-summary .total', $form));
            self.total += self.items.present.price;
          } else {
            $('.items-summary [rel="present"]', $form).remove();
            self.total -= self.items.present.price;
          }
          $('.items-summary .total var').text('$' + self.total);
        });
        $('[name="follow-up"]', $form).change(function() {
          var $t;
          $t = $(this);
          if ($t.attr('checked')) {
            $('<div class="item" rel="follow-up"><label>In-Country Follow Up</label><var>$' + G.site.data.global.followUpPrice + '</var></div>').insertBefore($('.items-summary .total', $form));
            self.total += self.items.followup.price;
          } else {
            $('.items-summary [rel="follow-up"]', $form).remove();
            self.total -= self.items.followup.price;
          }
          $('.items-summary .total var').text('$' + self.total);
        });
        $creditForm.find('.same-address').change(function() {
          if ($(this).is(':checked')) {
            $('[name="cc-street"]', $creditForm).val($('[name="street"]', $form).val());
            $('[name="cc-city"]', $creditForm).val($('[name="city"]', $form).val());
            $('[name="cc-state"]', $creditForm).val($('[name="state"]', $form).val());
            $('[name="cc-zip"]', $creditForm).val($('[name="zip"]', $form).val());
          } else {
            $('[name="cc-street"], [name="cc-city"], [name="cc-state"], [name="cc-zip"]', $creditForm).val('');
          }
        });
        $('.flow-btn', $form).click(function(e) {
          var $t, step;
          e.preventDefault();
          $t = $(this);
          step = $t.attr('rel');
          self.loadStep(step);
        });
        $('[name="agree"]', $form).change(function() {
          return $(this).tipsy('hide');
        });
        $('.submit-btn', $form).click(function() {
          var paymethod;
          paymethod = $('[name="payment-method"]:checked', $form).val();
          self.submit(function() {
            if (!$('.pay-method input[type="checkbox"]:checked', $form).length) {
              $.validate.error($('.pay-method [value="check"]'), 'You need to select a payment method.', {
                gravity: 's'
              });
              return;
            }
            self.loadStep('confirm');
          });
        });
      },
      submit: function(next) {
        var $bio, $cc, $city, $company, $country, $email, $fax, $followUp, $form, $name, $phone, $present, $state, $street, $title, $website, $zip, data, paymethod, postRegister, sanitizePhone, website, _ref, _ref2;
        if (next == null) {
          next = function() {};
        }
        $form = $('#attendee-register-form');
        $name = this.el.find('[name="name"]');
        $company = this.el.find('[name="company"]');
        $country = this.el.find('[name="country"]');
        $email = this.el.find('[name="email"]');
        $fax = this.el.find('[name="fax"]');
        $phone = this.el.find('[name="phone"]');
        $present = this.el.find('[name="present"]');
        $bio = this.el.find('[name="bio"]');
        $title = this.el.find('[name="title"]');
        $street = this.el.find('[name="street"]');
        $city = this.el.find('[name="city"]');
        $state = this.el.find('[name="state"]');
        $zip = this.el.find('[name="zip"]');
        $followUp = this.el.find('[name="follow-up"]');
        $website = this.el.find('[name="website"]');
        paymethod = this.el.find('[name="payment-method"]:checked').val();
        sanitizePhone = function(phone) {
          phone = phone.replace(/[^\+0-9]+/g, '');
          if (phone.length === 10) {
            phone = '+1' + phone;
          }
          return phone;
        };
        website = $website.val();
        website = (!_.isEmpty(website) && website.indexOf('http') === -1 ? 'http://' : '') + website;
        data = {
          firstName: $name.val().substr(0, $name.val().lastIndexOf(' ')).trim(),
          lastName: $name.val().substr($name.val().lastIndexOf(' ')).trim(),
          company: $company.val(),
          title: $title.val(),
          addresses: [
            {
              name: 'work',
              street: $street.val(),
              city: $city.val(),
              state: $state.val(),
              zip: $zip.val(),
              country: $country.val(),
              primary: true
            }
          ],
          emails: [
            {
              name: 'home',
              val: $email.val(),
              primary: true
            }
          ],
          phones: [
            {
              name: 'mobile',
              val: sanitizePhone($phone.val()),
              primary: true
            }
          ],
          website: website,
          data: {
            paymethod: paymethod,
            present: (_ref = $present.is(':checked')) != null ? _ref : false,
            followUp: (_ref2 = $followUp.is(':checked')) != null ? _ref2 : false,
            bio: $bio.val(),
            paid: false
          }
        };
        postRegister = function() {
          $.post('/app/activeamerica/api/attendee', data).success(function(r) {
            G.attendee = r;
            $.post('/app/activeamerica/mail_registration', {
              type: 'attendee',
              id: r._id,
              token: 'dcc6404a7804dfd2a9863bc04778b8ac'
            });
            next(null, r);
          }).error(function(r) {
            console.error(r);
            next(r);
          });
        };
        if (!_.isEmpty($fax.val())) {
          data.phones.push({
            name: 'fax',
            val: sanitizePhone($fax.val())
          });
        }
        if (paymethod === 'credit') {
          $cc = $('#credit-card-form');
          $cc.validate('validate', function(err) {
            if (!err) {
              data.data.cc = $.base64.encode($cc.serialize());
              postRegister();
            }
          });
        } else {
          postRegister();
        }
      },
      validateEmail: function(email, next) {
        if (next == null) {
          next = function() {};
        }
        $.get('/app/activeamerica/api/attendee', {
          'emails.val': email
        }).success(function(r) {
          next(null, r);
        }).error(function(r) {
          console.error(r);
          next(r);
        });
      }
    };
    RegisterDelegateForm = {
      el: $('#register-chinese-form'),
      init: function() {
        var self;
        self = this;
        if (!this.el.length) {
          return;
        }
        $('.submit-btn', this.el).click(function() {
          self.submit();
        });
        $('.another-btn', this.el).click(function() {
          self.reset();
        });
        self.reset();
      },
      reset: function() {
        var $form, $photo, $photoIn, $success, $upload, self, upOpts;
        self = this;
        $form = $('form', this.el);
        $success = $('.success-msg', this.el);
        $photo = $('.photo', this.el);
        $photoIn = $('input[name="data[photo]"]', this.el);
        $upload = $('.upload-passport', this.el);
        upOpts = {
          onUpload: function(err, url) {
            $photo.css({
              display: 'inline-block',
              width: 200,
              height: 200,
              background: "url(" + url + ")"
            });
            $photoIn.val(url);
          }
        };
        $('.tipsy').remove();
        $form[0].reset();
        $form.fadeIn();
        $photo.css({
          background: 'none',
          width: 0,
          height: 0
        });
        $upload.empty().attr('class', 'upload-passport').uploader(upOpts);
        $success.hide();
      },
      submit: function(next) {
        var $form, $photo, $success, $upload, self;
        if (next == null) {
          next = function() {};
        }
        self = this;
        $form = $('form', this.el);
        $success = $('.success-msg', this.el);
        $photo = $('input[name="data[photo]"]', this.el);
        $upload = $('.upload-passport', this.el);
        $form.validate('validate', function(err) {
          var data;
          if (err) {
            $(window).scrollTo($('.ui-error'), 500);
          } else {
            if (_.isEmpty($photo.val())) {
              $.validate.error($upload, 'Photo required');
              $(window).scrollTo($('.ui-error'), 500);
              return;
            }
            data = $form.serialize();
            $.post('/app/activeamerica/api/delegate', data).success(function(r) {
              $.post('/app/activeamerica/mail_registration', {
                type: 'delegate',
                id: r._id,
                token: 'dcc6404a7804dfd2a9863bc04778b8ac'
              });
              next(null, r);
              $form.hide();
              $success.fadeIn();
            }).error(function(r) {
              $.error('Cannot create new delegate', r);
              next(r);
            });
          }
        });
      }
    };
    Attendees = {
      el: $('#whos-attending-content'),
      template: {
        attendee: '<li>\
				<div class="info">\
					<a class="company" href="{{website}}" target="_blank">{{company}}</a>\
					<span class="contact">{{firstName}} {{lastName}}</span>\
				</div></li>'
      },
      init: function() {
        var $currType, $currYr, currType, currYr, hash, lastIn, self;
        self = this;
        if (!this.el.length) {
          return;
        }
        $('.year a', this.el).click(function() {
          var $t, currType, currYr;
          $t = $(this);
          $t.siblings('.active').removeClass('active');
          $t.addClass('active');
          self.get();
          currYr = $('.year .active', this.el).text();
          currType = $('.type .active', this.el).attr('rel');
          window.location.hash = (currType + '-' + currYr).toLowerCase();
        });
        $('.type a', this.el).click(function() {
          var $t, currType, currYr;
          $t = $(this);
          $t.siblings('.active').removeClass('active');
          $t.addClass('active');
          self.get();
          currYr = $('.year .active', this.el).text();
          currType = $('.type .active', this.el).attr('rel');
          window.location.hash = (currType + '-' + currYr).toLowerCase();
        });
        if (window.location.hash !== '') {
          hash = window.location.hash.replace('#', '');
          lastIn = hash.lastIndexOf('-');
          currYr = hash.substr(lastIn + 1);
          currType = hash.substr(0, lastIn);
          $currType = $('.type a[rel="' + currType + '"]');
          $currYr = $('.year a.' + currYr + '-btn');
          $currType.siblings('.active').removeClass('active');
          $currType.addClass('active');
          $currYr.siblings('.active').removeClass('active');
          $currYr.addClass('active');
          self.get();
        } else {
          $('.type .active', this.el).trigger('click');
        }
      },
      get: function(next) {
        var $list, params, self, type, year;
        if (next == null) {
          next = function() {};
        }
        self = this;
        $list = $('#attendees-list');
        year = this.el.find('.year .active').text();
        type = this.el.find('.type .active').hasClass('dmo-btn') ? 'attendee' : 'delegate';
        params = {
          year: year,
          limit: 0,
          valid: true,
          sort: type === 'attendee' ? 'company asc' : 'firstName asc'
        };
        $.get('/app/activeamerica/api/' + type, params).success(function(r) {
          $list.empty();
          if (_.isEmpty(r)) {
            $list.html('To be announced');
          } else {
            _.each(r, function(attendee) {
              $(_.template(self.template.attendee, attendee)).appendTo($list);
            });
          }
        }).error(function(r) {
          console.error(r);
        });
      }
    };
    Schedule = {
      el: $('#schedule-content'),
      init: function() {
        var self;
        self = this;
        if (!this.el.length) {
          return;
        }
        $('nav .us-btn', this.el).click(function() {
          var $t;
          $t = $(this);
          $t.siblings('.active').removeClass('active');
          $t.addClass('active');
          $('.content[rel="chinese"]').hide();
          $('.content[rel="us"]').show();
          window.location.hash = 'us-vendors';
        });
        $('nav .chinese-btn', this.el).click(function() {
          var $t;
          $t = $(this);
          $t.siblings('.active').removeClass('active');
          $t.addClass('active');
          $('.content[rel="chinese"]').show();
          $('.content[rel="us"]').hide();
          window.location.hash = 'chinese-delegates';
        });
        switch (window.location.hash) {
          case '#us-vendors':
            $('nav .us-btn', this.el).trigger('click');
            break;
          case '#chinese-delegates':
            $('nav .chinese-btn', this.el).trigger('click');
        }
      }
    };
    Attendees.init();
    RegisterForm.init();
    RegisterDelegateForm.init();
    Schedule.init();
    Slideshow.init();
    Countdown.init();
  });
}).call(this);

