// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};


var animationSpeed = 300;
var DEBUG = document.location.search.match(/debug=true/) != null;

function trackEvent(action, label) {
  if (typeof label == "undefined") {
    label = null;
  }
  
  if (label != null) {
    label = label.replace(/<br[ \/]*>/g, ' ');  
  }

  if (DEBUG == true) {
    var item = ['Price Predictor', action, label == null ? '(null)' : label].join(" -- ");
    var e = $('#ppDebug').append('<li>' + item + '</li>').get(0);
    e.scrollTop = e.scrollHeight;
  } else {  
    pageTracker._trackEvent('Price Predictor', action, label);
  }  
}

function trackPageview(url) {
  parts = parseUri(url)
  url   = parts.path
  
  if (parts.anchor) {
    url += '/' + parts.anchor;
  }
  
  if (parts.query) {
    url += '?' + parts.query;
  }
    
  if (DEBUG == true) {
    $('#ppDebug').append('<li>' + url + '</li>')
  } else {
    pageTracker._trackPageview(url);
  }  
}

function runPricePredictor() {
  PricePredictor.run();
}

String.prototype.slugify = function() {
	var text = this.toLowerCase();
	text = text.replace(/&amp;/, 'and');
	text = text.replace(/[^-a-zA-Z0-9\s]+/ig, '');
	text = text.replace(/-/gi, "_");
	text = text.replace(/\s/gi, "-");
	return text;
};

function TimeMagazine() {
  return this;
}

TimeMagazine.setCategory = function(category) {
  var url = null;
  
  switch(category) {
    case 'clothing-and-accessories' : url = "http://www.time.com/time/searchresults?N=46&Nty=1&Ns=p_date_range|1&Ntt=fashion&x=16&y=10"; break;
    case 'education-and-housing'    : url = "http://www.time.com/time/searchresults?N=46&Nty=1&Ns=p_date_range|1&Ntt=college+cost+&x=35&y=11"; break;
    case 'fitness-and-personal-care': url = "http://www.time.com/time/searchresults?N=46&Nty=1&Ns=p_date_range|1&Ntt=fitness&x=33&y=9"; break;
    case 'travel-and-entertainment' : url = "http://www.time.com/time/searchresults?D=Travel&sid=1215922814F2&Ntt=Travel&Ntk=NoBody2009&Ntx=mode+matchallpartial%2bsnip%2bp_body%3a25&N=46&Nty=1&Ns=p_date_range%7c1"; break;
    case 'food'                     : url = "http://www.time.com/time/searchresults?N=46&Nty=1&Ns=p_date_range|1&Ntt=food&x=39&y=9"; break;
    case 'pets'                     : url = "http://www.time.com/time/searchresults?N=46&Nty=1&Ns=p_date_range|1&Ntt=pets&x=31&y=10"; break;
    case 'durable-goods'            : url = "http://www.time.com/time/searchresults?N=46&Nty=1&Ntt=shopping&x=19&y=15&srchCat=Covers"; break;
  };
  
  if (url) {
    $('#mod-back_in_time').find('a.time-magazine').attr('href', url);
  }
}


function Cart() {
  return this;
}

Cart.initialize = function() {
  Cart.size  = $('#cart-size');
  Cart.year  = $('#cart-year');
  Cart.total = $('#cart-total');
};

Cart.calculate  = function() {
  var total = 0;
  var size  = 0;
  
  $('#cart').find('li .price span:visible').each(function() {
    size  += 1;
    total += parseFloat($(this).text().slice(1));
  });

  Cart.size.html(size);
  Cart.total.html(total.toFixed(2));
};

Cart.collapse = function() {
  $('#myCost div.toggled').slideUp('fast');
};

Cart.expand = function() {
  $('#myCost div.toggled').slideDown('fast');
};

Cart.isEmpty = function() {
  return $('#cart').find('li').length == 0;
}

Cart.setYear = function(year) {
  Cart.year.html(year);
  Cart.calculate();
  
  trackEvent('Select Year', year);
};

Cart.getYear = function() {
  return Cart.year.text();
}

Cart.addItem = function($item) {
  $item = $item.clone().productify();
  
  var name  = $item.find('p.name').html();
  var recycle_icon = '<a href="#" class="ui-icon ui-icon-refresh"><span>REMOVE</span></a>';
  $cart = $('#cart');
  
  $item.fadeOut(animationSpeed, function() {
    var $list = $('ul',$cart).length ? $('ul',$cart) : $('<ul class="ppContent"/>').appendTo($cart);
    // var $list = $('ul',$cart)

    $item.find('a.ui-icon-trash').remove();
    $item.append(recycle_icon).fadeIn(animationSpeed);
    
    var api = $cart.scrollable({api: true});
    api.getItemWrap().append($item);
    api.reload().seekTo(api.getSize() - 6);
    Cart.expand();
    Cart.calculate();
  });

  trackEvent('Add Product', name);
};

Cart.removeItem = function($item) {
  var name = $item.find('p.name').html();

  var trash_icon = '<a href="#" class="ui-icon ui-icon-trash"><span>ADD</span></a>';
  // var $ppContent = $('#' + $item.attr('data-category-id')).children('ul.ppContent')
  $item.animate({marginLeft: -200}, {duration: animationSpeed - 100, queue:false}).fadeOut(animationSpeed, function() {
    $item.remove();
    var api = $('#cart').scrollable({api: true})
    api.reload().move(-1)
    Cart.calculate();
    if (Cart.isEmpty()) Cart.collapse()
  });

  trackEvent('Delete Product', name)
};

Cart.clearAll = function() {
  $('#cart').find('ul').html('');
  Cart.calculate();
  Cart.collapse();
  
  trackEvent('Clear All Products');
};

function PricePredictor() {}
PricePredictor.running = true;
PricePredictor.run = function() {
  if (!PricePredictor.running) {
    window.location.href = window.location.href.replace(/\/tour/, '')
  }
    
/*  alert("run");
  var splash = $('#ppSplash');

  if (splash.is(':visible')) {
    splash.fadeOut('slow'); 
    $('#nav_move').fadeIn('fast');
  }*/
};

PricePredictor.close = function() {
  PricePredictor.run();
}

PricePredictor.tour = function() {
 //$('#nav_move').fadeOut('slow');
 $('#ppSplash').fadeIn('slow');
};

// Invoke DoubleClick tracking pixel
function trackDoubleClick(cat_id) {
  var url;
  switch(cat_id) {
    case '#clothing-and-accessories' : url = 'http://ad.doubleclick.net/activity;src=2648958;type=allia438;cat=price032;ord=1'; break;
    case '#education-and-housing' : url = 'http://ad.doubleclick.net/activity;src=2648958;type=allia438;cat=price552;ord=1'; break;
    case '#fitness-and-personal-care' : url = 'http://ad.doubleclick.net/activity;src=2648958;type=allia438;cat=price025;ord=1'; break;
    case '#travel-and-entertainment' : url = 'http://ad.doubleclick.net/activity;src=2648958;type=allia438;cat=price531;ord=1'; break;
    case '#food' : url = 'http://ad.doubleclick.net/activity;src=2648958;type=allia438;cat=price927;ord=1'; break;
    case '#pets' : url = 'http://ad.doubleclick.net/activity;src=2648958;type=allia438;cat=price489;ord=1'; break;
    case '#durable-goods' : url = 'http://ad.doubleclick.net/activity;src=2648958;type=allia438;cat=price839;ord=1'; break;
  }
  var axel = Math.random() + "";
  var num = axel * 1000000000000000000;
  var spotpix = new Image();
  spotpix.src = url + num;
  //console.log("DoubleClick tracking  URL: " + spotpix.src);
}

$(function() {
  Cart.initialize();
  Cart.calculate();
  
  $.fn.productify = function() {
    return this.draggable({
      cancel: 'a.ui-icon',
      revert: 'invalid', 
      helper: 'clone',
      cursor: 'move',
      appendTo: '#ghost',
      opacity: 0.75
    }).click(function(ev) {
      var $item = $(this);
      var $target = $(ev.target);

      if ($target.is('a.ui-icon-trash')) {
        Cart.addItem($item);
      } else if ($target.is('a.ui-icon-zoomin')) {
        viewLargerImage($target);
      } else if ($target.is('a.ui-icon-refresh')) {
        Cart.removeItem($item);
      }

      return false;
    })
    .find('.ppGraph').overlay({
      onBeforeLoad: function() {
        var name = this.getTrigger().closest('li').find('p.name').html();
        var overlay = this.getOverlay();
        
        // load the graph for the current year
        overlay.find('img.price-graph').attr('src', function(index, src) {
          return this.src.replace(/-\d{4}/, '-' + Cart.getYear());
        })
        
        trackEvent('View Product Detail', name);
      }
    })
    .tooltip({
      tip: '#graphTip',
      effect: 'slide',
      offset: [15, 0],
      predelay: 2500        
    })
    .end()
  }
  
  $(document).pngFix();
  
  if (DEBUG) {
    $('body').append($('<ul id="ppDebug">CATEGORY -- ACTION -- LABEL</ul>'));
  }
  

  // Absolute URL to avoid pulling from s3 (<base> tag in layout)
  $.getJSON("http://" + location.hostname + "/price_predictor/products.js?a=1", function(data) {
    var categories = []
    var product_categories = []
    var overlays   = []
    var templates  = {
      "category": _.template(
        '<li><a href="<%= url %>"><%= name %></a></li>'
      ),
      
      "product": _.template('\
        <li data-category-id="<%= category_id %>">\
          <div class="inner"">\
            <div class="price">\
              <% _.each(prices, function(price, year) { %>\
                <span class="year-<%= year %>">$<%= price %></span>\
              <% }); %>\
            </div>\
            <p class="name"><%= name %></p>\
            <img src="price_predictor/images/cart_items/<%= image %>" width="111" height="72" class="itemImg" />\
              <img src="price_predictor/images/item-graph-bu.gif" alt="" width="34" height="18" class="ppGraph" rel="#<%= overlay_id %>"/> \
          </div>\
          <a href="#" class="ui-icon ui-icon-trash"><span>Add Item</span></a>\
        </li>'
      ),
      
      "product_category": _.template('\
        <div id="<%= id %>" class="category" data-category="<%= id %>">\
          <ul class="ppContent">\
            <%= products %>\
          </ul>\
        </div>'
      ),
        
      "overlay": _.template('\
        <div class="overlay" id="<%= overlay_id %>">\
          <h2><%= name %></h2>\
          <div class="left">\
            <img src="price_predictor/images/cart_items/<%= image %>" width="111" height="72" class="imgLeft"/>\
            <p>Price estimates are based on inflation data, research and statistical models. <a href="http://">Read more</a>. <a href="http://">Pricing information</a> for Price Predictor items provided by IHS Global Insights.</p>\
            <img src="price_predictor/images/cart_graphs/<%= graph.image %>" alt="graph-coffee" class="price-graph" />\
          </div>\
          <div class="right">\
            <h3><%= graph.title %></h3>\
            <p><%= graph.description %></p>\
          </div>\
        </div>'
      )   
    }
    
    $.each(data, function(category, product_data) {
      var products = []
      var id = category.slugify()
      
      $.each(product_data, function(name, product) {
        var overlay_id = _.uniqueId('overlay')
        
        product.name        = name;
        product.category_id = id;
        product.overlay_id  = overlay_id
        
        products.push(templates.product(product));
        overlays.push(templates.overlay(product));
      })
      
      var base  = location.href;
      var index = base.indexOf('#');
      if (index > 0) {
        base = base.slice(0, index);
      }

      categories.push(templates.category({
        "url":  base + '#' + id,
        "name": category
      }))
      
      product_categories.push(templates.product_category({
        "id": id,
        "products": products.join("")
      }))
    })
    
    $('#overlays').append(overlays.join(""))
    
    $('#products').append(product_categories.join(""))
      .find('ul.ppContent').droppable({
        accept: '#cart li',
        grid: [80, 80],
        activeClass: 'ui-state-hover',
        hoverClass: 'ui-state-active',
        drop: function(ev, ui) {
          Cart.removeItem(ui.draggable);
        }
      })
      .find('li').productify()
    .end()  
    
    $('#categories').append(categories.join(""))
      .find('a').click(function(e) {
        //e.preventDefault();
        PricePredictor.run();
        //return false;
      }).end()
      .tabs("div#products > .category", {
        initialIndex: 0,
        onClick: function(event, tabIndex) {
          var tab      = this.getTabs().eq(tabIndex)
          var panel    = this.getPanes().eq(tabIndex);
          var name     = tab.html();
          var products = panel.find('li');
          var delay  = {
            minimum:  100,
            maximum:  1200,
            step:     300,
            length:   0,
            midpoint: 0,
            
            setLength: function(length) {
              this.length   = length;
              this.midpoint = Math.floor(length / 2);
            },
            
            delayFor: function(index) {
              if (index >= this.midpoint)  { index = this.length - index - 1; }
              return this.maximum - (index+1) * this.step;
            }  
          };
          
          delay.setLength(products.length);
          
          var yearSelector = '.price span.year-' + Cart.getYear();
          
          products.css({top: 200}).each(function(index) {
            var duration = delay.delayFor(index);
            $(this).animate({top: 0}, {queue: false, duration: duration, complete: function() {
              if ($.browser.msie && $.browser.version == 6) {
                $(this).find(yearSelector).height() // force redraw in the ie6
              }
            }})
          });
          
          if (this.hasLoaded) {
            trackEvent('Select Category', name);
            trackPageview(tab.get(0).href);
            trackDoubleClick(tab.get(0).hash);
          } else {
            this.hasLoaded = true;
          }
          
          TimeMagazine.setCategory(panel.attr('data-category'));
        }
      })
    .end();
      
    delete categories;
    delete overlays;
    delete product_categories;
    delete templates;
  }); // getJSON

  // let the trash be droppable, accepting the gallery items
  $('#cart').droppable({
    accept: 'ul.ppContent > li',
    activeClass: 'ui-state-hover',
    hoverClass: 'ui-state-active',
    drop: function(ev, ui) {
      Cart.addItem(ui.draggable);
    }
  });

  $('#cart-clear').click(function(e) {
    e.preventDefault();
    Cart.clearAll();
    return false
  })
  
  $('.toggle').toggle(
      function() { // handlerEven
          $(this).parent().siblings('.toggled').slideToggle('medium');
      },
      function() { // handlerOdd
          $(this).parent().siblings('.toggled').slideToggle('medium');
      }
  );

  $("#control[title]").tooltip({
    tip: '.mycostTip', 
    effect: 'slide',
    offset: [-70, -200],
    predelay: 2500        
  }); 

  $(".ppContent").scrollable(); 

  $('#nav_move').css({ 
    width: $('#yearSlider li:first a').width()+20, 
    height: $('#yearSlider li:first a').height()+20 
  });
  
  var pricePredictor = $('#pricePredictor').get(0)
  
  $('#yearSlider a').click(function(e) {
    e.preventDefault();
    var clickedYear   = $(this).text();
    var isCurrentYear = $(pricePredictor).hasClass("year-" + clickedYear);
    var offset = $(this).offset();
    var offsetBody = $('#ppContainer').offset(); //find the offset of the wrapping div 
    var left       = (offset.left - offsetBody.left + 0);
    
    $('#nav_move').show();
    
    if (!isCurrentYear) {
      $('#nav_move').animate({ 
        width: 155, 
        height: 38, 
        left:   left
      }, {
        duration: 350, easing: 'easeInOutCirc'
      });
    
      $('#yearSlider a').removeClass('cur')
      $(this).addClass('cur');
    
      pricePredictor.className = pricePredictor.className.replace(/year-\d{4}/g, '') + 'year-' + clickedYear
      Cart.setYear(clickedYear);
    } else {
      $('#nav_move').css({left: left})
    }
      
    return false;
  });
  
  // Check fragment. If has 4 digits, it has a year
  // else it only has a category. 
  // (NOTE will break if category contains 4 digits)
  if (!(year = document.location.hash.match(/\d{4}/))) year = 2010;
  $('#yearSlider li a:contains(' + year + ')').trigger('click');

  // TEMP
  anchor = document.location.hash.match(/(.+)\/\d{4}/);
  if (anchor[1] != undefined) {
    location.hash = anchor[1];
  }
 
  $('#categories a' + location.hash).trigger('click');
 
/*  $('#startTour').click(function() {
    PricePredictor.tour();
  })
*/  
  // $('#ppSplash').click(function() {
  //   PricePredictor.run()
  // });
}); // document ready

