/*
	These functions must come from the blocks of code at the bottom of the page. Do not include jQuery syntax in this file.
*/
var manual_cm_mmc = null;

function generateMmcFromNats(txt) {
	firstColon = txt.indexOf(":");
	semicolon = txt.indexOf(";");
	secondColon = txt.indexOf(":", firstColon + 1);

	if (semicolon != -1 && semicolon < firstColon) {
		campaign = txt.substring(semicolon + 1, firstColon);
		affiliate = txt.substring(0, semicolon);
	} else {
		campaign = null;
		affiliate = txt.substring(0, firstColon);
	}

	program = txt.substring(firstColon + 1, secondColon);
	return program + "-_-" + affiliate + (campaign ? ("-_-" + campaign + "-_-na") : "-_-na-_-na");
}

function kinkCreateCookie(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 + "=" + enc(value) + expires + "; path=/";
}

function kinkReadCookie(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)
			return unescape(c.substring(nameEQ.length, c.length));
	}
	return null;
}

function kinkEraseCookie(name) {
	kinkCreateCookie(name, "", -1);
}


function enc(s, uri) {
	if (typeof(encodeURIComponent) == 'function') {
		if (uri)
			return encodeURI(s);
		else
			return encodeURIComponent(s);
	}
	else {
		return escape(s);
	}
}

// sso redirection - non javascript clients will not benefit from this - session cookie insures they don't get sent back over and over again
ssoCookie = kinkReadCookie('sso_initial');

if (!ssoCookie) {
	pieces = document.location.hostname.split(".").reverse();

	//send "about:blank" urls to KOD, everyone else back where they came from
	ret = document.URL.substring(0, 4) == "http" ? enc(document.URL) : enc("http://kinkondemand.com");

	var port = (document.location.port && document.location.port != 80) ? ":" + document.location.port : ""; 
	
	if (pieces[0]) // in case there is an extra '.' on the end of the hostname
		newLocation = "http://sso.kink." +  pieces[0] + port + "/sso/check?ret=" + ret;
	else
		newLocation = "http://sso.kink." +  pieces[1] + port + "/sso/check?ret=" + ret;

	// store the original referrer for analytics use later - cookie will get removed later when CM sends out page view
	if (document.referrer) {
		kinkCreateCookie('orf', encodeURIComponent(document.referrer));
	}

	kinkCreateCookie('sso_initial', 'check');
	window.location = newLocation;
}

//	nats cookie -> mmc management
natsCookie = kinkReadCookie('nats');
if (natsCookie) {
	try {
		manual_cm_mmc = generateMmcFromNats(natsCookie);
	} catch(error) {
		manual_cm_mmc = "error-_-" + natsCookie + "-_-na-_-na";
	}
}


