(function($) {
	
	$.fn.stickynote = function(options) {
		var opts = $.extend({}, $.fn.stickynote.defaults, options);
		return this.each(function() {
			$this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			switch(o.event){
				case 'dblclick':
					$this.dblclick(function(e){$.fn.stickynote.createNote(o);})
					break;
				case 'click':
					$this.click(function(e){$.fn.stickynote.createNote(o);})
					break;
			}		
		});
	};
	
	$.fn.stickynote.defaults = {
		size 	: 'small',
		event	: 'click',
		color	: '#000000',
		container: '',
		assignData:'',
		type : 'user',
		deleteID:''
	};
	
	$.fn.stickynote.createNote = function(o) {
	    
	    if(o.type == 'user' && $('#hdnAddSticky').val() != '2' )
        {
            //alert('You do not have permission to create new Sticky note.');
            jAlert('You do not have permission to create new Sticky note.', 'Alert Dialog',function(r){if(r == true){}});
            return false;
        }
	    
	    var activeSticky = $('.jStickyCreate').length;
	    //User cannot have two unsaved sticky notes.
	    if(activeSticky > 0)
	    {
	        //alert('Please save your previous sticky note and then add new sticky note');
	        jAlert('Please save your previous sticky note and then add new sticky note.', 'Alert Dialog',function(r){if(r == true){}});
	        return;
	    }
	    
	    var setFocus = function($objStikcy)
        {
            $objStikcy.css("z-index",jqWindowsEngineZIndex++);
        }
	    
	    var allSticky = $('.jStickyMedium').length;
	    //User can not have more than 3 Sticky notes.
	    if(o.type == 'user')
	    {
	        if(allSticky >= 15)
	        {
	            //alert('You cannot have more than 10 sticky notes at a time.Please close some sticky notes to create the new one');
	            jAlert('You cannot have more than 15 sticky notes at a time.Please close some sticky notes to create the new one.', 'Alert Dialog',function(r){if(r == true){}});
	            return;
	        }
	    }
	    //--------------------------------------------------
	    
		var stickyTop = (allSticky * 20);
	    
		var _note_content = $(document.createElement('textarea')).addClass('txtArea');
		var _div_note 	= 	$(document.createElement('div'))
							.addClass('jStickyNote')
							.css('cursor','default');
							
		if(!o.text)
		{
			_div_note.append(_note_content);
			
			var _div_create = $(document.createElement('div'))
						.addClass('jStickyCreate')
						.attr('title','Save Sticky Note');
		
			_div_create.click(function(e)
			{
			    if($(this).parent().parent().find('textarea').val() == '')
			    {
			        //alert('Please enter some notes in this sticky');
			        jAlert('Please enter some notes in this sticky.', 'Alert Dialog',function(r){if(r == true){}});
			        return;
			    }
			    if($(this).parent().parent().find('textarea').val().length > 125)
			    {
			        //alert('Max 75 chars allowed.');
			        jAlert('Maximum 125 characters allowed.', 'Alert Dialog',function(r){if(r == true){}});
			        return;
			    }
			    
			    var dataToAssign = 'assignsticky';
			    
			    if($('.dvAssignTo').length > 0)
			    {
			        var eleSticky = document.getElementsByName('checksticky');
			        var flag = false;
			        if(eleSticky.length > 0)
			        {
			            for(i=0; i<eleSticky.length; i++)
			            {
			                if(eleSticky[i].checked)
			                {
			                    if(!flag)
			                    {
			                        dataToAssign += '$';
			                        flag = true;
			                    }
			                    dataToAssign += eleSticky[i].value + "~";
			                }
			            }
			            if(flag)
			                dataToAssign = dataToAssign.substring(0, (dataToAssign.length - 1));
			        }
			        
			    }
			    
			    dataToAssign += '$' + $(this).parent().parent().find('textarea').val()
			    
			    $.ajax(
                        {  
                            type: "POST",
                            url: 'MyHandleRequest.aspx',  // Send the login info to this page
                            data: { msg :  dataToAssign},    //equivalent to url parameter "msg=Hellow%20Nurse!"
                            async: true,    //default is asynchronous request can set to false
                            cache: false,
                            success: function(data)
                            {  
                               var arrResult = data.split('~');
                               if(arrResult[0] == 'success')
                               {
                                    $('.jStickyDelete').attr('rel',arrResult[1]);
                               }
                               else if(arrResult[0] == 'error')
                               {
                                    //alert(arrResult[1]);
                                    jAlert(arrResult[1], 'Alert Dialog',function(r){if(r == true){}});
                               }
                            }
                         }
                       );  
			    
				var _p_note_text = 	$(document.createElement('p'))
									.css('color',o.color)
									.html	(
											$(this)
											.parent().parent()
											.find('textarea')
											.val()
											);
			    
			    
			    
			    
				$(this)
				.parent().parent()
				.find('textarea')
				.before(_p_note_text)
				.remove(); 
				
				$(this).parent().parent().find('.dvAssignTo').remove(); 
				$(this).parent().parent().find('.jSticky-assign').remove();
				
				$(this).remove();						
			})
		}	
		else
		{
			_div_note.append('<p style="color:'+o.color+'">'+o.text+'</p>');					
		}
		
		var _div_delete = 	$(document.createElement('div'))
							.addClass('jStickyDelete').attr('title','Delete Note')
							.attr('rel',o.deleteID);
		
		var _div_delete_wrapper = $(document.createElement('div'))
							.addClass('stickyNoteTopBtn');
							
        //delete button wrapper							
		_div_delete_wrapper.append(_div_delete);					
							
		
		    _div_delete.click(function(e)
		    {
		        if($(this).attr('rel') != '')
		        {
		            var stickyDelete = "delete~" + $(this).attr('rel');
		            $.ajax(
                            {  
                                type: "POST",
                                url: 'MyHandleRequest.aspx',  // Send the login info to this page
                                data: { msg : stickyDelete },    //equivalent to url parameter "msg=Hellow%20Nurse!"
                                async: true,    //default is asynchronous request can set to false
                                cache: false,
                                success: function(data)
                                {  
                                }
                             }
                           ); 
                } 
			    $(this).parent().parent().remove();
			    var stickyCount = 0;
			    var newTop = 0;
			    $('.jStickyMedium').each(function()
			    {
			        newTop = stickyCount * 20;
			        $(this).css({'top': newTop + 'px'});
			        stickyCount = stickyCount + 1;
			    });
		    })
		
		var _div_add = 	$(document.createElement('div'))
							.addClass('fltRight').css('cursor','pointer').attr('title','Add New').html('+');
							
		_div_add.click(function(e)
		{
		    if($('#hdnAddSticky').val() != '2' )
            {
                //alert('You do not have permission to create new Sticky note.');
                jAlert('You do not have permission to create new Sticky note.', 'Alert Dialog',function(r){if(r == true){}});
                return false;
            }
		    if(o.type == 'user')
			    $.fn.stickynote.createNote(o);
			else
			    $.fn.stickynote.createNote({size 	: 'small',event	: 'click',color	: '#000000',container: 'sticky',assignData: o.assignData ,type : 'user', deleteID:''});
		});
		
		var _div_assign = $(document.createElement('div')).addClass('jSticky-assign').attr('title','Assign this sticky to other users').attr('rel','noview').html('Assign To:');
		
		var stickyAssign = $('<div id=\"assignsticky\" class=\"dvAssignTo\" ></div>');
		if(o.assignData != '' && o.type == 'user')
		{
		    _div_assign.click(function(e)
		    {
		        if($(this).attr('rel') == 'noview')
		        {
		            $.ajax(
                            {  
                                type: "POST",
                                url: 'MyHandleRequest.aspx',  // Send the login info to this page
                                data: { msg : 'assignto~' },    //equivalent to url parameter "msg=Hellow%20Nurse!"
                                async: true,    //default is asynchronous request can set to false
                                cache: false,
                                beforeSend:function()
                                {
                                    $('.jStickyMedium').showoverlay({imgPath:'JSOS/elapsor.gif', topX:50, topY:100});
                                },
                                success: function(data)
                                {  
                                    stickyAssign.html(data);
                                    $('.jStickyMedium').hideoverlay();
                                    _div_assign.attr('rel','view');
                                    stickyAssign.toggle();
                                }
                             }
                           ); 
		        }
		        else
		        {
		            stickyAssign.toggle();
		        }
	        
		        
		    });
		}
		
		var _div_bottom_wrapper = $(document.createElement('div')).addClass('stickyNoteBottomBtn');
		
       
        if(!o.text)
        {
            _div_bottom_wrapper.append(_div_assign);
            
        }
        
        _div_bottom_wrapper.append(_div_create).append(_div_add);
        
        
        var _div_wrap 	= 	$(document.createElement('div'))
		                    .attr('name','jStickyMedium')
							.css({'position':'absolute','top': stickyTop + 'px','left':'80%','cursor':'default'})
							.append(_div_delete_wrapper)
							.append(_div_note)
							.append(_div_bottom_wrapper);
							
	    if(o.assignData != '')
        {
            
            _div_wrap.append(stickyAssign);
        }
        
        $(_div_wrap).draggable({containment:'document',scroll: false});
        
        $(_div_wrap).bind('mousedown', function(e)
        {
            setFocus($(this));
        });
							
        setFocus($(_div_wrap));
        								
		switch(o.size){
			case 'large':
				_div_wrap.addClass('jSticky-large');
				break;
			case 'small':
				_div_wrap.addClass('jStickyMedium');
				break;
		}		
		/*if(o.containment){
			_div_wrap.draggable({ containment: '#'+o.containment , scroll: false ,start: function(event, ui) {
				if(o.ontop)
					$(this).parent().append($(this));
			}});	
		}	
		else{
			_div_wrap.draggable({ scroll: false ,start: function(event, ui) {
				if(o.ontop)
					$(this).parent().append($(this));
			}});	
		}*/
		
		$('input[name=chkStickyAll]').live('click',function()
		{
		    var sAll = this;
		    $('input[name=checksticky]').each(function()
		    {
		        this.checked = sAll.checked;
		    });
		});
		
		$('body').append(_div_wrap);
	};
})(jQuery);
