//Firebug X -- allow use of console.log(), etc without busting IE, Safari, etc w/o Firebug
if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {};
}
//custom Javascript string function
if(!String.prototype.format){String.prototype.format=function(){var arg=arguments;var i=0;var x=function(){return arg[i++];};return this.replace(/(%s)/g,x);};}

//geo code
var GEO = {};
GEO.pageParams = function(){var url=window.location.search;var i=url.indexOf("?");if(i==-1){return {};}var ret={};var params=url.substr(i+1).split(new RegExp("[|&]{1}"));for(var i=0;i<params.length;i++){var curParam=params[i].split("=",2);if(curParam.length==1){ret[curParam[0]]=true;}else{if(curParam.length==2){ret[curParam[0]]=decodeURIComponent(curParam[1]);}}}return ret;}();
GEO.domainBase = document.domain.split('.').length > 1 ? document.domain.split('.')[document.domain.split('.').length-2]+'.'+document.domain.split('.')[document.domain.split('.').length-1] : document.domain;
GEO.noAffUrl = 'http://www.twoandahalfmenplayer.com/index.html';
GEO.persistParams = {'start':'','stop':'','ep':'','show':'','debug':''}; //URL params that should persist across redirects
GEO.affiliate = '';
GEO.currentURL = GEO.pageParams.affURL || 'no affURL passed in query params';

GEO.redirURL = '';
GEO.expectedURL = '';
GEO.redirParams = '?';
if(document.location.search.indexOf('?') != -1) {
	var p = document.location.search;
	p = p.substr(p.indexOf('?')+1).split('&');
	for(i = 0; i < p.length; i++){
		var curParam = p[i].split('=')[0];
		// if(p[i].split('=')[0] != 'affiliate' && p[i].split('=')[0] != 'ref' && p[i].split('=')[0] != 'uReq' && p[i].split('=')[0] != 'req' && p[i].split('=')[0].charAt(0) != '_') //don't pass along affiliate, ref, req, or special params
		if(curParam in GEO.persistParams || curParam.charAt(0) == '_') //only pass along query parameters that mean something to the player page or geoserver
			GEO.redirParams += p[i] + '&';
	}
}

function CookieCheck() {
	if(document.cookie.indexOf('videovalid') == -1) {
		if(document.cookie.indexOf('nosoup') != -1) {
			return false;
		}
		else {
			var uReq = new Date().getTime(); //unique request parameter; prevent Firefox from caching geoserver response & entering infinite loop
			var ref = document.location.href.replace(document.location.search,'');
			console.log('http://gksrv.%s/wbgeo%sref=%s&uReq=%s'.format(GEO.domainBase, GEO.redirParams, ref, uReq));
			window.parent.location = 'http://gksrv.%s/wbgeo%sref=%s&uReq=%s'.format(GEO.domainBase, GEO.redirParams, ref, uReq);
		}
	}
	else {
		GEO.affiliate = document.cookie.substr(document.cookie.indexOf('videovalid')).split(';')[0].split('=')[1]; //videovalid contains the affiliate name (ie 'WPIX')
		GEO.affiliate = GEO.affiliate.toUpperCase(); //set 'affiliate' to the value returned in videovalid -- this is used for ad serving
		GEO.redirURL = getAffiliateURL(GEO.affiliate); //grab the URL for the affiliate cookie check returned
		if (GEO.redirURL.indexOf('http://') == -1 && GEO.redirURL.indexOf('https://') == -1) // http(s):// not in URL; add it!
			GEO.redirURL = 'http://' + GEO.redirURL;
		GEO.expectedURL = GEO.redirURL.split('?')[0]; //everything but the query params, to see if they are on the right page
	}
	return true;
}

GEO.validCookie = CookieCheck();

GEO.cleanURL = (GEO.expectedURL.indexOf('://') == -1) ? GEO.expectedURL : GEO.expectedURL.substr(GEO.expectedURL.indexOf('://') + 3);
GEO.cleanURL = (GEO.cleanURL.charAt(GEO.cleanURL.length-1) != '/') ? GEO.cleanURL : GEO.cleanURL.substr(0,GEO.cleanURL.length-1);
GEO.cleanURL = (GEO.cleanURL.substr(0,4) != 'www.') ? GEO.cleanURL : GEO.cleanURL.substr(4);
// cleanURL should make it so that an expected URL of http://www.foxreno.com/twoandahalfmen/ matches anything containing 'foxreno.com/twoandahalfmen'
// examples:
//   http://foxreno.com/twoandahalfmen
//   http://foxreno.com/twoandahalfmen/index.html
//   http://www.foxreno.com/twoandahalfmen
//   http://www.foxreno.com/twoandahalfmenplayer
//   http://anything.foxreno.com/twoandahalfmen_player/index.html
console.log('GEO: current url: ' + GEO.currentURL + '; acceptable url: ' + GEO.cleanURL);

if(!GEO.validCookie){
	console.log('GEO: failed cookie check; redirect parent to no-affiliate page');
	if(window.location.href != GEO.noAffUrl)
		window.parent.location = GEO.noAffUrl;
}
else{
	if(GEO.redirURL != '' && GEO.cleanURL != '' && GEO.currentURL && GEO.currentURL.indexOf(GEO.cleanURL) == -1) { //make sure the expected url (minus http:// and trialing /) is part of where we are. This allows for unexpected 'www.', '/index.html', etc
		//good cookie, not on the right page; REDIRECT!
		console.log('GEO: passed cookie check; should be at ' + GEO.expectedURL + ' instead of ' + GEO.currentURL);
		var p = GEO.redirParams;
		var redirParams = (GEO.redirURL.indexOf('?') == -1) ? '?' : '&'; //don't append two ?s to the URL
		p = p.substr(p.indexOf('?')+1).split('&');
		for(i = 0; i < p.length; i++){
			var curParam = p[i].split('=')[0];
			// if(p[i].split('=')[0] != 'affiliate' && p[i].split('=')[0] != 'ref' && p[i].split('=')[0] != 'uReq' && p[i].split('=')[0].charAt(0) != '_') //don't pass along affiliate, ref, uReq, special params
			if(curParam in GEO.persistParams) //only pass along query parameters that mean something to the player page
				redirParams += p[i] + '&';
		}
		redirParams = (redirParams.charAt(redirParams.length-1) == '?' || redirParams.charAt(redirParams.length-1) == '&') ? redirParams.slice(0,redirParams.length-1) : redirParams;
		var fullRedir = GEO.redirURL + redirParams;
		console.log('Redirecting to ' + fullRedir);
		window.parent.location = fullRedir;
	}
}