(function (window, undefined) {

	var document = window.document,
		cookieSet = false,
		visitID = "0",
		uvp = window.uvp,
		oldEmbed = uvp.embedPlayer;

	/*
	  Retreive the visitID from the query string (if it exists) or a cookie
	*/
	function loadTrackingCookie(sessionID, playerID) {
		var cookie,
			parts, 
			lastSessionID, 
			lastVisitID;

		visitID = uvp.getQueryParam("m_visitID");		
		if (visitID !== undefined) {
			uvp.log("VisitID from query string: " + visitID);
			return visitID;
		}
		
		cookie = uvp.getCookie("UVPSettings" + playerID);
		if (cookie === null) {
			uvp.log("VisitID default (no cookie found): 0");
			return "0";
		}
				
		parts = cookie.split('|');
		lastSessionID = parts[0];
		lastVisitID = parts[1];
		if (lastSessionID === sessionID) {
			if (lastVisitID === "0") {
				visitID = "1";
			}
			else if (lastVisitID === "2") {
				visitID = "3";
			}
			else {
				visitID = "1";
			}
		}
		else {
			if (lastVisitID === "3") {
				visitID = "3";
			}
			else {
				visitID = "2";
			}
		}
		uvp.log("VisitID from cookie - was " + lastVisitID + ", now " + visitID);
		return visitID;
	}
	
	/*
	  Sets the UVP cookie
	*/
	function setTrackingCookie(sessionID, playerID) {
		var cookie = sessionID + "|" + visitID,
			expires = new Date();
		
		expires.setFullYear(expires.getFullYear() + 20);
		uvp.setCookie("UVPSettings" + playerID, cookie, {expires: 7300}); 
	}
	
	/*
	   Retreives a cookie
	
	   Copyright (c) 2006 Klaus Hartl (stilbuero.de)
	   Dual licensed under the MIT and GPL licenses
	*/
	uvp.getCookie = function (name) {
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	};

	/*
	   Sets a cookie
	
	   Copyright (c) 2006 Klaus Hartl (stilbuero.de)
	   Dual licensed under the MIT and GPL licenses
	*/
	uvp.setCookie = function (name, value, options) {
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString();
		}
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	};

	/*
		Retreives a parameter from the query string
		By John Terenzio | http://plugins.jquery.com/project/getqueryparam | MIT License
	*/
	uvp.getQueryParam = function (param) {
		var pairs = location.search.substring(1).split('&');
		for (var i = 0; i < pairs.length; i++) {
			var params = pairs[i].split('=');
			if (params[0].toLowerCase() == param.toLowerCase()) {
				return params[1] || '';
			}
		}
		return undefined;
	};

	/*
	  Wrap uvp.embedPlayer method to add cookie functionality
	*/
	uvp.embedPlayer = function (paramsObj, callbackFunction) {
		uvp.log("Visit Tracker - wrapping embedPlayer");

		if (paramsObj.m_visitID === undefined) {
			visitID = loadTrackingCookie(paramsObj.sessionID, paramsObj.id);
			paramsObj.m_visitID = visitID;
		}
		
		oldEmbed(paramsObj, callbackFunction);

		if (!cookieSet) {
			setTrackingCookie(paramsObj.sessionID, paramsObj.id);
			cookieSet = true;
		}
	}

	/*
	  Add a convienence method to UVPlayerInstance which returns the visit type
	*/
	uvp.fn.getVisitType = function () {
		return this.params.m_visitID;
	};
})(window);

