/****************************************************************************
// Copyright (C) thePlatform for Media, Inc. All Rights Reserved.
//****************************************************************************

/*
	
*/
var comcast = {issuerId: "", spId: "",  elementId : "comcast", imageUrl: "images/comcast.jpeg", title : "Xfinity",  targetUrl:"https://login.comcast.net/?"};
var comcast_qa = {issuerId: "https://sso.comcast.net/Comcast/IdP/sso", spId: "acs.euid.test.theplatform.com",  elementId : "comcast", imageUrl: "images/comcast_stage.jpg", title : "Xfinity QA", targetUrl:"https://idp-qa4.comcast.net/idp/startSSO.ping?PartnerSpId=www.theplatform.com&"};
var cox_dev =  {issuerId: "idm.cox.net", spId: "sp.vutopia.com", elementId : "cox",  imageUrl: "images/cox.jpeg", title : "Cox Dev", targetUrl: "https://idm.east.dev.cox.net:443/affwebservices/public/saml2sso?"};
var cox = {issuerId: "idm.cox.net", spId: "acs.euid.test.theplatform.com", elementId : "cox",  imageUrl: "images/cox.jpeg", title : "Cox", targetUrl: "http://cox.com/?"};
var twc_qa = {issuerId: "https://twcidp.eng.rr.com/nidp/saml2/metadata",spId: "https://acs.euid.test.theplatform.com",  elementId : "twc_qa",  imageUrl: "images/twc_rr_qa.jpeg", title : "RoadRunner QA", redirectLocationParamName: "RelayState", targetUrl: "https://twcidp.eng.rr.com/nidp/saml2/sso?c_id=*****&"};
var twc = {issuerId: "", spId: "", elementId : "twc",  imageUrl: "images/twc_rr.jpeg", title : "RoadRunner", targetUrl: "http://www.rr.com/?"};

var MvpdChooser = function() {
	this._initialize.apply(this, arguments);
};

MvpdChooser.prototype = {
	acsUrl: "http://acs.euid.sandbox.theplatform.com/",
	divId : "plMvpdChooser",
	rows : 2,
	columns : 3,
	iconHeight : 50,
	iconWidth : 170,
	mvpdList : [  ],
	_initialize: function() {
		// no op
	},
	setDivId: function( divId ) {
		this.divId = divId;
	},
	sortByVisited: function() {
		// TODO
	},
	display: function() {
		// find node by ID
		var container = returnObjById( this.divId );
		
		// Determine the previously authenticated MSO so we can hide all the others.
		// TODO
		
		// initialize some variables for append icons
		if ( this.mvpdList.length < this.columns )
		{
			this.columns = this.mvpdList.length;
		}
		
		var widthPercent = Math.floor(100/this.columns) - 1;
		var i;
		
		// append icons
		for ( i = 0; i < this.mvpdList.length; i+=1 )
		{
			// Break the column
			if ( (i) % this.columns === 0 && i !== 0 )
			{
				container.appendChild(document.createElement("br"));
			}	
			
			var element = document.createElement( "div" );
			element.setAttribute("id", this.mvpdList[i].elementId);
			
			if ( (i) % this.columns === (this.columns - 1) )
			{
				element.style.cssText = "margin-left: " + widthPercent * ( this.columns - 1 ) + "%; width: " + widthPercent + "%;";
			}
			else
			{		
				element.style.cssText = "float:left; width: " + widthPercent + "%;";
			}
			element.className = "mvpd";
			
			element.innerHTML = '<a href="' + 
						this.acsUrl + "acs/web/sso/startAuthentication?" +
						"relayState" + "=" + document.location + 
						"&issuerId" + "=" + this.mvpdList[i].issuerId + 
						"&spId" + "=" + this.mvpdList[i].spId +
				'">' + 
				'<img style="float:none; border:0;" src="' + 
						this.mvpdList[i].imageUrl + 
						'" height="' + this.iconHeight +
						'" width="' + this.iconWidth + 
				'"/></a>';
			element.innerHTML = element.innerHTML + '<br/><span>' +this.mvpdList[i].title + '<span/>';
			container.appendChild(element);			
		}
		var clear = document.createElement("div");
		clear.style.cssText = "clear: both";
		container.appendChild(clear);
	}
};

////////////////////////////////////////////////////
/////////  Authentication JS /////////////////////////
///////////////////////////////////////////////////
var AuthenticationHelper = function() {
	this._initialize.apply(this, arguments);
};

AuthenticationHelper.prototype = {
	
	acsUrl: "http://acs.euid.sandbox.theplatform.com/",
	
	idmUrl: "http://acs.euid.sandbox.theplatform.com/",
	
	// version number | status code | token | message
	parseCookieValue: /^(?:([0-9]+)\|)(?:([0-9]{3})\|)(?:(.*)\|)(?:(.*))/,
	
	_initialize: function() {
		// no op
	},
	
	isAuthenticated: function() {
		var result = false;
		var cookie = getCookie("authToken");
		var parseResult = this.parseCookieValue.exec(cookie);
		
		// if version number 1
		if ( parseResult && parseResult[1] === "1" )
		{
			if ( parseResult[2] === "200" )
			{
				result = true;
			}
		}
	
		return result;
	},
	
	hasTokenCookie: function() {
		var result = false;
		var cookie = getCookie("authToken");
		
		return (cookie && true);
	},
	
	getTokenMessage: function() {
		var message = null;
		var cookie = getCookie("authToken");
		var parseResult = this.parseCookieValue.exec(cookie);
		
		// if version number 1
		if ( parseResult && parseResult[1] === "1" )
		{
				message = parseResult[4];
		}
		
		return message;
	},

	idProvider: function() {
		var idp = getCookie("idP");
		// no parsing required 
		return idp;
	},

	getAuthenticationToken: function() {
		var result = null;
		var cookie = getCookie("authToken");
		var parseResult = this.parseCookieValue.exec(cookie);
		
		// if version number 1
		if ( parseResult && parseResult[1] === "1" )
		{
			if ( parseResult[2] === "200" )
			{
				result = parseResult[3];
			}
		}
		
		return result;
	},
	
	removeAuthenticationToken: function() {
		var date = new Date();
		date.setTime( date.getTime() - 1 );
		document.cookie = "authToken=; expires=" + date.toGMTString() + "; path=/; domain=.theplatform.com";
		return null;
	},
	hasAuthenticated: function() {
		// TODO
	},
	copyCommonCookies: function(cb) {
		var a = new JSONLoader();
		var b = this.acsUrl +  "acs/web/sso/getCookies?cookie=authToken&cookie=idP";
		var c = this;
		a.load(b,
			function() {
           		c.handleCommonCookiesResponse.apply(c, arguments);
				cb.apply();
       		});
	
	},
	
	handleCommonCookiesResponse: function(response) {
		if (response)
		{
			var expire= new Date();
			for ( var i = 0; i < response.entries.length; i++)
			{
			 	expire.setTime(response.entries[i].expires);
				
				if( expire <= new Date())
				{
					// add one hour when the ACS 'expires' bug is in effect.
					expire.setTime( expire.getTime() * 1000 * 60 * 60 * 1)	
				}
				
			 	setCookie(response.entries[i].name, response.entries[i].value, expire)	
			}
			
			if (response.entries && response.entries.length === 0)
			{
				// clear out any older cookies
				var expire = new Date(0);
				setCookie("authToken", "", expire);
				setCookie("idP", "", expire);
			}
		}
	}
	
};

function setCookie( name, value, expires)
{
	document.cookie = name +"="+value + "; expires="+expires.toUTCString() + "; path=/";
}

////////////////////////////////////////////////////
/////////   Cross-browser Helpers    ////////////////////
////////////////////////////////////////////////////
function showIframe( href ) {
	window.open(href);
}

function returnObjById( id ) 
{ 
    if (document.getElementById) 
        var returnVar = document.getElementById(id); 
    else if (document.all) 
        var returnVar = document.all[id]; 
    else if (document.layers) 
        var returnVar = document.layers[id]; 
    return returnVar; 
}

function getCookie ( name )
{
	var results = document.cookie.match ( '(^|;) ?' + name + '=([^;]*)(;|$)' );
	
	if ( results )
	{
		return ( unescape ( results[2] ) );
	}
	else
	{
		return null;
	}
}
