genius = {
    BuyApp: function(options) {
        this.el = options.el;
        this.steps = 3;
        this.options = options;
        this.initialize(options.step);
    },

    isEmailValid: function validateEmail(email)
    {
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        return email.match(re)
    }

};

$.extend(genius.BuyApp.prototype, {
    $: function(query) {
        return $(query, this.el);
    },

    initialize: function(step) {
        var self = this;
        this.$scrollable = this.$('.scrollable').scrollable({
            next: false,
            prev: false,
            vertical: false
        });
        this.scrollable = this.$scrollable.data('scrollable');
        this.$('.prev').click(function(event) {
            self.prev();
            event.preventDefault();
        });
        this.$('.next').click(function(event) {
            self.next();
            event.preventDefault();
        });
        this.setStep(step);
        this.initializeStep0();
        this.initializeStep1();
    },

    setStep: function(step) {
        if (this.step == step) {
            return;
        }
        this.step = step;
        for (var i = 0; i < this.steps; ++i) {
            if (i == this.step) {
                $('#navigation_info .step' + (i + 1)).addClass('current');
            }
            else {
                $('#navigation_info .step' + (i + 1)).removeClass('current');
            }
        }
        this.scrollable.seekTo(this.step);
        if (this.step == this.steps - 1) {
            this.$('.next').fadeOut(500);
        }
        else {
            this.$('.next').fadeIn(500);
        }
        if (this.step == this.steps - 2) {
            this.$('.next').addClass('last');
        }
        else {
            this.$('.next').removeClass('last');
        }
        if (this.step == 0 || this.step == this.steps - 1) {
            this.$('.prev').fadeOut(500);
        }
        else {
            this.$('.prev').fadeIn(500);
        }
    },

    next: function() {
        var self = this;
        if (this.step < this.steps - 1) {
            var result;
            switch (this.step) {
                case 0:
                    result = this.validateStep0();
                    if (result) {
                        this.ajax('validate_0', result, {
                            success: function(data) {
                                if (data.result) {
                                    self.setStep(self.step + 1);
                                }
                                else {
                                    self.$('#content .step1 form td').removeClass('error');
                                    for (var i in data.errors) {
                                        self.$('#content .step1 form input[name="step0[' + data.errors[i] + ']"]').closest('td').addClass('error');
                                    }
                                }
                            }
                        });
                    }
                    break;
                case 1:
                    result = this.validateStep1();
                    if (result) {
                        this.ajax('validate_1', result, {
                            success: function(data) {
                                if (data.result) {
                                    self.setStep(self.step + 1);
                                    self.$('.step3 .result').html(data.html);
                                    self.$('form').each(function(index, el) { el.reset(); });
                                }
                                else {
                                    self.$('#content .step2 form td').removeClass('error');
                                    for (var i in data.errors) {
                                        self.$('#content .step2 form input[name="step1[' + data.errors[i] + ']"]').closest('td').addClass('error');
                                    }
                                }
                            }
                        });
                    }
                    break;
            }
        }
    },

    prev: function() {
        if (this.step > 0 && this.step < this.steps - 1) {
            this.setStep(this.step - 1);
        }
    },

    ajax: function(command, data, options) {
        this.el.addClass('loading');
        var self = this;
        $.ajax(this.options.url + '?command=' + command, {
            data: data,
            type: 'POST',
            complete: function() {
                if (options && options.complete) {
                    options.complete();
                }
                self.el.removeClass('loading');
            },
            error: function(data) {
                if (options && options.error) {
                    options.error(data);
                }
            },
            success: function(data) {
                if (options && options.success) {
                    options.success(data);
                }
            }
        });
    },

    initializeStep0: function() {
        /*var self = this;
        var $input = this.$('#content .step1 form input[name="step0[url]"]');
        $input.keypress(function() {
            $input.closest('td').removeClass('valid');
            $input.closest('td').removeClass('invalid');
        });
        var lastValue;
        $input.blur(function() {
            var value = $input.val().toLowerCase();
            if (lastValue == value)
                return;
            $input.val(value);
            lastValue = value;
            self.ajax('check_domain', {
                domain: value
            }, {
                success: function(data) {
                    if (data.available) {
                        $input.closest('td').addClass('valid');
                        $input.closest('td').removeClass('invalid');
                    }
                    else {
                        $input.closest('td').removeClass('valid');
                        $input.closest('td').addClass('invalid');
                    }
                }
            });
        });
        if ($input.val().length)
            $input.blur();*/
    },
    validateStep0: function() {
        //return this.$('#content .step1 form').serializeArray();
        var error = false;
        var $url = this.$('#content .step1 form input[name="step0[url]"]');
        var $password = this.$('#content .step1 form input[name="step0[password]"]');
        var $password2 = this.$('#content .step1 form input[name="step0[password2]"]');
        var $email = this.$('#content .step1 form input[name="step0[email]"]');
        this.$('#content .step1 form td').removeClass('error');

        if ($url.closest('td').hasClass('invalid')) {
            $url.closest('td').addClass('error');
            error = true;
        }

        if ($password.val().length > 0 && $password.val().length < 6) {
            $password.closest('td').addClass('error');
            error = true;
        }

        if ($password.val() != $password2.val()) {
            $password2.closest('td').addClass('error');
            error = true;
        }

        if ($email.val().length < 5 || !genius.isEmailValid($email.val())) {
            $email.closest('td').addClass('error');
            error = true;
        }

        if (error) {
            return false;
        }
        else {
            return this.$('#content .step1 form').serializeArray();
        }
    },

    initializeStep1: function() {
    },
    validateStep1: function() {
        return this.$('#content .step2 form').serializeArray();
        ///TODO: validate fields, now they are validated only server side
    }
});

jQuery.fn.hint = function (blurClass) {
  if (!blurClass) {
    blurClass = 'blur';
  }

  return this.each(function () {
    // get jQuery version of 'this'
    var $input = jQuery(this),

    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = jQuery(this.form),
      $win = jQuery(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) {
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title

      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

$(function(){
    $('input[title!=""]').hint();
});
