var previewURL = (typeof window.UserContext != "undefined") ? UserContext.getUrl('/email/wysiwyg/richtextbody.jsp') : '/email/wysiwyg/richtextbody.jsp';
var blankPage = window.location.protocol + '//' + window.location.hostname + previewURL;
var editAreaIds = null;
var lockedImg = null;
var unLockedImg = null;
/** CONSTRUCTOR START **/
function setLockedImageSrc(src) {
    lockedImg = src;
}
function setUnlockedImageSrc(src) {
    unLockedImg = src;
}
function setEditableIds(ids) {
    editAreaIds = ids;
}
var editForm = null;
function registerEditForm(frm) {
    editForm = frm;
}
/** CONSTRUCTOR END  **/


top.currentSelObj;

var loaded = false;

function getDoc() {
    return document.getElementById(getEditName(top.currentSelObj.id)).contentWindow.document;
}
function getContentWindow() {
    return document.getElementById(getEditName(top.currentSelObj.id)).contentWindow;
}


var win_ie_ver = parseFloat(navigator.appVersion.split("MSIE")[1]);
function isIE() {
    return win_ie_ver >= 5.5;
}


function getEditName(objId) {
    return objId + '_editor';
}
function getEditValueName(objId) {
    return objId + '_editor_value';
}
function getLockedName(objId) {
    return objId + '_locked';
}
function getLockedImageName(objId) {
    return objId + '_locked_img';
}

function initializeEditor(){
    loaded = true;
    document.onmousedown = onMouseDown;
    // We need this sequence here because we need to resize the top frame AFTER we initialize the template areas.
    // Other wise we won't know what the REAL size of the inner frame is.
    // But then after we resize, the EmailTemplateAreas need to be reinitialized because the placement of hanging images need to
    // change according to the new size.

    // In preview mode, we won't be in a frame, and we don't have to deal with this.
    initEmailTemplateAreas();
    resizeTopFrame();
   	initEmailTemplateAreas();
}

function initEmailTemplateAreas() {
    for (var i = 0; i < editAreaIds; i++) {
        initEmailTemplateArea(editAreaIds[i]);
    }
}


var originalTDBGColor = null;
function handEditAreaMouseOver(obj){
    if(obj.style && obj.style.curslr) obj.style.cursor='pointer';
}

function handEditAreaMouseExit(obj) {
}

var emptyCellText = '';
function registerEmptyCellText(t) {
    emptyCellText = t;
}
function initEmailTemplateArea(elementId) {

    var currObj

    function getObjX(obj){
        if(!obj.offsetParent) return 0;
        var x = getObjX(obj.offsetParent);
        return obj.offsetLeft + x;
    }

    function getObjY(obj){
        if(!obj.offsetParent) return 0;
        var y = getObjY(obj.offsetParent);
        return obj.offsetTop + y;
    }

    function placeIndicatorElement(baseElement, indicatorElement, position) {
        var posLeft = getObjX(baseElement);
        var posTop = getObjY(baseElement);
        var width = baseElement.offsetWidth;
        var height = baseElement.offsetHeight;
        var elemWidth = indicatorElement.scrollWidth;
        var elemHeight = indicatorElement.scrollHeight;
        indicatorElement.style.position = 'absolute';
        indicatorElement.style.left = (posLeft + width) - (elemWidth + 3 + position);
        indicatorElement.style.top = (posTop + height) - (elemHeight + 3 );
        indicatorElement.style.visibility = 'visible';
    }

    currObj = document.getElementById(elementId)

    currObj.innerHTML = getValue(getEditValueName(elementId));

//see if the object has any text, if not put some in

    if(currObj.innerHTML==''){
        currObj.innerHTML= emptyCellText;
    }

    turnOnBorder(currObj)

    placeIndicatorElement(currObj ,document.getElementById(getLockedImageName(elementId)), 0);
    setLockedImage(elementId);
}


function resizeTopFrame() {
    var bodyWidth = document.getElementById('topTable').offsetWidth + 30;
    var bodyHeight = document.getElementById('topTable').offsetHeight + 60;

    if(bodyHeight < 500) bodyHeight = 560;
    if(bodyWidth < 450) bodyWidth = 480;

    if (parent.setFrameHeight){
	    parent.setFrameWidth(bodyWidth);
    	parent.setFrameHeight(bodyHeight );
    } else {
    	window.resizeTo(bodyWidth + 20, bodyHeight + 150);
    }
}

function onMouseDown(){
    if(!top.currentSelObj) return;
    blur();
}
var textAreaEdit = false;
function editTextArea(obj) {
    if (!loaded) return;
    if (top.currentSelObj) return;
    if (locked) return;
    locked = true;

    if (originalTDBGColor) {
        obj.style.backgroundColor=originalTDBGColor;
    }

    textAreaEdit = true;

    iFrameHTML = '<html>';
    iFrameHTML += '<body ';
    iFrameHTML += 'border=0 ';
    iFrameHTML += 'style=" ' ;
    iFrameHTML += 'color:'+obj.style.color+'; ';
    iFrameHTML += 'font-size:'+obj.style.fontSize+'; ';
    iFrameHTML += 'font-family:'+obj.style.fontFamily+'; ';
    iFrameHTML += '" ';
    iFrameHTML += 'TOPMARGIN="0" LEFTMARGIN="0" MARGINWIDTH="0" MARGINHEIGHT="0" MARGIN="0" ';
    iFrameHTML += '>';
    iFrameHTML += '<textarea id="textareaedit" wrap="virtual" style=" width:' +(obj.offsetWidth-4)+ '; height:' +(obj.offsetHeight-6)+ '; font-family:'+obj.style.fontFamily+'; font-size:'+obj.style.fontSize+'; ">';
    iFrameHTML +=  getValue(getEditValueName(obj.id));
    iFrameHTML += '</textarea>';
    iFrameHTML += '</body></html>';

	var srcPage = '';
	if (isIE()) {
		// For IE, we need to use a blank page from the server to avoid
		// security warnings for https.
		srcPage = blankPage;
	}
    obj.innerHTML = '<iframe title="' + backgroundIFrameTitle + '" src="' + srcPage +  '" id="'+ getEditName(obj.id) + '" style=" width:' +(obj.offsetWidth-4)+ '; height:' +(obj.offsetHeight-4)+ '; " frameborder="0" scrolling="no" marginheight=0 marginwidth=0></iframe>'
    top.currentSelObj = obj;

    top.editorWindow = getContentWindow();
    top.editorDoc = getDoc();
    getDoc().open();
    getDoc().write(iFrameHTML);
    getDoc().close();
    getDoc().getElementById('textareaedit').focus();
    locked = false;
}

var locked = false;


function edit(obj){

    if (!loaded) return;
    if (top.currentSelObj) {
        blur();
    }

    if (locked) return;

    locked = true;

    var widthOffset = 10 + 10 + 2 + 2;
    var heightOffset = 10 + 10 + 2 + 2;
    if (obj.currentStyle) {
        var paddingTop = obj.currentStyle.paddingTop;
        paddingTop = paddingTop.substring(0, paddingTop.length-2);
        paddingTop = paddingTop / 1;
        var paddingBottom = obj.currentStyle.paddingBottom;
        paddingBottom = paddingBottom.substring(0, paddingBottom.length-2);
        paddingBottom = paddingBottom / 1;
        var paddingLeft = obj.currentStyle.paddingLeft;
        paddingLeft = paddingLeft.substring(0, paddingLeft.length-2);
        paddingLeft = paddingLeft / 1;
        var paddingRight = obj.currentStyle.paddingRight;
        paddingRight = paddingRight.substring(0, paddingRight.length-2);
        paddingRight = paddingRight / 1;
        widthOffset = paddingLeft + paddingRight + 2;
        heightOffset = paddingTop + paddingBottom + 2;
    }

    iFrameHTML = '<html><style>p{margin-top:0px; margin-bottom:0px;}</style>';
    iFrameHTML += '<body ';
    iFrameHTML += 'border=0 ';
    iFrameHTML += 'style=" ' ;
    iFrameHTML += 'color:'+obj.style.color+'; ';
    iFrameHTML += 'font-size:'+obj.style.fontSize+'; ';
    iFrameHTML += 'font-family:'+obj.style.fontFamily+'; ';
    iFrameHTML += '" ';
    if (isIE()) {
        iFrameHTML += 'bgcolor="' + obj.style.backgroundColor + '" ';
    } else {
        iFrameHTML += 'background-color="'+obj.style.backgroundColor+'" ';
    }
    iFrameHTML += 'TOPMARGIN="0" LEFTMARGIN="0" MARGINWIDTH="0" MARGINHEIGHT="0"';
    iFrameHTML += '>';
    iFrameHTML +=  getValue(getEditValueName(obj.id));
    iFrameHTML +='</body></html>'
    //sub off the border width of the frame
    //in a perfect world you would init an object to hold all the edit frame attributes

    //obj.style.borderWidth=1;
    //obj.style.borderColor='FF0000';

	var srcPage = '';
	if (isIE()) {
		// For IE, we need to use a blank page from the server to avoid
		// security warnings for https.
		srcPage = blankPage;
	}
    obj.innerHTML = '<iframe title="' + backgroundIFrameTitle + '" src="' + srcPage + '" id="'+ getEditName(obj.id) + '" style="width:' + (obj.offsetWidth-widthOffset)+ '; height:' +(obj.offsetHeight-heightOffset)+ '; "  frameborder="0" scrolling="auto" marginheight=0 marginwidth=0></iframe>'
    top.currentSelObj = obj;
    top.currentSelObj.style.borderColor='FF0000'

    edit_on();
}

var iFrameHTML;
function edit_on() {
    if (!locked) return;
    top.editorWindow = getContentWindow();

    top.editorDoc = getDoc();
    if(!isIE()) {
        top.editorDoc.designMode = "on";
    }
    top.editorDoc.open();
    top.editorDoc.write(iFrameHTML);
    top.editorDoc.close();
    top.editorDoc.body.contentEditable = 'true';
    getContentWindow().focus();
    locked = false;
}

// Handles all mouse down on the page.
function blur(){

    if (!top.currentSelObj) return;
    if (locked) return;



    if (textAreaEdit) {
        setValue(getEditValueName(top.currentSelObj.id), getDoc().getElementById('textareaedit').value);
        top.currentSelObj.innerHTML = getDoc().getElementById('textareaedit').value;
    } else {
        setValue(getEditValueName(top.currentSelObj.id), getDoc().body.innerHTML);
        top.currentSelObj.innerHTML = getDoc().body.innerHTML;

    }


    initEmailTemplateArea(top.currentSelObj.id);
    top.currentSelObj = null;
    top.editorDoc = null;
    top.editorWindow = null;
    initEmailTemplateAreas();
    resizeTopFrame();
}
function handleFocus() {
    if (parent.openedWindow && !parent.openedWindow.closed) parent.openedWindow.focus();
}

function getValue(elementName) {
    return editForm.elements[elementName].value;
}

function setValue(elementName, val) {
    editForm.elements[elementName].value = val;
}

var setLockedConfirmText = null;
function registerLockingConfirmText(t) {
    setLockedConfirmText = t;
}
function toggleLocked(elementName) {
    var locked = getLockedName(elementName);
    var isLocked = getValue(locked);
    if (isLocked == '0') {
        if (setLockedConfirmText && !window.confirm(setLockedConfirmText)) return;
        setValue(locked, '1');
    } else {
        setValue(locked, '0');
    }
    setLockedImage(elementName);
}
function setLockedImage(elementName) {
    var locked = getLockedName(elementName);
    var isLocked = getValue(locked);
    var img = getLockedImageName(elementName);
    var imgElem = document.getElementById(img);
    if (isLocked == '0') {
        imgElem.src = unLockedImg;
    } else {
        imgElem.src = lockedImg;
    }
}

function changeHand(obj) {
    if (obj.style && obj.style.cursor) obj.style.cursor = 'pointer';
}

