//-----------------------------------//
// COOKIE WIDGET CLASS DEFINITION
//-----------------------------------//
(function(scope, name) {
	//create a base class
	var $ = window[scope], c = function(wrapper, options) {
		if(this.__construct) {
			this.__construct(wrapper, options || {}); //call the construct
		}
	};
	
	/* Base Class Definition
	-------------------------------------*/
	c.prototype = (function() {
		var p =  c.prototype;  //scope
		
		/* Private Properties
		-------------------------------------*/
		var _this = null;
		
		var _months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 
					   'August', 'September', 'October', 'November', 'December'];
		
		/* Construct
		-------------------------------------*/
		p.__construct = function(wrapper, options) {
			//set the wrapper
			this.wrapper = $(wrapper);
			//merge the default options
			options = this.getDefaultOptions(options);
			//give the scope away
			_this = this;
			
			//Set the options to public variables
			this.visitsNode 	= this.wrapper.find(options.visits);
			this.durationNode 	= this.wrapper.find(options.duration);
			this.firstNode 		= this.wrapper.find(options.first);
			this.viewed 		= this.wrapper.find(options.viewed);
			this.currentPage	= this.wrapper.find(options.currentPage);
			
			this.expire			= options.expire;
			
			this.today 			= new Date().getTime();
			this.avgDuration	= 0;
			
			this.visits 		= $.getCookie('visits');
			this.session		= $.getCookie('session');
			this.history		= $.getCookie('history');
			this.durations		= $.getCookie('durations');
			this.visits			= this.visits ? this.visits.split(',') : [];
			this.session		= this.session ? this.session.split(',') : [];
			this.history		= this.history ? this.history.split(',') : [];
			this.durations		= this.durations ? this.durations.split(',') : [];
			
			//COOKIE LOGIC
			//if first time
			if(this.visits.length == 0) {
				this.setFirstCookie();
			//they are returning
			} else {
				this.setReturnCookie();
				//get the duration calc
				this.avgDuration = this.getAverageDuration();
			}
			
			//no matter what set the history
			this.setHistoryCookie();
			
			var firstVisit = new Date();
			firstVisit.setTime(parseInt(this.visits[0]));
			
			//we are ready for some output
			this.firstNode.html(_months[firstVisit.getMonth()] + ' ' + 
								firstVisit.getDate() + ', ' +
								firstVisit.getFullYear());
			
			this.visitsNode.html(this.visits.length);
			
			var durationInSeconds = this.avgDuration / 1000;
			var durationInMinutes = this.avgDuration / (1000*60);
			
			var durationText = '0 seconds';
			
			switch(true) {
				case Math.round(durationInMinutes) > 1:
					durationText = Math.round(durationInMinutes) + ' minutes';
					break;
				case Math.round(durationInMinutes) == 1:
					durationText = Math.round(durationInMinutes) + ' minute';
					break;
				case Math.round(durationInSeconds) > 1:
					durationText = Math.round(durationInSeconds) + ' seconds';
					break;
				case Math.round(durationInSeconds) == 1:
					durationText = Math.round(durationInSeconds) + ' second';
					break;
			}
			
			this.durationNode.html(durationText);
			
			this.viewed.append(this.getHistoryListNode());
			this.currentPage.html(document.title);
		};
		
		/* Public Methods
		-------------------------------------*/
		p.getDefaultOptions = function(options) {
			options = options || {};
			options.expire 		= options.expire		|| 999;
			options.visits 		= options.visits 		|| '.visits';
			options.duration 	= options.duration 		|| '.duration';
			options.first 		= options.first 		|| '.first-visit';
			options.viewed 		= options.viewed 		|| '.viewed';
			options.currentPage	= options.currentPage 	|| '.current-page';
			
			return options;
		};
		
		p.setFirstCookie = function() {
			//set the cookies
			$.setCookie('visits', this.today, this.expire);
			$.setCookie('session', this.today, this.expire);
			//also set the visits and session
			this.visits.push(this.today);
			this.session.push(this.today);
			
			return this;
		};
		
		p.setReturnCookie = function() {
			//they have been to this site before
			lastVisit 	= parseInt(this.visits[this.visits.length - 1]);
			
			// if the difference in the time is greater than
			// 2 hours then it's a new visit
			if((this.today - lastVisit) > (1000*60*60*2)) {
				//add this date into visits
				this.visits.push(this.today);
				$.setCookie('visits', this.visits.join(','), this.expire);
				
				var duration = 0;
				
				//store the duration of the last session
				if(this.session.length > 1) {
					duration = this.session[this.session.length - 1] - this.session[0];
				}
				
				this.durations.push(duration);
				
				//clear the session
				this.session = [];
			}
			
			//add today into the session
			this.session.push(this.today);
			
			$.setCookie('session', this.session.join(','), this.expire);
			$.setCookie('durations', this.durations.join(','), this.expire);
			
			return this;
		};
		
		p.setHistoryCookie = function() {
			//parse out the history to an actual matrix
			for(var i = 0, length = this.history.length; i < length; i++) {
				this.history[i] = this.history[i].split('::::');
			}
			
			//did they not refresh?
			if(!this.history[this.history.length-1] || this.history[this.history.length-1][1] != window.location.href) {
				//push the current page into the matrix
				this.history.push([document.title, window.location.href, this.today]);
			}
			
			var tmp = [];
			
			//join each row into a delimiter
			for(var i = 0, length = this.history.length; i < length; i++) {
				tmp.push(this.history[i].join('::::'));
			}
			
			//now set the cookie
			//$.setCookie('history', tmp.join(','), this.expire);
			
			return this;
		};
		
		p.getAverageDuration = function() {
			var total = 0;
			
			if(this.durations.length > 0) {
				//get the average duration
				for(var i = 0, length = this.durations.length; i < length; i ++) {
					//add the difference of the next time and this time
					total += parseInt(this.durations[i]);
				}
				
				//this is the average duration in milliseconds
				return Math.round(total / length);
			}
			
			return 0;
		};
		
		p.getHistoryListNode = function() {
			var a, li, ul = document.createElement('ul'), key, histObject = {};
			
			ul.setAttribute('class', 'clearfix');
			
			for(var i = 0, length = this.history.length; i < length; i ++) {
				histObject[this.history[i][1]] = this.history[i];
			}
			
			i = 0;
			
			for(key in histObject) {
				if(i < 5) {
					a = document.createElement('a');
					a.setAttribute('href',histObject[key][1]);
					a.innerHTML = histObject[key][0];
					
					li = document.createElement('li');
					li.appendChild(a);
					ul.appendChild(li);
				}
				i ++;
			}
			
			return ul;
		};

		return p;
	})();
	
	//This is the jQuery adapter
	//so that anytime this method is
	//called it will create a new instance
	//of our actual class
	$.fn.extend(new function() {
		this[name] = function(options, returnInstance) {
			returnInstance = returnInstance || false;
			var instance = new c(this, options || {});
			if(returnInstance) {
				return instance;
			}
			return this;
		}
	});
	
	//we set it here because
	//flyout widget needs this
	$.extend({
		setCookie: function(name, value, days) {
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else var expires = "";
			document.cookie = name+"="+value+expires+"; path=/";
		},
		
		getCookie: function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) {
					var value = c.substring(nameEQ.length,c.length);
					return value != '' ? value : null;
				}
			}
			return null;
		},
		
		eraseCookie: function(name) {
			$.setCookie(name, '', -1);
		}
	});
})('jQuery', 'analytics');
