// From phpjs.org
function number_format(number, decimals, dec_point, thousands_sep) {  
  var n = !isFinite(+number) ? 0 : +number, 
      prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
      sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
      dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
      s = '',
      toFixedFix = function (n, prec) {
          var k = Math.pow(10, prec);
          return '' + Math.round(n * k) / k;
      };
  // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  if (s[0].length > 3) {
      s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  }
  if ((s[1] || '').length < prec) {
      s[1] = s[1] || '';
      s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
}

function checkSeriesFilters(context) {
  if (!context) {
    context = document;
  }
  
  var rows = $("tr[id^=series]:not(.highlighted)", context);
  var filters = new Array();
  var filters_checked = new Array();
  var show_standard = false;
  var show_voice = false;
  var show_mp4 = false, show_mp4_voice = false, show_text = false;
  
  $("#series-filters label").each(function() {
    var checked = $("> input", this).attr('checked');
    if (checked || checked == 'checked') {
      var filterClass = $(this).attr('for');
      
      if (filterClass == 'filter_standard') {
        show_standard = true;
      } else if (filterClass == 'filter_voice') {
        show_voice = true;
      } else if (filterClass == 'filter_mp4') {
        show_mp4 = true;
      } else if (filterClass == 'filter_mp4_voice') {
        show_mp4_voice = true;
      } else if (filterClass == 'filter_text') {
        show_text = true;
      } else {
        filters.push("." + filterClass);
      }
      
      filters_checked.push(filterClass);
    }
  });
  
  $.cookie("filters_checked", filters_checked.join(","));
  
  filters = filters.join(", ");
  rows = rows.hide().filter(filters);
  
  if (!show_standard) {
    rows = rows.not(".filter_standard");
  }
  if (!show_voice) {
    rows = rows.not(".filter_voice");
  }
  if (!show_mp4) {
    rows = rows.not(".filter_mp4");
  }
  if (!show_mp4_voice) {
    rows = rows.not(".filter_mp4_voice");
  }
  if (!show_text) {
    rows = rows.not(".filter_text");
  }
  
  rows.show();
  
  hideEmptyGroups();
}

function hideEmptyGroups() {
  $("#none-matched").hide();
  
  var hidden = 0;
  var sgtitle = $("td.sgtitle");
  
  sgtitle.each(function() {
    var tr = $(this).parent();
    var tbody = $(this).parents("tbody");
    
    tr.show();
    
    if (tr.siblings(":not(:hidden, :has(td.noseries))").length == 0) {
      tr.hide();
      hidden++;
    } else {
      showParentGroups(tbody.attr('class'));
    }
  });
  
  /* $("tbody").each(function () {
    if (this.id != '') {
      // This was causing poor performance in IE8.
      if ($("." + this.id).find("tr:not(:hidden)").length > 0) {
        $("> tr:has(td.sgtitle)", this).show();
      }
    }
  }); */
  
  if (hidden == sgtitle.length) {
    $("#none-matched").show();
  }
}

function showParentGroups(id) {
  if (id == 'sg0') return;
  
  var tbody = $('#' + id);
  tbody.find('tr:has(td.sgtitle)').show();
  
  if (tbody.hasClass('sg0')) {
    return;
  }
  
  showParentGroups(tbody.attr('class'));
}

function updateSummary(all_series) {
  var all_series = new Array();
  var total_series = 0;
  var has_voice = false;
  var total_reg_price = 0.00, total_sale_price = 0.00, total_sale_price_mp4 = 0.00, total_sale_price_text = 0.00;
  var multiformat_discount = 0.00;
  
  var ol = $("#cart-summary ol");
  var dl = $("#cart-summary dl");
  
  ol.html('');
  
  $("tr:has(td.seriesCheckbox input)").each(function() {
    var cells = $(this).children();
    var input = cells.filter(".seriesCheckbox").find("input");    
    var input_checked = input.attr('checked');
    var rel = cells.filter('.series_title').find('a[rel]').attr('rel');
    var pricing = parsePricingData($(this).attr('data-pricing'));
    
    if (input_checked || input_checked == 'checked') {
      all_series.push(this.id);
      var series_title = cells.filter('.series_title').html();
      var is_voice = $(this).hasClass('filter_voice') || $(this).hasClass('filter_mp4_voice');
      var reg_price = pricing['reg_price']; // cells.filter('.series_reg_price').html().replace('$', '').replace(',', '');
      var sale_price = pricing['sale_price']; // cells.filter('.series_sale_price').html().replace('$', '').replace(',', '');
      var sale_price_mp4 = typeof pricing['mp4_sale_price'] !== 'undefined' ? pricing['mp4_sale_price'] : 0.00;
      var sale_price_text = typeof pricing['text_sale_price'] !== 'undefined' ? pricing['text_sale_price'] : 0.00;
      
      /* if (useAddonPricing(this)) {
        var addon_reg_price = pricing['addon_reg_price'];
        var addon_sale_price = pricing['addon_sale_price'];
        multiformat_discount += parseFloat(sale_price) - parseFloat(addon_sale_price);
        reg_price = addon_reg_price;
        sale_price = addon_sale_price;
      } */
      
      var type = "";      
      
      if (is_voice) {
        has_voice = true;
        type = ' voice';
      }
      
      if ($(this).hasClass('lang')) {
        type = ' lang';
      }
      
      ol.append('<li class="' + rel + type + '"><a href=\"#' + this.id + '">' + rel + '</a></li>');
      
      total_series++;
      total_reg_price += parseFloat(reg_price);
      total_sale_price += parseFloat(sale_price);
      total_sale_price_mp4 += parseFloat(sale_price_mp4);
      
      if (!is_voice || $.inArray('series' + $(this).attr('data-base-id'), all_series) == -1) {
        total_sale_price_text += parseFloat(sale_price_text);
      }
    } else {
      ol.find('li.' + rel).remove();
    }
  });
  
  $.cookie("all_series", all_series.join(','));
  
  updateSummaryData(total_series, has_voice, total_reg_price, total_sale_price, total_sale_price_mp4, total_sale_price_text);
}

function useAddonPricing(tr) {
  if (!$(tr).hasClass('baseSeriesFormat') && !$(tr).hasClass('assocSeriesFormat')) {
    return false;
  }
  
  var is_mp4 = $(tr).hasClass('filter_mp4');
  var is_mp4_voice = $(tr).hasClass('filter_mp4_voice');
  var is_text = $(tr).hasClass('filter_text');
  
  var series_id = explode('_', $(tr).attr('id'))[0];
  var lang = $(tr).attr('data-lang');
  
  if (is_text) {
    // Return true if ANY series with lang match and series ID match is selected
    return $("tr." + series_id + "[data-lang='" + lang +"'], tr#" + series_id).not('.filter_text').has('td.seriesCheckbox input:checked').length > 0;
  } else {
    // Return true if series ID is selected
    return $("tr#" + series_id).has('td.seriesCheckbox input:checked').length > 0;
  }
}

function updateSummaryData(total_series, has_voice, total_reg_price, total_sale_price, total_sale_price_mp4, total_sale_price_text) {
  var num_selected_msg = total_series + " series selected";
  
  if (total_series > 0) {
    num_selected_msg += ':';
  }
  
  $("#summary-num-selected").html(num_selected_msg);
  
  $("#total-reg-price span.price").html('$' + number_format(total_reg_price, 2));
  $("#total-sale-price span.price").html('$' + number_format(total_sale_price, 2));
  $("#total-sale-price-mp4 span.price").html('$' + number_format(total_sale_price_mp4, 2));
  $("#total-sale-price-text span.price").html('$' + number_format(total_sale_price_text, 2));
  
  var plan = findSubscrPlan(total_series, has_voice);
  plan['monthly'] = parseFloat(plan['monthly']);
  plan['annually'] = parseFloat(plan['annually']);
  plan['voice_monthly'] = parseFloat(plan['voice_monthly']);
  plan['voice_annually'] = parseFloat(plan['voice_annually']);
  
  var monthly = plan['monthly'];
  
  if (has_voice) {
    monthly += plan['voice_monthly'];
  }
  
  monthly = number_format(monthly, 2);
  
  $("#subscr-price").html("<b>$" + monthly + "/month</b><br />(" + plan['name'] + ")");
  $("#subscr_plan_id").val(plan['id']);
}

// Find the most appropriate subscription plan for the series currently selected.
function findSubscrPlan(num_series, any_voice) {
  var chosen; // For the best-fit plan.
  var unlimited; // For the plan that allows unlimited series; use this if chosen is undefined.
  
  for (var k in subscr_plans) {
    if (subscr_plans.hasOwnProperty(k)) {
      var plan = subscr_plans[k];
      plan['allowed_series'] = parseInt(plan['allowed_series']);
            
      if (plan['allowed_series'] > 0 && num_series <= plan['allowed_series'] && (!any_voice || plan['voice_allowed'])) {
        if (typeof chosen !== 'undefined') {
          if (plan['allowed_series'] < chosen['allowed_series']) {
            chosen = plan;
          }
        } else {
          chosen = plan;
        }
      }
      
      if (typeof unlimited === 'undefined' && plan['allowed_series'] == 0 && (!any_voice || plan['voice_allowed'])) {
        unlimited = plan;
      }
    }
  }
  
  if (typeof chosen === 'undefined') {
    chosen = unlimited;
  }

  return chosen;
}

function restoreFromCookies() {
  var all_series = new Array();
  
  if ($.cookie('all_series') != null) {
    all_series = $.cookie('all_series').split(',');
  }
  
  $.each(all_series, function(k, v) {
    if (v != "") {
      checkAndShow($('#' + v));
    }
  });
  
  var filters_checked = new Array();
  
  if ($.cookie('filters_checked') != null) {
    filters_checked = $.cookie('filters_checked').split(',');
  }
  
  $.each(filters_checked, function(k, v) {
    if (v != "") {
      $("input#" + v).attr('checked', 'checked');
    }
  });
}

function checkAndShow(what) {
  what.filter(':hidden').show();
  fadeIn(what);
  what.find(".seriesCheckbox input").attr('checked', 'checked');
}

function fadeIn(tr) {
  tr.children("td").animate({backgroundColor: "#ffff9f"}, 1000);
  tr.addClass("highlighted");
}

function fadeOut(tr) {
  tr.each(function() {
    if ($(this).hasClass('darker')) {
      $(this).children("td").animate({backgroundColor: "#efefef"}, 500);
    } else {
      $(this).children("td").animate({backgroundColor: "#ffffff"}, 500);
    }
    $(this).removeClass("highlighted");
  });
}

function findBaseID(tr) {
  return tr.className.match(/(series\d+)/)[1];
}

$(function() {
  restoreFromCookies();
  checkSeriesFilters();
  updateSummary();
  
  $("#cart-summary").scrollFollow();
  $("#series-filters").scrollFollow();
  
  $("tr[id^=series] td.seriesCheckbox input").change(function() {
    var checked = $(this).attr('checked');
    var tr = $(this).parents("tr[id^=series]");
    
    if (checked == 'checked' || checked) {
      fadeIn(tr);
    } else {
      fadeOut(tr);
    }
    
    updateSummary();
  });
  
  // Show/hide the associated series.
  $("td.series_has_voice img").css("cursor", "pointer").attr("title", "Click to Display").click(function(e) {
    e.preventDefault();
    var tr = $(this).parents("tr[id^=series]");
    tr.siblings("tr.assocSeries.filter_voice." + tr.attr('id') + ":not(.highlighted)").toggle();
  });
  
  // Show/hide the associated series.
  $("td.series_has_lang img").css("cursor", "pointer").each(function() {
    $(this).attr("title", $(this).attr("alt") + " - Click to Display");
  }).click(function(e) {
    e.preventDefault();
    var tr = $(this).parents("tr[id^=series]");
    tr.toggleClass('lang_shown').siblings("tr.assocSeries.lang." + tr.attr('id') + ":not(.highlighted)").each(function() {
      if (tr.hasClass('lang_shown')) {
        $(this).show().addClass('lang_shown');
      } else {
        $(this).hide().removeClass('lang_shown');
      }
    });
  });

  $("#series-filters input").show().change(function() {
    checkSeriesFilters();
  });
  
  $("#series-filters a").click(function(e) {
    e.preventDefault();
    
    $(this).siblings("input").each(function() {
      var checked = $(this).attr('checked');
      
      if (checked || checked == 'checked') {
        $(this).removeAttr('checked');
      } else {
        $(this).attr('checked', 'checked');
      }
    });
    
    checkSeriesFilters();
  });
  
  /* $("#deselect_all").click(function(e) {
    e.preventDefault();
    
    var trs = $("tr[id^='series']");
    fadeOut(trs);
    trs.find("input:checked").removeAttr('checked');
    updateSummary();
  }); */
  
  $("#switch_to_voice").click(function(e) {
    e.preventDefault();
    
    $("tr.baseSeries:has(input:checked)").each(function() {
      var siblings = $(this).siblings('tr.assocSeries.filter_voice.' + this.id);
      
      if (siblings.length > 0) {
        $(this).find('input:checked').removeAttr('checked');
        fadeOut($(this));
      }

      checkAndShow(siblings);
    });
    
    updateSummary();
  });
  
  $("#switch_to_standard").click(function(e) {
    e.preventDefault();
    
    $("tr.assocSeries.filter_voice:has(input:checked)").each(function() {
      $(this).find('input:checked').removeAttr('checked');
      fadeOut($(this));
      checkAndShow($(this).siblings( 'tr.baseSeries#' + findBaseID(this) ));
    });
    
    updateSummary();
  });
  
  $("a#link-to-plans").colorbox({fragment: "#subscription-info", title: "Subscription Plans"});
  $("p.which-formats a").colorbox({fragment: "#which-formats", title: "Which formats should I choose?"});
  $("input#go-back").click(function() {
    window.location.href = "hosting-tutorials.php";
  });
});

function parsePricingData(data) {
  arr = explode('|', data);
  list = {};
  
  for (var k in arr) {
    exploded = explode('=', arr[k]);
    list[exploded[0]] = exploded[1];
  }
  
  return list;
}

// From phpjs.org
function explode(delimiter, string, limit) {
  var emptyArray = {
      0: ''
  };

  // third argument is not required
  if (arguments.length < 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined') {
      return null;
  }

  if (delimiter === '' || delimiter === false || delimiter === null) {
      return false;
  }

  if (typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object') {
      return emptyArray;
  }

  if (delimiter === true) {
      delimiter = '1';
  }

  if (!limit) {
      return string.toString().split(delimiter.toString());
  } else {
      // support for limit argument
      var splitted = string.toString().split(delimiter.toString());
      var partA = splitted.splice(0, limit - 1);
      var partB = splitted.join(delimiter.toString());
      partA.push(partB);
      return partA;
  }
}

