﻿/***************************************************************************************************************************************
*    Emanuele De Cupis 11/11/2008
*
*    Gestisce la possibilità di un utente di segnalare un documento come preferito
*    
*    Requisiti: 
*        jquery.js
*        
*    Parametri:
*        var user = [id_utente] >> id dell'utente loggato
*        var show_add = "Aggiungi al promemoria" >> html da visualizzare nel link per aggiungere un promemoria
*        var show_remove = "Elimina dal promemoria"  >> html da visualizzare nel link per eliminare un promemoria
*        var show_error = "errore"  >> html da visualizzare nel link in caso di errore
*        var show_default = ""  >> html da visualizzare nel link come default (es: non loggato)
*        var loader_img = "/immagini/loader.gif" >> path dell'immagine da visualizzare durante l'elaborazione dei dati
*
*    Html:
*        <a href="#" class="setPreferiti" id="p[id_documento]"></a> - dove [id_documento] è l'id del documento da annotare
*
*
***************************************************************************************************************************************/

$.editable.addInputType('notes', {
	element : function(settings, original) {
		var textarea = $('<textarea>').css({"border": "1px solid #DDDDDD"});
		if (settings.rows) {
			textarea.attr('rows', settings.rows);
		} else {
			textarea.height(settings.height);
		}
		if (settings.cols) {
			textarea.attr('cols', settings.cols);
		} else {
			textarea.width(settings.width);
		}
		$(this).append(textarea);
		return(textarea);
	},
	content : function(string, settings, original) { 
		$('textarea', this).text(string.replace(/(?:<br>|<BR>)/g, '\r'));
	},
	plugin : function(settings, original) {
		if (!$.browser.msie) {
			$('textarea', this).autogrow(settings.autogrow);
		} else {
		    $('textarea', this).height(80);
		    $('textarea', this).css({"overflow-y": "scroll"});
			return false
		}
	}
});

var preferiti = function(){
        return {    		
		    edit_note: function(obj, doc) {
				if (obj.editable != undefined) {
				    //var params = sn.getparams($("#note .editbox").attr("id"))

				    obj.editable(
    				
					    function(value, settings) {
						    $.post(
							    "/handlers/preferiti.ashx", 
							    { a:4, u: user, n: value, d: doc},
							    function(data) {
								    if (parseInt(data)==0) {
									    alert("Si è verificato un errore nell'elaborazione...")
								    }
							    }
						    );
    						
						    if(window.console) {
							    console.log(value);
						    }
							//patch: se c'è un link di bookmark?
								$("#p" + doc).each(function(i){
									$(this).html(show_remove)
								})
						    return value.replace(/(?:\n\r|\n|\r)/g, '<br>');
					    },
					    {
						    indicator : "...", 
						    cancel : 'Annulla',
							del    : '<button type="reset">Cancella</button>',
						    submit : 'OK',
						    type      : 'notes',
						    name 	  : 'notetext',
						    placeholder   : 'Clicca qui per inserire una nota...',
						    cssclass  : "editable",
						    onblur    : 'cancel' ,
							callback  : function(value, settings){
											var doc = $(this).parent().attr("id").slice(1)
											var v = $.trim(value).length + ""
											if(v > 0){
												var obj = "#n" + doc
												//alert(obj + doc)												
												preferiti.delete_note(obj, doc)
											} else {
												if($("#x" + doc).length > 0){
													$("#x" + doc).remove()
												}												
											}
										}
								
							
						    /*,
						    callback  : function(value, settings) {
							    $(this).html(value.replace(/(?:\n\r|\n|\r)/g, '<br>'));
						    }*/
					    }
				    );
			    }
		    },
			
			delete_note: function(obj, doc){
				obj = $(obj)
				
					//alert("?")
				if($("#x" + doc).length <= 0){
					//alert("!")
					obj.find(".title").append(" <a href='#' title='Elimina nota' class='delNota' id='x" + doc + "'> <em> - elimina</em> </a>")
				}
				$("#x" + doc).click(function() {
					$(this).html("<img src='" +  loader_img  + "' />")
					
						obj.find(".note_text").html("")
						$.post(
							"/handlers/preferiti.ashx", 
							{ a:4, u: user, n: "", d: doc},
							function(data) {
								if (parseInt(data)==0) {
									alert("Si è verificato un errore nell'elaborazione...")
								}
							}
						);
						preferiti.edit_note(obj.find(".note_text"), doc);
						$(this).remove()
						return false;
				});
			},
			
			handle_events: function() {					
				$(".note_prom .editbox").each(function(i) {
					var obj = $(this)					
					var title = obj.attr("title")
					var doc = obj.attr("id").slice(1)
						$(".note_prom").show();
						obj.append("<div class='title'>" + title + "</div>");
						$.get(
						    "/handlers/preferiti.ashx",
						    {u: user, d: doc, a:3},
							function(data) {
								data = $.trim(data)
								if(data.length > 0){						
									preferiti.delete_note("#n" + doc,doc)
									data = data.replace(/(?:\n\r|\n|\r)/g, '<br>')
								}
								obj.append("<div class='note_text'>" + data + "</div>")
								preferiti.edit_note(obj.find(".note_text"), doc);
								
							});
				});
				
				
				var buffer = new Array();
				$(".setPreferiti").each(function(i){
                var link = $(this)
                link.html("<img src='" +  loader_img  + "' />")
                var doc = this.id.slice(1);
                if(user > 0){
					if($.inArray(doc, buffer) < 0){
						//lo carico la prima volta
						buffer[buffer.length] = doc
						
						$.get("/handlers/Preferiti.ashx", {d: doc, u: user, a: 0}, function(data){
                        switch(data){
                            case "aggiunto":
                                $(".setPreferiti").each(function(i){
									if(this.id.slice(1)  == doc){
										$(this).html(show_remove)
										$(this).append("<input type='hidden' value='2' />")
									}
								});
                                break;
                            case "rimosso":
                                $(".setPreferiti").each(function(i){
									if(this.id.slice(1)  == doc){
										$(this).html(show_add)
										$(this).append("<input type='hidden' value='1' />")
									}
								});
								break;
                            case "errore":   
                                $(".setPreferiti").each(function(i){
									if(this.id.slice(1)  == doc){
										$(this).html(show_error)										
										$(this).append("<input type='hidden' value='0' />")
									}
								}); 
                                break;
                            default: 
                                $(".setPreferiti").each(function(i){
									if(this.id.slice(1) == doc){
										$(this).html(show_default)
										$(this).append("<input type='hidden' value='0' />")
									}
								});
                                break;                            
                        }
                    });
					}
					//todo: non farlo per gli id multipli
					//se i tag a sono vuoti?
                      
                }else{ 
                    link.html(show_default)                   
                }
                
            });
            
                        
            $(".setPreferiti").click(function(){
                var link = $(this)
				_id = this.id
                var action = $(this).find("input[type='hidden']").val()
					
				//patch per più link
				link.html("<img src='" +  loader_img  + "' />")
                var doc = this.id.slice(1);
                $.get("/handlers/Preferiti.ashx", {d: doc, u: user, a: action}, function(data){
                    switch(data){
                        case "aggiunto":
							$(".setPreferiti").each(function(i){
								if(this.id  == _id){
									$(this).html(show_remove)
									$(this).append("<input type='hidden' value='2' />")
								}
							});
                            break;
                        case "rimosso":
                            //elimino l'elemento dal dom
                            $("#e" + doc).hide("slow")
                            $("#e" + doc).remove()
							$(".setPreferiti").each(function(i){
								if(this.id  == _id){
									$(this).html(show_add)
									$(this).append("<input type='hidden' value='1' />")
								}
							});
                            break;
                        case "errore":   
							$(".setPreferiti").each(function(i){
								if(this.id  == _id){
									$(this).html(show_error)
									$(this).append("<input type='hidden' value='0' />")
								}
							});                     
                            break;
                        default: 
							$(".setPreferiti").each(function(i){
								if(this.id  == _id){
									$(this).html(show_default)
									$(this).append("<input type='hidden' value='0' />")
								}
							});
                            break;                            
                    }
                });
                return false
            });
			
			}
        }
    }();

$(function(){ 
	
	function  ciao() {
									         alert("ciao")
									     }
 
	preferiti.handle_events();
	
});  


