﻿/**********************************************************
	Template control object
**********************************************************/

var currentlyManipulatedObject = null;
var dragOffsetX=0;
var dragOffsetY=0;
var currentZIndex = 0;
var typeOfAction = "";
var startCoordinates = [0,0];
var counter = 0;
var disableMousecommands = false;
var isFocusEnabled = true;
var showDragList = true;
var templateContainer = null;

var oldMouseDownHandler = document.onmousedown;
var oldMouseUpHandler = document.onmouseup;
var currentMouseUpHandler = null;

function onMouseMove(e)
{
    e = GetEvent(e);
    
    if (e.button<=1)
    {
        switch(typeOfAction)
        {
            case "DragDrop": onMouseMove_DragDrop(e); break;
            case "Resize": onMouseMove_Resize(e); break;
        }
    }
    return false;
}

function onMouseMove_Resize(e)
{
    var table = currentlyManipulatedObject.getElementsByTagName("table")[0];
    var localCoordinates = getScreenCoordinates(e);
    
    localCoordinates[0] += parseInt(templateContainer.scrollLeft) - parseInt(templateContainer.offsetLeft);
    localCoordinates[1] += parseInt(templateContainer.scrollTop) - parseInt(templateContainer.offsetTop);
    
    var dimensions = [localCoordinates[0] - parseInt(currentlyManipulatedObject.offsetLeft) - Template.GetContainer().offsetLeft, parseInt(localCoordinates[1]) - parseInt(currentlyManipulatedObject.offsetTop) - parseInt(Template.GetContainer().offsetTop)];
    currentlyManipulatedObject.style["minWidth"] = 0;
    currentlyManipulatedObject.style["width"] = Math.max(dimensions[0], 1) + "px";
    currentlyManipulatedObject.style["height"] = Math.max(dimensions[1], 1) + "px";

    //Dispatch a message
    EventManager.Notify(EventManager.CreateEvent("EVENT_RESIZING", eval("_" + currentlyManipulatedObject.id), GetObjectStyle(currentlyManipulatedObject), null));
    
    return false;
}

function onMouseMove_DragDrop(e)
{
    var screenCoordinates = getScreenCoordinates(e);
    currentlyManipulatedObject.style["left"] = (screenCoordinates[0]-dragOffsetX)+"px";
    currentlyManipulatedObject.style["top"] = (screenCoordinates[1]-dragOffsetY)+"px";
    
    //Dispatch a message
    EventManager.Notify(EventManager.CreateEvent("EVENT_DRAGGING", eval("_" + currentlyManipulatedObject.id), GetObjectStyle(currentlyManipulatedObject), null));
    
    return false;
}

function onCloneDropped(e)
{
	//must be defined by the TemplateEditor page
	CloneControl(currentlyManipulatedObject.id, currentlyManipulatedObject.style["left"], currentlyManipulatedObject.style["top"]);

    currentlyManipulatedObject = null;
    document.onmousemove = null;
    document.onmouseup = null;
    //SendToBack(control);    //reset z-Index

    return false;	
}

function onEndDrag(e)
{
    e = GetEvent(e);
    
    var control = currentlyManipulatedObject; 
    var currentlyManipulatedObjectContentTable = currentlyManipulatedObject.getElementsByTagName("table")[0]; 
    //currentlyManipulatedObjectContentTable.setAttribute(classAttribute, "");

    //Dispatch a message before we store the object's style
    //some other control may want to manipulate it first
    currentlyManipulatedObject.getElementsByTagName("input")[0].value = GetObjectStyle(currentlyManipulatedObject);    
    EventManager.Notify(EventManager.CreateEvent("EVENT_ENDDRAG", eval("_" + currentlyManipulatedObject.id), GetObjectStyle(currentlyManipulatedObject), null));
    
    currentlyManipulatedObject.style["zIndex"] = currentZIndex;

    //document.onmousemove();    
    currentlyManipulatedObject = null;
    document.onmousemove = null;
    document.onmouseup = null;
    //SendToBack(control);    //reset z-Index

    return false;
}

function onEndResize(e)
{
    e = GetEvent(e);
    
    
    var control = currentlyManipulatedObject;
    var currentlyManipulatedObjectContentTable = currentlyManipulatedObject.getElementsByTagName("table")[0]; 
    //currentlyManipulatedObjectContentTable.setAttribute(classAttribute, "");

    //save the stylesettings
    currentlyManipulatedObject.getElementsByTagName("input")[0].value = GetObjectStyle(currentlyManipulatedObject);

    //Dispatch a message
    EventManager.Notify(EventManager.CreateEvent("EVENT_ENDRESIZE", eval("_" + currentlyManipulatedObject.id), GetObjectStyle(currentlyManipulatedObject), null));
    
    //document.onmousemove();
    currentlyManipulatedObject = null;
    document.onmousemove = null;
    document.onmouseup = null;
    //SendToBack(control);    //reset z-Index
    
    
    
    //special case - when resizing and the mouse ends up outside the control 
    //and the resize ends, the onmouseout event is not called
    control.onmouseout();

    return false;
}

function onInitiateMouseDownCommand(e)
{
    if (disableMousecommands)
        return true;
        
    e = GetEvent(e);
    var target = GetTarget(e);
    
    try
    {
        if (target.getAttribute(classAttribute) == "DragableItemHeaderList")
            return onInitiateDrag(e);
        else if (target.getAttribute(classAttribute) == "DragableItem_ResizeHandle")
            return onInitiateResize(e);
    
        //Don't bother with this event, let the system handle it
        return oldMouseDownHandler();
    }catch(Error){}
}

function onInitiateMouseUpCommand(e)
{
    e = GetEvent(e);
    
    if (e.button<=1)
        ;//alert('Mousebutton released');
        
    return false;
}

var clonedControl = null;
var clonedControlElement = null;
var isCloning = false;
function onInitiateDrag(e)
{
    var target = GetTarget(e);
    var screenCoordinates = getScreenCoordinates(e);
    var rootObjectNameElement = target.getElementsByTagName("input")[0];
    if (rootObjectNameElement.id != "RootObjectName") return; 
    
    //Clone a control by hold the Ctrl key pressed while dragging it
    if (IsCtrlKeyPressed)
    {
		clonedControlElement = document.getElementById(rootObjectNameElement.value).cloneNode(100);

		var inputs = clonedControlElement.getElementsByTagName("input");
		var idStrip = clonedControlElement.id.replace(/_SpanItemBase/gi, "");

		inputs[5].value = "ClonedControl";
		inputs[6].value = "ClonedControl";
		for (var i=0; i<inputs.length; i++)
			inputs[i].id = inputs[i].id.replace(idStrip, "ClonedControl");

		var controlID = eval("_" + $get(rootObjectNameElement.value).id).GetControlID();		
		clonedControl = new TemplateBaseControlClass();
		clonedControl.Initialize(clonedControlElement, controlID);
		
		Template.GetContainer().appendChild(clonedControlElement);
		currentlyManipulatedObject = clonedControlElement;
		isCloning = true;
	}
    else
    {
		isCloning = false;
		currentlyManipulatedObject = $get(rootObjectNameElement.value);
	}

	
    var currentlyManipulatedObjectContentTable = currentlyManipulatedObject.getElementsByTagName("table")[0]; 
    //currentlyManipulatedObjectContentTable.setAttribute(classAttribute, "DragableItem_Dragging");
    document.onmousemove = onMouseMove;
    document.onmouseup = isCloning ? onCloneDropped : onEndDrag;
    dragOffsetX = screenCoordinates[0] - (parseInt(currentlyManipulatedObject.style["left"]) + parseInt(currentlyManipulatedObjectContentTable.offsetLeft));
    dragOffsetY = screenCoordinates[1] - (parseInt(currentlyManipulatedObject.offsetTop) + parseInt(currentlyManipulatedObjectContentTable.offsetTop));
    typeOfAction = "DragDrop";

    EventManager.Notify(EventManager.CreateEvent("EVENT_INITIATEDRAG", eval("_" + currentlyManipulatedObject.id), GetObjectStyle(currentlyManipulatedObject), null));

    return false;
}

function onInitiateResize(e)
{
    var target = GetTarget(e);
    var screenCoordinates = getScreenCoordinates(e);
    var rootObjectNameElement = target.getElementsByTagName("input")[0];
    if (rootObjectNameElement.id != "RootObjectName") return;

    currentlyManipulatedObject = document.getElementById(rootObjectNameElement.value); 
	templateContainer = document.getElementById("TemplateContentContainer");

    document.onmousemove = onMouseMove;
    document.onmouseup = onEndResize;

    typeOfAction = "Resize";

    EventManager.Notify(EventManager.CreateEvent("EVENT_INITIATERESIZE", eval("_" + currentlyManipulatedObject.id), GetObjectStyle(currentlyManipulatedObject), null));

    return false;
}

function ControlIsEditable(control, value)
{
    if (control != null && control.getAttribute(classAttribute).indexOf("DragableItemBase")>=0)
    {
        var inputControl = control.getElementsByTagName("input")[1];
        inputControl.value = value ? "1" : "0";
    }
}

///
function ToggleHeaderListVisibility(element, visibility)
{
    if (!currentlyManipulatedObject && (showDragList || visibility == "hidden"))
    {
        if (element.getAttribute(classAttribute) == "DragableItemHeaderList")
            element.style["visibility"] = visibility;
    }
}

///
function ToggleResizeHandleVisibility(element, visibility)
{
    if (!currentlyManipulatedObject)
    {
        if (element.getAttribute(classAttribute) == "DragableItem_ResizeHandle")
            element.style["display"] = visibility;
    }
}

function BringToFront(element)
{
    if (!currentlyManipulatedObject && isFocusEnabled)
    {
//        
//        if (!element.style["zIndex"])
//            element.style["zIndex"] = 0;

        if (element.style["zIndex"] != 100000)
        {
            
            currentZIndex = element.style["zIndex"];
            element.style["zIndex"] = 100000;
            //element.title = currentZIndex + "_" + element.style.zIndex;
            //element.title = element.style.left;
        }
    }
}

function SendToBack(element)
{
    if (!currentlyManipulatedObject)
    {
//        getParentNode(getParentNode(element)).style.zIndex = currentZIndex;
        element.style["zIndex"] = "";
        //alert(currentZIndex);
    }
}

///
///
///
//function CallbackFunction_PropertiesUpdated(event)
//{
//    var classObject = eval(("_" + event.sender.id));

//    try{
//        //defined in TemplateBaseControlExtensions.js
//        SetScroll(eval((event.sender.id + "_Scrollable")), event.sender.style);
//    }catch(err){}
//    
//    classObject.SetProperties(GetObjectStyle(event.sender));
//}

//EventManager.AddListener("EVENT_CONTROLPROPERTIESUPDATED", EventManager.CreateEventListener("UpdateControlPropertiesStyle", CallbackFunction_PropertiesUpdated));

//
function TemplateBaseControlClass()
{
    this.controlObject = null;
    this.contentContainer = null;
    this.propertyContainer = null;
    this.customPropertyContainer = null;
    this.editableContainer = null;
    this.controlID = 0;
    this.editingInline = false;
}

//
TemplateBaseControlClass.prototype.Initialize = function(controlObject, controlID, contentType)
{
	this.controlObject = controlObject;
	this.controlID = controlID;
	var hiddenFields = controlObject.getElementsByTagName("input");
	this.propertyContainer = hiddenFields[0];
	this.editableContainer = hiddenFields[1];
	this.contentContainer = hiddenFields[2];
	this.customPropertyContainer = hiddenFields[3];
	//    EventManager.AddListener("EVENT_EDITCONTROLCONTENT", EventManager.CreateEventListener("EditControlProperties", this.OnNotify, this));
	//    EventManager.AddListener("EVENT_CONTROLCONTEXTMENU", EventManager.CreateEventListener("ControlContextMenu", this.OnNotify, this));

	if (contentType == "EditDesign")
	{
		controlObject.onmouseover = function(e)
		{
			BringToFront(controlObject);
			ToggleResizeHandleVisibility($get(controlObject.id.replace("SpanItemBase", "ResizeHandle")), 'block');
			ToggleHeaderListVisibility($get(controlObject.id.replace("SpanItemBase", "PanelDragableItem_DragArea")), 'visible');
		}

		controlObject.onmouseout = function(e)
		{
			ToggleResizeHandleVisibility($get(controlObject.id.replace("SpanItemBase", "ResizeHandle")), 'none');
			ToggleHeaderListVisibility($get(controlObject.id.replace("SpanItemBase", "PanelDragableItem_DragArea")), 'hidden');
			SendToBack(controlObject);
		}
	}

	if (this.OnInitialized)
		this.OnInitialized();
}

//MUST BE OVERRIDEN!!
TemplateBaseControlClass.prototype.GetEditorControlID = function() { return null; }
TemplateBaseControlClass.prototype.GetCustomPropertyControlID = function() { return null; }
//Optional overrides
TemplateBaseControlClass.prototype.ContentUpdated = function() { /*"NOT IMPLEMENTED (::ContentUpdated)";*/ }
TemplateBaseControlClass.prototype.PropertiesUpdated = function() { /*"NOT IMPLEMENTED (::PropertiesUpdated)";*/ }
TemplateBaseControlClass.prototype.CustomPropertiesUpdated = function() { /*"NOT IMPLEMENTED (::CustomPropertiesUpdated)";*/ }

//
TemplateBaseControlClass.prototype.GetControlID = function() { return this.controlID; }
TemplateBaseControlClass.prototype.GetControlObject = function() { return this.controlObject; }
//
TemplateBaseControlClass.prototype.IsEditable = function() { return parseInt(this.editableContainer.value) == 1; }
TemplateBaseControlClass.prototype.IsDeleted = function() { return this.controlObject.style["display"] == "none"; }
TemplateBaseControlClass.prototype.IsInlineEditing = function() { return this.editingInline; }
TemplateBaseControlClass.prototype.SetEditable = function(boolValue) { this.editableContainer.value = boolValue ? "1" : "0"; }
TemplateBaseControlClass.prototype.ToggleEditable = function() { this.SetEditable(!(parseInt(this.editableContainer.value) == 1)); }
//
TemplateBaseControlClass.prototype.GetContent = function() { return this.contentContainer.value; }
TemplateBaseControlClass.prototype.SetContent = function(newContent)
{
	var classObject = this;
	//
	EventManager.Notify(EventManager.CreateEvent("EVENT_CONTROLCONTENTBEFORECHANGE", classObject, this.contentContainer.value, null));
    this.contentContainer.value = newContent; 
    EventManager.Notify(EventManager.CreateEvent("EVENT_CONTROLCONTENTCHANGED", classObject, newContent, null));
    
    //
    this.ContentUpdated();
}

//
TemplateBaseControlClass.prototype.GetProperties = function() { return this.propertyContainer.value; }
TemplateBaseControlClass.prototype.SetProperties = function(newProperties, bypassUndoHistory)
{
	var classObject = this;
	//
	if (!bypassUndoHistory)
	    EventManager.Notify(EventManager.CreateEvent("EVENT_CONTROLPROPERTIESBEFOREUPDATE", classObject, classObject.propertyContainer.value + ";", null));
	    
	this.propertyContainer.value = newProperties;
	
	//
	this.controlObject.style.setAttribute("cssText", newProperties);
	
	try{
        //defined in TemplateBaseControlExtensions.js
        SetScroll(eval(this.controlObject.id + "_Scrollable"), this.controlObject.style);
    }catch(err){}

	//The control should be the very first to know about the changes made
	this.PropertiesUpdated();

	//then everything else that signed up for the event
	if (!bypassUndoHistory)
	    EventManager.Notify(EventManager.CreateEvent("EVENT_CONTROLPROPERTIESUPDATED", classObject, newProperties + ";", null));
}

//
TemplateBaseControlClass.prototype.GetCustomProperties = function() { return this.customPropertyContainer.value; }
TemplateBaseControlClass.prototype.SetCustomProperties = function(newProperties) 
{
	var classObject = this;
	//
	EventManager.Notify(EventManager.CreateEvent("EVENT_CONTROLCUSTOMPROPERTIESBEFOREUPDATE", classObject, classObject.customPropertyContainer.value, null));
	
	this.customPropertyContainer.value = newProperties; 
	this.CustomPropertiesUpdated();
	
	//
	EventManager.Notify(EventManager.CreateEvent("EVENT_CONTROLCUSTOMPROPERTIESBEFOREUPDATE", classObject, newProperties, null));
}

TemplateBaseControlClass.prototype.GetWidth = function() { return this.controlObject.style["width"]; }
TemplateBaseControlClass.prototype.SetWidth = function(value) { this.controlObject.style["width"] = value; }
TemplateBaseControlClass.prototype.GetHeight = function() { return this.controlObject.style["height"]; }
TemplateBaseControlClass.prototype.SetHeight= function(value) { this.controlObject.style["height"] = value; }

TemplateBaseControlClass.prototype.GetOffsetY = function() { return this.controlObject.style["top"]; }
TemplateBaseControlClass.prototype.SetOffsetY = function(value) { this.controlObject.style["top"] = value; }
TemplateBaseControlClass.prototype.GetOffsetX = function() { return this.controlObject.style["left"]; }
TemplateBaseControlClass.prototype.SetOffsetX = function(value) { this.controlObject.style["left"] = value; }

//
TemplateBaseControlClass.prototype.HasContentChanged = function(newContent) { return newContent != this.GetContent(); }

//CCM Customization
//
var module = "";
var moduleParameters = "";

var co = null;
var wh = null;

///
/// Called by the editor window when it has finished loading
///	The contents is set by this function
///
function EditContentWindowLoaded()
{
	//alert('EditContentWindowLoaded');
	var content = co.GetCustomContent ? co.GetCustomContent() : co.GetContent();
	if (typeof content == "string")
        content = unescape(content);
	
	wh.SetData(content);
}

///
/// Resets the global editor window parameters
///
function CancelEditing()
{
	wh = null;
	co = null;
}

///
/// Called by the editor window when the user wants to save their changes
///
function FinishedEditingContent(classObject, content)
{
	//alert('FinishedEditingContent');
	if (content != null)
    {
		classObject = eval("_" + classObject);
        //Is custom processing of the content needed?
        if (classObject.PreProcessEditorContent)
            content = classObject.PreProcessEditorContent(content);
        if (classObject.HasContentChanged(content))
            classObject.SetContent(content);
	}
	
	wh = null;
	co = null;
}

///
///
///
function EditAdvancedPropertiesWindowLoaded()
{
	var properties= co.GetCustomProperties();
	wh.SetData(properties);
}

function FinishedEditingAdvancedProperties(classObject, content)
{
	classObject = eval("_" + classObject);
	if (content != null && content != classObject.GetCustomProperties())
        classObject.SetCustomProperties(content);
}

///
///
///
TemplateBaseControlClass.prototype.InlineEditContent = function(saveChanges)
{
	var label = embeddedControl_PresentationControls[this.controlObject.id];

	if (label != null)
	{
		this.editingInline = label.contentEditable = !this.editingInline;
		label.focus();
		if (!this.editingInline)
		{
			if (saveChanges != true)
				label.innerHTML = this.GetContent();	//restore the label to its previous state
			else
			{
				var content = label.innerHTML;			//the label now contains the updated text

				if (this.PreProcessEditorContent)
					content = this.PreProcessEditorContent(content);
				if (this.HasContentChanged(content))
					this.SetContent(content);
			}
		}
	}
}

//
TemplateBaseControlClass.prototype.EditContent = function()
{
	var top = window.frameElement.offsetTop + 46;
	var left = window.frameElement.parentNode.offsetLeft + 30;
	var width = 100, height = 100;
	
	if (this.GetEditorControlID() == "HTMLEditor")
		width = parseInt(document.documentElement.offsetWidth) - 60;
	
//    var content = this.GetCustomContent ? this.GetCustomContent() : this.GetContent();
    //var result = window.showModalDialog("/DotNet/TemplateModule/EditControlContent.aspx?ControlID=" + this.GetEditorControlID() + "&Module=" + module + "&" + moduleParameters, content, "center:0;dialogLeft:" + left + "px;dialogTop:" + top + "px;status:1;dialogWidth:" + width + "px;dialogHeight:100px;unadorned:1;scroll:0;resizable:1");
    
    if (wh != null && !wh.closed)
    {
		if (confirm("Varning! Du har redan ett redigeringsfönster aktivt för en kontroll, om du öppnar ett nytt så kommer ändringarna i det gamla fönstret att gå förlorade.\nVill du fortsätta?"))
		{
			try
			{
				wh.close();
			}
			catch(err){}
		}
		else
		{
			wh.focus();
			return;
		}

		wh = null;
	}
	co = this;
	var resizable = this.GetEditorControlID() == "HTMLEditor" ? 1 : 0;
    wh = window.open("/DotNet/TemplateModule/Web/EditControlContent.aspx?LoadFunc=EditContentWindowLoaded&SaveFunc=FinishedEditingContent&ControlID=" + this.GetEditorControlID() + "&Module=" + module + "&" + moduleParameters + "&TemplateControlID=" + this.controlObject.id, "", "location=0, toolbar=0, menubar=0, padding=0, scrollbars=0, status=1, resizable=" + resizable + ", left=" + left + ", top=" + top + ", width=" + width + ", height=" + height);
}

//
TemplateBaseControlClass.prototype.EditProperties = function() { EventManager.Notify(EventManager.CreateEvent("EVENT_SHOWPROPERTIES", this.controlObject, null, null)); }

//
TemplateBaseControlClass.prototype.EditCustomProperties = function()
{
//	var top = window.frameElement.offsetTop + 46;
//	var left = window.frameElement.parentNode.offsetLeft + 30;
//    var result = window.showModalDialog("/DotNet/TemplateModule/EditControlContent.aspx?ControlType=CustomProperties&ControlID=" + this.GetCustomPropertyControlID(), this.GetCustomProperties(), "center:0;dialogLeft:" + left + "px;dialogTop:" + top + "px;status:1;dialogWidth:100px;dialogHeight:100px;unadorned:1;scroll:0;resizable:0");
//    if (result != null && result != this.GetCustomProperties())
//        this.SetCustomProperties(result);

	var top = window.frameElement.offsetTop + 46;
	var left = window.frameElement.parentNode.offsetLeft + 30;
	var width = 100, height = 100;
	
//    var content = this.GetCustomContent ? this.GetCustomContent() : this.GetContent();
    //var result = window.showModalDialog("/DotNet/TemplateModule/EditControlContent.aspx?ControlID=" + this.GetEditorControlID() + "&Module=" + module + "&" + moduleParameters, content, "center:0;dialogLeft:" + left + "px;dialogTop:" + top + "px;status:1;dialogWidth:" + width + "px;dialogHeight:100px;unadorned:1;scroll:0;resizable:1");
    if (wh != null)
		wh.close();
	co = this;
    wh = window.open("/DotNet/TemplateModule/Web/EditControlContent.aspx?LoadFunc=EditAdvancedPropertiesWindowLoaded&SaveFunc=FinishedEditingAdvancedProperties&ControlType=CustomProperties&ControlID=" + this.GetCustomPropertyControlID() + "&Module=" + module + "&" + moduleParameters + "&TemplateControlID=" + this.controlObject.id, "", "location=0, toolbar=0, menubar=0, padding=0, scroll=0, status=1, resizable=0, left=" + left + ", top=" + top + ", width=" + width + ", height=" + height);
//    
	
}