﻿$(function() {
  $('ul.results').pagination({
    items: 'ul.results > li:not(li.filtered)',
    showingClass: '#showing-records'
  });

  setTimeout(init, 1);

  $('div.filters:not(div.sort) a').live('click', function(e) {
    var obj = this;
    setTimeout(function() { filterClick(obj) }, 1);
    e.preventDefault();
    return false;
  });

  $('#sortby').change(function() {
    setTimeout(function() { sortChange() }, 1);
  });

  jQuery.fn.sort = function() {
    return this.pushStack([].sort.apply(this, arguments), []);
  };

  function sortName(a, b) {
    if (a.name == b.name)
      return 0;

    return a.name > b.name ? 1 : -1;
  }
  function sortNameDesc(a, b) {
    return sortName(a, b) * -1;
  }

  function sortPrice(a, b) {
    if (a.price == b.price)
      return 0;

    return a.price > b.price ? 1 : -1;
  }
  function sortPriceDesc(a, b) {
    return sortPrice(a, b) * -1;
  }

  function sortDate(a, b) {
    if (a.releaseDate == b.releaseDate)
      return 0;

    return a.releaseDate > b.releaseDate ? 1 : -1;
  }
  function sortDateDesc(a, b) {
    return sortDate(a, b) * -1;
  }

  function filterClick(obj) {
    var whash = window.location.hash != '' ? window.location.hash : '#/any/any/name';
    var hash = whash.split('/');
    var aclass;

    if ($(obj).hasClass('price'))
      aclass = 'price';
    else if ($(obj).hasClass('date'))
      aclass = 'date';

    if (aclass == 'price')
      hash[1] = $(obj).attr('rel');
    else if (aclass == 'date')
      hash[2] = $(obj).attr('rel');

    window.location.hash = hash.join('/');

    $('div.filters a.remove.' + aclass).remove();

    setTimeout(parseFilters, 1);
  }

  function sortChange() {
    var index = $('#sortby option').index($('#sortby option:selected'));
    var whash = window.location.hash != '' ? window.location.hash : '#/any/any/name';
    var hash = whash.split('/');

    if (index == 0)
      hash[3] = 'name';
    else if (index == 1)
      hash[3] = 'price';
    else if (index == 2)
      hash[3] = 'date';

    window.location.hash = hash.join('/');

    setTimeout(parseFilters, 1);
  }

  function parseFilters() {
    var whash = window.location.hash != '' ? window.location.hash : '#/any/any/name';
    var hash = whash.split('/');
    var pmin = 0;
    var pmax = 1000;
    var sale = false;
    var now = new Date();
    var dmax = new Date();
    var dmin = new Date();
    var sortIndex = 0;

    //-- correct if hash has problems --//
    if (hash.length != 3)
      whash = '#/any/any/name';

    //-- set sort option --//
    if (hash[3] == 'name')
      sortIndex = 0;
    else if (hash[3] == 'price')
      sortIndex = 1;
    else if (hash[3] == 'date')
      sortIndex = 2;
      
    //-- filters --//
    $('div.filters a.price[rel="' + hash[1] + '"]').each(function() {
      $(this).siblings('a.remove').remove();
      $(this).after('<a class="price remove" rel="any">[remove]</a>');
    });

    $('div.filters a.date[rel="' + hash[2] + '"]').each(function() {
      $(this).siblings('a.remove').remove();
      $(this).after('<a class="date remove" rel="any">[remove]</a>');
    });

    if (hash[1] == 'sale') {
      sale = true;
    } else if (hash[1] != 'any') {
      if (hash[1].indexOf('-') < 0)
        pmin = parseFloat(hash[1]);
      else {
        var ps = hash[1].split('-');
        pmin = parseFloat(ps[0]);
        pmax = parseFloat(ps[1]);
      }
    }

    if (hash[2] != 'any') {
      if (hash[2] == 'coming') {
        dmax.setDate(now.getDate() + (12 * 30));
        dmin.setDate(now.getDate());
      } else if (hash[2].indexOf('-') < 0) {
        dmax.setDate(dmax.getDate() - (parseInt(hash[2], 10) * 30));
        dmin.setDate(now.getDate() - (100 * 30));
      }
      else {
        var ds = hash[2].split('-');
        dmax.setDate(now.getDate() - (parseInt(ds[0], 10) * 30));
        dmin.setDate(now.getDate() - (parseInt(ds[1], 10) * 30));
      }
    } else {
      dmax.setDate(now.getDate() + (12 * 30));
      dmin.setDate(now.getDate() - (100 * 30));
    }

    for (var i = 0; i < apps.length; i++) {
      if (sale) {
        if (apps[i].inPromotion && apps[i].releaseDate >= dmin && apps[i].releaseDate <= dmax) {
          $(apps[i].appId).removeClass('filtered');
        } else {
          $(apps[i].appId).addClass('filtered');
        }
      }
      else {
        if (parseFloat(apps[i].price) >= pmin && parseFloat(apps[i].price) <= pmax && apps[i].releaseDate >= dmin && apps[i].releaseDate <= dmax) {
          $(apps[i].appId).removeClass('filtered');
        } else {
          $(apps[i].appId).addClass('filtered');
        }
      }
    }

    //-- if filtering results, apply sorting --//
    if ($('ul.results li:not(li.filtered)').length > 0) {
      $('#no-matches').hide();

      var ordered = [];

      if (hash[3] == 'name')
        ordered = apps.sort(sortName);
      else if (hash[3] == 'price')
        ordered = apps.sort(sortPrice);
      else if (hash[3] == 'date')
        ordered = apps.sort(sortDateDesc);

      for (var i = 1; i < ordered.length; i++) {
        $(ordered[i].appId).insertAfter(ordered[i - 1].appId);
      }
    } else {
      $('#no-matches').show();
    }

    $('a.pagination-update:first').trigger('click');

    //-- set app count --//
    var count = {
      price1: 0,
      price2: 0,
      price3: 0,
      price4: 0,
      sale: 0,
      date1: 0,
      date2: 0,
      date3: 0,
      date4: 0,
      date5: 0
    };

    now = new Date();
    var mon3 = new Date();
    var mon6 = new Date();
    var mon12 = new Date();

    mon3.setDate(now.getDate() - (3 * 30));
    mon6.setDate(now.getDate() - (6 * 30));
    mon12.setDate(now.getDate() - (12 * 30));

    for (var i = 0; i < apps.length; i++) {
      var price = parseFloat(apps[i].price);
      var releaseDate = apps[i].releaseDate;

      if (price >= 0 && price <= 9.99 && releaseDate >= dmin && releaseDate < dmax)
        count.price1++;
      else if (price >= 10 && price <= 29.99 && releaseDate >= dmin && releaseDate < dmax)
        count.price2++;
      else if (price >= 30 && price <= 49.99 && releaseDate >= dmin && releaseDate < dmax)
        count.price3++;
      else if (price >= 50 && releaseDate >= dmin && releaseDate < dmax)
        count.price4++;

      if (apps[i].inPromotion && releaseDate >= dmin && releaseDate < dmax)
        count.sale++;

      if (releaseDate <= now && releaseDate >= mon3 && price >= pmin && price <= pmax && (apps[i].inPromotion || !sale))
        count.date1++;
      else if (releaseDate <= mon3 && releaseDate >= mon6 && price >= pmin && price <= pmax && (apps[i].inPromotion || !sale))
        count.date2++;
      else if (releaseDate <= mon6 && releaseDate >= mon12 && price >= pmin && price <= pmax && (apps[i].inPromotion || !sale))
        count.date3++;
      else if (releaseDate <= mon12 && price >= pmin && price <= pmax && (apps[i].inPromotion || !sale))
        count.date4++;
      else if (releaseDate > now && price >= pmin && price <= pmax && (apps[i].inPromotion || !sale))
        count.date5++;
    }

    $('div.filters:not(div.sort) a:not(a.remove):eq(0) span').text('(' + count.price1 + ')');
    $('div.filters:not(div.sort) a:not(a.remove):eq(1) span').text('(' + count.price2 + ')');
    $('div.filters:not(div.sort) a:not(a.remove):eq(2) span').text('(' + count.price3 + ')');
    $('div.filters:not(div.sort) a:not(a.remove):eq(3) span').text('(' + count.price4 + ')');
    $('div.filters:not(div.sort) a:not(a.remove):eq(4) span').text('(' + count.sale + ')');
    $('div.filters:not(div.sort) a:not(a.remove):eq(5) span').text('(' + count.date1 + ')');
    $('div.filters:not(div.sort) a:not(a.remove):eq(6) span').text('(' + count.date2 + ')');
    $('div.filters:not(div.sort) a:not(a.remove):eq(7) span').text('(' + count.date3 + ')');
    $('div.filters:not(div.sort) a:not(a.remove):eq(8) span').text('(' + count.date4 + ')');
    $('div.filters:not(div.sort) a:not(a.remove):eq(9) span').text('(' + count.date5 + ')');
  }

  function init() {
    var whash = window.location.hash != '' ? window.location.hash : '#/any/any/name';
    var hash = whash.split('/');
    
    $('#sortby').val(hash[3] == 'date' ? 'release date' : hash[3]).dropdownmask();
  
    $('div.filters:not(div.sort) a').append(' <span></span>')
    parseFilters();
  }
});
