function init()
{	
	jQuery.noConflict();
	WorkWeekView();
	getSessionsList();	
	
	//Deshabilitamos el doble click en todas las celdas
	jQuery("div.ms-acal-rootdiv table.ms-acal-detail tbody tr td").dblclick(function(){return false;});	
	
	//setTimeout(getSessionsList, 2000);	
	//setTimeout(eventAgendaSurvey, 100);	
}

function WorkWeekView()
{	
	//Función que nos permite eliminar columnas de una tabla dada su posición.
	jQuery.fn.removeCol = function(col){
	    // Make sure col has value
	    if(!col){ col = 1; }
	    jQuery('tr td:nth-child('+col+'), tr th:nth-child('+col+')', this).remove();	    
	    return this;
	};
	
	//Obtenemos el ancho completo de la tabla, antes de quitar las columnas de sábado y domingo.
	var tableWidth = jQuery("div.ms-acal-rootdiv table").width();
	//Obtenemos el ancho del th de cada tr.
	var thWidth = jQuery("div.ms-acal-rootdiv table tbody tr:first th").width();
	//Obtenemos el valor resultante de cada celda (td)
	var tdWidth = (tableWidth - thWidth - 6)/5;
	
	//Eliminamos las dos últimas columnas de la tabla (weekend)
	jQuery("div.ms-acal-rootdiv table.ms-acal-detail tbody").removeCol(7);
	jQuery("div.ms-acal-rootdiv table.ms-acal-detail tbody").removeCol(7);		
	
	//Quitamos la cabecera --> no se puede cambiar de fecha
	jQuery(".ms-acal-header table tbody tr td:nth-child(1)").hide();
	jQuery(".ms-acal-header table tbody tr td:nth-child(2)").hide();
	
	//Ajustamos el ancho y alto de cada celda de la tabla, después de eliminar las columnas.
	jQuery("div.ms-acal-rootdiv table.ms-acal-detail tbody tr td").width(tdWidth);
	jQuery("div.ms-acal-rootdiv table.ms-acal-detail tbody tr:gt(1) td").height(50);	
}	

function ModalSurveyGlobal()
{
	var options = {
	    url: '/madrid/2011/Lists/EncuestaDelSummit/NewForm.aspx',
		title: 'Encuesta Global Summit',
		allowMaximize: true,
		showClose: true,
		width: 800,
		height: 600,
		dialogReturnValueCallback: null
		};
		
	SP.UI.ModalDialog.showModalDialog(options);
}

function ModalSurvey(eventID)
{
	var options = {
	    url: '/madrid/2011/Lists/EncuestaSesion/NewForm.aspx?Codigo='+eventID,
		title: 'Encuesta Summit',
		allowMaximize: true,
		showClose: true,
		width: 800,
		height: 600,
		dialogReturnValueCallback: null
		};
		
	SP.UI.ModalDialog.showModalDialog(options);
}

function getSessionsList()
{
	var soapEnv = " \
        <soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:soap='http://schemas.microsoft.com/sharepoint/soap/'> \
           <soapenv:Body> \
              <soap:GetListItems> \
                 <soap:listName>Sesiones 2011</soap:listName> \
                 <soap:rowLimit>100</soap:rowLimit> \
              </soap:GetListItems> \
           </soapenv:Body> \
        </soapenv:Envelope>";       
       
       jQuery.ajax({
       		url: "/madrid/2011/_vti_bin/lists.asmx",
       		type:"POST",
       		dataType: "xml",
       		data: soapEnv,
       		async:true,
       		complete: function(xData, status){       			
       			eventAgendaSurvey(xData.responseXML);      			
       		},
       		contentType: "text/xml; charset=\"utf-8\""       
       });
}

function processResult(xData, status) 
{
	alert(status);
	jQuery("#divOutPut").text(xData.responseText);  
}

function getSessionID(list, sessionCode)
{	
	return jQuery(list).find("z\\:row[ows_Codigo='"+sessionCode+"']").attr('ows_ID');
}

function DoSurvey(list, sessionCode)
{	
	if (jQuery(list).find("z\\:row[ows_Codigo='"+sessionCode+"']").attr('ows_PublicarEncuesta') == 1) return true;
	else return false;
}

function eventAgendaSurvey(lista)
{	
	var sessionsList = lista;
	var eventCode;
	var eventID;	
	jQuery("div.ms-acal-rootdiv div.ms-acal-item div.ms-acal-ddiv a").each(function(){
			
		var anchorText = jQuery(this).text();
		eventCode = anchorText.substring(0, anchorText.indexOf(' '));
		eventID = getSessionID(sessionsList, eventCode);
		
		jQuery(this).parent().append("<div class='eventCalendarText'>"+ anchorText+"</div>");		
		
		//Comprobamos si el checkbox de "Publicar Encuesta" es 'true' para habilitar el enlace a hacer la encuesta.
		if (DoSurvey(sessionsList , eventCode))
		{
			//jQuery(this).parent().append("<a href='javascript:ModalSurvey("+eventID+");' class='eventCalendarText'><img src='/SiteCollectionImages/survey-image.png' class='eventCalendarImg' alt='icono de encuesta' title='Hacer encuesta'></a>");		
			
			jQuery(this).parent().append("<img onclick='javascript:ModalSurvey("+eventID+");' src='/SiteCollectionImages/survey-image.png' class='eventCalendarImg' alt='icono de encuesta' title='Hacer encuesta'>");						
			
			AlignSurveyIcon();			
		}
		
		//Habilitamos que se pueda borrar la sesión/evento de la lista de calendario
		EnableDeleteEvent(jQuery(this).parent().parent(), eventCode);
		

		//Eliminamos es la etiqueta <a>
		jQuery(this).remove();	
	});
	
	jQuery("div.ms-acal-rootdiv div.ms-acal-item").mousedown(function(){			
		return false;
	});	
	
	//Establecemos el color del evento, según el tipo que sea.
	SetColors();	
}

function EnableDeleteEvent(jObject, eventCode)
{	
	jQuery(jObject).each(function(){	
	
		//Despues, deshabilitamos el click y doble click
		jQuery(this).parent().click(function(){return false;});		
		jQuery(this).parent().dblclick(function(){return false;});
		
		//A continuación insertamos el icono de 'close window'
		jQuery(this).prepend("<div style='clear:both'><!-- --></div>");
		jQuery(this).prepend("<img src='/SiteCollectionImages/x_close_window.png' alt='Delete Session' title='Delete Session' class='XDeleteSessionstyle'></img>")
		
		//El último paso es establecer la funcionalidad al hacer click sobre el icono 'close window'
		jQuery('img.XDeleteSessionstyle', this).click(function(){		
			GetCurrenUser(eventCode);			
			jQuery(this).parent().parent().remove();			
		});
	});
}


function AlignSurveyIcon()
{
	jQuery("div.ms-acal-rootdiv div.ms-acal-item").each(function(){
		var currentWidth = jQuery(this).width();
		var currentHeight = jQuery(this).height();
		var deleteIconHeight = jQuery("img.XDeleteSessionstyle").height();
		var textHeight = jQuery("div.eventCalendarText:first", this).height();
		var imgWidth = jQuery("img.eventCalendarImg", this).width();
		var imgHeight = jQuery("img.eventCalendarImg", this).height();
		
		jQuery("img.eventCalendarImg", this).each(function(){
			jQuery(this).css("margin-left", currentWidth - 5 - imgWidth);
			jQuery(this).css("margin-top", currentHeight - 5 - imgHeight  - textHeight - deleteIconHeight);
		});
	});
}

function SetColors()
{	
	jQuery("div.ms-acal-rootdiv div.ms-acal-item").each(function(){			
		if (jQuery(this).text().indexOf('BIN-') >= 0){jQuery(this).addClass("BINEvent"); jQuery("div.eventCalendarText", this).css("color", "white");}
		else if (jQuery(this).text().indexOf('C\u0026B') >= 0){jQuery(this).addClass("CBEvent");}
		else if (jQuery(this).text().indexOf('REL-') >= 0){jQuery(this).addClass("RELEvent"); jQuery("div.eventCalendarText", this).css("color", "white");}
	});	
}

function GetCurrenUser(eventCode)
{	
	//Retrieve the clientContext
	var clientContext = SP.ClientContext.get_current();
	
	//Retrieve the current website
	var oWeb = clientContext.get_web();

	//Retrieve the current user
	this.currentUser = oWeb.get_currentUser();
	
	//Loading the user
	clientContext.load(currentUser);
	
	//Finally execute the operation
	//pass to it a 2 callBack methods OnSucceed and OnFailure	
	var thisclass = this;
	var func = function(){ thisclass.GetCurrenUserSuccess(eventCode); };	
	clientContext.executeQueryAsync(Function.createDelegate(this, func), Function.createDelegate(this,this.GetCurrenUserFail));
}

function GetCurrenUserSuccess(eventCode) 
{	
	DeleteSession(eventCode, currentUser.get_title());
}

function GetCurrenUserFail(sender, args) 
{
	alert('Se ha producido un error: ' + args.get_message() + '\n' + args.get_stackTrace());
}

function DeleteSession(sessionCode, author)
{	
	//Retrieve the clientContext
	var clientContext = SP.ClientContext.get_current();
	
	//Retrieve the current website
	var oWeb = clientContext.get_web();	
	
	//Retrieve the lists
	var oList = oWeb.get_lists().getByTitle('CalendarioAgendaPersonal');	
	
	//Build the caml query
	var query = '<View Scope=\'RecursiveAll\'>'+
	                '<Query>'+	                    
                    	'<Where>'+
                    		'<And>'+                    	
			                    '<BeginsWith>'+
			                        '<FieldRef Name=\'Title\'/>' +
			                        '<Value Type=\'Text\'>'+ sessionCode +'</Value>'+
			                    '</BeginsWith>'+
			                    '<Eq>'+
			                        '<FieldRef Name=\'Author\'/>' +
			                        '<Value Type=\'Lookup\'>'+ author +'</Value>'+
			                    '</Eq>'+
		                    '</And>'+	                    
		                '</Where>'+			            
	                '</Query>'+
                '</View>';
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(query);
    
    //Retrieve the list items with the caml filter
	this.items = oList.getItems(camlQuery);	
	
	clientContext.load(this.items, 'Include(Title, ID, Author)');	
	clientContext.executeQueryAsync(Function.createDelegate(this, this.DeleteSessionSucces), Function.createDelegate(this, this.DeleteSessionFail));
}

function DeleteSessionSucces()
{	
	//if (this.items.get_count() == 1)
	//{		
		var listEnumerator = this.items.getEnumerator();
	    while (listEnumerator.moveNext()) 
	    {	    	
	        var item = listEnumerator.get_current();
	        var context = new SP.ClientContext.get_current();
    		var web = context.get_web();
    		item.deleteObject();
	        context.executeQueryAsync(Function.createDelegate(this, this.DeleteObjectSuccess), Function.createDelegate(this, this.DeleteObjectFailed));	        
	    }	
	//}
}

function DeleteSessionFail(sender, args)
{
	
	alert('failed. Message:' + args.get_message());
}

function DeleteObjectSuccess()
{	
	alert('Evento borrado con exito.');
}

function DeleteObjectFailed(sender, args)
{
	alert('Error al borrar evento. Message:' + args.get_message());
}

function AddEventToAgenda(id, code, level, title, description, eventStartDate, eventEndDate)
{
	eventStartDate= GetTimeMinusTwoHours(eventStartDate);
	eventEndDate = GetTimeMinusTwoHours(eventEndDate);

	//Retrieve the clientContext
	var clientContext = SP.ClientContext.get_current();
	
	//Retrieve the current website
	var oWeb = clientContext.get_web();
	
	//Retrieve the lists
	var oList = oWeb.get_lists().getByTitle('CalendarioAgendaPersonal');
	
	//Create new IteamCreationInformation
	var itemCreationInfo = new SP.ListItemCreationInformation();
	
	//the addItem takes the itemCreationInformation object
	//and returns the listItem
	var listItem = oList.addItem(itemCreationInfo);
	
	//Set the sesion lookup
	listItem.set_item("Sesion", id+';#'+title);
	
	//Set the title of the list Item
	listItem.set_item("Title", code+' '+title+' ('+level+')');
	
	//Set the description of the list Item
	listItem.set_item("Description", description);
	
	//Set the start date of the list Item
	listItem.set_item("EventDate", eventStartDate);	
	
	//Set the end date of the list Item
	listItem.set_item("EndDate", eventEndDate);
	
	//Call Update the listItem
	listItem.update();
	
	//Finally execute the operation
	//pass to it a 2 callBack methods OnSucceed and OnFailure
	clientContext.executeQueryAsync(Function.createDelegate(this,this.AddEventToAgendaSucceeded), Function.createDelegate(this,this.AddEventToAgendaFailed));
}

function GetTimeMinusTwoHours(str)
{
	var date = str.substring(0, str.indexOf(' '));
	var time = str.substring(str.indexOf(' ') + 1);
	var hour = time.substring(0, time.indexOf(':'));
	var minuAndSecs = time.substring(time.indexOf(':'));
	
	return (date+' '+(hour-2)+minuAndSecs);
}

function AddEventToAgendaSucceeded() {alert("Evento insertado satisfactoriamente.");}
function AddEventToAgendaFailed(sender,args) {alert("Error al insertar evento.");}

function AuxViewList()
{
	var soapEnv = " \
        <soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:soap='http://schemas.microsoft.com/sharepoint/soap/'> \
           <soapenv:Body> \
              <soap:GetListItems> \
                 <soap:listName>CalendarioAgendaPersonal</soap:listName> \
              </soap:GetListItems> \
           </soapenv:Body> \
        </soapenv:Envelope>";       
       
       jQuery.ajax({
       		url: "/madrid/2011/_vti_bin/lists.asmx",
       		type:"POST",
       		dataType: "xml",
       		data: soapEnv,
       		complete: function(xData, status){
       			jQuery("#divOutPut").text(xData.responseText);      			
       		},
       		contentType: "text/xml; charset=\"utf-8\""       
       });
}

