Vertis.widgets = (function () {
  // checkboxy i radio - w obiketach dedykowanych (ponizej)
  // tu tylko timeout sprwdzajacy zgodnosc stanu 
  var synchroCount = 0;

  if (!Vertis.isIE6)
    setTimeout( function() {
      Vertis.widgets.synchronizeInputs();
    }, 150);

  // eventy dla hint_inputa
  $('.vertis_widget.hint_input input').bind('focus', function () {
    Vertis.widgets.hintInput.enter(this)
    return false;
  });

  $('.vertis_widget.hint_input input').bind('blur', function () {
    Vertis.widgets.hintInput.blur(this)
    return false;
  });
  
  // funckja sprawdza zawartosc pola i adekwatnie zmienia wyswietlnie etykiety z hintem
  function hintSynchro() {
    var inputs = $('.vertis_widget.hint_input input');
    if (inputs.length == 0) {
      return;
    }
    inputs.each(function (nr, input) {
      if ( $(input).attr('value').length == 0)
        $(input).prev().fadeTo(20,$(input).hasClass('focus') ? 0.3 : 1);
      if ( $(input).attr('value').length > 0)
        $(input).prev().fadeTo(20, 0);
    });

    setTimeout( hintSynchro, 200);
  }

  setTimeout( hintSynchro, 200);
  
  return {
    hintInput: {
      enter: function(input) {
        $(input).addClass('focus');
      },

      blur: function(input) {
        $(input).removeClass('focus');
      }
    },
    synchronizeInputs: function() {
      synchroCount++;

      $('input[type="radio"]').each( function() {
        var source = $(this);
        var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));

        if (!replacer)
          return;
        replacer.addClass(source.attr('checked') ? 'checked' : 'unchecked');
        replacer.removeClass(source.attr('checked') ? 'unchecked' : 'checked');
      });
      $('input[type="checkbox"]').each( function() {
        var source = $(this);
        var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));

        if (!replacer)
          return;
        replacer.addClass(source.attr('checked') ? 'checked' : 'unchecked');
        replacer.removeClass(source.attr('checked') ? 'unchecked' : 'checked');
      });
    },
    initWidgets: function() {
      Vertis.vertisButton.init();
      Vertis.vertisSelect.init();
      Vertis.vertisTextArea.init();
      Vertis.vertisTextInput.init();
      Vertis.vertisCheckbox.init();
      Vertis.vertisRadio.init();
    }
  };
})();

Vertis.widgetDictionary = (function () {
  var count = 0;
  var old2new = new Array();
  var new2old = new Array();
  var selects = new Array();

  return {
    add: function(source, replacer) {
      var sourceId   = source.attr('id');
      var replacerId = replacer.attr('id');
      var type = 0; //1 - checkbox, 2 - radio

      if (source.attr('type') == 'checkbox')
        type = 1;
      else if (source.attr('type') == 'radio')
        type = 2;

      if (sourceId.length == 0) {
        sourceId = '_vertisNative' + (type==1 ? 'Checkbox' : 'Radio') + count;
        source.attr('id', sourceId);
      }

      if (replacerId.length == 0) {
        replacerId = 'vertis' + (type==1 ? 'Checkbox' : 'Radio') + '_toogle_' + count;
        replacer.attr('id', replacerId);
      }

      old2new [ sourceId ] = replacer;
      new2old [ replacerId ] = {
                    'source' : source,
                    'value'  : source.attr('checked') ? true : false
                  };
      count++;
    },

    getSource: function(replacerId) {
      return new2old[replacerId];
    },

    getReplacer: function(sourceId) {
      return old2new[sourceId];
    },

    addSelect: function(orginalId, obj) {
      if (orginalId && orginalId.length > 0)
        selects [orginalId] = obj;
    },

    getSelect: function(orginalId) {
      return selects [orginalId];
    }
  }
})();

Vertis.vertisButton = (function () {
  /**
   * funkcja dodajaca widget - zapewnia cala obrobke w html / css oraz zabezpiecza przed ponownym wykonaniem na danym elemencie 
   */
  function addButton(button) { 
    button = $(button);
    // zablokowanie widgetu dla ie 6 lub pozostawienie baz zmian jesli jest 'stand_alone'
    if (button.hasClass('stand_alone')) {
      return;
    }

    // pominiecie elementow ktore juz byly obrabiane
    if (button.hasClass('vertisButtonBlue') || button.hasClass('vertisButtonOrange') || button.hasClass('vertisButtonSmall'))
      return;

    // guzikow na ribbonie narazie nie ruszamy
    if (button.parents('#ribbon').length > 0) {
      return;
    }

    button.addClass('inline_block');

    // na modalu zawsze small 
    if (button.parents('#modal').length > 0 || button.parents('#confirmation').length > 0) {
      button.addClass('vertisButtonSmall');
      return;
    }

    // nasz button - standardowo bedzie niebieski
    if (button.attr('type') == 'button')
        button.addClass('vertisButtonBlue');

    // nasz SUBMIT button - standardowo bedzie pomaranczowy
    if (button.attr('type') == 'submit')
        button.addClass('vertisButtonOrange');
  }
  
  /**
   * inicjalizator 
   */
  function init() {
    $('input[type="button"]').each( function() {
      addButton(this);
    });
    $('input[type="submit"]').each( function() {
      addButton(this);
    });
    $('button').each( function() {
      addButton(this);
    });
  }

  init();
  
  return {
    process: function(button) {
      $(button).each ( function() {
        addButton(this);
      });
    },
    init: function() {
      init();
    }
  }
})();

Vertis.vertisSelect = (function () {
  /**
   * funkcja dodajaca widget - zapewnia cala obrobke w html / css oraz zabezpiecza przed ponownym wykonaniem na danym elemencie 
   */
  var count = 0;
  var elements = new Array();
  function addSelect(select) { 
    select = $(select);
    // zablokowanie widgetu dla ie 6 lub pozostawienie baz zmian jesli jest 'stand_alone'
    if (Vertis.isIE6 || select.hasClass('stand_alone')) {
      return;
    }

    // pominiecie elementow ktore juz byly obrabiane
    if (select.hasClass('vertisSelect'))
      return;

    // oznaczenie elementu jako zmienionego
    select.addClass('vertisSelect');

    // kontrola id
    var xx = select.attr('id');
    if(xx.length == 0)
      select.attr('id', '_select_'+count++);

    // obliczenie szerokosci wynikajacej z css
    var clone = select.clone();
    clone.wrap('<div style="position:absolute;" />');
    clone.parent().appendTo(select.parent());
    var cssWidth = parseInt(clone.parent().width());

    //cssWidth = parseInt(select.hide().css('width'));
    // obliczenie wysokosci - odejmuje 6, bo wychodzi na to ze tak jest ladniejszy ;)
    var xy = clone.parent().height();
    xy = clone.height();
    xy = clone.css('height');
    var cssHeight = parseInt(clone.parent().height()) - 6;

    // pobranie rozmiaru czcionki
    var fSize = clone.css('fontSize');
    clone.remove();
    var width = select.width();
    var diff = cssWidth - width;

    // dodanie roznicy w szerokosci zwracanej przez f. width od ustawionej w css, w zalezonsci od przegladarki, minus 2 ze wzgledu na border 1px
    width = (diff > 0) ? cssWidth + diff - 2 : cssWidth;
    
    var options = {
      fontSize: fSize,
      height: cssHeight + 'px',
      style:'dropdown'
    };

    if (select.hasClass('with-icons')) {
      var icons = [];
      select.children('option').each(function (i, option) {
        icons.push({
          'find': '.' + $(option).attr('class')
        });
      });
      options.icons = icons;
      width += 16;
    }
    select.width(width);

    select.selectmenu(options);
  }

  
  /**
   * inicjalizator 
   */
  function init() {
    $('select').each( function() { 
      addSelect(this);
    });
  }

  init();
  
  return {
    process: function(select) {
      $(select).each ( function() {
        addSelect(this);
      });
    },
    init: function() {
      init();
    }
  }
})();
        
Vertis.vertisTextArea = (function () {
  /**
   * funkcja dodajaca widget - zapewnia cala obrobke w html / css oraz zabezpiecza przed ponownym wykonaniem na danym elemencie 
   */
  function addTextArea(ta) { 
    ta = $(ta);
    // pozostawienie baz zmian jesli jest 'stand_alone'
    if (ta.hasClass('stand_alone')) {
      return;
    }

    // pominiecie elementow ktore juz byly obrabiane
    if (ta.hasClass('vertisTextarea'))
      return;

    // nasza ta 
    ta.addClass('vertisTextarea').width(ta.width()-6);

    // obsluga placeholder
    var placeholder = ta.attr('placeholder');
    if ( placeholder != null) {
      
      // reszte obsluguje kod z vertis.js
      return;
  
      // wstawienie hintu
      if (ta.val() == "") {
        ta.val(placeholder);
        ta.addClass('placeholderContent');
      }

      // event wejscia
      ta.focus( function () {
        var self = $(this);
        if (self.val() == self.attr('placeholder'))
          self.val('');
      });

      // event wyjscia
      ta.blur( function () {
        var self = $(this);
        if (self.val() == '')
          self.val(self.attr('placeholder'));
      });
    }
  }

  /**
   * inicjalizator 
   */
  function init() {
    $('textarea').each( function() {
      addTextArea(this);
    });
  }

  init();
  
  return {
    process: function(ta) {
      $(ta).each ( function() {
        addTextArea(this);
      });
    },
    init: function() {
      init();
    }
  }
})();

Vertis.vertisTextInput = (function () {
  /**
   * funkcja dodajaca widget - zapewnia cala obrobke w html / css oraz zabezpiecza przed ponownym wykonaniem na danym elemencie 
   */
  function addInput(input) { 
    input = $(input);
    // pozostawienie baz zmian jesli jest 'stand_alone'
    if (input.hasClass('stand_alone')) {
      return;
    }

    // pominiecie elementow ktore juz byly obrabiane
    if (input.hasClass('vertisTextInput'))
      return;

    // nasz input 
    input.addClass('vertisTextInput').width(input.width()-6);

    // obsluga placeholder
    var placeholder = input.attr('placeholder');
    if ( placeholder != null) {
      
      // reszte obsluguje kod z vertis.js
      return;
  
      // wstawienie hintu
      if (input.val() == "") {
        input.val(placeholder);
        input.addClass('placeholderContent');
      }

      // event wejscia
      input.focus( function () {
        var self = $(this);
        if (self.val() == self.attr('placeholder'))
          self.val('');
      });

      // event wyjscia
      input.blur( function () {
        var self = $(this);
        if (self.val() == '')
          self.val(self.attr('placeholder'));
      });
    }
  }

  /**
   * inicjalizator 
   */
  function init() {
    $('input[type="text"]').each( function() {
      addInput(this);
    });
    $('input[type="password"]').each( function() {
      addInput(this);
    });
  }

  init();
  
  return {
    process: function(input) {
      $(input).each ( function() {
        addInput(this);
      });
    },
    init: function() {
      init();
    }
  }
})();

Vertis.vertisCheckbox = (function () {
  /**
   * funkcja dodajaca widget - zapewnia cala obrobke w html / css oraz zabezpiecza przed ponownym wykonaniem na danym elemencie 
   */
  function addCheckbox(input) { 
    var source = $(input); 

    if (Vertis.isIE6 || source.hasClass('stand_alone')) {
      return;
    }
    
    // pominiecie elementow ktore juz byly obrabiane
    if (source.hasClass('pointInput'))
      return;

    var checked = source.attr('checked') ? 'checked' : 'unchecked';
    var replacer = $('<div class="vertisCheckbox '+checked+' inline_block"></div>');

    // oznaczenie elementu jako zmienionego
    source.addClass('pointInput');
    source.before(replacer);
    Vertis.widgetDictionary.add(source, replacer);

    source.focus( function() {
      var source = $(this);
      var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));
      if (!replacer.hasClass('focus'))
      {
        $('.focus').removeClass('focus');
        replacer.addClass('focus');
      }
    });
    
    source.blur( function() {
      var source = $(this);
      var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));
      replacer.removeClass('focus');
    });
    
    if (!$.browser.msie)
    source.change( function() {
      var source = $(this);
      var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));
      if (source.attr('checked'))
        replacer.addClass('checked').removeClass('unchecked');
      else
        replacer.addClass('unchecked').removeClass('checked');
    });
    
    if ($.browser.msie)
    source.keyup( function() {
      var source = $(this);
      var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));

      setTimeout(function() {
        if (source.attr('checked'))
          replacer.addClass('checked').removeClass('unchecked');
        else
          replacer.addClass('unchecked').removeClass('checked');
       }, 25);
    });
    
    // klikniecie w element zrodlowy - co prawda sam element nie jest widoczny, ale dzieki temu dziala kliekniecie w label
    if ($.browser.msie)
    source.click( function() {
      var source = $(this);
      var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));

      setTimeout(function() {
        if (source.attr('checked'))
          replacer.addClass('checked').removeClass('unchecked');
        else
          replacer.addClass('unchecked').removeClass('checked');
       }, 25);
    });
  }
  
  /**
   * inicjalizator 
   */
  function init() {
    $('input[type="checkbox"]').each( function() {
      addCheckbox(this);
    });
  }

  init();

  return {
    process: function(input) {
      $(input).each ( function() {
        addCheckbox(this);
      });
    },
    init: function() {
      init();
    },
    toogle: function(opcja, e) {
      var target = e.srcElement ? e.srcElement : e.target;
      var elem = $(target);
      elem.toggleClass('checked').toggleClass('unchecked');

      var checked = elem.hasClass('checked') ? true : false;
      var source = Vertis.widgetDictionary.getSource(elem.attr('id'));

      if (!elem.hasClass('focus'))
      {
        $('.focus').removeClass('focus');
        elem.addClass('focus');
        source.source.focus();
      }

      var source = Vertis.widgetDictionary.getSource(elem.attr('id'));
      if (checked)
        source.source.attr('checked', true);
      else
        source.source.attr('checked', false);

      //console.log('toogle '+opcja);
      //console.log(elem.attr('class'));
    }
  }
})();

Vertis.vertisRadio = (function () {
  /**
   * funkcja dodajaca widget - zapewnia cala obrobke w html / css oraz zabezpiecza przed ponownym wykonaniem na danym elemencie 
   */
  function addRadio(input) { 
    var source = $(input); 
    
    if (Vertis.isIE6 || source.hasClass('stand_alone')) {
      return;
    }

    // pominiecie elementow ktore juz byly obrabiane
    if (source.hasClass('pointInput'))
      return;

    var checked = source.attr('checked') ? 'checked' : 'unchecked';
    var name = source.attr('name');
    var replacer = $('<div class="vertisRadio '+checked+' name_'+name+' inline_block"></div>');

    // oznaczenie elementu jako zmienionego
    source.addClass('pointInput');
    source.before(replacer);
    Vertis.widgetDictionary.add(source, replacer);
    
    source.focus( function() {
      var source = $(this);
      var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));
      
      if (!replacer.hasClass('focus'))
      {
        $('.focus').removeClass('focus');
        replacer.addClass('focus');
      }

      if (source.attr('checked'))
      {
        $(".vertisRadio.name_"+source.attr('name')).each( function() {
          $(this).removeClass('checked').addClass('unchecked');
        });

        replacer.addClass('checked').removeClass('unchecked');
      }
    });

    source.blur( function() {
      var source = $(this);
      var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));
      replacer.removeClass('focus');
      
      setTimeout(function() {
        var chck = source.attr('checked');
        //console.log(chck ? 'checked' : 'unchecked');
        if (chck == false)
          replacer.addClass('unchecked').removeClass('checked');
        }, 76);
    });

    if (!$.browser.msie)
    source.change( function() {
      var source = $(this);
      var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));
      $(".vertisRadio.name_"+source.attr('name')).each( function() {
        $(this).removeClass('checked').addClass('unchecked');
      });
      replacer.addClass('checked').removeClass('unchecked');
    });
    
    if ($.browser.msie)
    source.keyup( function() {
      var source = $(this);
      var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));
      
      setTimeout(function() {
        if (source.attr('checked'))
          replacer.addClass('checked').removeClass('unchecked');
        else
          replacer.addClass('unchecked').removeClass('checked');
       }, 25);
    });
   
    // klikniecie w element zrodlowy - co prawda sam element nie jest widoczny, ale dzieki temu dziala kliekniecie w label
    if ($.browser.msie)
    source.click( function() {
      var source = $(this);
      var replacer = Vertis.widgetDictionary.getReplacer(source.attr('id'));
      $(".vertisRadio.name_"+source.attr('name')).each( function() {
        $(this).removeClass('checked').addClass('unchecked');
      });
      replacer.addClass('checked').removeClass('unchecked');
    });
  }
  
  /**
   * inicjalizator 
   */
  function init() {
   // affect all button except those with classes .wow, filters
   // $('input[type="radio"]:not(.wow, .filters)').each( function(nr, input) {
   $('input[type="radio"]').each( function(nr, input) {
      addRadio(this);
    });
  }

  init();

  return {
    process: function(input) {
      $(input).each ( function() {
        addRadio(this);
      });
    },
    init: function() {
      init();
    },
    toogle: function(opcja, e) {
      var target = e.srcElement ? e.srcElement : e.target;
      var elem = $(target);
      
      var checked = elem.hasClass('checked') ? true : false;      
      var input = Vertis.widgetDictionary.getSource(elem.attr('id'));
      
      if (!elem.hasClass('focus'))
      {
        $('.focus').removeClass('focus');
        elem.addClass('focus');
        input.source.focus();
      }


      if (checked)
        return;


      checked = true;      

      var input = Vertis.widgetDictionary.getSource(elem.attr('id'));

      var name = input.source.attr('name');

      $("input[type='radio'][name='"+name+"']").each( function() {
        $(this).attr('checked', false);
      });

      $(".vertisRadio.name_"+name).each( function() {
        $(this).removeClass('checked').addClass('unchecked');
      });

      input.source.attr('checked', true);
      elem.toggleClass('checked').toggleClass('unchecked');

      //console.log('toogle '+opcja);
      //console.log(elem.attr('class'));
    }
  }
})();
