var Rec = new Object();

/* fields */
Rec.requestCalled = 0;
Rec.handlers = { 'mcl' : null , 'sim' : null };
Rec.handlers_random = { 'mcl' : true, 'sim' : false };
/* deprecated */
Rec.handler = null;
Rec.max_results = 5;


/* methods */
Rec.click = function(client) {

	var url = 'http://upsearch.uplexis.com.br/IDG/rec';
	
	/* get user */
	var user = Rec.getCookie('upl_rec_id');
	if (user == '' || user == null || user.substring(0,9) == 'undefined' ) {
		user = Rec.randomHex(32);
		Rec.setCookie('upl_rec_id', user, 30);
	}

	var referrer = window.location.href;

	var full_url =	url + '?' +
			'user=' + user + '&' +
			'client=' + client + '&' +
			'url=' + encodeURIComponent(referrer) + '&' +
			'rnd=' + Math.random() /* prevents caching */
			;
	Rec._sgajRequest(full_url);
}


Rec.setCookie = function(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+
	";path=/";
}


Rec.getCookie = function(c_name) {
	var current_cookies = document.cookie;
	
	if (current_cookies.length>0)
	{
		c_start=current_cookies.indexOf(c_name + "=");
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=current_cookies.indexOf(";",c_start);
			if (c_end==-1) c_end=current_cookies.length;
			return unescape(current_cookies.substring(c_start,c_end));
		}
	}
	return "";
}

Rec.randomHex = function(num_digits) {
	var result = '';
	var possible_chars = '0123456789abcdef';
	
	// compatibility test
	var rnum = Math.floor(Math.random() * possible_chars.length);
	var test_char = possible_chars.substring(rnum, rnum + 1);
	
	if (test_char == '' || test_char == null) {
		return Math.random();
	}
	// end of test
	
	for(var i = 0; i < num_digits; i++) {
		var rnum = Math.floor(Math.random() * possible_chars.length);
		var chosen = possible_chars.substring(rnum, rnum + 1);
		result = result + chosen
	}
	return result;
}

Rec.setMaxResults = function(new_max_results) {
	if (new_max_results >= 1 && new_max_results <= 10) {
		Rec.max_results = new_max_results;
	}
}

Rec.addHandler = function(type, handler_function, max_results) {
	if (! max_results) {
		max_results = 5;
	}
	Rec.handlers[type] = {"handler" : handler_function, "max_results" : max_results};
}

Rec.setHandler = function(handler_function) {
	Rec.handler = handler_function;
}

Rec._filter_results = function(method, links, max_results) {
	var result = [];
	var randomize = Rec.handlers_random[method];
	while(result.length < max_results && links.length > 0) {

		/* now, choose a link from this method */
		var chosen_link = 0;

		if (randomize) {
			var link_weight = [];
			var weight = 0;
			for(var j = 0; j < links.length; j++) {
				weight = weight + links[j].score;
				link_weight.push(weight);
			}
			
			var rnum = Math.random() * weight;
			for(var j = 0; j < link_weight.length; j++) {
				if (rnum < link_weight[j]) {
					chosen_link = j;
					break;
				}
			}
		} else {
			var max_weight = -1.0;
			for(var j = 0; j < links.length; j++) {
				var weight = links[j].score;
				if (weight > max_weight) {
					max_weight = weight;
					chosen_link = j;
				}
			}
		}
		var link = links[chosen_link];
		
		for(var i = 0; i < links.length; i++) {
			if (links[i].url == link.url) {
				links.splice(i,1);
			}
		}
		
		var link_method = link.method;
		
		if (link_method == "" || link_method == null) {
			link_method = method;
		}
		
		link.url = link.url + "#rec:" + link_method;
		//delete(link.score);
		result.push(link);
		
	}
	result = result.sort(
			function(left,right) { 
					if ( left.score >= right.score ) return -1;
					else return 1;
				} 
			);
	return result;
}

/* processa o json full e escolhe os links a devolver */
Rec.old_process = function(json) {
	var result = [];
	while(result.length < Rec.max_results) {
		var method_weight = [];
		var method_name = [];
		var weight = 0;
		for(var method in json) {
			method_name.push(method);
			//weight = weight + json[method].length;
			if (json[method].length > 0) {
				weight = weight + 1;
			}
			method_weight.push(weight);
		}
		if (weight == 0) {
			/* no methods to choose */
			break;
		}
		var rnum = Math.random() * weight;
		var chosen_method;
		for(var j = 0; j < method_weight.length; j++) {
			if (rnum < method_weight[j]) {
				chosen_method = method_name[j];
				break;
			}
		}
		
		/* now, choose a link from this method */
		var link_weight = [];
		weight = 0;
		for(var j = 0; j < json[chosen_method].length; j++) {
			weight = weight + json[chosen_method][j].score;
			link_weight.push(weight);
		}
		
		var rnum = Math.random() * weight;
		var chosen_link;
		for(var j = 0; j < link_weight.length; j++) {
			if (rnum < link_weight[j]) {
				chosen_link = j;
				break;
			}
		}
		var link = json[chosen_method][chosen_link];
		
		/* exclude link from all the other methods, to avoid repetition */
		for(var method in json) {
			for(var i = 0; i < json[method].length; i++) {
				if (json[method][i].url == link.url) {
					json[method].splice(i,1);
				}
			}
		}
		
		link.url = link.url + "#rec:" + chosen_method;
		delete(link.score);
		result.push(link);
		
		// json[chosen_method].splice(chosen_link,1); // already excluded above
	}
	
	Rec.handler(result);
}

Rec.process = function(json) {
	if ( Rec.handler != null ) {
		Rec.old_process(json);
		return;
	}
	
	for(var method in Rec.handlers) {
		if (Rec.handlers[method] != null) {
			var handler = Rec.handlers[method].handler;
			var max_results = Rec.handlers[method].max_results;
		
			var results = Rec._filter_results(method, json[method], max_results);
		
			handler(results);
		}
	}
}

Rec.defaultHandler = function(items, method_name) {
	var class_suffix = ''
	if (method_name) {
		class_suffix = '_' + method_name;
	}
	var div_main = document.getElementById('upl_rec_area' + class_suffix);
	if (div_main != undefined) {
		if (items.length == 0) {
			return;
		}
		var div_table = document.createElement("table");
		div_table.setAttribute('class', 'upl_rec_table' + class_suffix);
		var div_tbody = document.createElement("tbody");

		for(var pos = 0; pos < items.length; pos++) {
			var item = items[pos];
	
			var div_row = document.createElement("tr");
			div_row.setAttribute('class', 'upl_rec_row' + class_suffix);

			var div_cell = document.createElement("td");
			div_cell.setAttribute('class', 'upl_rec_cell' + class_suffix);

			var link = document.createElement("a");
			link.setAttribute('class', 'upl_rec_link' + class_suffix);
			link.setAttribute('href', item.url);
			link.setAttribute('title', item.score);
			
			var linkText = document.createTextNode(item.title);
			link.appendChild(linkText);

			div_cell.appendChild(link);
			
			div_row.appendChild(div_cell);
			
			div_tbody.appendChild(div_row);
		}
		div_table.appendChild(div_tbody);
		div_main.appendChild(div_table);
	}
}

Rec._sgajRequest = function(url) {
	var urlCaller = function() {
		if (!Rec.requestCalled) {
			Rec.requestCalled = 1;
			var requestScript=document.createElement("script");
			requestScript.src=url;
			var pageHead=document.getElementsByTagName('head')[0];
			pageHead.appendChild(requestScript);
		}
	};
	
	if (window.addEventListener) {
		window.addEventListener("load", urlCaller, false)
		window.addEventListener("DOMContentLoaded", urlCaller, false);
	} else if (window.attachEvent) { /*IE exclusive method for binding an event*/
		window.attachEvent("onload", urlCaller)
	} else if (document.getElementById) { /*support older modern browsers*/
		window.onload=urlCaller
	}
}

