// JavaScript Document

String.prototype.replaceAll = function(pcFrom, pcTo){
	var i = this.indexOf(pcFrom);
	var c = this;
	while (i > -1){
	c = c.replace(pcFrom, pcTo); 
	i = c.indexOf(pcFrom);
	}
	return c;
}

var keywordCloud = {
	words: {},
	totalRevenue: 0,
	ignore: { 'the': true, 'a':true, 'of':true, 'bug': true, '1': true, '2':true, 'rt': true, 'its':true, 'doesnt': true,
	'it':true, 'is':true, 'in': true, 'at': true, 'and':true, 'com':true, 
	'tinyurl':true, 'to': true, '0':true, 'and':true, 'bit':true, 'ly':true, 'https':true, 'on':true, 'no':true, 
	 'but':true,  'an':true, 'also':true, 'www':true
	}
};


jQuery.query = function(s) {
	var r = {};
	if (s) {
			var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
			q = q.replace(/\&$/, ''); // remove the trailing &
			jQuery.each(q.split('&'), function() {
					var splitted = this.split('=');
					var key = splitted[0];
					var val = splitted[1];
					// convert numbers
					if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
					// convert booleans
					if (val == 'true') val = true;
					if (val == 'false') val = false;
					// ignore empty values
					if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0) r[key] = val;
			});
	}
	return r;
};


keywordCloud.init = function () {
	var params = $.query(location.search);
		if(typeof(params["pid"]) != 'undefined') {
			$("#inputProfileId").val(params["pid"]);
				
			}
}

keywordCloud.generate = function() {
	keywordCloud.words = {};
	keywordCloud.totalRevenue = 0;
	jQuery.each($("td.ga_keyword"), 
	function( i, nodesrc ){
			var cells, bounce, visits, newvisits;
			console.log("Procssing " + i + " " +  nodesrc.innerHTML + " " + this);
			node = nodesrc.innerHTML;
			node = node.replaceAll("http://","");
			node = node.replaceAll("/"," ");
			node = node.replaceAll("\\"," ");
			node = node.replaceAll("."," ");
			//node = node.replaceAll("."," ");
			node = node.replaceAll("."," ");
			node = node.replaceAll(","," ");
			node = node.replaceAll("- "," ");
			node = node.replaceAll(" -"," ");
			node = node.replaceAll("_"," ");
			//node = node.replaceAll(":"," ");
			//node = node.replaceAll("'"," ");
			node = node.replaceAll('"',' ');
			node = node.replaceAll('"',' ');
			node = node.replaceAll(')','');
			node = node.replaceAll('(','');
			node = node.replaceAll('!','');
			node = node.replaceAll('?','');
			node = node.replaceAll('>','');
			node = node.replaceAll('<','');
			node = node.replaceAll('[','');
			node = node.replaceAll(']','');
			node = node.replaceAll(';','');
			node = node.replaceAll('@','');
			var nodes = node.split(" ");
			cells = nodesrc.parentNode.getElementsByTagName("td"); 
			visits =  parseInt(cells.item(5).innerHTML);
			entrances = parseInt(cells.item(3).innerHTML);
			bouncerate =  parseInt(cells.item(6).innerHTML) / entrances;
			bounces = parseInt(cells.item(6).innerHTML);
			goalCompletionsAll =  parseInt(cells.item(9).innerHTML) ;
			goalStartsAll = parseInt(cells.item(8).innerHTML) ;
			revenue =  parseInt(cells.item(7).innerHTML) ;
			
			console.log("Visits is " + visits + " bounce " + bouncerate + "GA start " + goalStartsAll);
			for(var i =0;i<nodes.length;i++) {
				text = nodes[i];
				console.log("processing " + nodes[i]);
				//ga:keyword	ga:medium	ga:source	ga:entrances	ga:newVisits	ga:pageviews
				
				if( typeof(keywordCloud.ignore[text.toLowerCase()]) == 'undefined') {
					console.log("Non stop word " + keywordCloud.words[text.toLowerCase()]  );
					if(typeof(keywordCloud.words[text.toLowerCase()]) == 'undefined') {
						keywordCloud.words[text.toLowerCase()] = new Object; 
						keywordCloud.words[text.toLowerCase()].count=visits;
						keywordCloud.words[text.toLowerCase()].pretty=nodes[i];
						keywordCloud.words[text.toLowerCase()].terms=1;
						keywordCloud.words[text.toLowerCase()].termlist = [text.toLowerCase()];
						
						keywordCloud.words[text.toLowerCase()].bounceSum=bouncerate;
						keywordCloud.words[text.toLowerCase()].entranceSum=entrances;
						
						keywordCloud.words[text.toLowerCase()].goalCompletionsAll=goalCompletionsAll;
						keywordCloud.words[text.toLowerCase()].goalStartsAll=goalStartsAll;
						
						keywordCloud.words[text.toLowerCase()].bounceSum=bounces;
						keywordCloud.words[text.toLowerCase()].revenue=revenue;
												
						
						console.log("adding " + nodes[i]);
					} else {
							keywordCloud.words[text.toLowerCase()].revenue+=revenue;
	
							keywordCloud.words[text.toLowerCase()].count+= visits;
							keywordCloud.words[text.toLowerCase()].goalCompletionsAll+=goalCompletionsAll;
							keywordCloud.words[text.toLowerCase()].goalStartsAll+=goalStartsAll;
							keywordCloud.words[text.toLowerCase()].bounceSum+= bounces;
							keywordCloud.words[text.toLowerCase()].entranceSum+= entrances;
							
							keywordCloud.words[text.toLowerCase()].termlist.push(text.toLowerCase());

					}

				keywordCloud.words[text.toLowerCase()].terms++ 
				keywordCloud.totalRevenue += revenue;
			}
		
	}
	console.log(keywordCloud.words);
	
}) 
keywordCloud.render();
}

keywordCloud.byVisits = function(a,b) {
	return a.visits > b.visits;
}

keywordCloud.render = function() {
	var str = "";
	var word = false;
	var insertTo = $("#keywordCloud");
	insertTo.html(" ");
	console.log($("#metric").val());
	for(var i in  keywordCloud.words) {
		word = keywordCloud.words[i];
	
		opacity = 1- ((word.bounceSum/word.entranceSum) * 1.5) ;
		if(opacity < .2) opacity = .2;
		if($("#metric").val() == 'conversion' ) {
			console.log(word.goalCompletionsAll + " of " + word.goalStartsAll + " yields " + (word.goalCompletionsAll/word.goalStartsAll));
			if(word.goalCompletionsAll) {
				opacity = .5 + 2.5*(word.goalCompletionsAll/word.entranceSum);
			} else {
				opacity = .5
			}
		}
		if($("#metric").val() == 'revenue') {
			console.log("revenue " + word.revenue + " of " + keywordCloud.totalRevenue + " at " + (word.revenue/keywordCloud.totalRevenue) );
			opacity = .2 + (word.revenue/keywordCloud.totalRevenue)/1.2;
		}
		str += "<span style='vertical-align:middle;padding:8px;font-size:" + Math.log(word.count);
		str += "em;opacity:"+(.5+opacity/2) +"' id='w" + word.pretty + "'";
		str += " title='Across " + word.terms +  " terms: $" + word.revenue + " from " + word.count +  " visits, " +  Math.round(word.bounceSum/word.entranceSum*100)  + "% bouncing" + " and " + Math.round(word.goalCompletionsAll/word.goalStartsAll*100) + " % goal completion and " + Math.round(word.goalCompletionsAll/word.entranceSum*100) + "% overall goal conversion '" ;
		str+= ">" + word.pretty + " </span>";
		insertTo.append(str);
		str = '';
	}
	
}