var form;
var Vertis = (function () {

  
  // usuwa Cookisa z wybranym tabem w produktach, ustawia potem 1: Widok gadzetow w ribbonie
  $(".more").click(function() {
    var date = new Date();
    document.cookie = 'lastTab' + '=' + escape(1) + ';expires=' + date.toGMTString() + ';path=/;';
    document.cookie = 'lastTab' + '=' + escape(1) + ';;path=/;';
  });
  $(".order_now").click(function() {
    var date = new Date();
    document.cookie = 'lastTab' + '=' + escape(1) + ';expires=' + date.toGMTString() + ';path=/;';
    document.cookie = 'lastTab' + '=' + escape(1) + ';;path=/;';
  });
  $(".buy_now").click(function() {
    var date = new Date();
    document.cookie = 'lastTab' + '=' + escape(1) + ';expires=' + date.toGMTString() + ';path=/;';
    document.cookie = 'lastTab' + '=' + escape(1) + ';;path=/;';
  });

  $('html').addClass('jsEnabled');
  var _animationTime = 1000;

  var _autocomplete = $('<ul id="autocomplete"></ul>'),
      _info = $('#info').parent(),
      _infoText = $('#infoText'),
      _busy = $('#busy'),
      _wait = $('#wait'),
      _isBusy = false,
      _modal = $('#modal').parent(),
      _modalTitle = $('#modal #modal_titletext'),
      _modalBody = $('#modal #modal_body'),
      _modalNoClose = false,
      _submitBlocked = false,
      _cropBorder = $('<div class="cropBorder"></div>'),
      _wrapper = '<div style="position: relative;"></div>';

  $('form.ajax').live('submit', function () {
    try {
      $(this).triggerHandler('validate');
      Vertis.form.submit(this);
    } catch (msg) {
      if (msg && msg.length > 0) {
        Vertis.info.text(msg).flash('error');
      }
    }
    return false;
  });


  $('#loginForm').bind('onsuccess', function (e, response) {
    window.location.href = response;
    throw 'no modal';
  });
  $('#passwordRecover form').bind('onsuccess', function (e, response) {
    $('#passwordRecover').html(response);
    throw 'no modal';
  });
  $('#changePasswordByNonAuthorized form').bind('onsuccess', function (e, response) {
    var data = $.evalJSON(response);
    $('#changePasswordByNonAuthorized').html(data.msg);
    setTimeout(function () {
      window.location = data.url
    }, 5000);
    throw 'no modal';
  });

  $('.modal-close').live('click', function () {
    Vertis.modal.fadeOut()
    return false;
  });

  var _showBusy = false;
  return {
    ajax: function (options) {
      options.url += ((options.url.indexOf('?') == -1) ? '?' : '&') + 'cachebuster=' + new Date().getTime();
      var origin = (options && options.complete && typeof options.complete == 'function') ? options.complete : null;
      var error  = (options && options.error    && typeof options.error    == 'function') ? options.error    : null;

      if (undefined === options.type && undefined !== options.method) {
        options.type = options.method;
      }

      options.complete = function () {
        if (origin) {
          origin();
        }
        Vertis.busy.stop();
      };

      options.error = function (response) {
        // wylogowany
        if (response.status == 401) {
          window.location.href = $('#login_url').text(); 
          return;
        }
        // przekazany handler
        if (error)
          error(response);
      };

      Vertis.busy.start();
      $.ajax(options);
    },

    busy: {
      delay: 200,

      start: function () {
        _showBusy = true;
        setTimeout(function () {
          if (_showBusy) {
            _isBusy = true;
            _wait.show();
            _busy.fadeIn(_animationTime);
          }
        }, Vertis.busy.delay);
      },

      stop: function () {
        _showBusy = false;
        _busy.fadeOut(_animationTime);
        _wait.hide();
        _isBusy = false;
      }
    },

    isIE6: ($.browser.msie && $.browser.version == '6.0'),
    cookie: {
      set: function(name, value, expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        var _cookie = name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) + ";path=/";
        document.cookie = _cookie;
      },
      get: function (name) {
        if (document.cookie.length>0)
          {
          c_start=document.cookie.indexOf(name + "=");
          if (c_start!=-1)
            {
            c_start=c_start + name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            var _cookie = unescape(document.cookie.substring(c_start,c_end));
            return _cookie;
            }
          }
        return "";
      }
    },
    flash: function (container, text, timeout) {
      container = $(container);
      timeout = timeout || 500;

      if (container.length < 1) {
        return;
      }

      container.wrapInner('<span class="fademe" />'); //without this IE8 removes tds from DOM
      container.children('span.fademe').fadeOut(timeout, function () {
        if (typeof text != 'undefined') {
          container.text(text);
        }
        container.children('span.fademe').fadeIn(timeout);
        container.children('span.fademe').unwrap();
      });
    },

    form: {
      blockSubmit: function (bool) {
        _submitBlocked = bool;
      },
      clearErrors: function (form) {
        $(form).find('.hasError').removeClass('hasError');
        $(form).find('.error').remove();
        $(form).find('.globalErrors').css('display', 'none');
      },
      clearFields: function (form) {
        $(form).find('*[name][value]:visible').val('');
        Vertis.widgets.synchronizeInputs();
      },
      feed: function (form, obj) {
        for (field in obj) {
          // fix na wstawianie null w IE
          if (obj[field] == null)
            obj[field] = '';
          var input = $(form).find('*[name$="[' + field + ']"]');
          if (input.attr('type') == 'checkbox') {
              input.attr('checked', obj[field]);
          } else {
            input.val(obj[field]);
          }
        }
        Vertis.widgets.synchronizeInputs();

      },
      submit: function (formObject) {
        if (_submitBlocked) {
          return;
        }
        form = formObject;
        _submitBlocked = true;
        
        Vertis.form.clearErrors(form);

        Vertis.ajax({
          data: 'data=' + $.toJSON(Vertis.form.toObject(form)),
          url:  $(form).attr('action'),
          type: $(form).attr('method'),
          success: function(response) {
            try {
              $(form).triggerHandler('onsuccess', response);
              Vertis.info.text(response).flash();
            } catch (err){}
          },
          error: function(response) {
            try {
              $(form).triggerHandler('onerror', response);
              var errors = $.evalJSON(response.responseText);
              $(form).find('.hint_error').addClass('ok');
              for (field in errors.fields) {
                $(form).find('#' + field + '_field *').addClass('hasError'); // * to select inputs and textareas
                $(form).find('#' + field + '_error').removeClass('ok').append($('<div class="error">' + errors.fields[field]  + '</div>'));
              }
              if (errors.global.length > 0) {
                // sprawdzam czy jest to form rejestracji
                if ($(form).parents('#register_form').length > 0) {
                  $(form).find('#username_field *').addClass('hasError');
                  $(form).find('#username_error').removeClass('ok').append($('<div class="error">' + errors.global.join('<br />')  + '</div>'));
                } else {
                  $(form).find('.globalErrors').css('display', 'table-row').find('td').html('<div class="error">' + errors.global.join('<br />') + '</div>');
                }
              }
            } catch (err) {}
          },
          complete: function() {
            _submitBlocked = false;
          }
        });
      }, 
      toObject: function (form) {
        var result = {};
        var aaPattern = /(\w+)(\[(\w+)\])?/  // 1[3]
        
        var elements = form.elements;
        var nrElements = elements.length;
        for (var i = 0; i < nrElements; i++) {
          var element = $(elements[i]);
          var name = element.attr('name');
          if (name) {
            // if it's named form element
            // Marcin:
            // poprawka - bo dla checkboxow i radio val() zwraca bzdury, np w FF zawsze wartosc ktora byla przy ladowaniu strony
            if (element.attr('type') == 'checkbox') {
              var value = element.attr('checked') ? 'on' : '';
            } else if (element.attr('type') == 'radio') {
              if (element.attr('checked')) {
                var value = element.val();
              }
            } else {
              element.trigger('focusin');
              var value = element.val();
              //.toJSON can't validate the & properly telling lies
              if(value.indexOf('&') != -1) { 
                value = value.replace(/&/ig, '%26');
              }
              element.trigger('focusout');
            }
            var aArray = name.match(aaPattern); //associative array
            if (!result[aArray[1]]) {
              result[aArray[1]] = {};
            }

            if ( value == undefined)
              value = null;

            if (aArray[3]) {
              result[aArray[1]][aArray[3]] = value; 
            } else {
              result[aArray[1]] = value; 
            }
          }
        }
        
        return result;
      }
    },

    info: {
      fadeIn: function () {
        _info.fadeIn(_animationTime);

        return Vertis.info;
      },
      fadeOut: function () {
        _info.fadeOut(_animationTime);

        return Vertis.info;
      },
      flash: function (error) {
        (error == 'error') ? _infoText.addClass('error') : _infoText.removeClass('error');
        
        Vertis.info.fadeIn();
        setTimeout(Vertis.info.fadeOut, 2000);
      },
      show: function () {
        _info.show();

        return Vertis.info;
      },
      text: function (msg) {
        if (typeof msg == 'undefined') {
          // if called as getter
          return _infoText.text();
        }

        _infoText.text(msg);
        return Vertis.info;
      }
    },

    modal: {
      bind: function (type, callback) {
        _modal.bind(type, callback);
      },
      detach: function () {
        return _modalBody.children().detach();
      },
      feed: function (obj, title) {
        _modalBody.empty().append($(obj));
        _modalTitle.empty().text(title);
        _modalBody.removeAttr('style');
      
        return Vertis.modal;
      },
      titleAppend: function (content) {
        _modalTitle.append(content);
      },
      bodyPrepend: function(content) {
        _modalBody.prepend(content);
      },
      disableClosing: function () {
        _modalNoClose = true;
        $('#modal_fadeOut').fadeTo(200, 0.5).css('cursor', 'default');
      },
      enableClosing: function () {
        _modalNoClose = false;
        $('#modal_fadeOut').fadeTo(200, 1).css('cursor', 'pointer');
      },
      fadeOut: function () {
        if (_modalNoClose)
          return;

        Vertis.overlay.hide();
        _modal.fadeOut();
        Vertis.overlay.unbind('click.modal');
        _modal.triggerHandler('onclose');
        _modal.unbind('onclose');

        return Vertis.modal;
      },
      fadeIn: function () {
        Vertis.overlay.show();
        _modal.fadeIn();
        Vertis.overlay.bind('click.modal', Vertis.modal.fadeOut);
        if ( typeof Vertis.widgets != 'undefined')
          Vertis.widgets.initWidgets();

        // fix na niepoprawne centrowanie w IE - touch it!
        if ($.browser.msie)
          _modalBody.find('img').one('load', function() {
            _modal.css('left', 'auto');
          });

        return Vertis.modal;
      },
      keepSize: function () {
        _modalBody.attr('style', ['width: ', parseInt(_modalBody.width(), 10), 'px; height: ', parseInt(_modalBody.height(), 10), 'px;'].join(''));

        return Vertis.modal;
      },
      prepend: function (obj) {
        _modalBody.prepend($(obj));

        return Vertis.modal;
      },
      text: function (str, title) {
        Vertis.modal.feed('<span>'+str+'</span>', title);

        return Vertis.modal;
      }
    },

    overlay: $('#overlay'),

    showCropBorder: function (photo, widths) {
      var border = _cropBorder.clone(); 
      photo = $(photo);
      photo.wrap(_wrapper).after(border);

      if (widths.top && widths.right && widths.bottom && widths.left) {
        border.css({
          borderWidth: [widths.top, 'px ', widths.right, 'px ', widths.bottom, 'px ', widths.left, 'px'].join(''),
          height: photo.height() - widths.top - widths.bottom,
          width: photo.width() - widths.left - widths.right
        });
      }
    }
  };
})();

Vertis.confirmation = (function () {
  var _confirmation = $('#confirmation').parent(),
      Button = {
    Cancel: $('#confirmationCancel').click(function () {Vertis.confirmation.hide();}),
    OK: $('#confirmationOK').click(function () {Vertis.confirmation.hide();})
  };

  return {
    fadeIn: function () {
      if ($.browser.msie)
        Vertis.overlay.show();
      else
        Vertis.overlay.fadeIn(_animationTime);
      
      _confirmation.fadeIn(_animationTime);
      
      // fix na niepoprawne centrowanie w IE - touch it!
      if ($.browser.msie)
        $('#confirmationText').find('img').one('load', function() {
          $('#confirmation').css('left', 'auto');
        });

      return Vertis.confirmation;
    },
    fadeOut: function () {
      if ($.browser.msie)
        Vertis.overlay.hide();
      else
        Vertis.overlay.fadeOut(_animationTime);
      
      _confirmation.fadeOut(_animationTime);

      return Vertis.confirmation;
    },
    hide: function () {
      Vertis.overlay.hide();
      _confirmation.hide();

      return Vertis.confirmation;
    },
    show: function (params) {
      if (typeof params.title != 'undefined') {
        Vertis.confirmation.title(params.title);
      }

      if (typeof params.text != 'undefined') {
        Vertis.confirmation.text(params.text);
      }

      if (typeof params.onOK == 'function') {
        Button.OK.unbind('click.binded').bind('click.binded', params.onOK);
      }

      Vertis.overlay.show();
      _confirmation.show();
      
      // fix na niepoprawne centrowanie w IE - touch it!
      if ($.browser.msie)
        $('#confirmationText').find('img').one('load', function() {
          $('#confirmation').css('left', 'auto');
        });

      return Vertis.confirmation;
    },
    title: function (txt) {
      $('#confirmationTitletext').empty().text(txt);

      return Vertis.confirmation;
    },
    text: function (txt) {
      $('#confirmationText').empty().append(txt);

      return Vertis.confirmation;
    }
  };
})();

Vertis.bannerform = {
  'switch': function () {
    var prevForm = $('#form .bannerform:first');
    var form = $('#form .bannerform:last');
    var formRoot = form.parent().get(0);

    if (form.attr('id') == 'login_form')
      Vertis.cookie.set('showLoginFormFirst', '1', 365);
    else  
      Vertis.cookie.set('showLoginFormFirst', '0', 365);
    
    form.fadeTo(10,0);
    prevForm.fadeTo(350, 0 , function() {
      form.prependTo(formRoot);
      form.fadeTo(350,1, function() {
        prevForm.hide();
      });

    });
  }
}

Vertis.cartgroup = {
  'wrap': function (id) {
    // TODO dopiac cos co zrobi lepszejszy accordion czy cus
    $('#cartgroup_'+id).toggleClass('wrapped');
  }
}


$.fn.placeholder = function(){
   // quit if there's support  for html5 placeholder
  if (this[0] && 'placeholder' in document.createElement('input')) return; 
        

  if($(this).val() == '') {
    $(this).val($(this).attr('placeholder'));
    $(this).addClass('placeholderContent');
  }

  return this
    .live('focusin',function(){
      if ($(this).val() === $(this).attr('placeholder')) {
        $(this).val('');
        $(this).removeClass('placeholderContent');
      }
    }).live('focusout',function(){
      if ($(this).val() === ''){
        $(this).val( $(this).attr('placeholder') );
        $(this).addClass('placeholderContent');
      }  
    });
}
$('input[placeholder], textarea[placeholder]').placeholder();

Vertis.croptool = {
  execute: function (params) {
    try {
      var method = arguments[0];
      var argv = [];
      for (var i = 1; i < arguments.length; i++) {
        argv.push(arguments[i]);
      }
      var _croptool = $('#crop').get(0);
      return _croptool[method].apply(_croptool, argv);
    } catch (err) {}
  }
};

$('#cartRemovePromo').live('click', function () {
  Vertis.confirmation.show({
    text: 'Czy na pewno usunąć promocję dla tego koszyka?',
    title: 'Potwierdź',
    onOK: function () {window.location.href = '/cart/removePromo'}
  });
})
