// just a helper
String.prototype.rot13 = function(){
    return this.replace(/[a-zA-Z]/g, function(c){
        return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
    });
};

var EntitlementProvider = {
	HBO_VOD:"HBO_VOD", SHOWTIME_HD:"SHOWTIME_HD",CDV:"CDV",ENCORE:"ENCORE",ENCORE_HD:"ENCORE_HD",
	CINEMAX_HD:"CINEMAX_HD", TMC_HD:"TMC_HD", CINEMAX_VOD:"CINEMAX_VOD", DTV:"DTV", PLAYBOY:"PLAYBOY",
	STARZ_HD:"STARZ_HD", HSD:"HSD", HBO_HD:"HBO_HD", STARZ_VOD:"STARZ_VOD", SHOWTIME_VOD:"e"
};

var EntitlementsMapping = {
	HBO_VOD:"d", SHOWTIME_HD:"aj",CDV:"c",ENCORE:"h",ENCORE_HD:"ad",
	CINEMAX_HD:"ak", TMC_HD:"ai", CINEMAX_VOD:"g", DTV:"b", PLAYBOY:"i",
	STARZ_HD:"m", HSD:"a", HBO_HD:"al", STARZ_VOD:"f", SHOWTIME_VOD:"e"
};


var EntitlementMngrEvent = {
	ENTITLEMENTS_RECEIVED: "entitlements_received"
};

/**

	@usage
	var foo = new EntitlementManager();
	$(foo).bind(EntitlementMngrEvent.ENTITLEMENTS_RECEIVED, function(){
		// do stuff
		foo.hasSubscribedTo(EntitlementProvider.HBO_HD); // return true/false
	});
	foo.getEntitlements();
*/
var EntitlementManager = function() {
	this.TOKEN = "token";
	this.LAST_VERSION = "edata.last_success_version";
	this.data = null;
	this._responseTimeStamp = -1;
	this._entitlements = null;
};

jQuery.extend(EntitlementManager.prototype, {
	serviceUrl: function () {
		return document.config.edataServer;
	},
	
	getEntitlements: function() {
		if(jQuery.cookie.read(this.TOKEN) == null || this.lastTokenWasADifferentUser()){
			try {
				var newToken = this._replaceAlphaChars(getPortalData().guid, "");
			} catch (e) {
				throw new Error(e.message + " - Are you sure the user is logged in?");
			}

			jQuery.cookie.write(this.TOKEN, newToken.toString());
		 }
		
		// if lastTimestamp doesnt exist then 
		if(Prefs.get(this.LAST_VERSION)) {
			this._responseTimeStamp = Prefs.get(this.LAST_VERSION);
			var currentTimeStamp = new Date().getTime();
			// if current timestamp exceeds expiration time ...
			if(currentTimeStamp > this._responseTimeStamp + (1000 * 60 * 15)) {
				//... then use the current instead
	 			this._responseTimeStamp = currentTimeStamp;
			}

		}else {
			this._responseTimeStamp = new Date().getTime();
		}

		// Create the JSONP callback function
		var callback_name, i=0;
		while (callback_name = "entitlement_callback_" + i++)
			if (typeof window[callback_name] == 'undefined') break;
		var _this = this;
		window[callback_name] = function() {
			_this._parseEntitlement.apply(_this, arguments);
			window[callback_name] = (function() {})();
		}
		
		jQuery.ajax({
			url: this.serviceUrl(),
			data: {
				version: this._responseTimeStamp,
				token: this.getUserToken(),
				type:'jsonp',
				jsonp: callback_name
				},
			dataType: "script",
			cache: true
		});
	},
	
	_parseEntitlement: function(response) {
		this.data = response.data;
		this._parseEntitlementData();
		if(this._isStatus200())
			Prefs.set(this.LAST_VERSION, this._responseTimeStamp);
		jQuery(this).trigger(EntitlementMngrEvent.ENTITLEMENTS_RECEIVED);
	},
	
	_parseEntitlementData: function(){
		
		var edata = this.data.edata;
		if(edata.length >0 ) {
			var hashObj = new Object();
			var arr = edata.split('&');
			var tokens;		
			for( i=0;i<arr.length;i++) {
				tokens = arr[i].split('=');
	    		eval('hashObj.'+tokens[0] +' = "'+ tokens[1]+'"');
			}

			this._entitlements = hashObj;
			delete hashObj;
		} else {
			this._entitlements = {};
		}
	},
	
	isInOdolBeta: function() {
		if(this.data == null){
			return null;
		} else if (this._isStatus200()) {
			return this.data.tempPass;
		} else {
			return false;
		}
	},
	
	hasSubscribedTo: function(chn) {
			var chnChar = EntitlementsMapping[chn];
			return chnChar ? (this._entitlements[chnChar] == 'y') : null;
	},
	
	_isStatus200: function() {
		return (this.data.status == 200);
	},
	
	getUserToken: function() {
		return jQuery.cookie.read(this.TOKEN);
	},
	
	_replaceAlphaChars: function(str,re_str) {
		//var re = new RegExp("[^\d]","g");
		return str.replace(/[^\d]/g,"");
	},	
	
	lastTokenWasADifferentUser: function(){
		if(getPortalData() == null)
			return false;
			
		// get old token
		var oldToken = this.getUserToken();

		// take user's guid and perform ROT13 on it
		var currentGuid = getPortalData().guid;
		var rottedGuid = this._replaceAlphaChars(currentGuid, "");
		
		// return true if they do not match
		// return false if they do match
		return (oldToken != rottedGuid);
		return false;
	},

	
	getLastSuccessfulVersion: function() {
		return Prefs.get(this.LAST_VERSION);
	},
	
	clearCookies: function() {
		jQuery.cookie.remove(this.TOKEN);
		Prefs.remove(this.LAST_VERSION);
	}
});

