﻿$(function () {
  //Clear filters
  $('.filterwrapper input:checked').each(function () {
    if ($(this).attr('keep_checked') != "1") {
      this.checked = false;
    }
  });

  //Bind events
  $('.filterwrapper input').change(function () {
    window._filterTimeout ? clearTimeout(window._filterTimeout) : void (0);
    window._filterTimeout = setTimeout(function () {
      filter.updateUi();
    }, 1000);
  });

});

var filter = {
  paging: {
    page: 0
  },

  updateUi: function (callback) {
    this.applyFilter(function (data) {
      if (data) {
        //Update only properties which have no selection
        $('.filterwrapper ul ul').filter(function () {
          return $(this).find('input:checked').length > 0 ? false : true;
        }).find('li').each(function () {
          var id = parseInt($(this).attr('data-id'));
          var value = $(data.values).filter(function () { return this.id == id }).get(0);
          value.productcount == 0 ? $(this).removeClass('active') : $(this).addClass('active');
          $(this).find('b').html(value.productcount);
        });

        //Load html
        $('#content_locked').html(data.pagehtml);
        if (filter.paging.page < 1) { filter.paging.page = 0; };

        window.scrollTo(0, 0);

        //Next
        $('.pagenav .page_next').click(function (e) {
          filter.paging.page++;
          filter.updateUi();
          e.preventDefault();
        });
        $('.pagenav .page_back').click(function (e) {
          filter.paging.page--;
          filter.updateUi();
          e.preventDefault();
        });
      }

      $('.filterwrapper li input').attr('disabled', 'disabled');
      //$('.filterwrapper li.active > input').removeAttr('disabled');

      $('.filterwrapper li.active > input').each(function () {
        if ($(this).attr('keep_checked') != "1") {
          $(this).removeAttr('disabled');
        }
      });


      callback();
    });
  },

  applyFilter: function (callback) {
    var selectedFilters = this.getSelectedFilters();
    $.postJSON('/webservices/filter.asmx/filter', $.toJSON({ url: this.getFilterUrl(), filters: selectedFilters }), function (data) {
      callback(data.d);
    });
  },

  getSelectedFilters: function () {
    var filters = new Array();
    $('.filterwrapper ul ul').each(function () {
      var filter = {
        id: parseInt($(this).attr('data-id')),
        values: new Array()
      }
      $(this).find('input:checked').each(function () {
        filter.values.push({ id: parseInt($(this).parent().attr('data-id')) });
      });
      filter.values.length > 0 ? filters.push(filter) : void (0);
    });
    return filters;
  },

  getFilterUrl: function () {
    //var iscategory = document.location.pathname.toString().toLowerCase().indexOf('categorie') > -1 ? true : false;
    
    var url = Url.decode(document.location.pathname.toString().toLowerCase());

    //Include paging
    this.paging.page > 0 ? url = url.replace('.aspx', '') + '/p' + (this.paging.page + 1) + '.aspx' : void (0);

    return url;
  }

};

var Url = {

  // public method for url encoding
  encode: function (string) {
    return escape(this._utf8_encode(string));
  },

  // public method for url decoding
  decode: function (string) {
    return this._utf8_decode(unescape(string));
  },

  // private method for UTF-8 encoding
  _utf8_encode: function (string) {
    string = string.replace(/\r\n/g, "\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

      var c = string.charCodeAt(n);

      if (c < 128) {
        utftext += String.fromCharCode(c);
      }
      else if ((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      }
      else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }

    return utftext;
  },

  // private method for UTF-8 decoding
  _utf8_decode: function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while (i < utftext.length) {

      c = utftext.charCodeAt(i);

      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      }
      else if ((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i + 1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      }
      else {
        c2 = utftext.charCodeAt(i + 1);
        c3 = utftext.charCodeAt(i + 2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }

    }

    return string;
  }

}

/*!
* jQuery JSON plugin
* Standard there is no post available for JSON
*/

jQuery.extend({
  postJSON: function (url, data, callback) {
    $.ajax({
      type: "POST",
      url: url,
      data: data,
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (data) {
        callback(data);
      }
    });
  }
});
