﻿/** ------------------------- 
 * history.js
 * @author: chris casciano
 * description: Handles functionality related to baynote recommendations engine. Keeps track of specific user actions. Stores data in cookie for server-side retrieval.
 */

var Vevo = window.Vevo || {};

// Vevo.History
Vevo.History = (function() {
	var $Vevo = $(Vevo);
	var CONSTANTS = {
		favoriteCookie: "vevoLastActions"
		//,viewCookie: "vevoHistoryLastPlayed"
	};

	/** shorthand 
	*/
	var c = CONSTANTS;

	function writeCookie(arr) {
		var cData = '';
		for (var i = 0; i++; i < arr.length) {
			cData += arr[i];
		}
	}

	function addFavorite($node) {
		//Vevo.Cookie.delCookie(c.favoriteCookie);
		var cData = Vevo.Cookie.getCookie(c.favoriteCookie);
		//console.log(cData);
		if (null == cData) {
			cData = {};
		}
		if (!$.isArray(cData.favs)) {
			cData.favs = [];
		}

		if (-1 == $.inArray(window.location.protocol + '//' + window.location.host + $node.attr("href"), cData.favs)) {
			var s = window.location.protocol + '//' + window.location.host + $node.attr("href");
			cData.favs.unshift(s.split('#')[0]);
			if (3 < cData.favs.length) {
				cData.favs.length = 3;
			}
			var encoded = $.toJSON(cData);
			Vevo.Cookie.setCookie(c.favoriteCookie, encoded, { expires: 365, path: '/' });
		}
		//console.log(encoded);
	} // addFavorite

	function removeFavorite($node) {
	} // removeFavorite

	return {
		init: function() {
			$Vevo.bind('updatedFavorite', function(e, obj) {
				//console.log(obj);
				if (obj.status) {
					// add favorite to history
					addFavorite(obj.$node);
				} else {
					// remove favorite from history
					removeFavorite(obj.$node);
				}
			});
		}, // Vevo.History.Init

		recordURL: function() {
			//Vevo.Cookie.delCookie(c.favoriteCookie);
			var cData = Vevo.Cookie.getCookie(c.favoriteCookie);
			//console.log(cData);
			if (null == cData) {
				cData = {};
			}
			if (!$.isArray(cData.visited)) {
				cData.visited = [];
			}

			if (-1 == $.inArray(window.location.href, cData.visited)) {
				cData.visited.unshift(window.location.href.split('#')[0]);
				if (5 < cData.visited.length) {
					cData.visited.length = 5;
				}
				var encoded = $.toJSON(cData);
				Vevo.Cookie.setCookie(c.favoriteCookie, encoded, { expires: 365, path: '/' });

				//console.log(encoded);
			}


		}, // recordURL

		recThresholdTest: function() {
			var favData = Vevo.Cookie.getCookie(c.favoriteCookie);
			var numFavs = 0;
			if ((null != favData) && $.isArray(favData.favs)) {
				numFavs = favData.favs.length;
			}
			if (numFavs >= 1) {
				return true;
			}
			return false;
		} // recThresholdTest
	};
})();    // Vevo.History

$(document).ready(function() {
	Vevo.History.init();
});
