Rico.loadModule('DragAndDrop','Corner');

Rico.onLoad( function() {

	//ログ textareaに出力
//	Rico.setDebugArea('logger');
//  <textarea class="logBox" id="logger" rows='8' cols='60'></textarea>

	if(navigator.cookieEnabled == false){
		//ブラウザの cookie がオフになっています。cookie をオンにしてください。
		alert('your browser should handle cookies');
		return;
	}
	
	var ajax = new Ajax.Request('bookmark_xml.php', 
								{ 
									method:'get', 
									parameters: 'workspace_index='+workspace_index+"&cache="+(new Date()).getTime(), 
									onComplete: set_default_data
								});



});


function set_default_data(httpObj){
	var roundCorners = Rico.Corner.round.bind(Rico.Corner);

	//
	CustomDraggable = Class.create();
	CustomDraggable.prototype = Object.extend(new Rico.Draggable(), CustomDraggableMethods);

	//workspaceの角を丸くする
/*
	if(!Prototype.Browser.IE && !Prototype.Browser.Opera){
		roundCorners('workspace');
	}
*/

	if($('username') && $('password')){
		//login formのevent set
		$('username').onfocus = function(){
			if(this.value=="E-mail") this.value="";
			this.className = "black";
		};
		$('username').onblur = function(){
			if(this.value=="") this.value="E-mail";
			this.className = "gray";
		};
		$('password').onfocus = function(){
			if(this.value=="Password") this.value="";
			this.className = "black";
			this.type = "password";
		};
	}

	var XML = httpObj.responseXML;
	var bookmark_tag = XML.getElementsByTagName("bookmark");
	for(i=0;i<bookmark_tag.length;i++){
		id= parseInt(bookmark_tag[i].getElementsByTagName("id")[0].firstChild.nodeValue);

		//角を丸にする(IEはできない、height指定がNGであるため)
/*
		if(!Prototype.Browser.IE && !Prototype.Browser.Opera){
			roundCorners('dragme_'+id);
		}
*/

		//
		if(!$('dragme_'+id)){
			continue;
		}

		//ドラッグするBOX
		dndMgr.registerDraggable( new CustomDraggable('dragme_'+id) );
	
		Event.observe($('dragme_'+id), "dblclick", dblclick, false);
		
		//context menu
		a_id = 'dragme_'+id+'_a_menu';
		context_menu = new Control.ContextMenu(a_id,{
			leftClick: true,
			delayCallback: false
		});
		//property
		context_menu.addItem({
		label: msg_8,
			callback: function(){
				c = get_draggable_arr_index(currentdraggable_id);
				a = dndMgr.draggables[c].htmlElement.id+'_a_menu';
				bookmark_window.property = bookmark_window.window_factory($(a),'property',{afterClose: function(){this.destroy();}});
				bookmark_window.property.open();
			},
			enabled: true
		});
		//delete
		context_menu.addItem({
			label: msg_9,
			callback: function(){
				keydown_delete();
			},
			enabled: true
		});
	  
	  
	}
	Event.observe(document, "keydown", keydown, false);

	//
	CustomDropzone = Class.create();
	CustomDropzone.prototype = Object.extend(new Rico.Dropzone(), CustomDropzoneMethods);

	//ドラッグスペースを設定
	for(i=1;i<=bw_max;i++){		
		if(!$('droponme'+i)){
			continue;	
		}
		//bookmarkがある場合、
		if(typeof($('droponme'+i).getElementsByTagName("div")[0])!="undefined"){
			is_canAccept=false;
		}else{
			is_canAccept=true;			
		}
		dndMgr.registerDropZone( new CustomDropzone('droponme'+i,is_canAccept) );
	}   	


	//
	TabDropzone = Class.create();
	TabDropzone.prototype = Object.extend(new Rico.Dropzone(), TabDropzoneMethods);

	//ドラッグスペースを設定(tab)
	for(i=1;i<=tab_max;i++){		
		//bookmarkがある場合、
		if($('tabdroponme'+i).className=="tab_select"){
			is_canAccept=false;
		}else{
			is_canAccept=true;			
		}
		dndMgr.registerDropZone( new TabDropzone('tabdroponme'+i,is_canAccept) );
	}  
	

	//tab menu
	context_menu = new Control.ContextMenu('tab_rename',{
		leftClick: true,
		delayCallback: false
	});
	//rename
	context_menu.addItem({
	label: msg_13,
		callback: function(){
			bookmark_window.tab_rename   = bookmark_window.window_factory($('tab_rename'),'tab_rename',{afterClose: function(){this.destroy();}});
			bookmark_window.tab_rename.open();
		},
		enabled: true
	});
	//delete
	context_menu.addItem({
		label: msg_9,
		callback: function(){
			if(!confirm(tab_delete_msg)){
				return;	
			}
			qs = '?workspace_index='+workspace_index;
			qs+= '&workspace_id='+workspace_id;
			window.open('./tab_delete.php'+qs, '_self');
		},
		enabled: true
	});
}

function dblclick(){
	url = this.getElementsByClassName('box_url')[0].firstChild.nodeValue;
	bookmark_open(url);
}
function bookmark_open(url){
	RegularExp = new RegExp( bookmark_server_domain, "g" );
	if(url.match(RegularExp)){
		target = "_self";	
	}else{
		target = "_blank";	
	}
	window.open(url,target);
}
function keydown(e){
	if(!currentdraggable_id)	return;

	x = y = 0;

	//left=37 up=38 right=39 down=40
	switch (e.keyCode){
		case 13:
			//enter
			keydown_enter();
			break;
		case 46:
			//delete
			keydown_delete();
			break;
		case 37:
			keydown_draggable_select(-1,0);
			break;
		case 38:
			keydown_draggable_select(0,-1);
			wheel(e);
			break;
		case 39:
			keydown_draggable_select(1,0);
			break;
		case 40:
			keydown_draggable_select(0,1);
			wheel(e);
			break;
		default:
			return;
	}


}

function wheel(event){
	var delta = 0;
	if (!event) /* For IE. */
			event = window.event;
	if (event.wheelDelta) { /* IE/Opera. */
			delta = event.wheelDelta/120;
			if (window.opera)
					delta = -delta;
	} else if (event.detail) { /** Mozilla case. */
			delta = -event.detail/3;
	}
	/** If delta is nonzero, handle it.
	 * Basically, delta is now positive if wheel was scrolled up,
	 * and negative, if wheel was scrolled down.
	 */
	if (delta)
			handle(delta);
	if (event.preventDefault) {
			event.preventDefault();
	}
	event.returnValue = false;
}

function keydown_draggable_select(x,y){
	c = get_draggable_arr_index(currentdraggable_id);
	zone_id = dndMgr.draggables[c].htmlElement.parentNode.id;
	index = parseInt(zone_id.replace(/droponme([0-9]+)/, "$1"));	
	line = Math.floor((index-1)/bw_line);


	if(x==1 || x==-1){
		for(s=1;s<=3;s++){
			if(s==1){
				d_line = line;
				d_index = index;
			}else if(s==2 && line>0){
				d_line =  line-1;
				d_index = index - bw_line;
			}else if(s>=2 && line<bw_max/bw_line-1){
				d_line =  line+1;
				d_index = index + bw_line;
				s=3;
			}else{
				break;	
			}
			
			for(i=d_index+x; d_line*bw_line+1<=i && i<=d_line*bw_line+bw_line; i=i+x){
				if(draggable_move(c,i)){
					return;	
				}
				if(i>bw_max || 0 >i)	break;
			}
		}
	}
	
	if(y==1 || y==-1){
		for(s=1;s<=3;s++){
			if(s==1){
				d_line = line;
				d_index = index;
			}else if(s==2 && index%bw_line!=1){
				d_line =  line;
				d_index = index - 1;
			}else if(s>=2 && index%bw_line!=0){
				d_line =  line;
				d_index = index + 1;
				s = 3;
			}else{
				break;	
			}
			
			for(i=d_index+(bw_line*y); 1<=i && i<=bw_max; i=i+(bw_line*y)){
				if(draggable_move(c,i)){
					return;	
				}
				if(i>bw_max || 0 >i)	break;
			}
		}
	}
}
function draggable_move(c,i){
	if(typeof($('droponme'+i).getElementsByTagName("div")[0])!='undefined'){
		dragme_id = $('droponme'+i).getElementsByTagName("div")[0].id;
		p = get_draggable_arr_index(dragme_id);

		dndMgr.draggables[c].deselect();
		dndMgr.draggables[p].select();
		
		if ( dndMgr.draggables[p].isSelected() ) {
			dndMgr.currentDragObjects.push(dndMgr.draggables[p]);
			dndMgr.lastSelectedDraggable = dndMgr.draggables[p];
		}
		return true;
	}
	return false;
}
function keydown_enter(){
	c = get_draggable_arr_index(currentdraggable_id);
	url = dndMgr.draggables[c].htmlElement.getElementsByClassName('box_url')[0].firstChild.nodeValue;
	bookmark_open(url);
}
function keydown_delete(){
	c = get_draggable_arr_index(currentdraggable_id);
	
//	title = dndMgr.draggables[c].htmlElement.getElementsByClassName('box_title')[0].firstChild.nodeValue;

	if(!confirm(bookmark_delete_msg)){
		return;	
	}
	

	var ajax = new Ajax.Request('bookmark_delete.php', 
								{ 
									method:'post', 
									parameters: 'bookmark_id='+dndMgr.draggables[c].htmlElement.id+"&cache="+(new Date()).getTime()
								});
	  
	dndMgr.draggables[c].htmlElement.parentNode.removeChild(dndMgr.draggables[c].htmlElement);
}

function get_draggable_arr_index(id){
	for(i=0;i<dndMgr.draggables.length;i++){
		if(dndMgr.draggables[i].htmlElement.id==id){
			return 	i;
		}
	}
	return null;
}

var currentdraggable_id = null;

var CustomDraggableMethods = {

   initialize: function( htmlElement ) {
      this.type        = 'Custom';
      this.htmlElement = $(htmlElement);
	  this.selected      = false;
   },

   select: function() {
//      Rico.writeDebugMsg("CustomDraggableMethods.select:"+this.htmlElement.id);

      this.selected = true;

	  var el = this.htmlElement;

      // show the item selected.....
//      el.style.color           = "#ffffff";
//      el.style.backgroundColor = "#C0C0C0";
	  el.className = "box_select";

	  currentdraggable_id = this.htmlElement.id;

	  div_menu_icon = this.htmlElement.getElementsByClassName('box_menu_icon')[0]
	  div_menu_icon.style.visibility='';
  },

   deselect: function() {
//      Rico.writeDebugMsg("CustomDraggableMethods.deselect:"+this.htmlElement.id);
	  
      this.selected = false;

	  
	  this.htmlElement.className = "box";
//      var el = this.htmlElement;
//      el.style.color           = "#2b2b2b";
//      el.style.backgroundColor = "transparent";


	  currentdraggable_id = null;
	  
	  div_menu_icon = this.htmlElement.getElementsByClassName('box_menu_icon')[0]
	  div_menu_icon.style.visibility='hidden';
   },

   startDrag: function() {
//      Rico.writeDebugMsg("CustomDraggableMethods.startDrag:"+this.htmlElement.id);
   },

   cancelDrag: function() {
//      Rico.writeDebugMsg("CustomDraggableMethods.cancelDrag:"+this.htmlElement.id);
	  this.htmlElement.className = "box";
   },

   endDrag: function() {
//      Rico.writeDebugMsg("CustomDraggableMethods.endDrag");
	  this.htmlElement.className = "box";
		
      if ( CustomDraggable.removeOnDrop )
         this.htmlElement.style.display = 'none';

	  //tabにdropされた場合
	  if(this.htmlElement.parentNode.id.match(/tabdroponme/)){  
		  var ajax = new Ajax.Request('bookmark_move_workspace.php', 
										{ 
											method:'post', 
											parameters: 'bookmark_id='+this.htmlElement.id+"&to_workspace_index="+this.htmlElement.parentNode.id+"&cache="+(new Date()).getTime()
										});
		  this.htmlElement.parentNode.removeChild(this.htmlElement);
	  //workspace内にdropされた場合
	  }else{
		  var ajax = new Ajax.Request('bookmark_move.php', 
										{ 
											method:'post', 
											parameters: 'bookmark_id='+this.htmlElement.id+"&zone_id="+this.htmlElement.parentNode.id+"&cache="+(new Date()).getTime()
										});
	  }
	  
	  
	},
 
   getSingleObjectDragGUI: function() {
//   	  Rico.writeDebugMsg("CustomDraggableMethods.getSingleObjectDragGUI");
	  this.htmlElement.className = 'box_drag';
      return this.htmlElement;
   },

   getDroppedGUI: function() {
//   	  Rico.writeDebugMsg("CustomDraggableMethods.getDroppedGUI");
      return this.htmlElement;
   },

   toString: function() {
      return this.name;
   }

}

var CustomDropzoneMethods = {
   initialize: function( htmlElement, is_canAccept ) {
      this.htmlElement  = $(htmlElement);
      this.absoluteRect = null;
	  this.is_canAccept = is_canAccept;
   },
 
   activate: function() {
//   	  Rico.writeDebugMsg("CustomDropzoneMethods.activate:"+this.htmlElement.id);
	  
      var htmlElement = this.getHTMLElement();
      if (htmlElement == null  || this.showingActive)
         return;

      this.showingActive = true;
      this.saveBackgroundColor = htmlElement.style.backgroundColor;

      var fallbackColor = "#ffea84";
      var currentColor = Rico.Color.createColorFromBackground(htmlElement);
      if ( currentColor == null )
         htmlElement.style.backgroundColor = fallbackColor;
      else {
         currentColor.isBright() ? currentColor.darken(0.2) : currentColor.brighten(0.2);
//         htmlElement.style.backgroundColor = currentColor.asHex();
      }
   },

   deactivate: function() {
//   	  Rico.writeDebugMsg("CustomDropzoneMethods.deactivate:"+this.htmlElement.id+":"+this.showingActive);
	  
      var htmlElement = this.getHTMLElement();
      if (htmlElement == null)
         return;
	
	  //移動元のzoneを移動できるようにする
	  if(typeof(htmlElement.getElementsByTagName("div")[0])=="undefined" && this.is_canAccept==false){
		  Rico.writeDebugMsg("CustomDropzoneMethods.deactivate:"+this.htmlElement.id+":is_canAccept set true");
		  this.is_canAccept = true;
	  }


	  if(!this.showingActive || typeof(this.showingActive)=='undefined')
	  	 return;



      htmlElement.style.backgroundColor = this.saveBackgroundColor;
      this.showingActive = false;
      this.saveBackgroundColor = null;
	  

   },
   
   showHover: function() {
//   	  Rico.writeDebugMsg("CustomDropzoneMethods.showHover:"+this.htmlElement.id);
      var htmlElement = this.getHTMLElement();
      if ( htmlElement == null || this.showingHover )
         return;

      this.saveclassName = htmlElement.className;

      this.showingHover = true;
      htmlElement.className = "zone zone_hover";
   },

   hideHover: function() {
      var htmlElement = this.getHTMLElement();
      if ( htmlElement == null || !this.showingHover )
         return;

      htmlElement.className = this.saveclassName;
      this.showingHover = false;
   },
   
   canAccept: function(draggableObjects) {
   	  if(this.is_canAccept){
	      return true;
	  }else{
	 	  return false;
	  }
   },
   accept: function(draggableObjects) {
//	  Rico.writeDebugMsg("CustomDropzoneMethods.accept:"+this.htmlElement.id);
	  
      var htmlElement = this.getHTMLElement();
      if ( htmlElement == null )
         return;

      n = draggableObjects.length;
      for ( var i = 0 ; i < n ; i++ )
      {
         var theGUI = draggableObjects[i].getDroppedGUI();
		 
/*         if (Element.getStyle(theGUI,'position')=='absolute')*/
         if ( RicoUtil.getElementsComputedStyle( theGUI, "position" ) == "absolute" )
         {
            theGUI.style.position = "static";
            theGUI.style.top = "";
            theGUI.style.top = "";
         }
         htmlElement.appendChild(theGUI);
      }
	  
	  //移動先のzoneを移動できなくする
	  this.is_canAccept = false;
   }
}

var TabDropzoneMethods = {
   initialize: function( htmlElement, is_canAccept ) {
      this.htmlElement  = $(htmlElement);
      this.absoluteRect = null;
	  this.is_canAccept = is_canAccept;
   },
   canAccept: function(draggableObjects) {
   	  if(this.is_canAccept){
	      return true;
	  }else{
	 	  return false;
	  }
   },

	activate: function() {
//   	  Rico.writeDebugMsg("TabDropzoneMethods.activate:"+this.htmlElement.id);
	  
      var htmlElement = this.getHTMLElement();
      if (htmlElement == null  || this.showingActive)
         return;

      this.showingActive = true;
      this.saveBackgroundColor = htmlElement.style.backgroundColor;

      var fallbackColor = "#ffea84";
      var currentColor = Rico.Color.createColorFromBackground(htmlElement);
      if ( currentColor == null )
         htmlElement.style.backgroundColor = fallbackColor;
      else {
         currentColor.isBright() ? currentColor.darken(0.2) : currentColor.brighten(0.2);
      }
   },
   showHover: function() {
//   	  Rico.writeDebugMsg("TabDropzoneMethods.showHover:"+this.htmlElement.id);
      var htmlElement = this.getHTMLElement();
      if ( htmlElement == null || this.showingHover )
         return;

      this.saveclassName = htmlElement.className;

      this.showingHover = true;
      htmlElement.className = "tab_hover";
   },
   hideHover: function() {
      var htmlElement = this.getHTMLElement();
      if ( htmlElement == null || !this.showingHover )
         return;

      htmlElement.className = this.saveclassName;
      this.showingHover = false;
   }

}
