if (typeof vcc != "object")	vcc = {};

if (vcc.ce == null) vcc.ce = {};

vcc.ce.debug = false;
vcc.ce.showDebug = false;

vcc.ce.iUserScoreMax = 20;
vcc.ce.iUserScore = vcc.ce.iUserScoreMax;

vcc.ce.iPageRating = 0;
vcc.ce.aPageTags = [];
vcc.ce.aPageModels = [];

vcc.ce.scngContentCategories = [];

vcc.ce.pageUrl = document.location.href;
vcc.ce.pageUrl = vcc.ce.pageUrl.substring(vcc.ce.pageUrl.indexOf("://") + 3);
vcc.ce.pageUrl = vcc.ce.pageUrl.substring(vcc.ce.pageUrl.indexOf("/"));

vcc.ce.page = null;
vcc.ce.user = null;

vcc.ce.calloutTypes = [
	[ "S", "S", "P" ], //1
	[ "S", "S", "P" ], //2
	[ "S", "S", "P" ], //3
	[ "S", "P", "P" ], //4
	[ "S", "P", "B" ], //5
	[ "S", "P", "B" ], //6
	[ "S", "P", "P" ], //7
	[ "B", "P", "S" ], //8
	[ "B", "B", "P" ], //9
	[ "B", "B", "P" ] //10
];

vcc.ce.aCallouts = [];

vcc.ce.CallOut = function(iId, sTitle, sText, sImage, sUrl, aTypes, aTags, aModels, sCallToAction) {
	this.id = iId;
	this.title = sTitle;
	this.text = sText;
	this.image = sImage;
	this.url = sUrl;
	this.types = aTypes;
	this.tags = aTags;
	this.models = aModels;
	this.calltoaction = sCallToAction;
}

vcc.ce.trackBanner = function(market, segment, id, action, url) {
	//alert(market + " " + segment + " " + id + " " + action + " " + url);
	if (typeof(pageTracker) == "object") {
		pageTracker._trackPageview("/cnfexp/" + market + "/" + segment + "/" + id + "/" + action);
	}
}

vcc.ce.sCookieTemplate = '{ "score": ' + vcc.ce.iUserScoreMax + ', "models": {}, "tags": {} }';

$(document).ready(function() {
	if (vcc.bIsInAuthoringMode)
		return;
	
	var oDebugCookie = document.cookie.match(new RegExp("ce_debug=([^;]*)"))
	var sCookieString = (oDebugCookie)?unescape(oDebugCookie[1]):oDebugCookie;
	vcc.ce.showDebug = (vcc.ce.debug && sCookieString != null);
	
	var oCECookie = vcc.ce.getCookie("ce");
	if (oCECookie == null)
		return;
		
	vcc.ce.page = { tags: vcc.ce.aPageTags, models: vcc.ce.aPageModels, pageRating: vcc.ce.iPageRating };
	vcc.ce.user = { tags: oCECookie.tags, models: oCECookie.models, score: oCECookie.score };
	
	//Loop through all tags and model for this page and add them to user object
	for (var i = 0; i < vcc.ce.page.tags.length; i++) {
		var sTag = vcc.ce.page.tags[i].toLowerCase();
		var count = vcc.ce.user.tags[sTag];
		vcc.ce.user.tags[sTag] = (count == null) ? 1 : count + 1;
	}
	if (vcc.ce.page.models.length > 0) {
		for (var i = 0; i < vcc.ce.page.models.length; i++) {
			var sModel = vcc.ce.page.models[i].toLowerCase();
			var count = vcc.ce.user.models[sModel];
			vcc.ce.user.models[sModel] = (count == null) ? 1 : count + 1;
		}
	} else if (vcc.currentModel != "") {
		var count = vcc.ce.user.models[vcc.currentModel];
		vcc.ce.user.models[vcc.currentModel] = (count == null) ? 1 : count + 1;
	}
	
	//Increment / decrement score
	if (vcc.ce.user.score > vcc.ce.iUserScoreMax)
		vcc.ce.user.score = vcc.ce.iUserScoreMax;
		
	if (vcc.ce.page.pageRating == -1 && vcc.ce.user.score > 1) {
		vcc.ce.user.score--;
	} else if (vcc.ce.page.pageRating == 1 && vcc.ce.user.score < vcc.ce.iUserScoreMax) {
		vcc.ce.user.score++;
	}
	vcc.ce.writeDebug();
	
	vcc.ce.saveUserCookie();
	vcc.ce.setCalloutTypes();
});

vcc.ce.setCalloutTypes = function() {
	if (document.getElementById("callouts") == null)
		return;
		
	//Calculate which callout types to get from the 10 different type configurations
	var iSteps = (vcc.ce.calloutTypes.length > 0) ? vcc.ce.iUserScoreMax / vcc.ce.calloutTypes.length : 1;
	var iIndex = Math.ceil(vcc.ce.user.score / iSteps);
	if (iIndex > 0)
		iIndex--;
	var oCalloutType = vcc.ce.calloutTypes[iIndex];
	var aCallouts = $("#callouts .callout");
	//Get the most popular models for the user. if we're on a model page, use this model only
	vcc.ce.writeToConsole("The top 3 models for this user are " + vcc.ce.getTopModelsForUser());
	var aModels = (vcc.currentModel != "") ? [vcc.currentModel] : vcc.ce.getTopModelsForUser();	
	var aTags = vcc.ce.getTopTagsForUser();
	vcc.ce.writeToConsole("The top 3 tags for this user are " + aTags + "\n");
	
	//Remove callouts linking to the page we're currently on	
	vcc.ce.aCallouts = vcc.ce.removeCalloutsWithUrl(vcc.ce.aCallouts, vcc.ce.pageUrl);
	
	$.each(aCallouts, function(index) {
		vcc.ce.writeToConsole("Getting banner no " + (index + 1));
		var sModel = null;
		if (aModels.length > 0)
			sModel = (aModels[index] != null) ? aModels[index] : aModels[Math.floor(Math.random() * aModels.length)];
		var sTag = null;
		if (aTags.length > 0)
			sTag = (aTags[index] != null) ? aTags[index] : aTags[Math.floor(Math.random() * aTags.length)];
			
		var item = vcc.ce.findCallout(oCalloutType[index], sTag, sModel);		
		if (item != null) {
			var sType = "";
			if (oCalloutType[index] == "S")
				sType = "sales";
			else if (oCalloutType[index] == "P")
				sType = "product";
			else if (oCalloutType[index] == "B")
				sType = "brand";
			vcc.ce.trackBanner(vcc.sMarket, sType, item.id, "impression", document.location.href.substring(document.location.href.indexOf("://") + 3));
			var sHtml = "<a href=\"" + item.url + "\" onclick=\"vcc.ce.trackBanner(vcc.sMarket, '" + sType + "', '" + item.id + "', 'action', document.location.href.substring(document.location.href.indexOf('://') + 3))\"><span class=\"text\"><strong>" + item.title + "</strong> " + item.text + "</span><img src=\"" + item.image + "\" alt=\"\" />";
			if (item.calltoaction != "")
				sHtml += "<span class=\"calltoaction\">" + item.calltoaction + "</span>";
			sHtml += "</a>";
			this.innerHTML = sHtml;
			if (vcc.ce.showDebug) {
				//Create box with info about which banner type this banner slot should display
				var oBannerType = document.createElement("div");
				oBannerType.className = "ce_debug_bannertype";
				oBannerType.innerHTML = sType;
				oBannerType.style.left = (index * 332) + "px";
				document.getElementById("callouts").appendChild(oBannerType);
				
				//Create box with info about this callout banner
				var oCalloutInfo = document.createElement("div");
				oCalloutInfo.className = "ce_debug_bannerinfo";
				oCalloutInfo.style.left = (index * 332) + "px";
				var sInfoHtml = "<strong>Banner data</strong><br /><strong>Type: </strong>";
				$.each(item.types, function(index) {
					sInfoHtml += this;
					if (index < item.types.length - 1)
						sInfoHtml += ", ";
				});
				sInfoHtml += "<br />";
				sInfoHtml += "<strong>Models: </strong>";
				$.each(item.models, function(index) {
					sInfoHtml += this;
					if (index < item.models.length - 1)
						sInfoHtml += ", ";
				});
				sInfoHtml += "<br />";
				sInfoHtml += "<strong>Tags: </strong>";
				$.each(item.tags, function(index) {
					sInfoHtml += this;
					if (index < item.tags.length - 1)
						sInfoHtml += ", ";
				});
				oCalloutInfo.innerHTML = sInfoHtml;
				document.getElementById("callouts").appendChild(oCalloutInfo);
			}
		} else {
			this.innerHTML = "";
		}
	});
	if (document.all) {
		aCallouts.css( { "display": "block" });		
	} else {
		aCallouts.fadeIn(1000);
	}
}

vcc.ce.getTopModelsForUser = function() {	
	var aModels = [];
	for (var model in vcc.ce.user.models) {
		aModels.push({ model: model, clicks: vcc.ce.user.models[model] });
	}
	aModels.sort(vcc.ce.sortByClicks);
	var aTopModels = [];
	if (aModels.length > 3) {
		aTopModels = [ aModels[0].model, aModels[1].model, aModels[2].model ];
	} else {
		for (var i = 0; i < aModels.length; i++) {
			aTopModels.push(aModels[i].model);
		}
	}
	return aTopModels;
}

vcc.ce.getTopTagsForUser = function() {
	var aTags = [];
	for (var tag in vcc.ce.user.tags) {
		aTags.push({ tag: tag, clicks: vcc.ce.user.tags[tag] });
	}
	aTags.sort(vcc.ce.sortByClicks);
	var aTopTags = [];
	if (aTags.length > 3) {
		aTopTags = [ aTags[0].tag, aTags[1].tag, aTags[2].tag ];
	} else {
		for (var i = 0; i < aTags.length; i++) {
			aTopTags.push(aTags[i].tag);
		}
	}
	return aTopTags;
}

vcc.ce.sortByClicks = function(a, b) {
	return b.clicks - a.clicks;
}

vcc.ce.findCallout = function(sType, sTag, sModel) {
	vcc.ce.writeToConsole("Get banners of type " + sType);
	//Find the ones with matching callout type - P, B or S	
	var aMatchingCallouts = vcc.ce.findCalloutsByType(vcc.ce.aCallouts, sType);
	var iMatches = aMatchingCallouts.length;
	vcc.ce.writeToConsole("Found " + iMatches + " banners");
	if (iMatches == 0) {
		vcc.ce.writeToConsole("Since none were found, get banners of all types");
		aMatchingCallouts = vcc.ce.aCallouts;
		iMatches = aMatchingCallouts.length;
		vcc.ce.writeToConsole("Found " + iMatches + " banners");
	}
	//Find the ones with matching models
	if (sModel != null) {
		vcc.ce.writeToConsole("From these, get banners tagged with the model " + sModel);
		var aCalloutsBackup = aMatchingCallouts;
		aMatchingCallouts = vcc.ce.findCalloutsByModel(aMatchingCallouts, sModel);		
		iMatches = aMatchingCallouts.length;
		vcc.ce.writeToConsole("Found " + iMatches + " banners");
		if (iMatches == 0) {
			vcc.ce.writeToConsole("Since none were found, get banners tagged with all models");
			aMatchingCallouts = aCalloutsBackup;
			iMatches = aMatchingCallouts.length;
		}
	}
	//Find the ones with matching tags
	if (sTag != null) {
		vcc.ce.writeToConsole("From these, get banners with the tag " + sTag);
		var aCalloutsBackup = aMatchingCallouts;
		aMatchingCallouts = vcc.ce.findCalloutsByTag(aMatchingCallouts, sTag);		
		iMatches = aMatchingCallouts.length;
		vcc.ce.writeToConsole("Found " + iMatches + " banners");
		if (iMatches == 0) {
			vcc.ce.writeToConsole("Since none were found, get banners with all tags");
			aMatchingCallouts = aCalloutsBackup; //Since we didn't find anything, revert to the latest found callouts
			iMatches = aMatchingCallouts.length;
		}
	}	
	if (iMatches == 0)
		return null;
	
	if (iMatches == 1) {
		vcc.ce.writeToConsole("After filtering we have narrowed it down to 1 matching banner. Use this.\n");
	} else {
		vcc.ce.writeToConsole("After filtering we still have more than one banner to choose from. Choosing a banner to use by random.\n");
	}
	
	var oCalloutToReturn = (iMatches == 1) ? aMatchingCallouts[0] : aMatchingCallouts[Math.floor(Math.random() * iMatches)];
	vcc.ce.removeCalloutFromCollection(oCalloutToReturn);
	
	return oCalloutToReturn;
}

vcc.ce.writeDebug = function() {
	//DEBUG
	if (vcc.ce.debug) {
		//User data
		var oDebugDiv = document.createElement("div");
		oDebugDiv.id = "ce_debug_user";		
		document.body.appendChild(oDebugDiv);
		
		if (vcc.ce.showDebug) {
			var sHtml = "<div class=\"ce_debug_box\"><strong>User data</strong><br /><br />";
			sHtml += "<strong>Models</strong><br />";
			for (var model in vcc.ce.user.models) {
				sHtml += model + ": " + vcc.ce.user.models[model] + "<br />";
			}		
			sHtml += "<br /><strong>Tags</strong><br />";
			for (var tag in vcc.ce.user.tags) {
				sHtml += tag + ": " + vcc.ce.user.tags[tag] + "<br />";
			}
			sHtml += "<br /><strong>Score</strong><br />" + vcc.ce.user.score;
			sHtml += "<br /><br /><a href=\"#\" onclick=\"vcc.ce.deleteUserData(); return false;\">Delete user data</a>";
			sHtml += "<br /><br /><a href=\"#\" onclick=\"vcc.ce.disableDebug(); return false;\">Disable dynamic banner debug</a>";
			
			sHtml += "</div>";		
			oDebugDiv.innerHTML = sHtml;
			
			//Page data
			var oDebugDiv = document.createElement("div");
			oDebugDiv.id = "ce_debug_page";		
			document.body.appendChild(oDebugDiv);
			var sHtml = "<div class=\"ce_debug_box\"><strong>Page data</strong><br /><br />";
			sHtml += "<strong>Models</strong><br />";
			if (vcc.currentModel != "") {
				sHtml += vcc.currentModel + "<br />";
			} else {
				$.each(vcc.ce.aPageModels, function() {
					sHtml += this + "<br />";
				});
			}
			sHtml += "<br /><strong>Tags</strong><br />";
			$.each(vcc.ce.aPageTags, function() {
				sHtml += this + "<br />";
			});
			sHtml += "<br /><strong>Score</strong><br />" + vcc.ce.iPageRating;
			sHtml += "<br /><br /><strong>Console</strong><br /><textarea id=\"ce_debug_console\"></textarea>";
			sHtml += "</div>";	
			oDebugDiv.innerHTML = sHtml;
		} else {
			var sHtml = "<div class=\"ce_debug_box\"><a href=\"#\" onclick=\"vcc.ce.enableDebug(); return false;\">Enable dynamic banner debug</a></div>";
			
			oDebugDiv.innerHTML = sHtml;
		}
	}
}

vcc.ce.deleteUserData = function() {
	var date = new Date();
	date.setFullYear(date.getFullYear() - 1);
	vcc.ce.setCookie("ce", "false", date, "/");
	alert("User data deleted");
}

vcc.ce.enableDebug = function() {
	var date = new Date();
	date.setFullYear(date.getFullYear() + 1);
	vcc.ce.setCookie("ce_debug", "true", date, "/");
	window.location.reload();
}

vcc.ce.disableDebug = function() {
	var date = new Date();
	date.setFullYear(date.getFullYear() - 1);
	vcc.ce.setCookie("ce_debug", "false", date, "/");
	window.location.reload();
}

vcc.ce.consoleRowCount = 1;

vcc.ce.writeToConsole = function(sText) {
	if (!vcc.ce.showDebug)
		return;
	var oConsole = document.getElementById("ce_debug_console");
	if (oConsole == null)
		return;
	oConsole.value += vcc.ce.consoleRowCount++ + ": " + sText + "\n";
}

//Removes a callout item from the callout array, to make sure it won't be used twice
vcc.ce.removeCalloutFromCollection = function(oCallout) {
	var iCalloutIndex = null;
	for (var i = 0; i < vcc.ce.aCallouts.length; i++) {
		if (vcc.ce.aCallouts[i].id == oCallout.id) {
			iCalloutIndex = i;
			break;
		}
	}
	if (iCalloutIndex != null)
		vcc.ce.aCallouts.splice(iCalloutIndex, 1);
}

vcc.ce.setCalloutToUsed = function(oCallout) {
	oCallout.used = true;	
}

vcc.ce.removeCalloutsWithUrl = function(aCalloutsStore, sUrl) {
	sUrl = sUrl.toLowerCase();
	var aMatchingCallouts = [];
	for (var i = 0; i < aCalloutsStore.length; i++) {
		var oCallout = aCalloutsStore[i];
		if (oCallout.url.toLowerCase() != sUrl)
			aMatchingCallouts.push(oCallout);	
	}
	return aMatchingCallouts;
}

vcc.ce.findCalloutsByType = function(aCalloutsStore, sType) {	
	var aMatchingCallouts = [];
	for (var i = 0; i < aCalloutsStore.length; i++) {
		var oCallout = aCalloutsStore[i];
		if ($.inArray(sType, oCallout.types) > -1)
			aMatchingCallouts.push(oCallout);	
	}
	return aMatchingCallouts;
}

vcc.ce.findCalloutsByTag = function(aCalloutsStore, sTag) {
	var aMatchingCallouts = [];
	for (var i = 0; i < aCalloutsStore.length; i++) {
		var oCallout = aCalloutsStore[i];
		if ($.inArray(sTag, oCallout.tags) > -1)
			aMatchingCallouts.push(oCallout);
	}
	return aMatchingCallouts;
}

vcc.ce.findCalloutsByModel = function(aCalloutsStore, sModel) {
	var aMatchingCallouts = [];
	for (var i = 0; i < aCalloutsStore.length; i++) {
		var oCallout = aCalloutsStore[i];
		if ($.inArray(sModel, oCallout.models) > -1)
			aMatchingCallouts.push(oCallout);
	}
	return aMatchingCallouts;
}

//THESE FUNCTIONS CAN BE USED BY THIRD PARTIES TO ADD TAGS, MODELS AND CHANGE RATING

vcc.ce.addTag = function(sTag) {
	if (vcc.ce.user == null)
		return;
	sTag = sTag.toLowerCase();
	var count = vcc.ce.user.tags[sTag];
	vcc.ce.user.tags[sTag] = (count == null) ? 1 : count + 1;
	vcc.ce.saveUserCookie();
}

vcc.ce.addModel = function(sModel) {
	if (vcc.ce.user == null)
		return;
	sModel = sModel.toLowerCase();
	var count = vcc.ce.user.models[sModel];
	vcc.ce.user.models[sModel] = (count == null) ? 1 : count + 1;
	vcc.ce.saveUserCookie();
}

vcc.ce.setRating = function(iRating) {
	if (vcc.ce.user == null)
		return;
	//iRating can be -1, 0 and 1
	if (iRating < 0 && vcc.ce.user.score > 1) {
		vcc.ce.user.score--;
	} else if (iRating > 0 && vcc.ce.user.score < vcc.ce.iUserScoreMax) {
		vcc.ce.user.score++;
	}
	vcc.ce.saveUserCookie();
}

//Used to map SCNG categories to content categories
vcc.ce.getTagForSCNGCategory = function(sKey) {
	sKey = sKey.toLowerCase();
	for (var i = 0; i < vcc.ce.scngContentCategories.length; i++) {
		var scngCategory = vcc.ce.scngContentCategories[i];
		if (sKey == scngCategory.name.toLowerCase() || sKey == scngCategory.id.toLowerCase() || sKey == scngCategory.categoryname.toLowerCase())
			return scngCategory.categoryname;
	}
	return null;
}

vcc.ce.saveUserCookie = function() {
	var date = new Date();
	date.setFullYear(date.getFullYear() + 1);
	//Tags
	sCookie = "{ \"tags\": { ";
	for (var i in vcc.ce.user.tags) {
		sCookie += ("\"" + i + "\": " + vcc.ce.user.tags[i] + ", ");
	}
	
	if (sCookie.lastIndexOf(", ") + 2 == sCookie.length)
		sCookie = sCookie.substring(0, sCookie.length - 2);
		
	//Models
	sCookie += " }, \"models\": { ";
	for (var i in vcc.ce.user.models) {
		sCookie += ("\"" + i + "\": " + vcc.ce.user.models[i] + ", ");
	}
	
	if (sCookie.lastIndexOf(", ") + 2 == sCookie.length)
		sCookie = sCookie.substring(0, sCookie.length - 2);
	
	//Score
	sCookie += " }, \"score\": " + vcc.ce.user.score;
	sCookie += " }";
	vcc.ce.setCookie("ce", sCookie, date, "/");	
}

/* Cookies */

vcc.ce.setCookie = function(sName, sValue, oExpires, sPath) {
	var sCookie = sName + "=" + escape(sValue)
	if(oExpires) sCookie += ";expires=" + oExpires.toGMTString()
	if(sPath) sCookie += ";path=" + sPath
	document.cookie = sCookie
}

vcc.ce.getCookie = function(sName) {
	var t=document.cookie.match(new RegExp(sName + "=([^;]*)"))
	var sCookieString = (t)?unescape(t[1]):t;
	var oCookie = null;
	if (sCookieString != null) {
		oCookie = eval("(" + sCookieString + ")");
	} else {
		oCookie = eval("(" + vcc.ce.sCookieTemplate + ")");
	}
	return oCookie;
}

vcc.ce.delCookie = function(sName) {
	if (vcc.ce.getCookie(sName)) document.cookie = sName + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT"
}