複雑なjqドラッグ、枠選択ドラッグ、ajax伝値、削除とドラッグの衝突の解決


*{margin: 0 auto;}
    	.dragdiv{border: 2px solid black;height: 100px;width: 800px;margin-top: 20px;}
    	span{background: red;width: 50px;height: 50px;margin: 20px;display: inline-block;}
    	.top span{
    		background: #f9f9f9;
    		border: 1px solid #fbfbfa;
    		border-radius: 6px;
    		width: 50px;
    		height: 50px;
    		font-size: 16px;
    		margin: 9px;
    		margin-top: 1px;
    		padding: 9px;
    		display: inline-block;
    		text-align: left;
    		overflow: hidden;
    		vertical-align: top; 
    	}
    	.top span:HOVER,.bottom ul li:HOVER{background: #D1D1D1} 
    	input{
    		border: none;
    		background: none;
    		height: 24px;
    		width: 100%;
    		text-overflow: ellipsis;
    		white-space: nowrap;
    	}
    	
    	.bottom_right{
    		padding: 0px;
    	}
    	ul,li{
        	margin: 0px;
            padding: 0px;
            list-style: none;
        }
        ul{
        	display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            width: 100%;
            border-bottom: 1px solid #C9C9C9;
        }
        ul:last-child{border-bottom: none;}
    	.bottom_right ul li{
    		box-sizing: border-box;
    		width: calc((100% - 10px) / 10);
    		width:-moz-calc((100% - 10px) / 10);
			width:-webkit-calc((100% - 10px) / 10);
    		border-left: 1px solid #C9C9C9; 
    		height: 50px;
    		flex:auto;         
    		line-height: 50px;  
    	}
    	li .span{
    		width: 100%;
    		height: 100%;
    		display: block;
    		overflow: hidden;
    		position: relative;
    	}
    	li .span div{
    		
    		width: 11px;
    		height: 11px;
    		padding: 1px;
		    font-size: 12px;
		    position: absolute;
		    right: 1px;
		    top: 1px;
    	}
    	.bottom_right ul li.selected,
    	.bottom_right ul li.temp-selected{background: #D1D1D1}

 





 
 
		
		$(function(){
	    	
			//    ,         
			$(".List_div1").hide();
			
			$("input").prop("readonly","readonly");
			
			$(".div1").show();
			
	    	    drag.init('List_div1',"scheduling/schedulingAdd"); 
		    
		    //       
                     initSelectBox('.bottom_right',"    ","    ");
		}); 

		//      ,   class:selected
	    $("body").on("click",function() {
	    	$(".bottom_right li").removeClass('selected');
	    }); 
	    
	    //    
		$(".bottom ul li").hover(function() {
			$(this).css({'background':'#D1D1D1','color':'black'});
		},function(){
			$(this).removeAttr("style");
		});
		
		//  
		var drag = {
	
		    class_name : null,  //       
			permitDrag : false,	//        
	
			_x : 0,             //  x  
		    _y : 0,			    //  y  
		    _left : 0,          //          
		    _top : 0,           //          
	
		    old_elm : null,     //     
		    tmp_elm : null,     //           
		    new_elm : null,     //           
		    url : null,			//ajax    
		    
		    //   
		    init : function (className,url){
	
		        //           classname(     ,   id   )
		        drag.class_name = className;
		        
		        //ajax    
		        drag.url=url;
		        
		         //        ,          (            )
		        $('.' + drag.class_name).on('mousedown', '.top span', function(event){
		            //                 ,          
		            drag.permitDrag = true;
		            //           
		            drag.old_elm = $(this);
		            
		            //         
		            drag.mousedown(event);
		            return false;
		        });
	
		        //       
		        $(document).mousemove(function(event){
		            //           ,       
		            if(!drag.permitDrag) return false;
		            //       
		            drag.mousemove(event);
		            return false;
		        });
	
		        //      
		        $(document).mouseup(function(event){
		            //           ,       
		            if(!drag.permitDrag) return false;
		            //              
		            drag.permitDrag = false;
		            //          
		            drag.mouseup(event);
		            return false;
		        });
	
		    },
	
			//          
			mousedown : function (event){
		           
		        //1.      ,        
		        drag.tmp_elm = $(drag.old_elm).clone();
	
		        //2.              
		        drag._x = $(drag.old_elm).offset().left;
		        drag._y = $(drag.old_elm).offset().top;
	
		        var e = event || window.event;
		        drag._left = e.pageX - drag._x;
		        drag._top = e.pageY - drag._y;
		        
			        //3.         ,             
			        $(drag.tmp_elm).css({
			            'position' : 'absolute',
			            'background-color' : '#D1D1D1',
			            'left' : drag._x,
			            'top' : drag._y,
			        });
					
		        //4.      
		        tmp = $(drag.old_elm).parent().append(drag.tmp_elm);
		        drag.tmp_elm = $(tmp).find(drag.tmp_elm);
		        $(drag.tmp_elm).css('cursor', 'move');
	
			},
	
			//          
			mousemove : function (event){
				
		        //2.    
		        var e = event || window.event;
		        var x = e.pageX - drag._left;
		        var y = e.pageY - drag._top;
		        var maxL = $(document).width() - $(drag.old_elm).outerWidth();
		        var maxT = $(document).height() - $(drag.old_elm).outerHeight();
		        //          
		        x = x < 0 ? 0: x;
		        x = x > maxL ? maxL: x;
		        y = y < 0 ? 0: y;
		        y = y > maxT ? maxT: y;
			        //3.         
			        $(drag.tmp_elm).css({
			            'left' : x,
			            'top' : y,
			        });
	
		        //              
		        $.each($('.' + drag.class_name + ' .bottom ul li'), function(index, value){
		        		
			            //          (  )
			            var box_x = $(value).offset().left;     //     x  
			            var box_y = $(value).offset().top;      //     y  
			            var box_width = $(value).outerWidth();  //   
			            var box_height = $(value).outerHeight();//   
			            //            
			            if(e.pageX > box_x && e.pageX < box_x-0+box_width && e.pageY > box_y && 
			            		e.pageY < box_y-0+box_height && $(value).find("span").length<=0
			            ){
			            	
			            	//            (        :x、y            ,          )
			                if($(value).offset().left !== drag.old_elm.parent().offset().left 
			                || $(value).offset().top !== drag.old_elm.parent().offset().top){
			                    $(value).css('background-color', '#D1D1D1');
			                }
			            }else{
			                //        
			                $(value).removeAttr("style");
			            }
		        });
	
			},
	
		    //          
		    mouseup : function (event){
	
		        //      
		        $(drag.tmp_elm).remove();
	
		        //              
		        var e = event || window.event;
		        
		        $.each($('.' + drag.class_name + ' div ul li'), function(index, value){
	
		            //          (  )
		            var box_x = $(value).offset().left;     //     x  
		            var box_y = $(value).offset().top;      //     y  
		            var box_width = $(value).outerWidth();  //   
		            var box_height = $(value).outerHeight();//   
		            
		            //                     
		            if(e.pageX > box_x && e.pageX < box_x-0+box_width && e.pageY > box_y &&
		            	e.pageY < box_y-0+box_height && $(value).find("span").length<=0
		            ){
		            	
		                //            (        :x、y            ,          )
		                if($(value).offset().left !== drag.old_elm.parent().offset().left 
		                || $(value).offset().top !== drag.old_elm.parent().offset().top){
		                    //         
		                    tmp = $(drag.old_elm).clone();
		                  	var newObj;
		                  	//newObj=$(value).append(ht);
		                  		
		                  	//        
		                  	var id=tmp.find('input[name="id"]').val(),
								page="schedulingList",
								type=$(value).index()+1,
								department=$(value).index(),
								time=$(value).parent().index();
		                  	
		                  	//    
		                  	$.ajax({
		            			type: "POST",
		            			url: drag.url,
		           	 		dataType: "json",
		            			data: {
		            				"id":id, "page":page, 
		            				"type":type, "department":department, 
		            				"time":time, "date": $("#dt").val()
		            			},
		            			success: function (data) {
		            				//           
		            				html(data);
		            			},
		            			error: function (data) {
		            				html(data);
		            			}
		        			}); 
		                    
		                    
		                    //     
		                    $(drag.old_elm).remove();
		                    //          
		                    //drag.new_elm = $(newObj).find(tmp);
		                }
		            }
		            //         class_name
		            
		            $(value).removeAttr("style");
		        });
		    },
		};
		
        var initSelectBox = function(selector, url, delUrl, selectCallback) {
        	
            function clearBubble(e) {
                if (e.stopPropagation) {
                    e.stopPropagation();
                } else {
                    e.cancelBubble = true;
                }

                if (e.preventDefault) {
                    e.preventDefault();
                } else {
                    e.returnValue = false;
                }
            }
            var $container = $(selector);
            var vv=null,
            	va=null;
            var arrs = [];
            
          	
          
    	    
            //      
            $container
	        	
                .on('mousedown', function(eventDown) {
                	
                    //         
                    var isSelect = "up";
                    //           
                    var startX = eventDown.x || eventDown.pageX;
                    var startY = eventDown.y || eventDown.pageY;
                    
                    //          ,      
                    $(selector).find('li').each(function(i,txt) {
                    	
                        var $item = $(this);
                        
                        var itemX_pos = $item.prop('offsetWidth') + $item.prop('offsetLeft');
                        var itemY_pos = $item.prop('offsetHeight') + $item.prop('offsetTop');
                        
                        var condition1 = itemX_pos > startX;
                        var condition2 = itemY_pos > startY;
                        var condition3 = $item.prop('offsetLeft') < startX;
                        var condition4 = $item.prop('offsetTop') < startY;
                        
                        if (condition1 && condition2 && condition3 && condition4) {
                        	vv=$item.index();
                        }
                    });
                    //        ,      
                    var _x = null;
                    var _y = null;
                    //var left;
                    //        、  
                    clearBubble(eventDown);
                    //          
                    $(selector).on('mousemove', function(eventMove) {
                        //        ,       、  
                        _x = eventMove.x || eventMove.pageX;
                        _y = eventMove.y || eventMove.pageY;
                        //            ,    select-item   
                        var _left   = Math.min(_x);
                        var _top    = Math.min(_y, startY);
                        var _width  = Math.abs(_x);
                        var _height = Math.abs(_y - startY);
                        
                        //          ,      
                        $(selector).find('li').each(function(i,txt) {
                        	
                            var $item = $(this);
                            
                            var itemX_pos = $item.prop('offsetWidth') + $item.prop('offsetLeft');
                            var itemY_pos = $item.prop('offsetHeight') + $item.prop('offsetTop');
                            //     li         ,       ( temp-selected ,    mouseup     temp-selected     selected)
                            var condition1 = itemX_pos > _left;
                            var condition2 = itemY_pos > _top;
                            var condition3 = $item.prop('offsetLeft') < _left;//(_left + _width);
                            var condition4 = $item.prop('offsetTop') < (_top + _height);
                            isSelect="move";
                            if (condition1 && condition2 && condition3 && condition4) {
                            	$item.addClass('temp-selected');
                            	if($item.index()!=vv && $item.find("span").length>0){
                            		$item.removeClass('temp-selected');
                            	}
                                
                            } 
                            
                            else if($item.index()!=vv || $item.find("span").length<=0){
                            		$item.removeClass('temp-selected');
                            }
                        });
                        //        、  
                        clearBubble(eventMove);
                    });
                    $(document).on('mouseup', function() {
                        $(selector).off('mousemove');
                        if(isSelect=="move"){
	                        $(selector)
	                            .find('li.temp-selected')
	                            .removeClass('temp-selected')
	                            .addClass('selected');
	                       
		                    $('.selected').each(function(i) {
		                    	//     
		                    	if(vv==$(this).index()){
		                    		//  span   ,      span,  class,       ,     
			                    	if($(this).find(".span").length > 0){
			                    		va=$(this).find(".span").clone();
			                    		$(this).addClass('selectedww');
			                    		return true;
			                    	}
			                    	//   span   ,  class,     ,    class ‘selectedww’
			                    	else{
			                    		$(this).addClass('selectedw');
			                    		$(selector).find("li").removeClass('selectedww');
			                    	}
		                    	}
		                    	//     ,  class,      
		                    	if($(this).find("span").length<=0 && vv!=$(this).index()){
		                    		$(this).addClass('selectedwww');
		                    	}
		                    });
		                    
		                    
				    var page,
					//      
					ss=$('.selectedww').index()+1;
							
		                    //      
		                    var id=[],			 //     id,      
		                    pId=[],			 	 //     ,pId
				    type=[],			 //     ,     /  
				    department=[],		 //     ,   / 
				    time=[],			 //     ,  / 
				    de_id = [];			 //    id,      
		                    
							//    selectedwww   class,      
		                    if($('.selectedwww').hasClass("selectedwww")){
		                    	//     
		                    	$('.selectedww').each(function(i) {
			                    	
			                    	arrs.push($(this).find(".span input[name='id']").val());
			                    	//    pId
			                    	var ts=[$(this).find(".span input[name='pId']").val()];
			                    	
			                    	//         
			                    	$('.bottom_right ul li:nth-child('+ss+')').each(function(j) {
			                    		//       pId ==     pId,      id
					                	if($(this).find('.span input[name="pId"]').val() == ts){
					                		de_id.push($(this).find('.span input[name="id"]').val());
					                		//$(this).find('.span').remove();
					               	 	}
				            		});
			                    });
		                    	
		                    	//    
		                	    arrs.unique3();
		                		//     undefined
		                	    de_id.unique1();
		                	    
		                    	//        
		                	    $('.selectedwww').each(function(i) {
		                	    	id[i]=arrs[i];
			                   		type[i]=$(this).index()+1;//     /  
			                   		department[i]=$(this).index();//   / 
			                   		time[i]=$(this).parent().index();//  / 
			                    }); 
		                	    page="update";
		                    }  
		                    
		                  //      
		                    //$('.selectedw').append(va); 
		                   
		                    //    ,    selectedw   class
		                    if($('.selectedw').hasClass("selectedw") && (va!=null && va!="")){
		                    	//        
			                   	$('.selectedw').each(function(i) {
			                   		id[i]=va.find('input[name="id"]').val();
			                   		type[i]=$(this).index()+1;//     /  
			                   		department[i]=$(this).index();//   / 
			                   		time[i]=$(this).parent().index();//  / 
			                    });
			                   	page="add";
		                    }
		                    if(id.length>0){
	                 			$.ajax({
	    		           			type: "POST",
	    		           			url: url,
	    		          	 		dataType: "json",
	    		          	 		traditional: true,
	    		           			data: {
	    		           				"id":id, "de_id":de_id, 
	    		           				"page":page, "type":type, 
	    		           				"department":department, 
	    		           				"time":time, "date": $("#dt").val()
	    		           			},
	    		           			
	    		           			success: function (data) {
	    		           				//           
	    		           				html(data);
	    		           			},
	    		           			error: function (data) {
	    		           				html(data);
	    		           			}
	    	       				}); 
	                 			
	                 		}
	                        
		                 	
		                    $(selector).find("li").removeClass('selected selectedw selectedww selectedwww');
	                        va=null,arrs=[],de_id=[];
		                    if (selectCallback) {
	                            selectCallback();
	                        }
                        }
                        else{
		                    //       ,      
		                    //$(".bottom_right ul li .span div").off('click');
		                  	//      
		            	    $(".bottom_right ul li .span div").on("click",function() {
		            	    	var id=$(this).parent().find('input[name="id"]').val();
		            	    	var d=$(this).parent().parent().index();
		                  		if(confirm('      ?')) 
		                  		{
		                  			$.ajax({
		    		           			type: "POST",
		    		           			url: delUrl,
		    		          	 		dataType: "json",
		    		          	 		traditional: true,
		    		           			data: {
		    		           				"id":id, "d":d, 
		    		           				"date":$("#dt").val()
		    		           			},
		    		           			
		    		           			success: function (data) {
		    		           				//           
		    		           				html(data);
		    		           			},
		    		           			error: function (data) {
		    		           				html(data);
		    		           			}
		    	       				});  
		                  			//alert(id);
		                  			//window.location.href="scheduling/schedulingDel?id="+id+"&date="+$("#dt").val();  
		                    		return true; 
		                  		} 
		                  		return false; 
		            	    }); 
                        }
                        
                    });
                    
                });
          
        };

		//     undefined
        Array.prototype.unique1 = function(){
        	var res = [];
       	 	for(var i = 0; i < this.length; i++){
       	  		if(typeof(this[i])!='undefined' && this[i]!="") {
	       	  		res.push(this[i]);
	    	    }
       	 	}
       	 	return res;
        };
        //    
        Array.prototype.unique3 = function(){
       		var res = [];
       	 	var json = {};
       	 	for(var i = 0; i < this.length; i++){
       	  		if(!json[this[i]]){
       	   			res.push(this[i]);
       	   			json[this[i]] = 1;
       	  		}
       	 	}
       	 	return res;
       	}