var _Dragged=null;
var _ActiveField=null;
var _DlgWinFeatures="location=0, toolbar=0, status=0, menubar=0, scrollbars=1, resizable=1, width=640, height=500";

/* --------------------------------------------------------------------------------
Drag & Drop
---------------------------------------------------------------------------------*/

function cancelEvent() {
	window.event.returnValue = false;
}

function initDrag(oElem) {
	if (_Dragged==null) {
		oElem.dragDrop();
	} else { _Dragged=null; }
	event.returnValue=false;
}

function onDrop(oElem) {
	var oData = window.event.dataTransfer;
	var oFrm = document.createElement("IFRAME"); 
	oFrm.width=200;
	oFrm.height=200;
 
    //Try to get dragged element from current page
	var oDragged=( parent.frmRight!=null ? parent.frmRight._Dragged : _Dragged );
	//The element may also be dragged from the left frame
	if (oDragged==null) { oDragged=parent.frmLeft._Dragged; }

	oFrm.width=1;oFrm.height=1;oFrm.border=0;
	document.body.appendChild(oFrm);
	
	var sPlacement=(chkInBoundary(window.event,oElem)==1 ? "before" : "after");
	
	oFrm.src="/eway/applications/portaldesigner/portalEditActions.aspx?drag=" + oDragged.id + "&drop=" + oElem.id + "&placement=" + sPlacement;
    window.status=oFrm.src;
	_Dragged=null;
	event.cancelBubble=true;
	event.returnValue=false;

	return true;
}

function onDropLeft(oElem) {
    _Dragged=null;
}

function onDragStart() {
	var oData = window.event.dataTransfer;
	_Dragged=window.event.srcElement;

	if (_Dragged.id==null || _Dragged.id.indexOf("dd")==-1) {
		while (_Dragged.id==null || _Dragged.id.indexOf("outl")==-1) {
			_Dragged=_Dragged.parentElement;
		}
	}
	oData.effectAllowed="move";
	oData.dropEffect="move";
	event.cancelBubble=true;
}

function onDragEnter(oElem) {
    return false;
}

function onDragOver(oElem) {
    window.event.cancelBubble=true;
    displayDropMarker(window.event,oElem);
    return false;
}

function onDragEnd(oElem) {
    _Dragged=null;
    var oDiv=document.getElementById("divDropMarker");
    if (oDiv==null) oDiv=parent.frmRight.window.document.getElementById("divDropMarker"); 
    if (oDiv!=null) oDiv.style.display="none";
   
    return true;
}

/* --------------------------------------------------------------------------------
End - Drag & Drop
---------------------------------------------------------------------------------*/









/* --------------------------------------------------------------------------------
Designer tree
---------------------------------------------------------------------------------*/

function nodeClicked(sTreeCtl, sValuePath) {
    parent.frmRight.location.href="redirector.aspx?valuepath=" + sValuePath + "&e=" + _EditMode;
}


    
function contextMenuItemClicked(sTreeId,sCmd) {
    var sNodeValue=contextMenuNode(sTreeId);
    var aNodeValue=sNodeValue.split("_");
    switch (sCmd) {
        case "area_addelement":
            var aNodeValue=sNodeValue.split("_");
            var pid=aNodeValue[1];
            var aid=aNodeValue[2];
            var area=aNodeValue[3];
            var oWin=window.open("createElementWizard.aspx?pid=" + pid + "&areaname=" + area + "&elemid=" + aid + "&addas=pagearea","wiz", _DlgWinFeatures);
            oWin.focus();      
            break;
        case "portal_props":
            var pid=aNodeValue[1];
            var oWin=window.open("properties.aspx?tabpage=portal&pid=" + pid,"wiz", _DlgWinFeatures);
            oWin.focus();      
            break;
        case "portal_editmode":
            if (_EditMode==1) { _EditMode=2; } else { _EditMode=1; }
            break;
        default:
            alert("Not Implemented");
            break;        
    }
}


/* --------------------------------------------------------------------------------
End - Designer tree
---------------------------------------------------------------------------------*/


/* --------------------------------------------------------------------------------
Inline editing - marker
---------------------------------------------------------------------------------*/

function displayBoundary(oElem) {
    if (oElem==null) oElem=window.event.srcElement;
    var oElem=document.getElementById(oElem.id.substr(0,oElem.id.length-1));
    if (oElem!=null) {
        oDiv=document.getElementById("divBoundary");
        if (oDiv!=null) {
            oDiv.style.top=findPos("sy",oElem);
            oDiv.style.left=findPos("sx",oElem);
            oDiv.style.height=oElem.offsetHeight;
            oDiv.style.width=oElem.offsetWidth;
            oDiv.style.display="block";
            event.cancelBubble=true;
        }
    }
    //oElem=getContainer(oElem,"outl");
}

function displayDropMarker(oEvent, oElem) {
    oElem=getContainer(oElem,"outl");

    oDiv=document.getElementById("divDropMarker");

    oDiv.style.left=findPos("sx",oElem);
    oDiv.style.width=oElem.offsetWidth;
    oDiv.style.border="";
    oDiv.style.borderTop="solid 1px black";
    if (chkInBoundary(oEvent,oElem)==1) {
        oDiv.style.top=findPos("sy",oElem);
    } else {
        oDiv.style.top=findPos("ey",oElem);
    }
    oDiv.style.display="block";
}

function hideBorder(elem) {
    return (!chkInBoundary(window.event,elem));
}

function initEditImages() {
    window.detachEvent("onresize",initEditImages);
    var aElems=document.getElementsByTagName("div");
    for (var i=0; i<aElems.length; i++) {
        var oElem=aElems[i];
        if (oElem.id!=null) {
            if (startsWith(oElem.id,"outl")) {
                var nDx=2,nDy=2;
                if (oElem.id.indexOf("_")>-1) nDx=-9;
                var x=findPos('sx',oElem); var y=findPos('sy',oElem);
                var oImg=document.getElementById(oElem.id + "i");
                if (oImg!=null) {
                    oImg.onmouseover=displayBoundary;
                    oImg.style.left=x+nDx;
                    oImg.style.top=y+nDy;
                    oImg.style.cursor="pointer";
                }
            }            
            if (startsWith(oElem.id,"highlight")) {
                var sHighlight=oElem.id.split("!")[1];
                var oHighlight=document.getElementById("outl!" + sHighlight);
                if (oHighlight!=null) {
                    oElem.style.left=findPos("sx",oHighlight);
                    oElem.style.top=findPos("sy",oHighlight);
                    oElem.style.height=oHighlight.offsetHeight;
                    oElem.style.width=oHighlight.offsetWidth;
                    oElem.style.display="block";
                }
            }
        }
    }
    window.attachEvent("onresize",initEditImages);

    var oElem=document.getElementById("divEditHighLight");
}

/* --------------------------------------------------------------------------------
End - Inline editing - marker
---------------------------------------------------------------------------------*/


/* --------------------------------------------------------------------------------
DOM Functions
---------------------------------------------------------------------------------*/

function findPos(coord,obj){
    var curPos = 0;
    switch (coord) {
        case "ex": curPos+=obj.offsetWidth; break;
        case "ey": curPos+=obj.offsetHeight; break;
    }
    while(obj){
        if(obj.style.position !="absolute"){
            switch (coord) {
                case "sx": case "ex":
                    curPos += obj.offsetLeft; break;
                case "sy": case "ey":
                    curPos += obj.offsetTop; break;
            }
        } else {
            switch (coord) {
                case "sx": case "ex":
                    curPos += parseInt(obj.style.left); break;
                case "sy": case "ey":
                    curPos += parseInt(obj.style.top); break;
            }
        }
        obj =  obj.offsetParent;
    }
    return curPos;
}

function chkInBoundary(e, obj) {
    var mx=e.clientX; var my=e.clientY + document.body.scrollTop;
    var sx=findPos("sx",obj); var sy=findPos("sy",obj);
    var ex=findPos("ex",obj); var ey=findPos("ey",obj);
    if (mx>=sx && mx<=ex && my>=sy && my<=ey) {
        if (my > (ey-((ey-sy)/2)) ) return 2; else return 1;
    } else {
        return 0;
    }
}

function getContainer(obj, sFindPrefix) {
    while (true) {
        if (!(obj.id!=null && obj.id.substr(0,sFindPrefix.length)==sFindPrefix)) {
            obj=obj.parentElement; }
        else { break; }
    }
    return obj
}

function setElemPositionAtPointer(oEvent, oTargetElem) {
	nHeight=oTargetElem.offsetHeight;
	nScrollTop=document.body.scrollTop;
	
	nPosY1=window.event.clientY + nScrollTop;
    oTargetElem.style.posTop=nPosY1-2;

	nWidth=oTargetElem.offsetWidth;
	nPosX1=window.event.clientX + document.body.scrollLeft;

	oTargetElem.style.posLeft=nPosX1-2; 
}




/* --------------------------------------------------------------------------------
End - DOM Functions
---------------------------------------------------------------------------------*/



/* --------------------------------------------------------------------------------
Inline Editing
---------------------------------------------------------------------------------*/

function displayEditContextMenu(oElem) {
    document.body.detachEvent("onclick",hideEditContextMenu);
    var oEvent=window.event;
    var oMenu=document.getElementById("editMenu");

    _ActiveField=getContainer(oElem,"fld_");
        
    oMenu.style.display="block";
    oMenu.style.zIndex=1000;
    
    oElem=document.getElementById("editMenun2");
    oElem.detachEvent("onmouseover",setSubMenuPosition);
    oElem.attachEvent("onmouseover",setSubMenuPosition);
    var aLinks=oElem.getElementsByTagName("A");
    if (aLinks.length>0) { 
        aLinks[0].removeAttribute("href");
        aLinks[0].style.cursor="default";
        aLinks[0].attributes("onclick").value="return false;";
    }

    setElemPositionAtPointer(oEvent,oMenu);
    document.body.attachEvent("onclick",hideEditContextMenu);
    updateFields();
    return false;
}

function updateFields() {

    var oInput=null;
    var oFrm=document.getElementsByTagName("FORM")[0];
    var aFields=document.getElementsByTagName("SPAN");
    for (var i=0; i<aFields.length; i++) {
        var oField=aFields[i];
        if (oField.id!=null && oField.id.substr(0,4)=="fld_" && oField.dirtyflag=="1") {
            var sId=oField.id + "_i";
        
            oInput=document.getElementById(sId);
            if (oInput==null) { 
                oInput=document.createElement("INPUT"); 
                oInput.type="hidden";
                oInput.name=sId;
                oInput.id=sId;
                oFrm.appendChild(oInput);
            }
            oInput.value=oField.innerHTML;
        }
    }
}

function setDirtyFlag(element,_event){

    try{
        if((!IsNull(_event)) && (!IsNull(_event.keyCode))){
            
            if((_event.keyCode == 8) || (_event.keyCode == 46) || (_event.keyCode == 16) || (_event.keyCode == 17)){
                if(!IsNull(element)){
                    element.dirtyflag = '1';
                }
            }
        }
    }catch (exception){}
}

//check if obj is null or undefined
function IsNull(obj){
    return ((obj == null) || (obj == undefined));
}

function hideEditContextMenu() {
    var oMenu=document.getElementById("editMenu");
    oMenu.style.display="none";
}

function initHideEditContextMenu() {
    //_EventObj=window.event;
    //window.setTimeout("hideEditContextMenu()", 2000);
    //var oEvent=window.event;
    //var oMenu=document.getElementById("editMenu");
    //    if (!chkInBoundary(oEvent,oMenu)) {
    //        oMenu.style.display="none";
    //}
}

function openInEditor() {
    if (_ActiveField==null) return;
    var aFieldId=_ActiveField.id.split("_");
    var nObjectId=parseInt(aFieldId[1]);
    window.open("/eway/library/openForm.aspx?param1=" + nObjectId + "&param5=write", "editobj", _DlgWinFeatures);
}

function insertElement(sCmdId) {
    if (_ActiveField==null) return;

    _ActiveField.focus();
    _ActiveField.dirtyflag="1";
    var oSel=document.selection;
    var oRange=oSel.createRange();
    document.execCommand(sCmdId,false,null);
}

function insertHTML(sHTML) {
    if (_ActiveField==null) return;

	_ActiveField.focus();
    _ActiveField.dirtyflag="1";
	
	var oSel=document.selection;
	var oRange=oSel.createRange();
	var sType=oSel.type;

	if (sType=="Control") {
		oRange.item(0).outerHTML = sHTML;
	} else {
		oRange.pasteHTML(sHTML);
	}
}


function setSubMenuPosition() {
    var oParent=event.srcElement;
    oParent=getContainer(oParent,"editMenu");
    var nPosY=findPos("sy",oParent);
    var oElem=document.getElementById(oParent.id + "Items");
    oElem.style.top=nPosY;
    var oElem=document.getElementById(oParent.id + "Items_MenuIFrame");
    oElem.style.top=nPosY;
}

function insertImage() {
    var sURL="/eway/library/richtext/pickers/pickerDlg.aspx";
    var oArg=new DialogArgument;
    var oImg=document.createElement("IMG");
    oArg.IsNewElement=true;
    oArg.Parameter=oImg;
    openPickerDialog(sURL,oArg,640,450);
    if (oArg.HasResult==true) {
        insertHTML(oArg.Parameter.outerHTML);
    }
}

function insertLink(bEwayLink) {
    var sText="";
    var oSel=document.selection;
    var oRng=oSel.createRange();
    
    switch (oSel.type) {
       case "Control":
            sText=oRng.item(0).outerHTML;
            break;
        case "Text":
            if((oSel.text != undefined) && (oSel.text != null)){
                sText = oSel.text;
            }else if((oRng.text != undefined) && (oRng.text != null)){
                sText = oRng.text;
            }
            break;
    }

    var sURL="/eway/library/richtext/pickers/pickerDlg.aspx";
    if (bEwayLink==true) sURL+="?dialog=ewaylink";
    var oArg=new DialogArgument;
    var oAnchor=document.createElement("A");
    oAnchor.innerHTML=sText;
    oArg.IsNewElement=true;
    oArg.Parameter=oAnchor;
    openPickerDialog(sURL,oArg,360,450);
    if (oArg.HasResult==true) {
        insertHTML(oArg.Parameter.outerHTML);
    }
}

function insertAttachments() {
    
    var sContextProfileDesc = "";
    var ObjectId = "";
    var sURL="/eway/library/richtext/pickers/pickerDlg.aspx?page=attachmentdlg";
    var oArg=new DialogArgument;

    if((_ActiveField.id != null) && (_ActiveField.id != undefined)){
        var sOid = _ActiveField.id;
        sOid = sOid.split("_");
        if(sOid.length > 1){
            ObjectId = sOid[1];
            if(isNaN(ObjectId)){
                ObjectId = "";
            }
        }
        //
    }
    if(sURL.indexOf("oid=") == -1){
        sURL += "&oid=" + ObjectId;
    }
        
    if((_ActiveField.contextprofiledesc != null) && (_ActiveField.contextprofiledesc != undefined)){
        sContextProfileDesc = _ActiveField.contextprofiledesc;
    }
    sURL += "&contextprofiledesc=" + sContextProfileDesc;
    
    openPickerDialog(sURL,oArg,450,600);
    if (oArg.HasResult==true) {
        insertHTML(oArg.ReturnValue);
    }
}

function onEditDblClick(oSrcElem) {
    var sURL="/eway/library/richtext/pickers/pickerDlg.aspx";
    var oSel=document.selection;
    var oArg=new DialogArgument;
    var nWidth=450, nHeight=630;
    if (oSel.type=="Control") {
        var oRng=oSel.createRange();
        var oElem=oRng(0);
        switch (oElem.tagName) {
            case "IMG":
                oArg.Parameter=oElem;
                break;
            case "TABLE":
                oArg.Parameter=oElem;
                nHeight=400;
                break;
            default:
                break;
        }
    }
    if (oSel.type=="Text") {
        var oRng=oSel.createRange();
        var oTmpElem=oRng.parentElement();
        //Look for TD-tag
        while (oTmpElem!=null) {
            if (oTmpElem.tagName=="TD") {
                oArg.Parameter=oTmpElem;
                nHeight=500;
                break;
            }
            oTmpElem=oTmpElem.parentElement;
        }

        //Look for A-tag
        if (oArg.Parameter==null) {
            var oTmpElem=window.event.srcElement;
            while (oTmpElem!=null) {
                if (oTmpElem.tagName=="A") {
                    oArg.Parameter=oTmpElem;
                    nWidth=450; nHeight=350;
                    if (oTmpElem.href.indexOf("javascript:loadState(")>-1) sURL+="?dialog=ewaylink";
                    break;
                }
                oTmpElem=oTmpElem.parentElement;
            }
        }
    }

    if (oArg.Parameter!=null) {
        openPickerDialog(sURL,oArg,nHeight,nWidth);
        if (oArg.ReturnValue=="showtable") openPickerDialog(sURL,oArg,nHeight,nWidth);
        var oTmpElem = oSrcElem;
        while (oTmpElem != null){
            if( oTmpElem.className == "EditFieldArea"){
                oTmpElem.dirtyflag = "1";
                break;
            }else{
                oTmpElem = oTmpElem.parentElement;
            }
        }

    }
    
    return true;
}


/* --------------------------------------------------------------------------------
End - Inline Editing
---------------------------------------------------------------------------------*/

/* --------------------------------------------------------------------------------
Structure Editing
---------------------------------------------------------------------------------*/

function displayStructContextMenu(oElem) {
/*     document.body.detachEvent("onclick",hideEditContextMenu);

    var oEvent=window.event;
    var oMenu=document.getElementById("editMenu");
        
    oMenu.style.display="block";
    oMenu.style.zIndex=1000; 
    setElemPositionAtPointer(oEvent,oMenu); 
    
    oEvent.returnValue=false;
    
    var sImgId=oElem.id; 
    var nAreaId=sImgId.substr(5,sImgId.length-6);
    document.getElementById("ctxareaid").value=nAreaId;
    
    document.body.attachEvent("onclick",hideEditContextMenu);*/
}

function openPropertiesContext(sTabPage) {
    var nAreaItemId=parseInt(document.getElementById("ctxareaid").value);
    var nPortalId=parseInt(document.getElementById("ctxportalid").value);
    var oImg=document.getElementById("outl!" + nAreaItemId + "i");
    var aParams=oImg.onclick.toString().split("','");
    var sElementPath=aParams[3].split("'")[0];
    openElementProperties(0,nAreaItemId,nPortalId,sElementPath,sTabPage);
}

function openElementProperties(nElementId, nAreaItemId, nPortalId, sElementPath, sTabPage) {
    if (sTabPage==null) { sTabPage="element"; }
    var sUrlParam="?pid=" + nPortalId
        +"&elementid=" + nElementId
        +"&areaitemid=" + nAreaItemId
        +"&objpath=" + sElementPath
        +"&tabpage=" + sTabPage;

    var oWH=window.open("/eway/applications/portalconfig/configpages/editPage.aspx" + sUrlParam,"elemprop",_DlgWinFeatures);
    oWH.focus();
}

function openAddElementWizard() {
    var nPortalId=parseInt(document.getElementById("ctxportalid").value);
    var nAreaItemId=parseInt(document.getElementById("ctxareaid").value);
    var sUrlParam="?pid=" + nPortalId
        +"&areaitemid=" + nAreaItemId;
        
    var oWH=window.open("/eway/applications/portaldesigner/createElementWizard.aspx" +  sUrlParam,"elemprop",_DlgWinFeatures);
    oWH.focus();
}
/* --------------------------------------------------------------------------------
End - Structure Editing
---------------------------------------------------------------------------------*/




function startsWith(str,find) {
    return str.substr(0,find.length)==find;
}
