/**********************************************************\
 Adapted from the sortable lists example by Tim Taylor
 http://tool-man.org/examples/sorting.html
 Modified by Tran Dat
\**********************************************************/
var TT_Drag = Class.create();
TT_Drag.prototype = {
    initialize : function () {
        this.big_zIndex = 99999;
        this.startX = undefined;
		this.startY = undefined;
		this.isDragging = false;
		this.initialMouseX = undefined;
		this.initialMouseY = undefined;
        this.DraggedHandle = undefined;
        this.DraggedElement = undefined;
		this._zIndex = undefined;
		this._pos = undefined;
        this.tt_bindFunctions();
    },
    
    tt_bindFunctions: function () {
        this.tt_startDrag = this.tt_startDrag.bindAsEventListener(this);
        this.tt_dragging = this.tt_dragging.bindAsEventListener(this);
        this.tt_endDrag = this.tt_endDrag.bindAsEventListener(this);
    },
    
	tt_makeDraggable : function (element, handle) {
		this.tt_onStart = new Function();
		this.tt_onFinished = new Function();
		this.tt_onDragging = new Function();
		this.DraggedElement = element;
		handle.onmousedown = this.tt_startDrag;
	},
    
    tt_startDrag: function (e) {
		var evt = e || window.event;
		this.initialMouseX = evt.clientX;
		this.initialMouseY = evt.clientY;
        this.startX = this.DraggedElement.offsetLeft;
		this.startY = this.DraggedElement.offsetTop;
		this.isDragging = false;
		this._zIndex = this.DraggedElement.style['zIndex'];
		this._pos = this.DraggedElement.style['position'];
        this.DraggedElement.style['zIndex'] = this.big_zIndex;
        this.DraggedElement.style['position'] = 'absolute';
        this.DraggedElement.style['border'] = '1px solid #000';
        this.tt_setPosition(this.startX, this.startY);
        this.tt_onStart(this.DraggedElement);
        var opt = {style:{'backgroundColor': 'transparent'}};
		Event.observe(document, 'mousemove', this.tt_dragging, false);
		Event.observe(document, 'mouseup', this.tt_endDrag, false);
    },
    
    tt_dragging: function (e) {
		var evt = e || window.event;
        this.DraggedElement.style['cursor'] = 'move';		
        var pageOffset = document.viewport.getScrollOffsets();
        var mouse = {
            x : evt.clientX + pageOffset[0],
            y : evt.clientY + pageOffset[1]
        };
		var dX = evt.clientX - this.initialMouseX;
		var dY = evt.clientY - this.initialMouseY;
		this.isDragging = true;
		this.tt_setPosition(dX,dY);
        this.tt_onDragging(mouse, this.DraggedElement);
    },
    
	tt_setPosition: function (dx,dy) {
		//this.DraggedElement.style['left'] = (this.startX + dx) + 'px';
		this.DraggedElement.style['top'] = (this.startY + dy) + 'px';
	},
    
    tt_endDrag: function () {
        this.DraggedElement.style['zIndex'] = this._zIndex;
        this.DraggedElement.isDragging = this.isDragging;
        this.DraggedElement.style['position'] = this._pos;
        this.DraggedElement.style['border'] = '';
        this.DraggedElement.style['cursor'] = '';        
        Event.stopObserving(document, 'mousemove', this.tt_dragging, false);
		Event.stopObserving(document, 'mouseup', this.tt_endDrag, false);
        this.tt_onFinished(this.DraggedElement);
    },

};

/**********************************************************\
   -   Drag Drop Object
    -   Adapted from the sortable lists example by Tim Taylor
    -   http://tool-man.org/examples/sorting.html
    -   Modified by Tran Dat
\ **********************************************************/
var TT_GridDragDrop = Class.create();
TT_GridDragDrop.prototype = {
    initialize : function () {
        this.LayoutInstance = null;
        this.nextThis = null;
        this.newContainer = null;
        this.listContainer = new Array();
        this.divTmpTarget = new Element("div", {'id':'cel_target'});
        this.tt_endDropCallBack = new Function();
        this.tt_bindFunctions();
        this.listID = {};
    },
    
    tt_bindFunctions: function () {
        this.tt_onStart = this.tt_onStart.bind(this);
        this.tt_onDragging = this.tt_onDragging.bind(this);
        this.tt_onFinished = this.tt_onFinished.bind(this);
    },
    
	tt_makeListContainer : function (containerItem) {
        this.listContainer.push(containerItem);
	},
    
    tt_makeDraggable: function (item, handle) {
		var Drag = new TT_Drag();
        Drag.tt_makeDraggable(item, handle);
		Drag.tt_onStart = this.tt_onStart;
        Drag.tt_onDragging = this.tt_onDragging;
		Drag.tt_onFinished = this.tt_onFinished;
    },
    
    tt_createTargetFrame : function (item) {
        this.divTmpTarget.style["width"] = (this.newContainer.getWidth() - 5) + "px";
        this.divTmpTarget.style["height"] = (item.getHeight() + 5) + "px";
        this.divTmpTarget.style["position"] = "relative";
        this.divTmpTarget.className = "tt_indicateCell";
    },

	tt_nextItem : function(item) {
		var sibling = item.nextSibling;
		while (sibling != null) {
			if (sibling.nodeName == item.nodeName) return sibling;
			sibling = sibling.nextSibling;
		}
		return null;
	},
    
    tt_onStart: function (item) {
        this.nextThis = this.tt_nextItem(item);
        this.newContainer = item.parentNode;
        this.tt_createTargetFrame(item);
        item.parentNode.insertBefore(this.divTmpTarget, item);
    },
    
    tt_onDragging: function (mouse, draggedItem) {
        if (!Position.within(this.newContainer, mouse.x, mouse.y))
            for (var i=0; i<this.listContainer.length; i++)
                if (Position.within(this.listContainer[i], mouse.x, mouse.y)) {
                    this.newContainer = this.listContainer[i];
                    break
                }
        var itemList = this.newContainer.childNodes;
        var item = null;
        for (var i=0; i<itemList.length; i++) {
            if(mouse.y <= itemList[i].offsetTop) {
                item = itemList[i];
                break
            }
        }
        this.tt_createTargetFrame(draggedItem);
        this.newContainer.insertBefore(this.divTmpTarget, item);
        this.nextThis = item;
    },
    
    tt_onFinished: function (item) {
        if (this.newContainer!=null) {
            item.style["top"] = "0px";
            item.style["left"] = "0px";
            this.newContainer.insertBefore(item, this.nextThis);
        }
        this.nextThis==null;
        if ($('cel_target')) $('cel_target').remove();
        this.tt_endDropCallBack(item);
    }
}


TT_RasterDragDrop = Class.create();
TT_RasterDragDrop.prototype = {
    initialize : function () {
        this.startX = 0;
        this.startY = 0;
        this.Container = null;
        this.tt_endDropCallBack = new Function();
    },
    
	tt_setContainerItem : function (container) {
        this.Container = container;
	},
    
	tt_makeItemDragable : function (item, handle) {
        var Drag = new TT_Drag();
		Drag.tt_makeDraggable(item, handle);
        this.tt_onStart = this.tt_onStart.bind(this);
        this.tt_onFinished = this.tt_onFinished.bind(this);
        Drag.tt_onStart = this.tt_onStart;
        Drag.tt_onFinished = this.tt_onFinished;
	},
    
    tt_onStart: function (item) {
        this.startX = item.offsetLeft;
		this.startY = item.offsetTop;
    },
    
    tt_onFinished: function (item) {
        var res = this.tt_checkNewWndPos(item);
        if (res) this.tt_endDropCallBack(item);
        else this.tt_restoreWndPos(item);
    },

    tt_checkNewWndPos: function(wnd){
		try {
        var pos = Position.cumulativeOffset(wnd);
        var se_x = parseInt(pos[0]) +  wnd.getWidth();
        var se_y = parseInt(pos[1]) +  wnd.getHeight();
        var res1 = Position.within( this.Container, se_x, se_y );
        var res2 = Position.within( this.Container, pos[0], pos[1] );
        return (res1 && res2)
		} catch (e) {return false}
	},
    
	tt_restoreWndPos: function(item) {
		item.style['left'] = this.startX + "px";
		item.style['top'] = this.startY + "px";
	}
};

var TT_ConfirmDialog = Class.create({
	initialize: function () {
		this.tt_bindFunctions();
		this.tt_buildGUI();
		this.tt_registerEvents();
	},
	
	tt_bindFunctions: function () {
        this.tt_handleYesClick = this.tt_handleYesClick.bindAsEventListener(this);
        this.tt_handleNoClick = this.tt_handleNoClick.bindAsEventListener(this);	
	},
	
	tt_buildGUI: function (){
        var btnNo  = {id: 'no',  value : 'no'};
        var btnYes = {id: 'yes', value : 'yes', isDefault: true};
        this.dialog = new TT_Dialog ('Confirm', '', [btnYes, btnNo], 300);
        this.dialog.tt_customField("Do you want to save ?");
        this.dialog.onEsc = this.tt_handleNoClick.bind(this);
        this.dialog.onEnter = this.tt_handleYesClick.bind(this);		
	},

    tt_registerEvents: function () {
        Event.observe($('btnyes'), 'click', this.tt_handleYesClick, false);
        Event.observe($('btnno'), 'click', this.tt_handleNoClick, false);
    },	
    
    tt_handleNoClick: function () {
        this.dialog.tt_closeDialog();
    },
    
    tt_handleYesClick: function () {
    	this.dialog.tt_closeDialog();
		TT_Event.notify(this, 'ok', GridDragDrop.listID);    	
    }    
});

var TT_Confirm = Class.create({
	initialize: function (url, name) {
			this.name = name;
			this.url = ANTIKGUIDE_PATH + url;
	        this.tt_bindFunctions();
	},
	
	tt_bindFunctions: function () {
		this.tt_confirmProc = this.tt_confirmProc.bindAsEventListener(this);
		this.tt_callback = this.tt_callback.bindAsEventListener(this);		
	},
	
	tt_showConfirm: function () {
		var Confirm = new TT_ConfirmDialog();
		TT_Event.observe(Confirm, 'ok', this.tt_confirmProc);
	},
	
	tt_confirmProc: function (listID) {
		Waitting.tt_show();
		listID["name"] = this.name;
        new Ajax.Request( this.url + '/dragTemplate', {
            parameters: {data: $H(listID).toJSON()},
            onComplete: this.tt_callback
        });
	},
	
	tt_callback: function (transport) {
        try { $('content').update(transport.responseText);
        } catch (e) { alert('add haendler callback error' + e.toString()); }
        Waitting.tt_close();	
	},
})
 