/**
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 */


Studio2.FieldDD = function(id, sGroup) {
	Studio2.FieldDD.superclass.constructor.call(this, id, sGroup);
};

	
Ext.extend(Studio2.FieldDD, Ext.dd.DDProxy, {

    startDrag: function(x, y) { 
        // make the proxy look like the source element
		var dragEl = this.getDragEl();
		var clickEl = this.getEl();
		dragEl.innerHTML = clickEl.innerHTML;
		dragEl.className = clickEl.className;
		Studio2.copyId = null;
//		this.showAnimation = true;

		if (Studio2.isSpecial(clickEl) && (Studio2.establishLocation(clickEl) == 'toolbox')) {
			var copy = Studio2.copyElement(clickEl);
			Studio2.setCopy(copy);
			clickEl.parentNode.insertBefore(copy,clickEl.nextSibling);
        	Dom.setStyle(clickEl, "display", "none");	// don't want it to take up any space		
		} else {
			Dom.setStyle(clickEl, "visibility", "hidden"); // want a empty space as we're dragging it away from this place
		}

    },

    endDrag: function(e) {
     	ModuleBuilder.state.isDirty=true;
        var srcEl = this.getEl();
        var proxy = this.getDragEl();      
        var proxyid = proxy.id;
        var thisid = this.id;
        
        if (Dom.getXY(srcEl)) { // if we have a valid srcEl still...hasn't been deleted earlier
			// Show the proxy element and animate it to the src element's location
			Dom.setStyle(proxy, "visibility", "");
			Dom.setStyle(srcEl, "display", ""); // display!=none for getXY to work
			Ext.get(proxy).alignTo(srcEl, 'tl', null, {
				callback: function(){
					Dom.setStyle(proxyid, "visibility", "hidden");
					Dom.setStyle(thisid, "visibility", "");
				}
			});
		}

		if (Studio2.isSpecial(srcEl) && Studio2.copy()) {
			Studio2.activateCopy(); // activateCopy makes it active, and removes the flag that says there is a copy
		} else {
			// Cleanup - if we still have a copy element here, then remove it
//			Studio2.removeCopy();
		}
    },

	onInvalidDrop: function(e) {
		var dragEl = this.getDragEl();
		dragEl.innerHTML = '';
		Studio2.removeCopy();
		Dom.setStyle(this.getEl(), "display", "block");	// make it visible again - we made special elements invisible in startDrag		
	},
	
    onDragDrop: function(e, id) {
		var srcEl = this.getEl();
		var destEl = Ext.get(id).dom; // where this element is being dropped
		
		var srcLocation = Studio2.establishLocation(srcEl);
		var destLocation = Studio2.establishLocation(destEl);

		// CASE: Trying to delete an item from the toolbox or move fields within the toolbox - don't allow
		if ( ((srcLocation == 'toolbox') && (destLocation == 'delete')) ||
			 ((srcLocation == 'toolbox') && (destLocation == 'toolbox'))) {
			Studio2.removeCopy();
			Dom.setStyle(srcEl, "display", "block");	// make it visible again - we made special elements invisible in startDrag		
			return;
		}
		
		
		// CASE: Delete a panel element
		// if source was in a panel (not toolbox) and destination is delete then remove this element
		if ((srcLocation == 'panels') && (destLocation == 'delete')) {
			var parent = srcEl.parentNode;
			var sibling = srcEl.previousSibling;
			while(sibling != null) {
				if (sibling.className && (sibling.className.indexOf('le_field') != -1)) {
					break;
				}
				sibling = sibling.previousSibling;
			}
			if (sibling == null) {
				sibling = srcEl.nextSibling;
				while(sibling != null) {
					if (sibling.className && (sibling.className.indexOf('le_field') != -1)) {
						break;
					}
					sibling = sibling.nextSibling;
				}
			}
			Studio2.removeElement(srcEl);
//			this.showAnimation = false; // can't show animation as the source no longer exists
			if (sibling == null) {
	        	// If we've just deleted the last field from a panel then we need to tidy up	
				Studio2.tidyFields(parent);	
			} else {
				Studio2.increaseFieldWidth(sibling);
			}
			return;
		} // end delete
		
		// CASE: Simple field swap
		// Either neither one is special, or they're both special and both in panels
		if (( ! Studio2.isSpecial(srcEl) && ! Studio2.isSpecial(destEl)) ||
			( Studio2.isSpecial(srcEl) && Studio2.isSpecial(destEl) && (srcLocation == 'panels') && (destLocation == 'panels')) ) {
			Studio2.swapElements(srcEl, destEl);

			this.runSpecialCode(srcEl, destEl);
			return;
		}

		// CASE: swapping a special field from the toolbox with a field in a panel
		
		if (Studio2.copy() && (destLocation == 'panels')) {
		
			// CASE: split a field
			// If destination is wider than one column, then do a field split
				
			if (Studio2.getColumnWidth(destEl) > 1) {
				Studio2.reduceFieldWidth(destEl); // reduce the column width of the destination
				var copy = Studio2.copyElement(srcEl);
				Studio2.activateElement(copy);
				destEl.parentNode.insertBefore(copy,destEl); // add a new field in to the left of the destination
				Dom.setStyle(copy, "display", "");
				return;
			}

			var prevField = Studio2.prevField(destEl); //see if the field we are replacing had any prev sibling, must be done before the swap or sibling becomes dangling.
			
			Studio2.swapElements( Studio2.copy(),destEl );
			// now make the original visible again
			Dom.setStyle(srcEl, "display", "");

			if(null!== prevField && !Studio2.isSpecial(prevField) && !Studio2.inArray(Studio2.expandableFields,prevField)){
				//register to be expandable
				Studio2.registerExpandableField(prevField);
				/*Studio2.expandableFields.push(prevField.id);
					var img = Studio2.getImageElement();
					img.onclick = function(){ //bind expandable behaviour
							Studio2.toggleFieldWidth(prevField.id);
					}
				prevField.insertBefore(img , prevField.childNodes[1]); //insert the image tag
				*/
			}
			return;
		}
		
		// CASE5: moving a plain field from the panel to a special field in the toolbox - just copy
		if ( ! Studio2.isSpecial(srcEl) && Studio2.isSpecial(destEl) && (destLocation == 'toolbox')) {
			// make a copy of the destination
			var copy = Studio2.copyElement(destEl);
			var destination = document.getElementById('availablefields');
			destination.appendChild(copy);
			Studio2.swapElements(copy,srcEl);
			Dom.setStyle(srcEl, "display", "");
			Studio2.activateElement(copy);			
			return;
		}
//		debugger;

		//CASE6: A regular field swapped with a special field. Src is special, dest is not special.
		if(Studio2.isSpecial(srcEl) && !Studio2.isSpecial(destEl) && destLocation == srcLocation){
		//console.log("case 6");
			Studio2.swapElements(srcEl, destEl);
			var siblingField = Studio2.prevField(document.getElementById(srcEl.id));

			////////////////oldSibling is the sibling of the special field (filler). After moving the filler to new destination
			///must disallow expandable behavior from this sibling if it has one.
			var oldSibling = Studio2.nextField(destEl);
			if(null == oldSibling)
				oldSibling = Studio2.prevField(destEl);
			if(null!==oldSibling && !Studio2.isSpecial(oldSibling)){
				Studio2.unregisterExpandableField(Studio2.expandableFields, oldSibling.id);
			}
			if(null!== siblingField && !Studio2.isSpecial(siblingField)){
					Studio2.registerExpandableField(siblingField);
			}
			return;
		}
		//CASE 7: A special field swapped with a regular field. Source is not-special, destination is special.
		if(!Studio2.isSpecial(srcEl) && Studio2.isSpecial(destEl) && destLocation == srcLocation) {
			/**
				if destination's left sibling is expandable.
					unregister left sibling from expandable.
				if src field's left sibling is not special
					register left sibling to expandable.
			*/
			//console.log("case7");
			Studio2.swapElements(srcEl, destEl);
			var destSibling = Studio2.prevField(srcEl);
			var srcSibling = Studio2.prevField(destEl);
			if( null !== destSibling ){
				Studio2.unregisterExpandableField(Studio2.expandableFields, destSibling.id);
			}
			if(null !== srcSibling && !Studio2.isSpecial(srcSibling)){
				Studio2.registerExpandableField(srcSibling);
			}
			return;
		}		
		
//console.log("case8");
		Studio2.swapElements( srcEl,destEl );
		this.runSpecialCode(srcEl,destEl);
		if ((srcLocation != destLocation)) {
			if (Studio2.isSpecial(srcEl) && ! Studio2.isSpecial(destEl))  {
				Studio2.removeElement(srcEl);
//				this.showAnimation = false;
				return;
			}
			if (Studio2.isSpecial(destEl) && ! Studio2.isSpecial(srcEl))  {
				Studio2.removeElement(destEl);
//				this.showAnimation = false;
				return;
			}
		}	


    },
    runSpecialCode: function(srcEl, destEl){
    	//console.log("running special code");
		//console.log("Src: " +srcEl.id + "Dest: " +destEl.id);
		//whos's who
		var srcLeftSibling = Studio2.prevField(srcEl);
		var srcRightSibling = Studio2.nextField(srcEl);
		var destRightSibling = Studio2.nextField(destEl);
		var destLeftSibling = Studio2.prevField(destEl);

		var srcExpandable = !Studio2.isSpecial(srcEl) && ((null==srcRightSibling && null==srcLeftSibling) 
							|| (null !== srcRightSibling) && Studio2.isSpecial(srcRightSibling));
		var destExpandable = !Studio2.isSpecial(destEl) && ((null==destRightSibling && null==destLeftSibling) 
							|| (null !== destRightSibling) && Studio2.isSpecial(destRightSibling));

		var srcUnexpandable = !Studio2.isSpecial(srcEl) && ((null!==srcLeftSibling && !Studio2.isSpecial(srcLeftSibling)) 
							|| ((null !== srcRightSibling) && !Studio2.isSpecial(srcRightSibling)));
		var destUnexpandable = !Studio2.isSpecial(destEl) && ((null!==destLeftSibling && !Studio2.isSpecial(destLeftSibling))
							|| ((null!== destRightSibling) && !Studio2.isSpecial(destRightSibling)));

	/*	if(null==srcLeftSibling && null==srcRightSibling)
			srcUnexpandable = false;
		if(null==destLeftSibling && null == destRightSibling)
			destUnexpandable = false;
*/
		//console.log("Source expandable " + srcExpandable);
		//console.log("Dest expandable " + destExpandable);
		//console.log("Dest UNexpandable " + destUnexpandable);
		//console.log("Source UNexpandable " + srcUnexpandable);
		

			if(srcExpandable){
				//console.log("Expanding: "+srcEl.id);
				Studio2.registerExpandableField( srcEl);
			}
			if(srcUnexpandable){
				Studio2.unregisterExpandableField(Studio2.expandableFields, srcEl.id);
			}
			if(destExpandable){
			//console.log("Expanding: "+destEl.id);
				Studio2.registerExpandableField(destEl);
			}
			if(destUnexpandable){
				Studio2.unregisterExpandableField(Studio2.expandableFields, destEl.id);
			}
		if(srcLeftSibling!==null && !Studio2.isSpecial(srcLeftSibling) && !Studio2.isSpecial(srcEl))
			Studio2.unregisterExpandableField(Studio2.expandableFields, srcLeftSibling.id);
		return;
    }

});


