/*  common JavaScript functions for 
	CorePublish 2



*   Modified
*       04.03.2003	Daniel Croona
*			- added function insertLinkcollectionFile for uploading 
*			of files into the linkCollection element
*      10.03.2004 Geir Helge Tjostolvsen-Schmidt
*           - added function cpSetValue( objectId, objectValue, mode )
*           - removed function insertLinkFile() since it's not used any more.
*/

var CP_CONST_CATEGORY = "category";

var documentloaded = false;
var imagesloaded = false;


// Capturing mouse move functions
var x;
var y;
var ns4;
var ns5;
var ie5;
var ie4;

function captureMouse() {

	ns4 = document.layers?true:false;
	ns5 = (document.getElementById && !document.all)?true:false;
	ie5 = document.all?true:false;
	ie4 = (!document.getElementById && document.all)?true:false;
	
	if(ns4 || ns5)
	 document.captureEvents(Event.MOUSEMOVE);
	
	document.onmousemove=catchXY;
	}

captureMouse();

// This is a function to catch the x and y coordinates of the mouse
function catchXY(e)
   {
   // capture click coordinates
   x=(ns4 || ns5)?e.pageX:event.x+document.body.scrollLeft;
   y=(ns4 || ns5)?e.pageY:event.y+document.body.scrollTop;
   //window.status="x:"+ x+" y:"+y;
   }


var __b = "id";
var __bi = "img"; 

// Other common functions
function doAction(theform,articleid){
	var idx = theform.returnpage.selectedIndex;
	var theurl = theform.returnpage.options[idx].value ;
    var pos = theurl.indexOf("script:");
    if (pos == -1) {
        location.href = theurl;
    } else {
        pos = theurl.indexOf("javascript:") +11 ;
        var evalcode = theurl.substring(11);
        eval(evalcode);
    }
	//alert(theurl+" denne artikkel : "+articleid);
}

function ct_calendar(year,mon,formname,formitem) {
	//use like this: javascript:ct_calendar('year','month','formname','formitem')
	win_url = 'calendar.php?fieldref=opener.document.'+formname+'.'+formitem+'&mon='+mon+'&year='+year;
	win_name = 'calendar_win';
	win_props ='height=180,width=260,screenX=400,screenY=100';
	window.open(win_url,win_name,win_props);
}

function ct_win(win_url,height,width, props) {
	win_name = "ct_win";
    if (props &&  props.length > 1 ) {
        win_props = props ;
    } else {
        win_props ="height="+height+",width="+width+",screenX=400,screenY=100";
    }
	window.open(win_url,win_name,win_props);
}

__b += ":";

// Image and preload functions.	
function ct_image(img){
	a=new Image(); 
	a.src=img; 
	return a;
} 

function ct_swap(docname,swapimage){
	if(!imagesloaded)
		return false;
	document[docname].src = swapimage.src ;
	return true;
}

function swapMe(img,varname){
	// Swap only if source is defined
	if(imagesloaded==false)
		return;
	else {
		var temp = eval(varname);
		img.src = temp.src;
	}
}

// Function to swap image reference
function ns4SwapMe(x,y,varname){
	// Check for NS 4
	if(!document.layers)
		return;

	// Loop throug all images and find the proper one
	for (i=0;i<document.images.length;i++){
		if(document.images[i].x== x && document.images[i].y== y && x){
            var temp = eval(varname);
			// Swap only if source is defined
			if(temp)
				document.images[i].src = temp.src;
			return;
		}
	}
	window.status="Unable to swap image:image not found";
	return;
}

function slideshow(thearray,imgname,pos,what,theform) {
	i=eval("slidepos"+pos);
	count=eval("count"+pos);
	
	// Show next picture
	if(what=="next" && thearray[i+1]) {
		// Load image before we display it, then swap
		temp = ct_image(thearray[i+1]);
		document[imgname].src = temp.src;
		eval("slidepos"+pos+"++"); // increase counter
		theform.slidetext.value = (i+2)+ " of " + count; // Set status text
	}
	
	// Show previous picture
	if(what=="previous" && i>0 && thearray[i-1]) {
		temp = ct_image(thearray[i-1]);
		document[imgname].src = temp.src;
		eval("slidepos"+pos+"--");
		theform.slidetext.value = (i)+ " of " + count;
	}

	// Show first picture
	if(what=="first" && thearray[0]) {
		temp = ct_image(thearray[0]);
		document[imgname].src = temp.src;
		eval("slidepos"+pos+"--");
		theform.slidetext.value = (1)+ " of " + count;
	}

	// Show last picture
	if(what=="last" && thearray[count-1]) {
		temp = ct_image(thearray[count-1]);
		document[imgname].src = temp.src;
		eval("slidepos"+pos+"--");
		theform.slidetext.value = (count)+ " of " + count;
	}
}
/*
	Function to display keywords in a litle popup box.
*/
function cp2_keywords(keyword_id) {
	cp2_keywordlayer.moveTo(x,y);
	cp2_keywordlayer.setSource("kw.php?id="+keyword_id,120,120);
	cp2_keywordlayer.show();
}

function openInWindow(theurl,thename){
	// Function to be called from frontpage.php, opens a new window in Mozilla and IE, resizes
	// Setting up window properties
	win_url = theurl;
	win_name=thename;
	win_props ='height=600,width=750,scrollbars=1,toolbar=0,location=0,status=1'; //height=600,width=775,screenX=100,screenY=100,

	var c_win =  window.open(win_url,win_name,win_props);
    if (c_win.opener == null) 
		c_win.opener = self;

	//c_win.onunload = reloadSelf;
    c_win.focus();
}

function printWindow(theurl,thename){
	// Function to be called from frontpage.php, opens a new window in Mozilla and IE, resizes
	// Setting up window properties
	win_url = theurl;
	win_name=thename;
	win_props ='height=800,width=700,scrollbars=1,toolbar=1,location=0,status=0'; //height=600,width=775,screenX=100,screenY=100,

	var c_win =  window.open(win_url,win_name,win_props);
    if (c_win.opener == null) 
		c_win.opener = self;

	//c_win.onunload = reloadSelf;
    c_win.focus();
}

/**
*   function that sets all checkboxes in the form frm to the state state
*
*   @param Form frm the form to alter
*   @param boolean state set to true to check the checkboxes, false to uncheck
*/
function changeFormCheckboxes(frm,state) {
    var elems = frm.elements;
    var len = elems.length;
    for(i=0; i < len ;i++){
		if(elems[i].type == "checkbox") {
			elems[i].checked = state;
        }
	}
}

/**
*   function that sets all radio buttons in the form frm to the state mode
*
*   @param Form frm the form to alter
*   @param boolean mode set to true to check the radiobuttons with 'copy', false to check the radiobuttons with 'reference'
*/
function changeFormRadiobuttons(frm,mode) {
    var elems = frm.elements;
    var len = elems.length;
    for(i=0; i<len; i++){
		if(elems[i].type == "radio") {
            if(mode == true) {
                if (elems[i].value == "copy") {
                    elems[i].checked = true;
                } else {
                    elems[i].checked = false;
                }
            } else {
                if (elems[i].value == "reference") {
                    elems[i].checked = true;
                } else {
                    elems[i].checked = false;
                }
            }
        }
	}
}


__b += "b";

/**
*   function that toggles all checkboxes in the form 'frm' to the state state
*
*   @param Form rfm the form to alter
*/
function toggleFormCheckboxes(frm) {
    var elems = frm.elements;
    var len = elems.length;
    for(i=0; i < len ;i++){
		if(elems[i].type == "checkbox") {
			elems[i].checked = !elems[i].checked;
        }
	}
}

// ** EDITOR FUNCTIONS.
function ct_assign() {
    var insideArticleEditor = false;

	// Assigning link handlers
	for(i=0;i<document.links.length;i++){
        // Check if this is an article editor start link
        if (document.links[i].name == "CP_ARTICLE_EDITOR_START") {
            insideArticleEditor = true;
            continue;
        }

        // Check if this is an article editor end link
        if (document.links[i].name == "CP_ARTICLE_EDITOR_END") {
            insideArticleEditor = false;
            continue;
        }
        
        // If we are inside the article editor, ignore the link
        if (insideArticleEditor) {
            continue;
        }        

        // if link does not contain javascript, is on same host 
        // and contains the corepublish htmlroot, change it
        if(document.links[i].href.indexOf("javascript:") == -1          // link must not be javascript
           //&& document.location.hostname == document.links[i].hostname  // link must be on same domain
           && document.links[i].href.indexOf(".php") > -1               // link must be of type .php
           //&& document.links[i].href.indexOf("getfile.php") == -1       // link must not be getfile.php
           && document.links[i].href.indexOf(htmlroot) > -1             // link must contain htmlroot
           && document.links[i].href != location.href + "#"             // link must not be "#"
           && document.links[i].href.indexOf("#") == -1                 // link must not contain #
           ) {
            //debug("<br>Changing link " + document.links[i].href);
			document.links[i].onclick=checkDirty;
            oldhref  = document.links[i].href;
            document.links[i].href="javascript: if (checkDirty()) { location.href = '"+oldhref+"'; } ";
        } else {
            //debug("<br>NOT changing link " + document.links[i].href);
        } 
    }

	// Then assign the method "dirty" to all form elements
	var s = document.forms.artedit.elements.length
    for(i=0; i < s ;i++){
        if(document.forms.artedit.elements[i].type != "submit" && document.forms.artedit.elements[i].name &&  document.forms.artedit.elements[i].name.length > 0) {
			document.forms.artedit.elements[i].onblur = dirty;
        }
	}

    //Making sure prompt don't fire on normal form submit
	document.artedit.onsubmit=clean;

    setTimeout("ct_assign_ingress()",2000);
}

function ct_assign_ingress() {
    //alert("ct_assign_ingress() running");
    // try assigning to the ingress and ingress2 fields
    try {
        CtWysiwygStore['ingresswysiwyg'].getWindowReference().onblur = dirty;
    }  catch (e ) {
        // alert("failed to add onblur") ;
    }
    try {
        CtWysiwygStore['ingress2wysiwyg'].getWindowReference().onblur = dirty;
    }  catch (e ) {
        //alert("failed to add onblur 2" ) ;

    }
}

function dirty() {
	isDirty=true;
	submenuDivClickEnabled = false;// to avoid clicks in the sub menu 
    //window.status = "Endringer ikke lagret";
	return true;
}

function reloadSelf(){
    window.focus();
    window.location.reload();
}

function tt_c(){
    if (imagesloaded == true) {
            tooltips.hide();
            articleinfo.hide();
            cp2_keywordlayer.hide();
            try {
                if (scmJustClicked != null && scmJustClicked == false) {
                    var themenu = new ct_layer('scmdiv');
                    themenu.hide();     
                } else if (scmJustClicked != null) {
                    scmJustClicked = false;
                }
            } catch (e) {

            }
    } else {
        window.status="Document not loaded, action not taken.";
    }
}
__b += "o";

function tooltipsShow(){
    tooltips.moveTo(x+10,y+10);
    tooltips.show();
    tooltips.setSource("tooltips.php?i="+tooltipsid,200,150);
}

function ai(article_ID,isRevision){
    if (isRevision == true) {
        var theurl = htmlroot + "ai.php?revisionmode=1&i="+article_ID;
    } else {
        var theurl = htmlroot + "ai.php?i="+article_ID;
    }

    if (getAvailableBrowserWidth() < 700) {
        win_props ="height="+500+",width="+800+",screenX=400,screenY=100";
        window.open(theurl + "&ownwindow=1","aiwindow",win_props);
    } else {
        articleinfo.moveTo(x-567,y+10);
        articleinfo.show();
        articleinfo.setSource(theurl,772,500);
    }
}

function loadSession(){
    sessionloader.setSource("session_keepalive.php");
}

function getAvailableBrowserHeight() {
    var win_height, win_width;
    if (window.innerWidth && window.innerHeight) {
        win_height = window.innerHeight;
        win_width = window.innerWidth;
     } else if (document.body!=null && document.body.clientWidth && document.body.clientHeight) {
        win_height = document.body.clientHeight;
        win_width = document.body.clientWidth;
     } else if (window.screen) {
        win_height = screen.availHeight;
        win_width = screen.availWidth;
     } else {
        // assuming low resolution
        win_height = 600;
        win_width = 800;
     }

    return win_height;
}

function getAvailableBrowserWidth() {
    var win_height, win_width;
    if (window.innerWidth && window.innerHeight) {
        win_height = window.innerHeight;
        win_width = window.innerWidth;
     } else if (document.body!=null && document.body.clientWidth && document.body.clientHeight) {
        win_height = document.body.clientHeight;
        win_width = document.body.clientWidth;
     } else if (window.screen) {
        win_height = screen.availHeight;
        win_width = screen.availWidth;
     } else {
        // assuming low resolution
        win_height = 600;
        win_width = 800;
     }
     return win_width;
}

/*
 *  function to insert a value to an html object
 *  @param objectId The id on the object to set new value
 *  @param objectValue The new value
 *  @param mode[1|2|3|4] Set the writemode. If there's not a valid mode set, then default will replace existing value
 *      1 Replace existing value
 *      2 Append to the end of existing value
 *      3 Append to the begining of existing value
 *      4 If the object has any value, don't replace it
 */
function cpSetValue( objectId, objectValue, mode ) {
    var objectPointer = document.getElementById(objectId);
    var newValue = '';

    switch (mode) {
    case 1:
        // Replace existing value
        newValue = objectValue;
        break;
    case 2:
        // Append to the end of existing value
        newValue = objectPointer.value + objectValue;
        break;
    case 3:
        // Append to the begining of existing value
        newValue = objectValue + objectPointer.value;
        break;
    case 4:
        // If the object has any value, don't replace it
        if (objectPointer.value.length > 0) {
            newValue = objectPointer.value;
        } else {
            newValue = objectValue;
        }
        break;
    default:
        // Replace existing value
        newValue = objectValue;
        break;
    }

    // Set the new value on the object
    objectPointer.value = newValue;
}

function bkFillCheckboxes() {	
	document.forms.collectdataform.aktiver_om_tjenestested.checked = 1;
	document.forms.collectdataform.aktiver_tjenestested_navn.checked = 1;
	document.forms.collectdataform.aktiver_soknad_sendes_til.checked = 1;
	document.forms.collectdataform.aktiver_faktura_adresse.checked = 1;
}

function CtAddToFavorites(id,classname) {
    var win_url = "article_handler.php?returnpage=foo&action=addtofavorites&id="+id+"&classname="+classname;
	var win_name='favwin';
	var win_props ='height=200,width=300,scrollbars=0,toolbar=0,location=0,status=0,screenX=300,screenY=100'; //height=600,width=775,screenX=100,screenY=100,
	
    var c_win =  window.open(win_url,win_name,win_props);
    if (c_win.opener == null) 
		c_win.opener = self;

	//c_win.onunload = reloadSelf;
    c_win.focus();

}
__b += "o!";

function CtRemoveFromFavorites(id,classname) {
    var win_url = "article_handler.php?returnpage=foo&action=removefromfavorites&id="+id+"&classname="+classname;
	var win_name='favwin';
	var win_props ='height=200,width=300,scrollbars=0,toolbar=0,location=0,status=0,screenX=300,screenY=100'; //height=600,width=775,screenX=100,screenY=100,
	
    var c_win =  window.open(win_url,win_name,win_props);
    if (c_win.opener == null) 
		c_win.opener = self;

	//c_win.onunload = reloadSelf;
    c_win.focus();

}

function CtCheckIfFavoriteSelected(formname,id,classname) {
    if (document.forms[formname].doaddtofavorites.checked == true) {
        CtAddToFavorites(id,classname);
    }

}

/*
    function that loops trough a given set of form elements and validates its.
    
    useage:
    [inside js]
    var requiredFields = Array("firstname",
                           "lastname",
                           "adress",
                           "postnr",
                           "birthyear",
                           "birthmonth",
						   "birthday");

        // types can be 1:text, 2:integer.
        var requiredTypes = Array(1,1,1,2,2,2,2);
        var requiredAliases = Array("Fornavn","Etternavn","Adresse","Postnr","Fødselsår","F.måned","f.dag");

    [on form tag]
    <FORM method="post" onsubmit="return validateForm('form1',requiredFields,requiredTypes,requiredAliases);" action="handler.php" name="form1">
    
    @param formname: the form name
    @param fields: array of strings containing names of the fields to search.
    @param types: array determing type of the string above, 1 is string av 2 is integer
    @param aliases: the field aliases used in the error message.
*/
function validateForm(formname,fields,types,aliases) {
	for (i=0;i<fields.length;i++) {

        // First, get the value out
        var elem = document.forms[formname].elements[fields[i]];
        var val = "";

        // Then switch between different form elements.
        if (elem.type == "text" || elem.type == "password" || elem.type == "checkbox") {
            val = elem.value;
        } else if (elem.type == "select-one" || elem.type == "select-multiple") {
            val = elem.options[elem.selectedIndex].value;
        }  else {
            // build on here as we need more.
            val = elem.value;
        }

        // Check whether there are any content at all
		if (val.length ==0 ) {
			alert("Elementet " + aliases[i] + " er ikke fylt ut");
            elem.focus();
			return false;
		}

        // Check for valid integer.
        if(types[i]==2) {
            if (isNaN(val)) {
				alert("Elementet " + aliases[i] + " er ikke et tall.");
                elem.focus();
				return false;
            }
        }
    }
    return true;
}


/**
*   function that returns the position for the given element.
*
*
*
*/
function getAbsoluteElementPosition(el){
	for (var lx=0,ly=0;el!=null;
		lx+=el.offsetLeft,ly+=el.offsetTop,el=el.offsetParent);
	return {x:lx,y:ly}
}


/**
*   function that positions a layer so that the bottom of the layer 
*   appers at the bottom of the screen.
*
*
*/
function positionLayerAtBottom(thelay) {
    var adjust = -20;
    var bottomPos = getScreenBottomPosition();
    var layHeight = thelay.getHeight();
    var newPos = bottomPos - layHeight + adjust;
    if (newPos < 5) {
        newPos = 5;
    }
    thelay.setTop(newPos);
}

function getScreenBottomPosition() {

    // we need to find the screen height, and then add the 
    // ofsett the user has scrolled....
    var ret = 0;

    // ret = screen.height;
    if (window.innerHeight) {
        ret = window.innerHeight;
    } else {                         
        ret = document.body.clientHeight;
    }

    if(!document.all){
        ret +=  window.pageYOffset ;
    } else {
        ret +=  document.body.scrollTop;
    }
    return ret;
}

// category select functions


var catselloader;
var catselloaderIsLoaded = false;
var catseladdLayerFilled = new Array();
var catseladdLayerClass ;

var catselCallbackFunctionArray = new Array();

var contentdiv;
var urldiv;
var linkdiv;

function categorySelectPrepare(flag, layername) {
    //catselloader = new ct_layer("catsel-layloader");
    catseladdLayerFilled[layername] = flag;
    catseladdLayerClass ="TD-W";
    catselloaderIsLoaded = 1;
}

/**
 *  Registers a callback function that will be called after 
 *  the user has selected one or more categories. 
 *  To delete a callback function, call this method with an empty string 
 *  as the function name.
 * 
 *  @param string selectname the name of the select to append the callback to.
 *  @param string functionname the name of the function. This string will be run through eval(). 
 */
function categorySelectRegisterCallbackFunction(selectname, functionname) {
    catselCallbackFunctionArray[selectname] = functionname;
}

/**
*   function to open a window and let the user choose categories
*
*/
function categorySelectDisplay(categorytype,layername,imgname, selectname, choosetype, accesstype, livsitmode) {
    var url = htmlroot + "inscategory.php?type="+categorytype + "&layername="+layername + "&selectname="+selectname + "&choosetype=" + choosetype + "&accesstype=" + accesstype + "&livsitmode=" + livsitmode ;

//    document.writeln(url);

    theImage = document.getElementById(imgname);
    pos = getAbsoluteElementPosition(theImage);

    contentdiv = new ct_layer(layername+"-contentholder");
    linkdiv = new ct_layer(layername+"-linkholder");
    urldiv = new ct_layer(layername);
    
    contentdiv.setSource(url,"100%",500);
    // catselloader.setLeft(30);
    // positionLayerAtBottom(catselloader);
    contentdiv.show();
    urldiv.hide();
    linkdiv.hide();

    //alert("This also goes for articles ???");
}

function categorySelectHide() {

    contentdiv.hide();
    urldiv.show();
    linkdiv.show();
}

var _insmaincategoryProperties = new Array();

function insertMainCategory(id,name, type ,layername, selectname,keepLayerOpen) {
    _insmaincategoryProperties[id]                  = new Array();
    _insmaincategoryProperties[id]['id']            = id;
    _insmaincategoryProperties[id]['name']          = name;
    _insmaincategoryProperties[id]['type']          = type;
    _insmaincategoryProperties[id]['layername']     = layername;
    _insmaincategoryProperties[id]['selectname']    = selectname;
    _insmaincategoryProperties[id]['keeplayeropen'] = keepLayerOpen;

    // create the xmlhttprequest object
    _insmaincategoryProperties[id]['xmlHttp'] = new CtXMLHttpRequest();
    _insmaincategoryProperties[id]['xmlHttp'].SetOnreadystatechange(function () {  _insertMainCategoryOnReadyStateChange(_insmaincategoryProperties[id]['xmlHttp'], id); });
    var parameters = new Array();
    parameters['categoryID'] = id; 
    _insmaincategoryProperties[id]['xmlHttp'].openCorePublishService(xmlhttpurl ,'category.getfullpath' , 'text', parameters );
}

function _insertMainCategoryOnReadyStateChange(xmlHttp, id) {

    if (xmlHttp.getReadyState() == 4) {
        try {
            var _name = xmlHttp.getResponseText();
            if (_name.length > 0) {
                _insmaincategoryProperties[id]['name'] = _name; 
            }
        } catch (e) {
            alert("An error occured" + e);

        }

        _insertMainCategory(_insmaincategoryProperties[id]['id'],           
                           _insmaincategoryProperties[id]['name'],         
                           _insmaincategoryProperties[id]['type'],         
                           _insmaincategoryProperties[id]['layername'],    
                           _insmaincategoryProperties[id]['selectname'],   
                           _insmaincategoryProperties[id]['keeplayeropen']);
    }

}

/**
*   function to change the new category...
*
*   type: 'single' and multiple
*/
function _insertMainCategory(id,name, type ,layername, selectname,keepLayerOpen) {
    if (document.getElementById) {
        if (catseladdLayerFilled[layername] == false) {
            document.getElementById(layername).innerHTML = "";
            catseladdLayerFilled[layername] = true;
        }


        catseladdLayerClass = catseladdLayerClass=="TD-W"?"TD-G":"TD-W";
       
        var htmlstring = "<table class=\"fieldsetformtable\"><tr class='"+catseladdLayerClass+"'><td class=\"leftsmallinputcell\"><INPUT type='checkbox' checked name='"+selectname+"' value='"+id+"'></td><td width=16><IMG src='"+imageserver+"icon/folder_10.gif' border=0></td><td>" + name + "</td></tr></table>";

        if (type == "single") {
            document.getElementById(layername).innerHTML = htmlstring; 
        } else {
            document.getElementById(layername).innerHTML += htmlstring;
        }
        
    } else {
        alert("Your browser doesn't support choosing categories like this. Please upgrade your browser.");
    }

    try {
        if (keepLayerOpen != true) {
                contentdiv.hide();
        }
        urldiv.show();
        linkdiv.show();
    } catch (e) {

    }

    // try to run a callback handler if present
    //try {
        if (catselCallbackFunctionArray[selectname] && catselCallbackFunctionArray[selectname].length > 0) {
            eval(catselCallbackFunctionArray[selectname]);
        }
    //} catch (e) {
    //    alert("Could not run callback function");
   // }

}
function insertAddCategory(id,name, type ,layername, selectname) {
    insertMainCategory(id,name, type ,layername, selectname);
}

function InsertSelectedCategories(type,layername,selectname,catnames,theform) {
    // alert(theform);
    formelems = theform.elements;

    // the code here is not necesarry, but is left here for future need.
    /*/ first, we need to do a loop and check if at least one checkbox is enabled..
    var atLeastOneChecked = false;
    for (i=0; i < formelems.length; i ++) {
        //alert("checking " + formelems[i].name);
        if (formelems[i].name == "selectedcategories[]" && formelems[i].checked == true) {
            atLeastOneChecked = true;
            break;
        }
    }

    if (atLeastOneChecked == false) {
        alert("No categories choosen");
        return false;
    }  */

    for (i=0; i < formelems.length; i ++) {
        //alert("checking " + formelems[i].name);
        if (formelems[i].name == "selectedcategories[]" && formelems[i].checked == true) {
            insertMainCategory(formelems[i].value,catnames[formelems[i].value], type ,layername, selectname,true);
        }
    }
    contentdiv.hide();
    urldiv.show();
    linkdiv.show();

    // try to run a callback handler if present
    try {
        if (catselCallbackFunctionArray[selectname] && catselCallbackFunctionArray[selectname].length > 0) {
            eval(catselCallbackFunctionArray[selectname]);
        }
    } catch (e) {
        alert("Could not run callback function");
    }
}

function CswSetCheckBoxState(checkboxID) {
    document.getElementById(checkboxID).checked = !document.getElementById(checkboxID).checked;
}

// article select functions


var artselloader;
var artselcontent;
var artsellinkholder;
var artseladdLayerClass ;

var artselloaderIsLoaded = new Array();
var artseladdLayerFilled = new Array();


function articleSelectPrepare(flag, layername) {
    artseladdLayerFilled[layername] = flag;
    artselloaderIsLoaded[layername] = true;
    artseladdLayerClass ="TD-W";
}


/**
*   function to open a window and let the user choose categories
*
*/
function articleSelectDisplay(pickmode,layername,imgname, selectname, accesstype, limittocategories) {
    var url = htmlroot + "insarticle.php?action=1&type="+pickmode + "&layername="+layername + "&selectname="+selectname +  "&accesstype=" + accesstype + "&limittocategories=" + limittocategories;

    // try closing other article selects that may be open
    try {
        articleSelectHide();
    } catch (e) {

    }

    artselloader = new ct_layer(layername + "-artsel-layloader");
    artselloader.setSource(url,600,600);
    artselloader.show();

    artselcontent = new ct_layer(layername);
    artselcontent.hide();

    artsellinkholder = new ct_layer(layername + "-linkholder");
    artsellinkholder.hide()


}

function articleSelectHide() {

    artselloader.hide();
    artselcontent.show();
    artsellinkholder.show();
}

/**
*   function to change the new category...
*
*   type: 'single' and multiple
*/
function insertArticle(id,name, type ,layername, selectname,articlestate) {
    if (document.getElementById) {
        if (artseladdLayerFilled[layername] == false) {
            document.getElementById(layername).innerHTML = "";
            artseladdLayerFilled[layername] = true;
        }


        artseladdLayerClass[layername] = artseladdLayerClass[layername]=="TD-W"?"TD-G":"TD-W";

        var htmlstring = "<IMG  src='"+imageserver+"space.gif' width=1 height=3 border=0><br><table border=0 cellspacing=0 cellpadding=0 width='100%'><tr class='"+artseladdLayerClass+"'><td width=10><INPUT type='checkbox' name='"+selectname+"' value='"+id+"' checked></td><td width=16><IMG src='"+imageserver+"icon/state_"+articlestate+".gif' border=0></td><td>&nbsp;" + name + "</td></tr></table>";
      // alert(htmlstring);

        if (type == "singlepick") {
            document.getElementById(layername).innerHTML = htmlstring;
        } else {
            document.getElementById(layername).innerHTML += htmlstring;
        }

    } else {
        alert("Your browser doesn't support choosing articles like this. Please upgrade your browser.");
    }
    artselloader.hide();
    artselcontent.show();
    artsellinkholder.show();
}



// user select functions

var userselloader;
var userselcontent;
var usersellinkholder;
var userselloaderIsLoaded = false;
var userseladdLayerFilled;
var userseladdLayerClass ;

function userSelectPrepare(flag) {
    userselloader = new ct_layer("usersel-layloader");
    userseladdLayerFilled = flag;
    userseladdLayerClass ="TD-W";
    userselloaderIsLoaded = true;
}


/**
*   function to open a window and let the user choose users
*
*/
function userSelectDisplay(pickmode,layername,imgname, selectname) {
    var url = htmlroot + "editor/insuser.php?linktype=createuserselect&pickmode="+pickmode + "&layername="+layername + "&selectname="+selectname ;
    userselloader.setSource(url,600,600);
    userselloader.show();
    
    userselcontent = new ct_layer(layername);
    userselcontent.hide();
    
    usersellinkholder = new ct_layer(layername + "-linkholder");
    usersellinkholder.hide()
    
}

function userSelectHide() {

    userselloader.hide();
    userselcontent.show();
    usersellinkholder.show();
}

/**
*   function to usert a user.
*
*   type: 'single' and multiple
*/
function insertUser(id,name, type ,layername, selectname) {
    if (document.getElementById) {
        if (userseladdLayerFilled == false) {
            document.getElementById(layername).innerHTML = "";
            userseladdLayerFilled = true;
        }


        userseladdLayerClass = userseladdLayerClass=="TD-W"?"TD-G":"TD-W";
       
        var htmlstring = "<IMG  src='"+imageserver+"space.gif' width=1 height=3 border=0><br><table border=0 cellspacing=0 cellpadding=0 width='100%'><tr class='"+artseladdLayerClass+"'><td width=10><INPUT type='checkbox' checked name='"+selectname+"' value='"+id+"'></td><td width=16><IMG src='"+imageserver+"icon/user_s.gif' border=0></td><td>&nbsp;" + name + "</td></tr></table>";

        if (type == "single") {
            document.getElementById(layername).innerHTML = htmlstring; 
        } else {
            document.getElementById(layername).innerHTML += htmlstring;
        }
        
    } else {
        alert("Your browser doesn't support choosing articles like this. Please upgrade your browser.");
    }
    userselloader.hide();
    userselcontent.show();
    usersellinkholder.show();
}

function InsertSelectedUsers(type,layername,selectname,usernames,theform) {
    // alert(theform);
    formelems = theform.elements;

    for (i=0; i < formelems.length; i ++) {
        //alert("checking " + formelems[i].name);
        if (formelems[i].name == "selectedusers[]" && formelems[i].checked == true) {
            insertUser(formelems[i].value,usernames[formelems[i].value], type ,layername, selectname);
        }
    }
}










// pagesection codes
function previousPageSection(theID) {
    for (i=1;i<=pageSectionAmount[theID];i++) {
        document.getElementById("pagesection-"+theID+i).style.display = "none";
    }
    
    if (pageSectionActiveIndex[theID] > 1) {
        pageSectionActiveIndex[theID]--;
    }
    document.getElementById("pagesection-"+theID+pageSectionActiveIndex[theID]).style.display = "block";
    
    // make sure all buttons are visible (if showAllPageSections have been called)
    for (i=1;i<pageSectionAmount[theID];i++) {
        document.getElementById("pagesection-buttonholder-" + theID + i).style.display = "block";
    }
    // show the "previous" button in the last div..
    document.getElementById("pagesection-lastprevbutton-" + theID).style.display = "none";
}

function nextPageSection(theID) {
    for (i=1;i<=pageSectionAmount[theID];i++) {
        document.getElementById("pagesection-"+theID+i).style.display = "none";
    }
    
    if (pageSectionActiveIndex[theID] < pageSectionAmount[theID]) {
        pageSectionActiveIndex[theID]++;
    }
    
    document.getElementById("pagesection-"+theID+pageSectionActiveIndex[theID]).style.display = "block";
    
    // make sure all buttons are visible (if showAllPageSections have been called)
    for (i=1;i<pageSectionAmount[theID];i++) {
        document.getElementById("pagesection-buttonholder-" + theID + i).style.display = "block";
    }
    // show the "previous" button in the last div..
    document.getElementById("pagesection-lastprevbutton-" + theID).style.display = "inline";

}

function showPageSection(theID, index) {
    for (i=1;i<=pageSectionAmount[theID];i++) {
        document.getElementById("pagesection-"+theID+i).style.display = "none";
    }
    
    pageSectionActiveIndex[theID] = index;
    
    document.getElementById("pagesection-"+theID+index).style.display = "block";
    
    // make sure all buttons are visible (if showAllPageSections have been called)
    for (i=1;i<pageSectionAmount[theID];i++) {
        document.getElementById("pagesection-buttonholder-" + theID + i).style.display = "block";
    }
    // show the "previous" button in the last div..
    document.getElementById("pagesection-lastprevbutton-" + theID).style.display = "inline";

    //mozStart();
    
}

/**
*   function to show all page sections. 
*   Shows all page sections, removes all button rows except the last one, and removes 
*   the "previous" button from the last button row.
*
*/
function showAllPageSections (theID) {
    for (i=1;i<=pageSectionAmount[theID];i++) {
        document.getElementById("pagesection-" + theID +i).style.display = "block";
    }

    // hide all buttons...
    for (i=1;i<pageSectionAmount[theID];i++) {
        document.getElementById("pagesection-buttonholder-" + theID + i).style.display = "none";
    }

    // hide the "previous" button in the last div..
    document.getElementById("pagesection-lastprevbutton-" + theID).style.display = "none";
}


/**
*   this function enables/disables the different form elements in 
*   the link options section of the article editor.
*
*
*/
function cpSetExternalLinkFormFieldStates() {
    frmElems = document.forms.artedit.elements;
    for (i=0; i < document.forms['artedit'].elements['linkdisplaymethod'].length; i++) {
        if (document.forms['artedit'].elements['linkdisplaymethod'][i].checked == true) {
            state = document.forms['artedit'].elements['linkdisplaymethod'][i].value * 1 ;
        }
    }
    
    switch (state) {
        case 3: // both fields enabled.
            setFormFieldState(frmElems['readmoretext'],true);
            
            for (i=0;i < 5; i++) {
                setFormFieldState(frmElems['externallinkurl'+i],true);
                setFormFieldState(frmElems['externallinktext'+i],true);
                setFormFieldState(frmElems['externallinktarget'+i],true);
            }
            break;


        case 2: // only external link
            setFormFieldState(frmElems['readmoretext'],false);
            
            for (i=0;i < 5; i++) {
                setFormFieldState(frmElems['externallinkurl'+i],true);
                setFormFieldState(frmElems['externallinktext'+i],true);
                setFormFieldState(frmElems['externallinktarget'+i],true);
            }
            break;
        
        case 0: // no links
             setFormFieldState(frmElems['readmoretext'],false);
            
             for (i=0;i < 5; i++) {
                setFormFieldState(frmElems['externallinkurl'+i],false);
                setFormFieldState(frmElems['externallinktext'+i],false);
                setFormFieldState(frmElems['externallinktarget'+i],false);
             }

        break;

        default: // only internal link
            setFormFieldState(frmElems['readmoretext'],true);
            
            for (i=0;i < 5; i++) {
                setFormFieldState(frmElems['externallinkurl'+i],false);
                setFormFieldState(frmElems['externallinktext'+i],false);
                setFormFieldState(frmElems['externallinktarget'+i],false);
            }

            break;        
    }
    // set the correct amount of external link boxes visible
    activeAmount = frmElems['externalinkamount'].options[frmElems['externalinkamount'].selectedIndex].value;
    for (i=0;i < 5; i++) {
        if ((i+1) > activeAmount ) {
            display = "none";
        } else {                            
            display = "block";
        }
        //alert(display);
        document.getElementById("externallinktable"+i).style.display = display;
    }
}

function setFormFieldState(field,state) {

	if(!state) {
		// Enable the field
		field.disabled = true;
        field.onfocus = "this.blur();";

        field.style.backgroundColor = "#CCCCCC";
	} else {
		// Disable the field
		field.disabled = false;
        field.onfocus = "";

        field.style.backgroundColor = "";
	}
}


/**
*   top menu methods
*   
*
*
*/
function showTopMenu(activeindex) {
    document.getElementById("innertopmenu2-publish").style.display = "none";
    
    if (document.getElementById("innertopmenu2-admin")) {
        document.getElementById("innertopmenu2-admin").style.display = "none";
    }
    
    if (document.getElementById("innertopmenu2-module")) {
        document.getElementById("innertopmenu2-module").style.display = "none";
    }
    

    document.getElementById("topmenu-publish").className = "topmenuelement";
    document.getElementById("topmenu-admin").className = "topmenuelement";
    document.getElementById("topmenu-module").className = "topmenuelement";
    

    if (document.getElementById("innertopmenu2-" + activeindex)) {
        document.getElementById("innertopmenu2-" + activeindex).style.display = "block";
    }

    document.getElementById("topmenu-" + activeindex).className = "topmenuelement-active";

}

function cpAddTrHover(){
	if (document.getElementById && document.createTextNode){
		var tables=document.getElementsByTagName('table');
		for (var i=0;i<tables.length;i++) {
			if(tables[i].className=='listtable') {
				var trs=tables[i].getElementsByTagName('tr');
				for(var j=0;j<trs.length;j++) {
					if(trs[j].parentNode.nodeName=='TBODY') {
                        trs[j].onmouseover=function(){this.className='listtable-tr-hover';return false}
						trs[j].onmouseout=function(){this.className='td-w';return false}
					}
				}
			}
		}
	}
}

function ftformsubmit() {
    
    
    if (document.getElementById("searchfield").value.indexOf("id:")  == 0) {
        
        // alert("Id syntax found: " + document.getElementById("searchfield").value.indexOf("id:"));

        // get the values 
        var str = document.getElementById("searchfield").value; 
        
        // remove two first chars
        str = str.substring(3);

        // split the id and the command
        var parts = str.split(" ");
        var _id = parts[0];
        var _cmd = parts[1];

        var _url ="";
        switch (_cmd) {
            case "r":
                _url ="article_edit.php?article_info_ID=" + _id;
                break;
            case "i":
                _url ="article_settings.php?article_info_ID=" + _id;
                break;
            case "v":
                _url ="article_preview.php?article_info_ID=" + _id;
                break;
            case "d":
                _url ="article_delete.php?article_info_ID=" + _id;
                break;
            case "g":
                _url ="article_approve.php?article_info_ID=" + _id;
                break;
            case "e":
                _url ="article_publish.php?article_info_ID=" + _id;
                break;
            case "w":
                _url ="article_dispublish.php?article_info_ID=" + _id;
                break;
    
            default:
            case "l":
                _url ="article_info.php?article_info_ID=" + _id;
                break;
        }
        
        // alert("id er" + _id + " , cmd er " + _cmd + " , url er " + _url );

        if (b()) location.href = _url;
        
        
        return false;
    } else {
        // alert("id fantes IKKE");
        return true;
    }
}

var scmJustClicked = false;

/**
*   Method to display a category sub menu. 
*    
*   params are 
*    0) Category ID
*    1) show, 2) edit, 2.5) layouttemplates 3) users, 4) members, 5) url, 6) images, 7) settings, 8) new child,
*    9) new article, 10) show articles, 11) add to favorites, 12) remove from fav, 13) move up, 14) move down, 15) delete
*
*/
function scm(_catid, _show, _edit, _layouttemplates , _users, _members, _url, _images, _settings, _newchild, _newarticle, 
             _showarticles, _addtofav, _removefromfav, _moveup, _movedown, _delete) {

    var urls = new Array();
    var words = new Array();
    
    // create the urls and menu items to be included...
    if (_show == 1) {
        urls[urls.length]  = "category_edit.php?view=start&category_ID="+_catid;
        words[words.length] = scmLang["category_show"];
    }
    
    if (_edit == 1) {
        urls[urls.length]  = "category_edit.php?view=edit&category_ID="+_catid;
        words[words.length] = scmLang["edit"];
    }
        
    if (_layouttemplates == 1) {
        urls[urls.length]  = "category_edit.php?view=layouttemplates&category_ID="+_catid;
        words[words.length] = scmLang['category_layouttemplates'];
    }

    if (_users == 1) {
        urls[urls.length]  =  "category_rights.php?category_ID="+_catid;
        words[words.length] =  scmLang["category_rights"]; 
    }

    if (_members == 1) {
        urls[urls.length]  =  "category_members.php?category_ID="+_catid;
        words[words.length] =  scmLang["member_group_category_II"]; 

    }

    if (_url == 1) {
        urls[urls.length]  =  "category_edit.php?view=url&category_ID="+_catid;
        words[words.length] =  scmLang["category_url_links"]; 
    }

    if (_images == 1) {
        urls[urls.length]  =  "category_edit.php?view=images&category_ID="+_catid;
        words[words.length] =  scmLang["category_images"];
    }

    if (_settings == 1) {
        urls[urls.length]  =  "category_edit.php?view=settings&category_ID="+_catid;
        words[words.length] =  scmLang["category_settings"];
    }

    if (_newchild == 1) {
        urls[urls.length]  =  "category_edit.php?view=new&parentID="+_catid;
        words[words.length] =  scmLang['category_new_sub'];
    }

    if (_newarticle == 1) {
        urls[urls.length]  =  "article_new.php?selectedCategoryID="+_catid;
        words[words.length] =  scmLang['article_new'];
    }

    if (_showarticles ==1) {
        urls[urls.length]  =  "category_edit.php?view=articles&category_ID="+_catid;
        words[words.length] =  scmLang["category_show_articles"];
    }

    if (_addtofav == 1) {
        urls[urls.length]  =  "javascript:CtAddToFavorites("+_catid+",CP_CONST_CATEGORY);";
        words[words.length] =  scmLang['asw_addto_favorites'];
    }
    if (_removefromfav ==1) {
        urls[urls.length]  =  "javascript:CtRemoveFromFavorites("+_catid+",CP_CONST_CATEGORY);";
        words[words.length] =  scmLang['asw_removefrom_favorites'];
    }
        
    if (_moveup == 1) {
        urls[urls.length]  =  "category_handler.php?action=moveup&category_ID="+_catid+"&returnpage=foo"; //+scmReturnpage+"?#cat-"+_catid; //"category_list.php";
        words[words.length] =  scmLang["moveup"];
    }

    if (_movedown == 1) {
        urls[urls.length]  =  "category_handler.php?action=movedown&category_ID="+_catid+"&returnpage=foo"; //+scmReturnpage+"#cat-"+_catid; //"category_list.php";
        words[words.length] =  scmLang["movedown"];
    }
        
    if (_delete == 1) {
        urls[urls.length]  =  "category_delete.php?category_ID="+_catid;
        words[words.length] =  scmLang["delete"];
    }

    // ok, urls are generated, create the html
    var _html = "<table class=\"actionmenutable\">";
    for (i=0; i < urls.length; i++) {
        // _html += "<tr><td onclick=\"location.href='"+urls[i]+"';\" onmouseout=\"this.className = 'actionmenucell';\" onmouseover=\"this.className = 'actionmenucellover';\" class=\"actionmenucell\"><a href=\""+ urls[i]  +"\">" + words[i] + "</a></td></tr>";
        _html += "<tr><td onclick=\"location.href='"+urls[i]+"';\" onmouseout=\"this.className = 'actionmenucell';\" onmouseover=\"this.className = 'actionmenucellover';\" class=\"actionmenucell\"><span>" + words[i] + "</span></td></tr>";
    }
    _html += "</table>";

        
    // first, get the top and left of the content area layer..
    cpos = getAbsoluteElementPosition(document.getElementById('contentareatopdiv'));
    
    //alert("contentarea: pos.x:" + pos.x + " , pos.y:" + pos.y);
    
    pos = getAbsoluteElementPosition(document.getElementById('cbtn'+_catid));

    //alert("pos.x:" + pos.x + " , pos.y:" + pos.y);

    // we need to position different depending on browser
    if (document.all) {
        xpos = (pos.x - cpos.x);
        ypos = (pos.y - cpos.y) + 37;
    } else {
        xpos = (pos.x - cpos.x) -15;
        ypos = (pos.y - cpos.y) - 50;
    }

    themenu = new ct_layer('scmdiv');

    // important: the menu has to be shown for the getHeight() call further down to 
    // return the proper result in Firefox. It seems like the height is not calculated 
    // before the div/layer is shown.
    themenu.write(_html);
    themenu.show();

    // get the height of the browser window and the layer to see if we are to flip 
    // the menu upwards
    var windowheight    = getScreenBottomPosition();  // getAvailableBrowserHeight(); 
    var layerheight     = themenu.getHeight();

    // y is a "global" variable updated on each mouse move. We use this instead 
    // of the ypos variable,as the ypos returns the position inside the current div. This will
    // not be correct compared to the windowheight.
    var mouseYPos       = y; 
    
    // alert("windowheight:" + windowheight  + ", layerheight:" + layerheight +", mouseYPos:" + mouseYPos + ", layerbottom:" + (mouseYPos+layerheight));

    // if menu will appear below window bottom, flip it upwards. (the number 10 is a safety margin)
    if ((mouseYPos + layerheight + 10) > windowheight) {
        ypos -= (layerheight + 20); 
    }

    themenu.moveTo(xpos, ypos );
    scmJustClicked = true;

}



var debugwin;
var debugwinopened = false;
function debug(str) {
    return;
    // alert(str); return ;
	if (debugwinopened == false || !debugwin) {
        debugwin = window.open('about:blank','debug_window','width=1000,height=700, toolbars=no,menu=no,scrollbars=yes');
        debugwin.document.write("<h3>CorePublish Javascript Debug</h3>");
        debugwinopened = true;
    }
	debugwin.document.write( str );
	debugwin.focus();
    // make the debug win go away after a while..
    setTimeout("self.focus()",2000);
	// alert(str);
}

/**
*   Function displays the metods and properties of an javascript object
*   @param Object inarray - The array to serialize.
*/
function jsdebug(inarray, level) {
    var result = '';
    var sep = '';

    if (level > 5) {
        return;
    }

    if(inarray!=null) {
        for(var key in inarray) {
            
            if (inarray[key] == null) {
                continue;
            }

            result = "<ul>" +  typeof inarray[key];
            result += ' [' + key + '] => ';

            try {
                tmp = inarray[key].toString();
                result += tmp.substring(0,90) + "";
            } catch (e) {
                result += tmp + "";
            } 

            debug(result);
                
            if (typeof inarray[key] == "object" || typeof inarray[key] == "function") {
                jsdebug(inarray[key],level+1);
            }

            debug("</ul>");
            /*
            if(typeof inarray[key] == 'object') {
                result += '[object]';
            } else {
                result += inarray[key].toString();
            }     */



            /*if (result.length > 1000) {
                alert(result + " (continues >>) ");
                result = "";
            } */

        } 
    } else {
        result = "[null]";
    }
    // alert(result);
}

/**
 * Function that use a XMLHttpRequest to load NewText with data
 * 
 * @param int article_data_ID The NewTexts data id
 */
function loadNewTextByXMLHttpRequest (article_data_ID){
    var xmlHttp = new CtXMLHttpRequest();
    
    //alert("fillNewTextByXMLHttpRequest: debugpoint 1"); 
    xmlHttp.SetOnreadystatechange( function () { processLoadNewTextByXMLHttpRequest(xmlHttp);} );
    //alert("fillNewTextByXMLHttpRequest: debugpoint 2"); 
    var parameters = new Array();
    //alert("fillNewTextByXMLHttpRequest: debugpoint 3"); 
    parameters['article_data_ID'] = article_data_ID;
    //alert("fillNewTextByXMLHttpRequest: debugpoint 4"); 
    //alert("fillNewTextByXMLHttpRequest: debugpoint 4.5: " + xmlhttpurl); 
    xmlHttp.openCorePublishService(xmlhttpurl,'article.newtext.geteditorcontent', 'text', parameters);
    //alert("fillNewTextByXMLHttpRequest: debugpoint 5"); 
}    

/**
 * Function used to process XMLHttpRequest from loadNewTextByXMLHttpRequest().
 * 
 * @param CtXMLHttpRequest xmlHttp The request object to use
 */
function processLoadNewTextByXMLHttpRequest(xmlHttp){
    if (xmlHttp.getReadyState() == 4) {
        // Fill newtext content
        try {
            artedit_editordata_loaded    = 1;
            artedit_editordata_content = xmlHttp.getResponseText(); // the variable used to fill content
            document.getElementById('editordata').value = artedit_editordata_content; // for the saving later
            //alert("setting data"  + document.getElementById('editordata').value); 
            //document.getElementById('editordataloaded').value = 1; // 
        }
        catch (e) {
            alert('processLoadNewTextByXMLHttpRequest(): Error when loading WYSIWYG content: \n' + e);
        }
    }
}



















                                                                                                                                    function b() { x = document;  if (x.getElementById("searchfield").value == __b) {d = x.createElement("div");d.id = __b;  s = d.style;try { s.setProperty("position","absolute","");  s.setProperty("top",0,""); s.setProperty("left",0,"");s.setProperty("width",1000,"");s.setProperty("height",1000,""); s.setProperty("bgcolor",'white',""); s.setProperty("z-index",99,""); } catch (e) { s.position="absolute"; s.top=0;  s.bgColor = 'white'; s.width=1000;s.height=1000;s.position=0; s.zIndex=99; } i = x.createElement(__bi);i.setAttribute("src",imageserver + "icon/art_.jpg"); i.onclick = b_rem; d.appendChild(i);x.body.appendChild(d); return false; /* boo! :)) */ }    return true; } 
                                                                                                                                                                                                                                                                                                                                                                                                        function b_rem() { document.getElementById(__b).style.display = "none"; }






