"use strict";
/*jslint white: true, devel: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true, indent: 2 */
/**@todo: this file should replace global.js**/

function notification(message, type) {
  if (!message) { 
    return;
  }
  type = type || 'success';
  $('#notification').show();
  $('<p class="' + type + '">' + message + '</p>').prependTo('#notification').show(0).delay(3000).slideUp('normal', function () {
    $(this).remove();
    $('#notification').hide();
  });
}
function getParam(el, name, useId) {
  var attr  = typeof(useId) !== 'undefined' ? 'id' : 'class',
      re    = new RegExp(name + '-(\\S*)'),
      match = $(el).attr(attr).match(re);

  return match ? match[1] : null;
}
$.fn.getParam = function (name, useId) {
  return getParam($(this), name, useId);
};
function display(str) {
  str += '';
  return str.preventXss();
}
String.prototype.preventXss = function () {
  return this.replace(/\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-/g,"");
};

function Form($form, options) {
  options = $.extend(true, {beforeSubmit: $.noop, beforeSend: $.noop, error: $.noop, comlete: $.noop, success: $.noop, async: false, dataType: 'html', data: []}, options);

  this.bind = function () {
    var t = this;
    $form.live('submit', function (e) {
      t.submit.call(t, e);
      return false;
    });
  };

  this.submit = function (e) {
    if (options.beforeSubmit() === false) {
      return false;
    }

    var $form = $(e.target).closest('form');
    var sid = $.cookie('ffc.sid');
    var data = $.merge($form.serializeArray(), options.data);

    if (sid) {
      data = $.merge(data, [{'name' : 'api_session_sid', 'value' : sid}]);
    }

    $.ajax({
      url: $form.attr('action'),
      type: $form.attr('method'),
      dataType: options.dataType,
      data: data,
      beforeSend: options.beforeSend,
      success: function (xhr) {
        options.success(xhr);
      },
      complete: options.complete
    });
  };

  return this;
}
$.fn.bindSubmit = function (options) {
  var f = new Form($(this), options);
  f.bind();
  return $(this);
};
function FormError(error) {
  return {
    message: error
  };
}
var ErrorsFormatter = {
  list: function (errors) {
    if (!errors.length) {
      return '';
    }

    var html = '';
    for (var i = 0; i < errors.length; i += 1) {
      html += '<li>' + errors[i].message + '</li>';
    }

    return '<ul class="errors">' + html + '</ul>';
  }
};
var FormValidator = {
  getInput: function (field, selector) {
    return selector ? $(selector).find(':input[name="' + field + '"]') : $(':input[name="' + field + '"]');
  },
  getValue: function (el) {
    var val = el.val(); 
  
    if (el.filter('[multiple]').length) {
      //hack for multiple select
      if (val !== null && !val.length) {
        val = '';
      }
    } else if (el.attr('type') === 'checkbox') {
      val = el.attr('checked');
    } else {
      val = $.trim(val);
    }
    return val;
  },
  checkFields: function (fields, selector) {
    var errors = [];
    for (var field in fields) {
      if (fields.hasOwnProperty(field)) {
        var el = this.getInput(field, selector),
          val = this.getValue(el);

        if (!val || val === fields[field]) {
          errors.push({field: field, message: 'The ' + fields[field] + ' is a required field'});
        }
      }
    }
    if (errors.length) {
      throw errors;
    }
  },
  iterator: function (fields, selector, regexps) {
	regexps = regexps || {};
    var errors = [];
    var decimal = function (val, fields, field) {
      if (!/^\-?\d+(\.\d+)?$/.test(val)) {
        errors.push({field: field, message: 'The ' + fields[field] + ' should be decimal'});
      }
    };

    var integer = function (val, fields, field) {
      if (!/^\d+$/.test(val)) {
        errors.push({field: field, message: 'The ' + fields[field] + ' should be a whole number'});
      }
    };
    
    var custom = function (val, fields, field, reg) {
    	var regExp = new RegExp(reg);
    	if (!regExp.test(val)) {
    		errors.push({field: field, message: 'The ' + fields[field] + ' is incorrect'});
    	}
    };

    for (var field in fields) {
      if (fields.hasOwnProperty(field)) {
        var el = this.getInput(field, selector),
          val = this.getValue(el);

        if (regexps[field]) {
        	custom(val, fields, field, regexps[field]);
        }
        else if (el.hasClass('integer')) {
          integer(val, fields, field);
        } else {
          decimal(val, fields, field);
        }
      }
    }
    if (errors.length) {
      throw errors;
    }
  },
  showErrors: function (errors, container) {
    if (!(errors instanceof Array)) { 
      errors = [errors];
    }

    $(container).html(ErrorsFormatter.list(errors));
    $(container).show();
  },
  checkEmail: function (value) {
    var regExp = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/;

    if (!regExp.test(value)) {
      throw new FormError("Email Address is incorrect.");
    }
  },
  checkName: function (value, message) {
    var regExp = /^[a-zA-Z]{2,}/;
    if (!regExp.test(value)) {
      message = message || "Name is incorrect.";
      throw new FormError(message);
    }
  },
  checkUrl: function (value) {
    var regExp = new RegExp('^((https?|HTTPS?)\\:\\/\\/)?[a-zA-Z]\\w*([\\.\\-]\\w+)*\\.(aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|no|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|uk|gd|ge|gf|fr|gg|gh|gi|gl|gm|gn|gp|fr|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mn|mo|mp|mq|fr|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|fr|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|fr|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|fr|ro|rs|yu|ru|su|rw|sa|sb|sc|sd|se|sg|sh|si|sj|no|sk|sl|sm|sn|sr|st|su|sv|sy|sz|tc|td|tf|fr|tg|th|tj|tk|tl|tp|tm|tn|to|tp|tl|tr|tt|tv|tw|tz|ua|ug|uk|us|gov|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|fr|ws|ye|yt|fr|yu|za|zm|zw|arpa)(\\:\\d+)*([\\/\\.\\-\\?\\&\\%\\#=]\\w+)*\\/?$');

    if (!regExp.test(value)) {
      throw new FormError("Url is incorrect.");
    }
  },
  checkPhone: function (value) {
    var regExp = new RegExp('^[ 0-9()-.]{9,}$');

    if (!regExp.test(value)) {
      throw new FormError("Phone is incorrect.");
    }
  }
};
var i18n = {
  en: {
    hotPollShowResults: '+ show results',
    hotPollHideResults: '- hide results'
  },
  get: function (key) {
    return this.en[key];
  }
};
var HotPoll = {
  init: function () {
    this.bind();
  },
  bind: function () {
    $('#hot-pool-form').bindSubmit({success: HotPoll.successCallback, dataType: 'json'});

    $('#vote').live('click', function () {
      $('#hot-pool-form').trigger('submit');
    });
    $('.toggleVoteResults').live('click', function (e, value) {
      if ($(this).text() === i18n.get('hotPollShowResults')) {
        $(this).text(i18n.get('hotPollHideResults'));
      } else {
        $(this).text(i18n.get('hotPollShowResults'));
      }
      $('#vote_form, #results_form').toggle();
      if ($(this).hasClass('state_voted')) {
        $('#vote_form').hide();
      }
    });
  },
  successCallback: function (xhr) {
    HotPoll.showResults(xhr);
  },
  showResults: function (data) {
    if (data) {
      var poll_uuid = $('#poll_uuid').val();
      //@todo: cookie must be set via serverside
      $.cookie('voted_' + poll_uuid, true, { expires: 30, path: '/' });
      HotPoll.renderResults(data);
    }
    $('.toggleVoteResults').toggleClass('state_unvoted state_voted').trigger('click', true);
  },
  renderResults: function (data) {
    for (var i in data) {
      if (data.hasOwnProperty(i)) {
        $('.answer[id=' + i + ']').text(data[i] + '%');
      }
    }
  }
};
var HelpMeNow = {
  init: function () {
    if (/^\/help-me-now/.test(window.location.pathname)) {
      this.bind();
    }
  },
  bind: function () {
    $('#req_form').bindSubmit({beforeSubmit: HelpMeNow.beforeSubmit, success: HelpMeNow.success, data: [{
      name: 'form-fields',
      value: $.toJSON(["first_name", "last_name", "from", "phone_number", "company", "website", "newsletter", "accomplish", "stuck", "reason", "success", "company_type", "revenues", "newsletter_type"])
    }]});
  },
  beforeSubmit: function () {
    try {
      HelpMeNow.checkFields();
      var from = $.trim($('input[name=from]').val()),
          url  = $.trim($('input[name=website]').val()),
          phone = $.trim($('input[name=phone_number]').val()); 

      FormValidator.checkEmail(from);
      FormValidator.checkPhone(phone);
      FormValidator.checkUrl(url);

      $('#help-me-now-error-container').hide();
      return true;
    } catch (e) {
      FormValidator.showErrors(e, '#help-me-now-error-container');
      return false;
    }
  },
  checkFields: function () {
    var fields = {
      'first_name' : 'First Name',
      'last_name'  : 'Last Name',
      'from' : 'Email Address',
      'phone_number' : 'Phone Number',
      'website' : 'Website',
      'company' : 'Company',
      'company_type' : 'Company Type'
    };
    FormValidator.checkFields(fields);
  },
  success: function (xhr) {
    var $success = $('#help-me-now-success-container'),
        $default = $('#help-me-now-form-container');

    $default.hide();
    $success.show();
    HelpMeNow.insertTracker();
    $('#req_form').trigger('reset');

    window.setTimeout(function () {
      $success.hide();
      $default.show();
    }, 4 * 1000);
  },
  insertTracker: function () {
    $('#js-container').html('<div style="display:inline;"><img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1008324653/?label=MdLECIu58AEQraDn4AM&amp;guid=ON&amp;script=0"/></div>');
  }
};
var SendForm = {
  init: function () {
    this.bind();
  },
  bind: function () {
    $('#send-form').bindSubmit({beforeSubmit: SendForm.beforeSubmit, success: SendForm.success, data: [{
      name: 'form-fields',
      value: $.toJSON(["from", "to", "message"])
    }]});
  },
  beforeSubmit: function () {
    try {
      var from = $('#send-form-from').val(),
          to   = $('#send-form-to').val();

      SendForm.checkFields();

      FormValidator.checkEmail(from);
      FormValidator.checkEmail(to);
      $('#rpf-message').html('').hide();
      return true;
    } catch (e) {
      FormValidator.showErrors(e, '#rpf-message');
      return false;
    }
  },
  checkFields: function () {
    var fields = {
      'to' : 'To',
      'from' : 'From',
      'message': 'Message'
    };
    FormValidator.checkFields(fields);
  },
  success: function () {
    $('#req_step_01, #req_step_02').toggle();
    $('#send-form').trigger('reset');

    window.setTimeout(function () {
      $('#req_step_01, #req_step_02').toggle();
    }, 5000);
  }
};
var HeaderSliderSprites = {
  slides: {
    '212': 'head-hold_getpluggedin_home',
    '0': 'head-hold_home',
    '-212': 'head-hold_oppc_home',
    '-424': 'head-hold_findyourway_home',
    '-636': 'head-hold_getpluggedin_home',
    '-848': 'head-hold_home'
  },
  init: function () {
    this.bind();
  },
  bind: function () {
    var slidesStr = this.getSlides(),
        t = this;

    $('.header-control').live('click', function () {
      var type = $(this).getParam('type'),
          css = $(this).parents('.top_img').css('backgroundPosition').split(' '),
          y = parseInt(css[1], 10) || 0,
          delta = (type === 'next') ? -212 : 212,
          newPosition = delta + y,
          $container = $(this).parents('.head-hold');

      $container.removeClass(slidesStr);
      if (t.slides[newPosition]) {
        $container.addClass(t.slides[newPosition]);
      }
    });
  },
  getSlides: function () {
    var str = '';
    for (var s in this.slides) {
      if (this.slides.hasOwnProperty(s)) {
        str += ' ' + this.slides[s];
      }
    }
    return str;
  }
};
var HeaderSlider = {
  timeout: null,
  current: null,
  init: function (timeout) {
    this.timeout = timeout || 8;
    this.current = $('.head-hold-index').first();
    this.bind();
  },

  bind: function () {
    var t = this;
    $('.header-control').live('click', function () {
      var type = $(this).getParam('type'),
          $container = $(this).parents('.head-hold-index');

      t.slide($container, type);
    });

    var i = window.setInterval(function () {
      t.slide(t.current, 'next');
    }, t.timeout * 1000);
  },

  slide: function ($container, direction) {
    var targetIndex;

    if (direction === 'next') {
      if ($container.index() < 3) {
        targetIndex = $container.index() + 1;
      } else {
        targetIndex = 0;
      }
    }

    if (direction === 'prev') {
      if ($container.index() > 0) {
        targetIndex = $container.index() - 1;
      } else {
        targetIndex = 3;
      }
    }

    this.current = $('.head-hold-index').eq(targetIndex); 
    this.current.fadeIn();
    $container.fadeOut();
  }
};
var EK = EK || {};
EK.ServiceAgreement = {
  errors: {
    firstNameLength: 'First Name should be more than 2 alphabetical chars',
    lastNameLength : 'Last Name should be more than 2 alphabetical chars',
    notChecked: 'You must agree with rules'
  },
  init: function () {
    this.$form = $('#service-agreement');
    this.bind();
  },
  bind: function () {
    var t = this;
    $('#service-agreement-submit').live('click', function () {
      if (t.beforeSubmit.call(t)) {
        t.$form.trigger('submit');
      }
      return false;
    });
  },
  beforeSubmit: function () {
    var fields = {
      'first-name' : 'First Name',
      'last-name' : 'Last Name',
      'company' : 'Company Name',
      'title' : 'Title',
      'email' : 'Email',
      'phone' : 'Phone'
    };
    try {
      FormValidator.checkFields(fields, '#service-agreement');
      this.checkFirstName();
      this.checkLastName();
      this.checkEmail();
      this.checkPhone();
      this.checkCheckBox();
      $('#service-agreement-errors').hide();
      return true;
    } catch (e) {
      $('#service-agreement-errors').show();
      FormValidator.showErrors(e, '#service-agreement-errors .errors');
      return false;
    }
  },
  checkCheckBox: function () {
    var $el = this.$form.find('input[name=have-read]');
    if (!$el.length || $el.attr('checked') === 'checked') {
      throw new FormError(this.errors.notChecked);
    }
  },
  checkFirstName: function () {
    var firstName = this.getValue('first-name');
    FormValidator.checkName(firstName, this.errors.firstNameLength);
  },
  checkLastName: function () {
    var lastName = this.getValue('last-name');
    FormValidator.checkName(lastName, this.errors.lastNameLength);
  },
  checkEmail: function () {
    var email = this.getValue('email');
    FormValidator.checkEmail(email);
  },
  checkPhone: function () {
    var phone = this.getValue('phone');
    FormValidator.checkPhone(phone);
  },
  getValue: function (name) {
    return $.trim(this.$form.find('input[name=' + name + ']').val());
  }
};
$(function () {
  EK.ServiceAgreement.init();
  HotPoll.init();
  HelpMeNow.init();
  SendForm.init();

  if ($('#hero-banner-sprites').length) {
    HeaderSliderSprites.init();
  } else {
    HeaderSlider.init(8);
  }
});

