var commentwidget_params = {
	widgetId: 10,
	userId: '',
	session: ''
}
var registrationUrl = 'http://pages.graziamagazine.it/people/account/registrazione';
var currentWidgetId = '';
var semaforo_post='verde';

$(document).ready(function(){
//	alert('COMPACT!');
	startWidgetComment();
});

function startWidgetComment()
{	
	setTimeout(
		function() 
		{	if(!document.getElementById('divformcomments'))
			{	startWidgetComment();}
			else
			{	initWidgetComment();}
		}
		, 250
	);
}


function initWidgetComment() {

	var cookieVals = getCookie('amerg_cookie');
	
	// 1. controllo se utente loggato o meno
	if (cookieVals!=null && cookieVals !=''){
		var cookie=cookieVals.split('*');
		commentwidget_params['userId'] = cookie[1];
	}else{
		var cookieCommenter = getCookie('commenter');
		if (cookieCommenter!=null && cookieCommenter !=''){
			$('.commentinome144').val(cookieCommenter);
		}
	}	
	if (commentwidget_params['userId'] != null && commentwidget_params['userId'] != ''){
			$('.commentinome144').parent().html('<div class="evecommentslabel">' + commentwidget_params['userId'] + '</div>');		
	}

	// 2. preparo funzione per INVIO Commento 
	$('.submit-commenti').click(function() {
		id = $(this).attr("id");
		var qIndex = id.indexOf('_',0);
		if (qIndex > 0) currentWidgetId = id.substring(qIndex + 1,id.length);
		
		sendComment(currentWidgetId); 
	});
	
}

function sendComment(wdgId) {
	
	var message = $('#evecommentsmessage_' + wdgId).val();
	if (message == '' || message == 'il tuo commento') {alert ('Non è consentito inviare un commento vuoto...');}
	else {
		if (commentwidget_params['userId'] != null && commentwidget_params['userId'] != ''){
			// UTENTE LOGATO
			commentwidget_params['userlogged'] = commentwidget_params['userId'];
			commentwidget_params['session'] = wdgId + '_' + commentwidget_params['userId'] + '_' + (new Date).getTime();
			commentwidget_params['message'] = message;
			commentwidget_params['item'] = $('#evecommentstype_' + wdgId).val() + '-' + wdgId;
			commentwidget_params['link'] = '' + window.location;
			commentwidget_params['guid'] = '' + window.location + '/' + wdgId + '/' + commentwidget_params['session'];
			//commentwidget_params['evecommentsclass'] = 'evecommentsregauthor';
			commentwidget_params['evecommentsclass'] = commentwidget_params['userId'];

			makePost(commentwidget_params,'',false);
			
		}else{
			var pseudo = $('#evecommentsusername_' + wdgId + ' input').val();

			if (pseudo == '') alert ('Non hai inserito il tuo username...');
			else{
				// UTENTE NON LOGATO
				var activityData = {key:'69a256025f66e4ce5d15c9dd7225d357'
								,activity: 'checkUserExist'
								,userId: escape(pseudo)};
			
				$.post("/service/utility/activity.php",activityData,function(resp){
					eval('var response=' + resp);

					if (response.success) {
						$('#evecommentsresponse_' + wdgId).html('Lo username che hai scelto è associato ad un utente registrato: registrati o scegli un altro username');
					}else{
						if (response.msg == ''){
							commentwidget_params['userId'] = pseudo;
							// UTENTE NON REGISTRATO
							commentwidget_params['usernotlogged'] = pseudo;
							commentwidget_params['session'] = wdgId + '_' + commentwidget_params['userId'] + '_' + (new Date).getTime();
							commentwidget_params['message'] = message;
							commentwidget_params['item'] = $('#evecommentstype_' + wdgId).val() + '-' + wdgId;
							commentwidget_params['link'] = '' + window.location;
							commentwidget_params['guid'] = '' + window.location + '/' + wdgId + '/' + commentwidget_params['session'];
							commentwidget_params['evecommentsclass'] = '';

							if (confirm('Lo username che hai scelto non esiste ancora, ti suggeriamo di iscriverti dopo aver inserito il tuo commento!')) {
								makePost(commentwidget_params,registrationUrl,true);
							}else{
								makePost(commentwidget_params,'',true);
							};							
						}else{
							alert('Server error durante invio del commento : ' + response.msg );
						}
					}
				});
			}
		}
	}
}
function makePost(data,landingpage,flCookie){
//alert('sono in makePost');
	if (semaforo_post=='verde') {
		semaforo_post='rosso';
		jQuery.ajax({
			type: 'POST',
			url: '/interfaces/API/dataPost.php',
			dataType: 'html',
			data: data,
			success: function (data, textStatus) {
				if (flCookie) {
					wCookie('commenter',commentwidget_params['userId'],1560);
				}
				if (landingpage == ''){
					window.location.reload();
				}else{
					if (parent!=null){
						//sono un iframe
						parent.window.location = landingpage;
					}
					else{
					    window.location = landingpage;
					}
				}
			},
			error: function (xhr, ajaxOptions, thrownError){
				alert('Server error durante chiamata a modulo Interfaces: ' + xhr.status );
			}
		});
	} else {
		alert('Azione già eseguita');
	}
}

function getSimpleUrl(){
	var url = '' + window.location;
	var qIndex = url.indexOf('?',0);
	if (qIndex > 0)
		url = url.substring(0,qIndex);
	return url;
}
function getCookie(NameOfCookie) {
	if (document.cookie.length > 0) {
		begin = document.cookie.indexOf(NameOfCookie+"=");
		if (begin != -1) {
			begin += NameOfCookie.length+1;
			end = document.cookie.indexOf(";", begin);
			if (end == -1) end = document.cookie.length;
			return unescape(document.cookie.substring(begin, end));
		}
	}
	return null;
}
function wCookie(nomeCookie,valoreCookie,durataCookie){
  var scadenza = new Date();
  var adesso = new Date();
  scadenza.setTime(adesso.getTime() + (parseInt(durataCookie) * 60000));
  document.cookie = nomeCookie + '=' + escape(valoreCookie) + '; expires=' + scadenza.toGMTString() + '; path=/; domain=.grazia.it';
}

var count_params = {userId: '', guid: '', activity: 'comments',	key:'69a256025f66e4ce5d15c9dd7225d357'}
var selectItemUrl = '/service/utility/activity.php?';	


function getCommentsList(id) {
	count_params['id'] = id;
	jQuery.ajax({
		type: 'POST',
		url: selectItemUrl,
		dataType: 'html',
		data: count_params,
		success: function (data, textStatus) {
		    var json_data = eval("("+data+")");
		    $('#commentslist').html(json_data["data"]);
		},
		error: function (xhr, ajaxOptions, thrownError){
			return '';
		}
	});	
}
