// -----------------------------------------------------------------------------
// REC.JS - Tracking verso il sistema Reccomender
// -----------------------------------------------------------------------------

if (window.console == undefined) { window.console = {log:function(){}}; }


var recProperties = {
	enabled  : true,
	baseUrl  : 'http://recs.virgilio.it',
	trackUrl : '/fe/Service/track/send?channel={channel}&item={item}&action={action}',
	// Viene solotracciata la votazione
	voteGalleryUrl  : '/fe/Service/track/send?channel={category}&item={item}&action={vote}',
	// Viene registrato il voto - Chiamata per passare alla piattaforma voti
	recordingVoteUrl  : '/fe/Service/user/vote/{category}/{item}?vote={vote}&a_tag_istat={a_tag_istat}&a_tag_from={a_tag_from}&src=virgilio&ckexp=oneshot',
  // Viene tracciata la visita ad un elemento (es: il play di un video)
	viewUrl  : '/fe/Service/user/virgilio/view/{item}?src={category}',	
	// Viene tracciata la visita ad un elemento (es: il play di un video)
	voteUrl  : '/fe/Service/user/virgilio/vote/{item}?src={category}&vote={vote}'
};

/*function loadUser(userId) {
	console.log("userId: " + userId);
	return userId;
}*/

function getFunctionName(func) {
	if (typeof func == "function" || typeof func == "object") {
		var fName = ("" + func).match(/function\s*([\w\$]*)\s*\(/);
	}
	if (fName !== null) {
		return fName[1];
	}
}

function rndNumber() {
    return Math.floor(Math.random() * 100000);
}

function RecServiceDefaultCallback (result) {
	console.log (result);
}

function RecService (divContainer, format, objects) {
	if(!matrixObject.recInstance)
		matrixObject.recInstance = this;

	this.format = format;
	this.objects = objects;
	this.divContainer = divContainer;
	this.offset = 0;

	// Callback Success
	this.success = RecServiceDefaultCallback;

	// Callback Error
	this.error = RecServiceDefaultCallback;

	// URL del servizio
	this.url = '';

	this.trackItemRequest = function (channel,item,action) {
		console.log ('[trackItemRequest] Start');

		if (recProperties.enabled) {

			if(channel == '' && item == '') {
				channel = matrixObject.recChannel;
				item = matrixObject.itemId;
			}

			this.url = recProperties.trackUrl;
			this.addPropertyToUrl('channel',channel);
			this.addPropertyToUrl('item',item);
			this.addPropertyToUrl('action',action);

			if(channel != undefined && item != undefined) {
				this.doRequest ();
			}

		}

		console.log ('[trackItemRequest] End');
	}

	this.voteItemRequest = function (category,item,vote,istat,from,recordingVote) {
		console.log ('[voteItemRequest] Start');

		if (recProperties.enabled) {
		  if (recordingVote) {
  			this.url = recProperties.recordingVoteUrl;
  			this.addPropertyToUrl('category',category);
  			this.addPropertyToUrl('item',item);
  			this.addPropertyToUrl('vote',vote);		  
		    this.addPropertyToUrl('src','virgilio');
		    this.addPropertyToUrl('a_tag_istat',istat);
		  	this.addPropertyToUrl('a_tag_from',from);
		  	this.addPropertyToUrl('ckexp','oneshot');
		  } else if (category=='video') {	
  			this.url = recProperties.voteUrl;
  			this.addPropertyToUrl('category',category);
  			this.addPropertyToUrl('item',item);
  			this.addPropertyToUrl('vote',vote);		  	
  		} else {
  			this.url = recProperties.voteGalleryUrl;
  			this.addPropertyToUrl('category',category);
  			this.addPropertyToUrl('item',item);
  			this.addPropertyToUrl('vote',vote);
  		}
			
			this.doRequest ();
		}

		console.log ('[voteItemRequest] End');
	}
	
	this.viewItemRequest = function (category,item) {
		console.log ('[viewItemRequest] Start');

		if (recProperties.enabled) {
  		this.url = recProperties.viewUrl;
  		this.addPropertyToUrl('category',category);
  		this.addPropertyToUrl('item',item);
			this.doRequest ();
		}

		console.log ('[viewItemRequest] End');
	}

	this.doRequest = function () {
		console.log ("[doRequest] Start");

		// Aggiunta di un numero random per evitare caching
		var url = recProperties.baseUrl+this.url+'&rnd='+rndNumber()+'&cb='+getFunctionName(this.success);
		console.log (url);

		$.ajax({
			type: 'GET',
			dataType: 'script',
			url: url,
			error: this.error,
			async:true
		});

		console.log ("[doRequest] End");
	}

	//
	this.addPropertyToUrl = function (name,value) {
		this.url = this.url.replace('{'+name+'}',value);
	}

	this.loadRecommendationBox = function(indice) {
		if(!matrixObject.firstCall) {
			matrixObject.firstCall = true;
			var html = '';
			var tpl = (matrixObject.template)? matrixObject.template: 'tpl1';
			var myObj = this.objects;
			var offset = this.offset;

			var start = (!isNaN(indice))? indice: 0;
			var end = (!isNaN(indice))? parseInt(indice)+1: myObj.length;
			for(i=start; i<end; i++) {
				loadRecBox(myObj, i, this.divContainer, this.format, offset, tpl, indice);
			}
		}
	}

	this.loadCustomRecommendationBox = function(indice) {
		var offset = this.offset*3;
		loadCustomRecBox(this.objects, this.divContainer, this.format, offset, indice);
	}

	$.fn.truncBox = function(options) {
		//set default options
		var defaults = {
			limit: 100
		};

		//call in the default otions
		var options = $.extend(defaults, options);

		//act upon the element that is passed into the design
		return this.each(function(i) {
			//check length of text to what out maximum is
			if($(this).text().length > defaults.limit) {
				//console.log("testo: " + $(this).html());
				var box = $(this).html();
				//$(this).html(box.substr(0,box.indexOf("</span>")+7) + box.substr(box.indexOf("</span>")+7,defaults.limit)).append("...");
				$(this).html(box.substr(0,defaults.limit)).append("...");
			}
		});
	};

	this.seeMoreItems = function() {
		this.offset++;
		var tpl = (matrixObject.template)? matrixObject.template: 'tpl1'
		$.each($("." + tpl + " > div.box"), function (index, item) {
			var indice = parseInt(matrixObject.recInstance.objects[index].offset)+1;
			var id = $(".recBox_" + index).get(0).id;
			var myId = id.substring(0, id.indexOf("_list"));
			if($("#" + id + " > div#item_" + indice).length != 0) {
				$("#" + myId).html($("#" + id + " > #item_" + indice).html());
				matrixObject.recInstance.objects[index].setOffset(indice);
				resizeBox(0, myId);
			} else {
				matrixObject.firstCall = false;
				matrixObject.recInstance.objects[index].setOffset(1);
				matrixObject.recInstance.loadRecommendationBox(index);
			}
		});

		//biTrack(matrixObject.recInstance.objects[0].recommandationType, 0);
		loadRecBI();

		var advList = ['adv7','adv_skin','adv2'];
		new AdvObject(advList).reloadADV();
		new AdvObject(advList).reloadGA();
	}

	this.seeMoreCustomItems = function() {
		this.offset++;
		var idx = (matrixObject.recInstance.objects[0].offset == 1)? 3: 3*matrixObject.recInstance.objects[0].offset;
		if($("#itemContainer > ul > li:eq(" + parseInt(idx+2) + ")").length != 0) {
			var indice = parseInt(matrixObject.recInstance.objects[0].offset)+1;
			if(document.location.host == 'singring.virgilio.it') {
				/*if($("#" + this.divContainer + " > .contenutobox > .autoPadDiv").length) {
					$("#" + this.divContainer + " > .contenutobox > .autoPadDiv > ul > li:eq(0)").html($("#itemContainer > ul > li:eq(" + parseInt(idx) + ")").html());
					$("#" + this.divContainer + " > .contenutobox > .autoPadDiv > ul > li:eq(1)").html($("#itemContainer > ul > li:eq(" + parseInt(idx+1) + ")").html());
					$("#" + this.divContainer + " > .contenutobox > .autoPadDiv > ul > li:eq(2)").html($("#itemContainer > ul > li:eq(" + parseInt(idx+2) + ")").html());
				} else {
					$("#" + this.divContainer + " > .contenutobox > ul > li:eq(0)").html($("#itemContainer > ul > li:eq(" + parseInt(idx) + ")").html());
					$("#" + this.divContainer + " > .contenutobox > ul > li:eq(1)").html($("#itemContainer > ul > li:eq(" + parseInt(idx+1) + ")").html());
					$("#" + this.divContainer + " > .contenutobox > ul > li:eq(2)").html($("#itemContainer > ul > li:eq(" + parseInt(idx+2) + ")").html());
				}*/

				$("#sing1").html($("#itemContainer > ul > li:eq(" + parseInt(idx) + ")").html());
				$("#sing2").html($("#itemContainer > ul > li:eq(" + parseInt(idx+1) + ")").html());
				$("#sing3").html($("#itemContainer > ul > li:eq(" + parseInt(idx+2) + ")").html());

			} else {
				$("#" + this.divContainer + " > ul > li:eq(0)").html($("#itemContainer > ul > li:eq(" + parseInt(idx) + ")").html());
				$("#" + this.divContainer + " > ul > li:eq(1)").html($("#itemContainer > ul > li:eq(" + parseInt(idx+1) + ")").html());
				$("#" + this.divContainer + " > ul > li:eq(2)").html($("#itemContainer > ul > li:eq(" + parseInt(idx+2) + ")").html());
			}
			matrixObject.recInstance.objects[0].setOffset(indice);
		} else {
			matrixObject.recInstance.objects[0].setOffset(1);
			matrixObject.recInstance.loadCustomRecommendationBox(idx);
		}

		//biTrack(matrixObject.recInstance.objects[0].recommandationType, 0);
		loadRecBI();

		var advList = ['adv7','adv_skin','adv2'];
		new AdvObject(advList).reloadADV();
		new AdvObject(advList).reloadGA();
	}

}

function loadRecBox(_myObj, _i, _divContainer, _format, _offset, _tpl, _indice) {
		var i = _i;
		var myObj = _myObj;
		var serviceUrl = (myObj[i].recommandationType == 'i2i')? '/tech-utility/recs/rec-i2i.jsp': '/tech-utility/recs/rec-i2u.jsp';
		var itemId = myObj[i].itemId;
		var entity = myObj[i].entity;
		var recType = myObj[i].recommandationType
		var container = _divContainer;
		var html = '';
		$.ajax({
			type: "GET",
			timeout: 6000,
			dataType : _format,
			url: serviceUrl,
			data: "id=" + itemId + "&type=" + recType + "&entity=" + entity + "&offset=" + _offset + "&template=" + _tpl + "&recData=" + matrixObject.userData,
			success: function(data) {
				var result = (data != "")? data: $("#tappo:eq(0) > div:eq(" + i + ")").html();
				if(!isNaN(_indice)) {
					//var itemBox = (i == 0)? result.replace("box", "box primo"): result;
					var itemBox = result;
					html = '';

					$("#" + entity + "_list").empty();
					$("#" + entity + "_list").html(itemBox);

					if(i != 0)
						$("#" + entity + "_list > div > div.baloon").remove();
					else
						$("#" + entity + "_list > div").addClass("primo");

					html += $("#" + entity + "_list > :eq(0)").html();

					$("#" + entity).empty();
					$("#" + entity).html(html);

					if($("#" + entity + "_list > div#errore").length) {
						html = $("#" + entity + "_list > div#errore").text();
						end = 0;
						$("#" + container).hide();
					}
					resizeBox(0);
				} else {
					var itemBox = '<div id="' + entity + '_list" style="display:none" class="recBox_' + i + '">' + result + '</div>';
					$("#itemContainer").append(itemBox);

					if($("#itemContainer > div:hidden").length == 3) {
						var html = '';

						for(var index=0; index<3; index++) {
							var id = $(".recBox_" + index).get(0).id;
							var myId = id.substring(0, id.indexOf("_list"));
							var first = (index == 0)? ' primo': '';
							var dft = ($(".recBox_" + index + " > div:eq(0)").is('.default'))? ' default': '';
							var myClass = 'box' + first + dft;

							if(index != 0)
								$(".recBox_" + index + " > div > div.baloon").remove();
							else
								$(".recBox_" + index + " > div").addClass("primo");

							if(_tpl == 'tpl1') {
								$("#" + container + " > ." + _tpl).append('<div class="' + myClass + '" id="' + myId + '">' + $(".recBox_" + index + " > div:eq(0)").html() + '</div>');
								if(index == 2)
									$("#" + container + " > ." + _tpl).append('<div class="clear"></div>');
							} else
								$("#" + container + " > ." + _tpl + " > .refresh").before('<div class="' + myClass + '" id="' + myId + '">' + $(".recBox_" + index + " > div:eq(0)").html() + '</div>');
						}

						if(document.location.host == 'donne.virgilio.it' || document.location.host == 'gossip.virgilio.it') {
							
							if($("#" + container + " > div .default").length > 1)
								$("#" + container + " > div .testata").text("I pił popolari");
							else if(myObj[0].recommandationType == 'i2i')
								$("#" + container + " > div .testata").text("Chi ha visto questo ha visto anche");
							
						} else {
						
							if($("#" + container + " > div .default").length)
								$("#" + container + " > div .testata").text("I pił popolari");
							else if(myObj[0].recommandationType == 'i2i')
								$("#" + container + " > div .testata").text("Chi ha visto questo ha visto anche");
						}

						if(!$("#errore").length) {
							$("#" + container).show();
							resizeBox(0);
							//Se il box viene visualizzato eseguiamo l'impression
							//if(isNaN(_indice))
								//biTrack(myObj[0].recommandationType, 0);

							$(document).ready(function() {
								loadRecBI();
							});
						}

					}
				}
			}
		});
}

function loadCustomRecBox(_myObj, _divContainer, _format, _offset, _indice) {
	var myObj = _myObj;
	var serviceUrl = (myObj[0].recommandationType == 'i2i')? '/tech-utility/recs/rec-i2i.jsp': '/tech-utility/recs/rec-i2u.jsp';
	var itemId = myObj[0].itemId;
	var entity = myObj[0].entity;
	var recType = myObj[0].recommandationType;
	var templateXsl = myObj[0].templateXsl;
	var container = _divContainer;

	$.ajax({
		type: "GET",
		timeout: 3000,
		dataType : _format,
		url: serviceUrl,
		data: "id=" + itemId + "&type=" + recType + "&entity=" + entity + "&offset=" + _offset + "&xsl=" + templateXsl + "&numItem=9",
		success: function(data) {
			if(isNaN(_indice)) {
				$("#itemContainer").html(data);
				if($("#itemContainer > ul > li").length >= 3) {
					var dft = ($("#itemContainer > ul > li:eq(0)").is(".default"))? 'class="default"': '';
					if(document.location.host == 'singring.virgilio.it') {
						$("#" + container + " > .contenutobox > ul").append("<li " + dft + " id=\"sing1\" \">" + $("#itemContainer > ul > li:eq(0)").html() + "</li>");
						$("#" + container + " > .contenutobox > ul").append("<li " + dft + " id=\"sing2\">" + $("#itemContainer > ul > li:eq(1)").html() + "</li>");
						$("#" + container + " > .contenutobox > ul").append("<li " + dft + " id=\"sing3\">" + $("#itemContainer > ul > li:eq(2)").html() + "</li>");
						
						if($("#itemContainer > ul > li:eq(0)").is(".default"))
							//$("#" + container + " > h4").text("I pił popolari");
							console.log("cambiare testata");
					} else {
						$("#" + container + " > ul").append("<li " + dft + ">" + $("#itemContainer > ul > li:eq(0)").html() + "</li>");
						$("#" + container + " > ul").append("<li " + dft + ">" + $("#itemContainer > ul > li:eq(1)").html() + "</li>");
						$("#" + container + " > ul").append("<li " + dft + ">" + $("#itemContainer > ul > li:eq(2)").html() + "</li>");
						if($("#itemContainer > ul > li:eq(0)").is(".default"))
							//$("#" + container + " > h4").text("I pił popolari");
							console.log("cambiare testata");
					}

					if(!$("#errore").length) {
						$("#" + container).show();
						//biTrack(myObj[0].recommandationType, 0);
						loadRecBI();
						$(document).ready(function() {
							loadRecBI();
						});
					}
				}
			} else {
				$("#itemContainer").empty();
				$("#itemContainer").html(data);

				if($("#itemContainer > ul > li").length < 3) {
					//matrixObject.recInstance.loadCustomRecommendationBox(0);
					matrixObject.recInstance.seeMoreCustomItems();
				} else {
					if(document.location.host == 'singring.virgilio.it') {
						/*
							$("#" + container + " > .contenutobox > ul > li:eq(0)").html($("#itemContainer > ul > li:eq(0)").html());
							$("#" + container + " > .contenutobox > ul > li:eq(1)").html($("#itemContainer > ul > li:eq(1)").html());
							$("#" + container + " > .contenutobox > ul > li:eq(2)").html($("#itemContainer > ul > li:eq(2)").html());
							FIX PER IE: problemi con il selettore per via di un div creato automaticamente da IE  - introduciamo gli ID sui LI
						*/
						$("li#sing1").html($("#itemContainer > ul > li:eq(0)").html());
						$("li#sing2").html($("#itemContainer > ul > li:eq(1)").html());
						$("li#sing3").html($("#itemContainer > ul > li:eq(2)").html());
					} else {
						$("#" + container + " > ul > li:eq(0)").html($("#itemContainer > ul > li:eq(0)").html());
						$("#" + container + " > ul > li:eq(1)").html($("#itemContainer > ul > li:eq(1)").html());
						$("#" + container + " > ul > li:eq(2)").html($("#itemContainer > ul > li:eq(2)").html());
					}
				}
			}
		}
	});
}

function resizeBox(count, id) {
	if(!id) {
		$.each($("#recommendation > div .box"), function (index, item) {
			if($("#" + item.id + " > p").height() > 55 && parseInt(count) <= 5) {
				count++;
				if($("#" + item.id + " > p > a:eq(1) > span:eq(1)").text().length != 0) {
					var size = $("#" + item.id + " > p > a:eq(1) > span:eq(1)").text().length - 8;
					$("#" + item.id + " > p > a:eq(1) > span:eq(1)").truncBox({limit: size});
				} else {
					var size = $("#" + item.id + " > p > a:eq(1) > span:eq(0)").text().length - 7;
					$("#" + item.id + " > p > a:eq(1) > span:eq(0)").truncBox({limit: size});
				}

				var f = "resizeBox(" + count + ", '" + item.id + "')";
				setTimeout(f, 100);
			}
		});

	} else {
		if($("#" + id + " > p").height() > 55 && parseInt(count) <= 5) {
			count++;

			if($("#" + id + " > p > a:eq(1) > span:eq(1)").text().length != 0) {
				var size = $("#" + id + " > p > a:eq(1) > span:eq(1)").text().length - 8;
				$("#" + id + " > p > a:eq(1) > span:eq(1)").truncBox({limit: size});
			} else {
				var size = $("#" + id + " > p > a:eq(1) > span:eq(0)").text().length - 7;
				$("#" + id + " > p > a:eq(1) > span:eq(0)").truncBox({limit: size});
			}
			var f = "resizeBox(" + count + ", '" + id + "')";
			setTimeout(f, 100);
		}
	}
}

RecService.loadUser = function () {
	$.ajax({
			dataType:"jsonp",
			jsonp:"cb",
			url:"http://recs.virgilio.it/fe/Service/user/rawValue",
			async : false,
			success:function(recData){
				matrixObject.userData = encodeURIComponent(recData);
				//console.log("utente1: " + matrixObject.userData);
			}
		});
}

function RecommendationItem() {

	// karaoke, artist etc
	this.entity = '';
	// i2i,i2u - default -> i2i
	this.recommandationType = 'i2i';
	// Only for i2i type. Ex: MA_pink-floyd
	this.itemId = '';
	this.offset = 1;
	//template xsl custom
	this.templateXsl = '';

	this.setEntity = function(entity) {
		this.entity = entity;
	}

	this.setRecommendationType = function(type) {
		this.recommandationType = type;
	}

	this.setItemId = function(id) {
		this.itemId = id;
	}

	this.setOffset = function(offset) {
		this.offset = offset;
	}

	this.setTemplateXsl = function(templateXsl) {
		this.templateXsl = templateXsl;
	}

}

function loadPlaceHolder(entity, img) {
	if(entity.toLowerCase() == 'artista' || entity.toLowerCase() == 'karaoke' || entity.toLowerCase() == 'testo')
		img.src = "http://singring.virgilio.it/images/placeholder/98x98.jpg";
	else if(entity.toLowerCase() == 'auto')
		img.src = "http://auto-moto.virgilio.it/images/placeholder/auto/200x150.png";
	else if(entity.toLowerCase() == 'moto')
		img.src = "http://auto-moto.virgilio.it/images/placeholder/moto/200x150.png";
	else if(entity.toLowerCase() == 'film' || entity.toLowerCase() == 'homevideo')
		img.src = "http://s3.amazonaws.com/virgilio/images/defhpposter.jpg";
	img.onerror = '';
}


