var visibleId;
var stayVisible;

function noLink() {
}
function decision(pos, ut) {
	if (confirm("Wollen Sie den Block wirklich l&ouml;schen?")) {
		location.href="main?module=content&action=removeItem&id="+pos+"&ut="+ut;
	} 
}

function closePreview() {
	var pop = getElement("previewbox");
	hide(pop);
}


/* popup handling */

var _ut = null;
var _id = null;

function moveItem(dir) {
	var url = "main?action=moveItem&id=" + _id + "&fswitch=" + dir + "&ut=" + _ut;
	location.href=url;
}
function insertItem(newtype) {
	var url = "main?action=insertItem&id=" + _id + "&fswitch=" + newtype + "&ut=" + _ut;
	location.href=url;
}


function getAbsLeft(o) {
	oLeft = o.offsetLeft
	while(o.offsetParent!=null) {
		oParent = o.offsetParent
		oLeft += oParent.offsetLeft
		o = oParent
	}
	return oLeft
}

function getAbsTop(o) {
	oTop = o.offsetTop
	while(o.offsetParent!=null) {
		oParent = o.offsetParent
		oTop += oParent.offsetTop
		o = oParent
	}
	return oTop
}

function openPopup(obj, popId, id, ut, event) {
	_ut = ut;
	_id = id;
	if (visibleId!=null)
		hide(visibleId);
	var pop = getElement(popId);
	visibleId = pop;
	if (pop.style.visiblity!='visible') {
	    
	    // var x = (document.layers)? e.pageX : event.x+document.body.scrollLeft
    	// var y = (document.layers)? e.pageY : event.y+document.body.scrollTop

		x = getAbsLeft(obj) + 0;
		y = getAbsTop(obj) + 5;
// alert("pop = " + pop.style.top);  // *******+	
		pop.style.left = x;
		pop.style.top = y;
// alert("pop = " + pop.style.top);  // *******+	
		
        // pop.style.left       = event.pageX ? pageXOffset + event.clientX -10: document.body.scrollLeft + event.x -10;
        // pop.style.top        = event.pageY ? pageYOffset + event.clientY -10: document.body.scrollTop  + event.y -10;

        pop.style.visibility = 'visible';
        
        // alert(pop.style.top); // ****
	}
}

function hidePopup(id) {
	if (stayVisible!=null) {
		status = "noch nicht hide";
		return;
	}
	var pop = getElement(id);
	hide(pop);
	stayVisible=null;
}
function queueHide(id) {
	var call = "hidePopup('"+id+"')";
	window.setTimeout( call, 500 ); 
}
function cancelHide(id) {
	// window.clearTimeout(aktiv);
	stayVisible=id;
	status = "cancelHide";
}
function forceHide(id) {
	stayVisible=null;
	queueHide(id);
}

/* popup window functions */
function closePopupWindow(windowId) {
	var pop = getElement(windowId);
	hide(pop);
}
function openPopupWindow(windowId) {
	// hide any open popup
	if (visibleId!=null)
		hide(visibleId);

	var pop = getElement(windowId);
	    
	//x = getAbsLeft(obj) + 0;
	//y = getAbsTop(obj) + 5;
	
	maxX = getInsideWindowWidth();
	maxY = getInsideWindowHeight();
//	alert("screen is " + maxX + " " + maxY);
	
	popupWidth = getObjectWidth(pop);
	popupHeight= getObjectHeight(pop);
	
	x = (maxX-popupWidth) / 2;
	y = (maxY-popupHeight) / 2;
// alert("x=" + x);	
	pop.style.left = x;
	pop.style.top = y - 20;

    pop.style.visibility = 'visible';
}


/* filepool functions */
function confirmRemoveFile(pos, ut) {
	if (confirm("Wollen Sie die Datei aus der Liste der Downloads entfernen?")) {
		location.href="main?module=content&action=itemAction&fswitch=remove&id="+pos+"&ut="+ut;
	} 
}
function showAddFileBox() {
	var pop = getElement('addFileBox');
	// show(pop);
	pop.style.display = "block";
	
}

function getElement( ID ) {
	if ( document.layers ) return eval("document.ids."+ID);
	if ( document.getElementById ) return document.getElementById(ID);
	if ( document.all ) return document.all[ID];
	// failed
	alert( "not able to reference '"+ID+"'!");
}

function send(target) {
	// leave();
	var frm = getElement("actionform");
	if (!frm)
		alert("no form found 'actionform'");
	frm.fswitch.value=target;
	
	// check if sid is present and unset
	if (frm.sid) {
		if (frm.sid.value=="")
			frm.sid.value=_id;
	}
	// alert(frm.sid.value);
	
	frm.submit();
}

// Global variables
var isCSS, isW3C, isIE4, isNN4, isIE6CSS;

// Initialize upon load to let all browsers establish content objects
function initDHTMLAPI( ) {
    if (document.images) {
        isCSS = (document.body && document.body.style) ? true : false;
        isW3C = (isCSS && document.getElementById) ? true : false;
        isIE4 = (isCSS && document.all) ? true : false;
        isNN4 = (document.layers) ? true : false;
        isIE6CSS = (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) ? 
            true : false;
    }
}

// Set event handler to initialize API
window.onload = initDHTMLAPI;
   
// Seek nested NN4 layer from string name
function seekLayer(doc, name) {
    var theObj;
    for (var i = 0; i < doc.layers.length; i++) {
        if (doc.layers[i].name = name) {
            theObj = doc.layers[i];
            break;
        }
        // dive into nested layers if necessary
        if (doc.layers[i].document.layers.length > 0) {
            theObj = seekLayer(document.layers[i].document, name);
        }
    }
    return theObj;
}
   
// Convert object name string or object reference
// into a valid element object reference
function getRawObject(obj) {
    var theObj;
    if (typeof obj == "string") {
        if (isW3C) {
            theObj = document.getElementById(obj);
        } else if (isIE4) {
            theObj = document.all(obj);
        } else if (isNN4) {
            theObj = seekLayer(document, obj);
        }
    } else {
        // pass through object reference
        theObj = obj;
    }
    return theObj;
}
   
// Convert object name string or object reference
// into a valid style (or NN4 layer) reference
function getObject(obj) {
    var theObj = getRawObject(obj);
    if (theObj && isCSS) {
        theObj = theObj.style;
    }
    return theObj;
}
   
// Position an object at a specific pixel coordinate
function shiftTo(obj, x, y) {
    var theObj = getObject(obj);
    if (theObj) {
        if (isCSS) {
            // equalize incorrect numeric value type
            var units = (typeof theObj.left == "string") ? "px" : 0;
            theObj.left = x + units;
            theObj.top = y + units;
        } else if (isNN4) {
            theObj.moveTo(x,y)
        }
    }
}
   
// Move an object by x and/or y pixels
function shiftBy(obj, deltaX, deltaY) {
    var theObj = getObject(obj);
    if (theObj) {
        if (isCSS) {
            // equalize incorrect numeric value type
            var units = (typeof theObj.left == "string") ? "px" : 0;
            theObj.left = getObjectLeft(obj) + deltaX + units;
            theObj.top = getObjectTop(obj) + deltaY + units;
        } else if (isNN4) {
            theObj.moveBy(deltaX, deltaY);
        }
    }
}
   
// Set the z-order of an object
function setZIndex(obj, zOrder) {
    var theObj = getObject(obj);
    if (theObj) {
        theObj.zIndex = zOrder;
    }
}
   
// Set the background color of an object
function setBGColor(obj, color) {
    var theObj = getObject(obj);
    if (theObj) {
        if (isNN4) {
            theObj.bgColor = color;
        } else if (isCSS) {
            theObj.backgroundColor = color;
        }
    }
}
   
// Set the visibility of an object to visible
function show(obj) {
    var theObj = getObject(obj);
    if (theObj) {
        theObj.visibility = "visible";
    }
}
   
// Set the visibility of an object to hidden
function hide(obj) {
    var theObj = getObject(obj);
    if (theObj) {
        theObj.visibility = "hidden";
    }
}
   
// Retrieve the x coordinate of a positionable object
function getObjectLeft(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (document.defaultView) {
        var style = document.defaultView;
        var cssDecl = style.getComputedStyle(elem, "");
        result = cssDecl.getPropertyValue("left");
    } else if (elem.currentStyle) {
        result = elem.currentStyle.left;
    } else if (elem.style) {
        result = elem.style.left;
    } else if (isNN4) {
        result = elem.left;
    }
    return parseInt(result);
}
   
// Retrieve the y coordinate of a positionable object
function getObjectTop(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (document.defaultView) {
        var style = document.defaultView;
        var cssDecl = style.getComputedStyle(elem, "");
        result = cssDecl.getPropertyValue("top");
    } else if (elem.currentStyle) {
        result = elem.currentStyle.top;
    } else if (elem.style) {
        result = elem.style.top;
    } else if (isNN4) {
        result = elem.top;
    }
    return parseInt(result);
}
   
// Retrieve the rendered width of an element
function getObjectWidth(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetWidth) {
        result = elem.offsetWidth;
    } else if (elem.clip && elem.clip.width) {
        result = elem.clip.width;
    } else if (elem.style && elem.style.pixelWidth) {
        result = elem.style.pixelWidth;
    }
    return parseInt(result);
}
   
// Retrieve the rendered height of an element
function getObjectHeight(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetHeight) {
        result = elem.offsetHeight;
    } else if (elem.clip && elem.clip.height) {
        result = elem.clip.height;
    } else if (elem.style && elem.style.pixelHeight) {
        result = elem.style.pixelHeight;
    }
    return parseInt(result);
}
   
// Return the available content width space in browser window
function getInsideWindowWidth( ) {
    if (window.innerWidth) {
        return window.innerWidth;
    } else if (isIE6CSS) {
        // measure the html element's clientWidth
        return document.body.parentElement.clientWidth;
    } else if (document.body && document.body.clientWidth) {
        return document.body.clientWidth;
    }
    return 0;
}
   
// Return the available content height space in browser window
function getInsideWindowHeight( ) {
    if (window.innerHeight) {
        return window.innerHeight;
    } else if (isIE6CSS) {
        // measure the html element's clientHeight
        return document.body.parentElement.clientHeight;
    } else if (document.body && document.body.clientHeight) {
        return document.body.clientHeight;
    }
    return 0;
}


function showNewsletterPreview(el_id) {
	var x = getElement(el_id);
	x.style.display = 'table-row;';
}



function toggle(what) {
	obj = getElement(what);
	if (obj.style.display=="none" || obj.style.display=="") {
		obj.style.display="block";
	} else {
		obj.style.display="none";
	}
}


// methods for the c4 file repository

function removeFile(id, messageHtml) {
	span = getElement(id+"_label");
	span.innerHTML = messageHtml;
	x = getElement("actionform");
	x[id].value = "";
	x = getElement(id+"_display");
	x.className = "fileitem_label";	
	// hide trashcan symbol
	span = getElement(id+"_recycle");
	span.style.display = "none";
}

function startUploadFrame(id, noUploadFlag) {

	// make td higher
	box =  getElement(id + "_td");
	if(box==null) {
		window.setTimeout("startUploadFrame('"+id+"',"+noUploadFlag+")", 1000);
		return;
	}

	frm = getElement("actionform");
	module  = frm[id+"_c4frModule"].value;
	context = frm[id+"_c4frContext"].value;
	options = frm[id+"_c4frOptions"].value;
	fileCount=frm[id+"_c4frFileCount"].value;

	h = 95 + ((fileCount-1) * 40);
	box.height = h; 

	// hide fileN_display and show fileN_box
	box = getElement(id + "_display");
	box.style.display = "none";
	box = getElement(id + "_box");
    box.style.display = "block";
	
	/*
		build the upload frame, send data
		- sid = id of the field 
		- c4frModule = module of the module controller to handle the file
		- c4frContext = some key/label describing what the field is
		- c4frOptions = what is the file? "file" or "image"
	*/
	storeFolder = null;
	selectFolder = null;
	x = frm[id+"_c4frStoreIntoFolder"];
	if (x!=null) {
		storeFolder = x.value;
		if (storeFolder.length==0) {
			storeFolder = null;
		}
	}
	x = frm[id+"_c4frSelectFromFolder"];
	if (x!=null) {
		selectFolder = x.value;
		if (selectFolder.length==0) {
			selectFolder=null;
		}
	}
	// build the href, use the flag if set
	flag = "";
	if (noUploadFlag==true) {
		flag = "&noupload=true";
	} 
	src = '<iframe height="'+h+'" width="100%" id="'+id+'_frame" src="main?module=c4fr&action=start&sid=' 
		+ id + '&c4frModule=' + module + '&c4frContext=' + context + '&c4frOptions=' 
		+ options + '&c4frFileCount=' + fileCount;
		
	if (storeFolder!=null) {
		src = src + '&c4frStoreIntoFolder=' + storeFolder;
	}
	if (selectFolder!=null) {
		src = src + '&c4frSelectFromFolder=' + selectFolder;
	}
	src = src + flag + '" class="uploadframe" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" ></iframe>'
	box.innerHTML = src;
}

/*
 * called from the iframe 
 */
function closeUploadFrame(id) {
	box = getElement(id + "_box");
	box.style.display = "none";
	box = getElement(id + "_display");
	box.style.display = "block";
	// resize td again
	box = getElement(id + "_td");
	box.height = 20;
	
	try {
		customCloseUploadFrame(id);
	} catch(e) {
		// swallow
	}
}
/*
 * called from the response-html after an upload (file)
 *
function handlePostUploadFile(id, label, filehandle) {
	alert("handlePostUploadFile(" + id + "," + label + "," + filehandle +")" );
	closeUploadFrame(id);
	// change the label and filehandle
	var x = getElement(id + "_label");
	x.innerHTML = label;
	x = getElement("actionform");
	x[id].value = filehandle;
	x = getElement(id+"_display");
	x.className = "fileitem_label green";
	// show trashcan again
	x = getElement(id+"_recycle");
	x.style.display = "block";
}
*/
/*
 * called from the response-html after an upload (image)
 *
function handlePostUploadImage(fieldname, imageTag, filehandle) {
	debug("handlePostUploadImage(" + fieldname + "," + imageTag + "," + filehandle +")" );
	closeUploadFrame(id);
	// replace the entire <img> tag
	var x = getElement(fieldname + "_label");
	x.innerHTML = imageTag;
	// put the filehandle into the form-field
	x = getElement("actionform");
	x[fieldname].value = filehandle;
	x = getElement(fieldname+"_display");
	x.className = "fileitem_label green";	
}
*/
/*
 * called from the response-html after an upload (image): get the html-snipplet with AJAX
 */
function handlePostUploadImageWithAjax(fieldname, filehandle) {
	debug("handlePostUploadImageWithAjax(" + fieldname + "," + filehandle +")" );
	closeUploadFrame(fieldname);
	
	callUrl = "main";
	callParams = "module=c4fr&action=showImageTag&sid=" + filehandle + "&fieldname=" + fieldname;
	replaceHtmlAfterAjaxRequest(callUrl, callParams);
	// put the filehandle into the form-field
	x = getElement("actionform");
	x[fieldname].value = filehandle;
	x = getElement(fieldname+"_display");
	x.className = "fileitem_label";	
	
	try {
		customPostUploadProcessing(fieldname, filehandle);
	} catch(e) {
		// swallow
	}
}
/*
 * called from the response-html after an upload (image): get the html-snipplet with AJAX
 */
function handlePostUploadFileWithAjax(fieldname, filehandle) {
	debug("handlePostUploadFileWithAjax(" + fieldname + "," + filehandle +")" );
	closeUploadFrame(fieldname);
	
	callUrl = "main";
	callParams = "module=c4fr&action=showFileTag&sid=" + filehandle + "&fieldname=" + fieldname;
	replaceHtmlAfterAjaxRequest(callUrl, callParams);
	// put the filehandle into the form-field
	x = getElement("actionform");
	x[fieldname].value = filehandle;
	x = getElement(fieldname+"_display");
	x.className = "fileitem_label";	
	
	try {
		customPostUploadProcessing(fieldname, filehandle);
	} catch(e) {
		// swallow
	}
	
}
/*
 * called from the response-html after an upload without a file (stupid user!)
 */
function handleNoUpload(id) {
	debug("handleNoUpload(" + id + ")" );
	// trick: restart the upload iframe, set a flag, so an error msg gets displayed
	startUploadFrame(id, true);
}
function debug(was) {
	// alert(was);
}


function replaceHtmlAfterAjaxRequest( callUrl, callParams ) 
{	
	debug("creplaceHtmlAfterAjaxRequest(" + callUrl + ", " + callParams + ")" );
	var myAjax = new Ajax.Request( 
		callUrl, 
		{   method: 'get', 
			parameters: callParams,
			onComplete: handleReplaceHtmlAfterAjaxRequest
		});
}
function handleReplaceHtmlAfterAjaxRequest(req)
{
	data = req.responseText.evalJSON();
	replaceTagId = data.tag;
	htmlData     = data.htmlData;
	x = getElement(replaceTagId);
	x.innerHTML = htmlData;
}

function linkTo(url) {
	call = "main?module=site&action=linkto&sid="+url;
	location.href = call;
}

function showPreview() {
	window.open('main?module=site&action=start', 'preview');
}


function showMoreText(sid) {
	x = 'morecontent-'+sid;
	var more = getElement(x);
	if (more!=null) {
		more.style.display = "block";
		new Effect.ScrollTo(x, {offset: -100});
	}
}
