/// <reference path="wz_dragdrop.js" />
/// <reference path="DDUtils.js" />
/// <reference path="DragHelper.js" />

var Class_HOLDER = 'comp_holder';
var Class_Component = "Components";
var pos_Absolute = 'absolute';
var pos_Relative = 'relative';
var _containers = new Array();
var _oldLocation;
var yOld, xOld;
var xNew, yNew;
var _templateBox = null;
var _containerBox = null;

function my_PickFunc()
{
    var itemName    = dd.obj.name;
    var parentName  = dd.obj.parent.name;
    _oldLocation = Sys.UI.DomElement.getLocation($get(itemName));
  
    var bounds = GetElementBounds($get(itemName), null);
    if (itemName.indexOf("Elem") > -1 && dd.obj.is_dragged)
    {
        ShowDropCue($get(parentName), $get(itemName), bounds);
    }    
    if (dd.obj.parent)
    {
        dd.obj.parent.maximizeZ();
    }
    dd.obj.maximizeZ();
        
}  

function my_DragFunc()
{
    var itemName    = dd.obj.name;
//    var location    = Sys.UI.DomElement.getLocation($get(itemName));
    var location    = new Sys.UI.Point(dd.e.x, dd.e.y);
    var container   = FindTargetContainer(location.x, location.y); 
    RepositionDropCue(container, $get(itemName), location.x, location.y);    
//    if (container != null)
//    {
//        window.status = container.id  + ':: (' + location.x + ',' + location.y + ')';
//    }
    
}


function my_DropFunc()
{
    var itemName    = dd.obj.name;
    var parentName  = dd.obj.parent.name;
    var parentObj   = $get(parentName);

    var bounds = GetElementBounds($get(itemName));
    if (dd.obj.is_resized)
    {
        Golwgn.UI.Services.LayoutHandler.SaveLocation(itemName, bounds.x, bounds.y, bounds.width, bounds.height, parentName, OnMethodSucceeded, OnMethodFailed,'');
        ReAlignContainers(parentObj);
        HideDropCue();
        return;
    }
    if (_oldLocation.x == bounds.x && _oldLocation.y == bounds.y)
    {
        HideDropCue();
        return;
    }
    
    var dropSuccess = false;
    var targetContainer = _targetContainer;
    var targetContainerName;
    var dropcueBounds = GetDropCueBounds();
        
    if (targetContainer)
    {
        targetContainerName = targetContainer.id;
        var holder = FindChildByClass(targetContainer, Class_HOLDER);
        if(holder)
        {
            var childObj = RemoveAndCloneChild(itemName);
            dd.obj.del();    
            holder.insertBefore(childObj, _dropCue);
            ADD_DHTML(itemName);
            dd.elements[targetContainerName].attachChild(itemName);
            dropSuccess = true;
            HideDropCue();
        }
    }
    if (dropSuccess)
    {
        dd.elements[itemName].resizeTo(dd.elements[targetContainerName].w, dropcueBounds.height);
        if (targetContainerName != parentName)
        {
            AdjustElements(parentName);
		    ReAlignContainers(parentObj);
            SaveComponentOrder(parentObj);
        }
        AdjustElements(targetContainerName);
		ReAlignContainers(targetContainer);
        SaveComponentOrder(targetContainer);
        
        dd.elements[targetContainerName].maximizeZ();
        dd.elements[itemName].maximizeZ();
        var bounds = GetComponentBounds(dd.elements[itemName]);
        Golwgn.UI.Services.LayoutHandler.SaveLocation(itemName, bounds.x, bounds.y, bounds.width, bounds.height, targetContainerName, OnMethodSucceeded, OnMethodFailed,'');
    }
    else
    {
        dd.obj.moveTo(_oldLocation.x, _oldLocation.y);
    }
    ResizeTemplate();
    HideDropCue();

}    
   

function RemoveAndCloneChild(childName)
{
    var childObj = $get(childName);
    var clonedObj;
    if (childObj)
    {
        var parentObj = $get(childName).parentNode;
        for(var i = 0; i < parentObj.childNodes.length; i++)
        {    
            if(parentObj.childNodes[i].id == childName)
            {
                clonedObj = parentObj.removeChild(parentObj.childNodes[i]);
                break;
            }
        }
    }
    return clonedObj;
}   

function my_ResizeFunc()
{
    if (dd.obj)
    {
        var containerName = dd.obj.parent.name;
        var itemName = dd.obj.name;
        RepositionComponents(containerName, itemName);
        ResizeTemplate();
    }
    
}

function AdjustElements(containerName) {
    AdjustElements(containerName, null, true);
}

function AdjustElements(containerName, itemToIgnore, ignoreDropCue) {
    var container = $get(containerName)
    var location  = Sys.UI.DomElement.getLocation(container);
    var y = 8;
    var holder = FindChildByClass($get(containerName), Class_HOLDER);
    for (var i =0 ; i < holder.childNodes.length; i++)
    {
        var item = holder.childNodes.item(i);
        if (item && item.id)
        {
            var itemName = item.id.toString();
            if (itemName.indexOf("Elem") > -1 ||
                (!ignoreDropCue && item.className != null && item.className == Class_DROPCUE && item.style.visibility =='visible'))
            {
                if (item != itemToIgnore)
                {
                    var bounds = Sys.UI.DomElement.getBounds(item);
					
                    if (dd.elements[itemName]) {
						item.style.position = pos_Absolute;
						var top = parseInt(location.y) + y;
                        dd.elements[itemName].moveTo(location.x, top);
                        //alert(top + ', ' +  dd.elements[itemName].y);
                    }
                    Sys.UI.DomElement.setLocation(item, 0, y);
                    
                    y += parseInt(bounds.height) + 8;
                }
            }
        }
    }
}

function GetTargetContainer()
{
    var targetName, targetContainer, targetContainerName;
    var dropTarget = dd.obj.getEltBelow();
    if(dropTarget != null )
    {
        targetName = dropTarget.name;
        if (dropTarget.name.indexOf('Container') > -1 ) //3 : Another container
        {
            targetContainerName = targetName;
            targetContainer     = $get(targetContainerName);
        }
        else if (dropTarget.name.indexOf("Elem") > -1 ) //4 : Component in another container.
        {
            targetContainerName = dropTarget.parent.name;
            targetContainer     = $get(targetContainerName);
        }        
    }
    return targetContainer;
}


function RepositionComponents(containerName, currentItem)
{
    var location    = Sys.UI.DomElement.getLocation($get(containerName));
    var y           =  8;
    var holder      = FindChildByClass($get(containerName), Class_HOLDER);
    var itemFound = false;
    for (var i =0 ; i < holder.childNodes.length; i++)
    {
        var item = holder.childNodes.item(i);
        if (item && item.id)
        {
            var itemName = holder.childNodes[i].id;
            if (itemName.indexOf("Elem") > -1)
            {
                var bounds = Sys.UI.DomElement.getBounds(item);
                if (itemFound)
                {
                    Sys.UI.DomElement.setLocation(item, 0, y);
                    if (dd.elements[itemName])
                    {
                        dd.elements[itemName].moveTo(location.x, location.y + y);
                    }
                }
                if (itemName == currentItem)
                {
                   itemFound = true;
                }
                y += bounds.height + 8;
            }
        }
    }
}

function Initialize(templateHolder, containerHolder)
{
    if (containerHolder != null && templateHolder != null)
    {
		_templateBox  = templateHolder;
		_containerBox = containerHolder;
        for (var i = 0 ;i < containerHolder.childNodes.length; i++)
        {
           var item = containerHolder.childNodes.item(i);
           if(item.id && item.id.indexOf("Container") > -1) {
               _containers.push(item.id);
                //## REMOVED 28th July - Orig
                //AdjustElements(item.id);
           }
        }
        ResizeTemplate();
    }
}

function FindTargetContainer(x, y)
{
    var container = null;
    for (var i = 0 ; i < _containers.length; i++)
    {
        var containerName = _containers[i];
        var tempContainer = $get(containerName);
        var bounds = Sys.UI.DomElement.getBounds(tempContainer);
        var allowEdit = tempContainer.getAttributeNode("_allowEdit").nodeValue;
        if (allowEdit == "True" &&  bounds.y <= y && y < bounds.y + bounds.height)
        {
            if (bounds.x <= x && x < bounds.x + bounds.width)
            {
                container = $get(containerName);
                break;
            }
        }
    }
    return container;
}

function ResizeTemplate()
{
	if (_templateBox != null && _containerBox != null)
	{
		var bounds = Sys.UI.DomElement.getBounds(_templateBox);
		var maxHeight = 0;
		for (var i = 0 ;i < _containerBox.childNodes.length; i++)
		{
			var item = _containerBox.childNodes.item(i);
			if(item.id && item.id.indexOf("Container") > -1)
			{
				var tempHeight = GetContainerHeight(item, null, true);
				if (tempHeight > maxHeight)
				{
					maxHeight = tempHeight;
				}
				ReAlignContainers(item);
			}
		}
		if (maxHeight > 530)
		{
			_templateBox.style.height = maxHeight + 190 + 'px';  //## this should be 110 when login is on homepage

        }

	}
}

function GetContainerHeight(container, itemToIgnore, ignoreDropCue)
{
    var height = 0;
	if (container != null) 
	{
		var bounds = Sys.UI.DomElement.getBounds(container);
		//height += bounds.y;
		var holder = FindChildByClass(container, Class_HOLDER);
		for (var i =0 ; i < holder.childNodes.length; i++)
		{
			var item = holder.childNodes.item(i);
			if (item && item.id)
			{
				var itemName = holder.childNodes[i].id;
				if (itemName.indexOf("Elem") > -1 ||
					(!ignoreDropCue && item.className != null && item.className == Class_DROPCUE && item.style.visibility =='visible'))
				{
					if (item != itemToIgnore)
					{
						var bounds = Sys.UI.DomElement.getBounds(item);
						height += bounds.height + 8;
					}
				}
			}
		}
		height = (bounds.height > height ? bounds.height : height);
	}

    return height;

}


function ReAlignContainers(container)
{
	if (container == null)
	{
		return;
	}
	
	try
	{
	var topMargin =  50;
	if(_templateBox != null)
	{
		var bounds = Sys.UI.DomElement.getBounds(_templateBox);
		topMargin = bounds.y;
	}
	var height = GetContainerHeight(container, null, true);
	var cBounds = Sys.UI.DomElement.getBounds(container);
	var xLeft	= cBounds.x;
	var xRight	= cBounds.x + cBounds.width;
	var yTop	= cBounds.y;
	var yBottom = cBounds.y + ( height > cBounds.height ? height : cBounds.height);
//	var yBottom = ( height > cBounds.height ? height : cBounds.height);

//	if (height < cBounds.height)
//	{ // Component is resized, but the content is still with in the height of the container.
//		return;
//	}
		for (var i = 0 ; i < _containers.length; i++)
		{
			var containerName = _containers[i];
			var tempContainer = $get(containerName);
			if (tempContainer != container)
			{
				var bounds = Sys.UI.DomElement.getBounds(tempContainer);
				var yTest = (yTop <= bounds.y && bounds.y <= yBottom) ;
				// Test if the target falls with in source along the x-axis (horizontal) .
				var xs1Test = (xLeft <= bounds.x && bounds.x <=  xRight) ;
				var xs2Test = (xLeft <= bounds.x + bounds.width  && bounds.x + bounds.width <= xRight);
				
				// Test if the source falls with in target along the x-axis (horizontal) .
				var xt1Test = (bounds.x <= xLeft && xLeft < bounds.x + bounds.width) ;
				var xt2Test = (bounds.x <= xRight && xRight < bounds.x + bounds.width) ;
				
				if (yTest && (xs1Test || xs2Test || xt1Test || xt2Test))
				{
	//                alert( container.id + '(' +xLeft + ',' + yTop + ',' + xRight + ',' + yBottom + '),\r\n' + 
	//                containerName + '(' + bounds.x  + ',' + bounds.y + ',' + bounds.width + ',' + bounds.height + ')' );
					Sys.UI.DomElement.setLocation(tempContainer, 0, yBottom-topMargin	);
					ReAlignContainers(tempContainer);

				}
			}
		}
    }
    catch(e) 
    {
//		alert(e.toString());
    }
}

function SaveComponentOrder(container)
{
	var tempOrder = 1;
	var orderString = "";
	if (container != null) 
	{
		//height += bounds.y;
		var holder = FindChildByClass(container, Class_HOLDER);
		for (var i =0 ; i < holder.childNodes.length; i++)
		{
			var item = holder.childNodes.item(i);
			if (item && item.id)
			{
				var itemName = holder.childNodes[i].id;
				if (itemName.indexOf("Elem") > -1)
				{
					var compID = itemName.substring(4);
					orderString +=  (orderString.length == 0? "" : ",")  + tempOrder + "-" + compID
					tempOrder++;
				}
			}
		}
		
		// Call the web service to save the component display order
        Golwgn.UI.Services.LayoutHandler.SaveComponentOrder(container.id, orderString, OnMethodSucceeded, OnMethodFailed,'');
 
	}

}