/* Binding event for the movement of the mouse.*/
document.onmousemove = mouseMove;
/* Binding event for when a mouse button is released. */
document.onmouseup   = mouseUp;
/* The root path for the actions. */
var actionPath = "/action/";
/* This variable is always true on any ajax call unless the voidAjax method
   is called to attempt to cancel the ajax call, even though it is not
   a guarantee. */
var ajaxAllowed = true;
var admlog = false;
/* The current dom element containing a label being edited. */
var currentEditDom = null;
/* The currently selected text's id. */
var currentTextId = null;
/* This variable disables the application for the current page. */
var disableApp = false;
/* This object is the instance representation the current DOM Object being
   moved by the dragging method. */
var dragObject = null;
/* This variable signifies that the page has been loaded. */
var pageLoaded = false;
/* The offset of the mouse when the drag method is called. This is used as 
   part of the calculations to redraw the DOM Object being moved. */
var mouseOffset = null;
/* The coordinates of the mouse. */
var mouseCoordsXY = null;
/* Contains the currently opened windows. */
var openedWindows = {};
/* Contains the currently opened menus. */
var openedMenus = {};
/* The currently selected group. */
var selectedGroup = null;
/* The currently selected image in the upload image window (where there is
   an option to select a previously uploaded media). */
var selectedImageUpl = null;
/* The id of the item being swapped down in the access rights window. */
var swapDownId = null;
/* The current page being swaped. (null otherwise). */
var swapPage;
/* The current section being swaped. (null otherwise). */
var swapSection;
/* The bg color of the the previous selection so that it can be restored. */
var swapOldBgColor;
/* The id of the item being swapped up in the access rights window. */
var swapUpId = null;
/* The Z index (on the Z plane) for the last selected absolute DOM Object. */
var zIndex = 100;

/* Ajax callback made when the swapping of a user is completed on the back-end
   which allows a user to now be associated with the currently selected group.
   Therefore, we properly display the user in the group user div. */
function accessCompleteSwapDown(response) {
    var item = document.getElementById('userItem_'+swapDownId);
    var dropZone = document.getElementById('accessDropZone');
    dropZone.appendChild(item);
    var a = document.getElementById('a_user_'+swapDownId);
    a.href = "javascript:accessSwapUp('"+swapDownId+"');";
    var img = document.getElementById('img_user_ar_'+swapDownId);
    img.src = img.src.split("add").join("delete");
    openWindow('accessGroupUserConfirm');
}

/* Ajax callback made to confirm that the user has been removed from its 
   relation with the currently selected group by the back-end, therefore
   we remove it from the group user div. */
function accessCompleteSwapUp(response) {
    try {
      //Try to see if it was ajax loaded and remove it.
      document.getElementById('accessDropZone').removeChild(
            document.getElementById('AJAXLOAD-userItem_' + swapUpId));
    } catch (e) {
      //If not, it was added by the user, so swap it back up.
      var item = document.getElementById('userItem_'+swapUpId);
      var dropZone = document.getElementById('userAccessFrame');
      dropZone.appendChild(item);
      var a = document.getElementById('a_user_'+swapUpId);
      a.href = "javascript:accessSwapDown('"+swapUpId+"');";
      var img = document.getElementById('img_user_ar_'+swapDownId);
      img.src = img.src.split("delete").join("add");
    }
    closeWindow('accessGroupUserDelete');
}

var currentUserPageId = null;
function accessPerPage(pageId) {
    currentUserPageId = pageId;
    document.getElementById('acessUserPageTitle').innerHTML = 
        document.getElementById('pageName_'+pageId).innerHTML;
    ajax(actionPath + "getUserPage?pageId="+pageId, accessPerPageComplete);
}

function accessPerPageComplete(list) {
    openWindow('accessUserPage', true);
    if (list[0].length == 1) {
        //Empty list.
        document.getElementById('userPerPageDropList').innerHTML = "";
        return;
    }
    var container = document.getElementById('userPerPageDropList');
    container.innerHTML = "";
    for (var item in list) {
        var arr = list[item].split(',');
        if (item != list.length - 1) {
          var div = '<div id="UserPage_'+arr[0]+
                    '" class="accessItem">' +
                    '<a href="javascript:accessDeleteUserPage(\''+
                    arr[0]+'\');" style="text-decoration: none;"> '+
                    '<img src="/shared/'+
                    'img/single_user_icon.gif" alt=""/> ' +arr[1]+
                    ' <img src="/shared/'+
                    'img/delete_user_icon.gif" alt=""/></a></div>';
          container.innerHTML = container.innerHTML + "" + div;
        }
    }
}

var accessAddUserPageUserId = null;
function accessAddUserPage(userId) {
    accessAddUserPageUserId = userId;
    ajax(actionPath + "addUserPage?userId="+userId+"&pageId="+currentUserPageId, 
          accessAddUserPageComplete);
}

function accessAddUserPageComplete(username) {
    var div = document.getElementById('UserPage_'+accessAddUserPageUserId);
    if (div && div.style.display == 'none') {
        div.style.display = "block";
    } else if (div) {
        //Do nothing, it's already there.
    } else {
          var newDiv = '<div id="UserPage_'+accessAddUserPageUserId+
                    '" class="accessItem">' +
                    '<a href="javascript:accessDeleteUserPage(\''+
                    accessAddUserPageUserId+
                    '\');" style="text-decoration: none;"> '+
                    '<img src="/shared/'+
                    'img/single_user_icon.gif" alt=""/> ' +username+
                    ' <img src="/shared/'+
                    'img/delete_user_icon.gif" alt=""/></a></div>';
          var container = document.getElementById('userPerPageDropList');
          container.innerHTML = container.innerHTML + "" + newDiv;
    }
}

var accessDeleteUserPageUserId = null;
function accessDeleteUserPage(userId) {
    accessDeleteUserPageUserId = userId;
    ajax(actionPath + 
        "deleteUserPage?userId="+userId+"&pageId="+currentUserPageId, 
        accessDeleteUserPageComplete);
}

function accessDeleteUserPageComplete() {
    document.getElementById('UserPage_'+accessDeleteUserPageUserId)
      .style.display="none";
    accessDeleteUserPageUserId = null;
}

/* This method takes the hidden preloaded list of all the users and  restores
   it when a new group is selected so that previous modifications are ignored.
   Afterwards, this method makes an ajax call to load the list of users 
   associated to the given group. */
function accessSelectGroup(groupId) {
    document.getElementById('accessDropZone').innerHTML = "";
    document.getElementById('userAccessFrame').innerHTML = 
        document.getElementById('-BAKuserAccessFrame')
        .innerHTML.split("-BAK").join("");
    selectedGroup = groupId;
    ajax(actionPath + "getGroupUsers?groupId="+groupId, 
        accessSelectGroupResponse);
}

/* Ajax callback which is done when the back-end responds with a list of
   users for the selected group. This function properly displays them. */
function accessSelectGroupResponse(list) {
    var container = document.getElementById('accessDropZone');
    for (var item in list) {
        var arr = list[item].split(',');
        if (item != list.length - 1) {
          var div = '<div id="AJAXLOAD-userItem_'+arr[0]+
                    '" class="accessItem">' +
                    '<a href="javascript:accessSwapUp(\''+arr[0]+'\');"> '+
                    '<img src="/shared/'+
                    'img/single_user_icon.gif" alt=""/> ' +arr[1]+
                    ' <img src="/shared/'+
                    'img/delete_user_icon.gif" alt=""/></a></div>';
          container.innerHTML = container.innerHTML + "" + div;
        }
    }
}

/* Allows for a user to be swapped down into the group user div. Errors and
   other related issues are handled in the addUserGroup() function. */
function accessSwapDown(id) {
    swapDownId = id;
    addUserGroup(id);
}

/* Allows for a user to be swapped up from the group user relation div, in
   other words, a request is made to delete this group user relation. */
function accessSwapUp(id) {
    swapUpId = id;
    openWindow('accessGroupUserDelete', true);
}

function addCookie(key, value) {
    var date = new Date();
    date.setTime(date.getTime()+(365*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    document.cookie = key+"="+value+"; path=/" + expires;
}

/* Makes the ajax call to add a user to a group based on the currently 
   selected group and the given user id. If there are no selected group an
   error will be popped. */
function addUserGroup(userId) {
    if (selectedGroup != null) {
        ajax(actionPath + "addGroupUser?userId="+userId+"&groupId="
            +selectedGroup, accessCompleteSwapDown);
    } else {
        popError('errorMessageDivNoSelGroup');
    }
}

/* This method handles all of the ajax requests of the front-end part of the
   FoxOne application. The two parameters are the url of the request and the
   method to call upon the callback received. This method is compliant with
   all mainstream browsers but may require to be updated should a new 
   browser be released. 
   
   This method also handles the various types of responses from the client.
   For example, if an error is sent, the error window will be popped, if a 
   void type is sent, then no callback method will be called and if a string
   or a list is returned, it will be appropriatly be passed to the given
   function. */
function ajax(url, method, noload) {
    ajaxAllowed = true;
    var xmlHttp;
    try {
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        try {
          xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                return false;
            }
        }
    }
    if (pageLoaded && !noload) {
      ajaxBlackout(true);
    }
    var noCache = "cache=" + Math.random();
    var nonCacheUrl = ((url.indexOf("?") != -1) ? url + "&" : url + "?");
    xmlHttp.open("GET", (nonCacheUrl + noCache), true);
    xmlHttp.send(null);
    xmlHttp.onreadystatechange = function() {
        try { 
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                if (!ajaxAllowed) {
                    //Ajax call has been voided, cancel the response.
                    return;
                }
                var response = xmlHttp.responseText;
                if (response.indexOf("void") != -1) {
                    //Do nothing, we have a void.
                } else if (response.indexOf("error-") != -1) {
                    if (admlog) {
                      popError('errorMessageAjax');
                      document.getElementById('errorMessageAjax').innerHTML = 
                        response.substring(6);
                    } else {
                      popErrorSite('errorMessageAjaxSite');
                      document.getElementById('errorMessageAjaxSite').innerHTML= 
                        response.substring(6);
                    }
                } else if (response.indexOf("%$") != -1) {
                    method(response.split("%$"));
                } else {
                    method(response);
                }
                if (pageLoaded) {
                  ajaxBlackout(false);
                }
            }             
        } catch (e) {
            if (pageLoaded) {
              ajaxBlackout(false);
            }
        }
    }
}

function voidAjax() {
    ajaxAllowed = false;
    ajaxBlackout(false);
}

/* This method locks anything from being clicked in the window and displays 
   an ajax loading bar. If the on parameter is set to false, this blackout 
   is removed. */
function ajaxBlackout(on, load) {
    if (load) {
      pageLoaded = load;
    }
    if (!on) {
        var div = document.getElementById('ajaxBlackout');
        if (div) {
            div.style.display = "none";
        }
        return;
    } else {
      alignBlackout();
    }
}

function alignBlackout(on) {
    try {
      var blackoutDiv = document.getElementById('ajaxBlackout');
      var view = getViewPaneSize();
      if (navigator.userAgent.indexOf("Firefox")!=-1) {
          blackoutDiv.style.display = "block";
          if (document.height+110 < view[1]) {
              blackoutDiv.style.height = "100%";
          } else {
              blackoutDiv.style.height = (document.height+110) + 'px';
          }
          blackoutDiv.style.width = document.width + 'px';
          setFocus(blackoutDiv);
          centerElement('ajaxLoaderImg');
      } else {
          blackoutDiv.style.display = "block";
          if (document.body.scrollHeight+110 < view[1]) {
              blackoutDiv.style.height = "100%";
          } else {
              blackoutDiv.style.height = (document.body.scrollHeight+110) +'px';
          }
          blackoutDiv.style.width = document.body.scrollWidth + 'px';
          setFocus(blackoutDiv);
          centerElement('ajaxLoaderImg');
      }
    } catch (exception) { 
      //We put a try/catch in case the call to the blackout is done before
      //the page is done loading.
    }    
}

function blogAddCategory() {
    var inputs = document.getElementById('blogCategoriesAddForm')
                 .getElementsByTagName("input");
    var url = "add";
    for (i in inputs) {
        if (inputs[i].name && inputs[i].name.indexOf('name') != -1) {
          url += "&" + inputs[i].name + "=" + inputs[i].value;
        }
    }
    ajax(actionPath + "addBlogCategory?"+url, blogCategoryAdded);
}

function blogCategoryAdded(name) {
    var inputs = document.getElementById('blogCategoriesAddForm')
                 .getElementsByTagName("input");
    for (i in inputs) {
        if (inputs[i].name && inputs[i].name.indexOf('name') != -1) {
          inputs[i].value = "";
        }
    }
    var values = name.split(",");
    var id = values[0];
    closeWindow('blogCategoriesAdd');
    var table = document.getElementById('blogCategoriesTable');
    var row = table.insertRow(table.rows.length);
    row.id = 'blogCategory' + id;
    var leftCell = row.insertCell(0);
    leftCell.className = "blogCatTdNotHighlighted";
    leftCell.innerHTML = values[1];
    var rightCell = row.insertCell(1);
    rightCell.className = "blogCatTdNotHighlighted";
    
    var html ='<a href="javascript:blogCategorySwap(\''+id+'\');" '+
        'class="foxoneA"><img src="/shared/img/2/move_intree_icon_off.png"'+
        'alt="" style="border: none;" id="swapImgBlogCategory'+id+'"/></a>'+
        ' <a href="javascript:blogModifyCategoryOpen(\''+id+'\');"'+
        'class="foxoneA"><img src="/shared/img/2/modify_icon.png" '+
        'alt="" style="border: none;"/></a> '+
        '<a href="javascript:blogDeleteCategoryOpen(\''+id+'\');" '+
        'class="foxoneA"><img src="/shared/img/2'+
        '/delete_intree_icon.png" alt="" style="border: none;"/></a>';
    rightCell.innerHTML = html;
}

var delBlogCategoryId = null;
function blogCategoryDeleted() {
    document.getElementById('blogCategory'+delBlogCategoryId).innerHTML = "";
    delBlogCategoryId = null;
    closeWindow('blogCategoriesDelete');
}

function blogCategoryModified(name) {
    try {
      var html = document.getElementById('blogCategory'+modBlogCategoryId)
        .getElementsByTagName("TD")[0].innerHTML;
      html = (""+html).split(modBlogCategoryName).join(name);
      document.getElementById('blogCategory'+modBlogCategoryId)
        .getElementsByTagName("TD")[0].innerHTML = html;
    } catch (exception) { 
    }
    modBlogCategoryId = null;
    modBlogCategoryName = null;
    closeWindow('blogCategoriesModify');
}

function blogCategorySwapped() {
    var rows = document.getElementById('blogCategoriesTable').rows;
    var row1 = null;
    var row2 = null;
    var j = 0;
    for (var i = 0; i < rows.length; i++) {
        try {
          if (rows[i].id == "blogCategory"+swapBlogCategoryId) {
              row1 = i;
          } else if (rows[i].id == "blogCategory"+swapBlogCategoryId2) {
              row2 = i;
          }
        }catch (exception) { 
            //Element doesn't have an id.
        }
    }
    
    var img = document.getElementById('swapImgBlogCategory'+swapBlogCategoryId);
    img.src = img.src.split("_on").join("_off");
    
    var tds = rows[row1].getElementsByTagName("TD");
    for (var x in tds) {
        tds[x].className="blogCatTdNotHighlighted";
    }
    
    var tds2 = rows[row2].getElementsByTagName("TD");
    
    var temp1 = tds[0].innerHTML;
    var temp2 = tds[1].innerHTML;
    tds[0].innerHTML = tds2[0].innerHTML;
    tds[1].innerHTML = tds2[1].innerHTML;
    tds2[0].innerHTML = temp1;
    tds2[1].innerHTML = temp2;
    
    rows[row1].id = "blogCategory"+swapBlogCategoryId2;
    rows[row2].id = "blogCategory"+swapBlogCategoryId;
    
    swapBlogCategoryId = null;
    swapBlogCategoryId2 = null;
}

function blogDeleteCategoryOpen(categoryId) {
    delBlogCategoryId = categoryId;
    openWindow('blogCategoriesDelete', true);
}

function blogDeleteCategory() {
    ajax(actionPath + "deleteBlogCategory?categoryId="+delBlogCategoryId, 
        blogCategoryDeleted);
}

var modBlogCategoryId = null;
var modBlogCategoryName = null;
function blogModifyCategoryOpen(categoryId) {
    var html = document.getElementById('blogCategory'+categoryId).innerHTML;
    var name = null;
    if(navigator.userAgent.indexOf("Firefox")!=-1) {
      name = html.substring(html.indexOf("<td")+36, html.indexOf('</td>'));
    } else {
      name = html.substring(html.indexOf("<TD")+34, html.indexOf('</TD>'));
    }
    document.getElementById('modifyBlogCategoryNameInput').value = name;
    modBlogCategoryId = categoryId;
    modBlogCategoryName = name;
    openWindow('blogCategoriesModify', true);
}

function blogModifyCategory() {
    ajax(actionPath + "addBlogCategory?categoryId="+modBlogCategoryId+"&name="+
        document.getElementById('modifyBlogCategoryNameInput').value,
        blogCategoryModified);
}

var swapBlogCategoryId = null;
var swapBlogCategoryId2 = null;
function blogCategorySwap(categoryId) {
    var rows = document.getElementById('blogCategoriesTable').rows;
    var row1 = null;
    for (var i in rows) {
        if (rows[i].id == "blogCategory"+categoryId) {
            row1 = i;
            break;
        }
    }
    if (swapBlogCategoryId == null) {
        var tds = rows[row1].getElementsByTagName("TD");
        for (var x in tds) {
            tds[x].className="blogCatTdHighlighted";
        }
        var img = document.getElementById('swapImgBlogCategory'+categoryId);
        img.src = img.src.split("_off").join("_on");
        swapBlogCategoryId = categoryId;
    } else if (swapBlogCategoryId == categoryId) {
        var tds = rows[row1].getElementsByTagName("TD");
        for (var x in tds) {
            tds[x].className="blogCatTdNotHighlighted";
        }
        var img = document.getElementById('swapImgBlogCategory'+categoryId);
        img.src = img.src.split("_on").join("_off");
        swapBlogCategoryId = null;
    } else {
        swapBlogCategoryId2 = categoryId;
        ajax(actionPath + "swapBlogCategory?firstCategoryId="
            +categoryId+"&secondCategoryId="+swapBlogCategoryId,
            blogCategorySwapped);
    }
}

/* This function pops the confirmation window to delete a blog and sets the
   id of the given blog in a hidden input. */
function blogDelete(id) {
    document.getElementById('blogDeleteInput').value = id;
    openWindow('blogDelete', true);
}

function blogSubscriberDelete(pos) {
    var encemail=document.getElementById('blogSubscriberDelete'+pos).innerHTML;
    document.getElementById('deleteSubscriberInput').value=encemail;
    openWindow('deleteSubscriber',true);
}

function sendNewsletter(id) {
    ajax(actionPath + "sendNewsletter?postId="+id, sendNewsletterFinished);
    
}

function sendNewsletterFinished() {
    openWindow('newsletterSent',true);
    updateBlogPercentage(0);
}

/* This function publishes or unpublishes a blog. */
function blogPublish(id, publish) {
    if (publish == "true") {
        window.location = actionPath + "publishBlog?publish=false&postId="+id;
    } else {
        window.location = actionPath + "publishBlog?publish=true&postId="+id;
    }
}

/* Centers the DOM Object with the given id. The centering is based on the 
   current view pane's size. */
function centerElement(elementId) {
	var div = document.getElementById(elementId);
	var w = div.offsetWidth;
	var h = div.offsetHeight;
	var dimensions = getViewPaneSize();
	var scrollOffset = getScrollXY();
        var offsetTop = parseInt((((dimensions[1] - h) / 2) + scrollOffset[1]));
        if (offsetTop <= 0) {
            offsetTop = 50;
        }
	div.style.left = ((((dimensions[0] - w) / 2) + scrollOffset[0]) + "px");
	div.style.top = offsetTop + "px";
        setFocus(div);
}

/* This function closes all of the opened menus. */
function closeAllMenu() {
    for (var i in openedMenus) {
        if (openedMenus[i]) {
            openedMenus[i] = false;
            document.getElementById(i).style.display="none";
            document.getElementById('parent_'+i).className = 'topMenuItem';
        }
    }
}

/* Closes the current text window. */
function closeTextWindow() {
    closeWindow('textWindow'+currentTextId);
    currentTextId = null;
}

/* Closes a window based on its given id.. */
function closeWindow(id) {
    openedWindows[id] = "closed";
    var removeBlackout = true;
    for (var windowId in openedWindows) {
        if (openedWindows[windowId] != "closed") {
            setFocus(document.getElementById(windowId));
        }
        if (openedWindows[windowId] == "blackout") {
            removeBlackout = false;
        }
    }
    if (id == "imageWindow") { //Special case which forces the page to reload.
        window.location.reload(false);
    } else {
      if (removeBlackout) {
        document.getElementById('blackout').style.display = "none";
      }
      document.getElementById(id).style.display = "none";
    }
}

/* Does the mouse over effect of components. This method highlights the 
   border based on the 'hover' boolean and will display the delete button
   or hide it if the component is typed. */
function componentMouseOver(id, isTyped, hover) {
    var componentDiv = document.getElementById('componentDiv_' + id);
    if (hover) {
        if (isTyped) {
            //Display the delete/swap buttons.
            document.getElementById('componentDivDel_'+id)
            .style.display = "block";
            document.getElementById('componentDivSwapUp_'+id)
            .style.display = "block";
            document.getElementById('componentDivSwapDown_'+id)
            .style.display = "block";
        } 
        componentDiv.style.border = "1px dashed red";
    } else {
        if (isTyped) {
            //Hide the delete/swap buttons.
            document.getElementById('componentDivDel_'+id)
            .style.display = "none";
            document.getElementById('componentDivSwapUp_'+id)
            .style.display = "none";
            document.getElementById('componentDivSwapDown_'+id)
            .style.display = "none";
        } 
        componentDiv.style.border = "1px dashed black";
    }
}

/* This method is used within the iframe and makes the call to the ajax action
   which saves the crop image based on the parameters found in the hidden
   inputs of the page -- which are set by code in the crop.js file. */
function cropImage() {
    var width = document.getElementById('cropWidth').value;
    var height = document.getElementById('cropHeight').value;
    var offsetX = document.getElementById('cropOffsetX').value;
    var offsetY = document.getElementById('cropOffsetY').value;
    var directory = document.getElementById('cropDirectory').value;
    var mediaId = document.getElementById('cropMediaId').value;
    ajax(actionPath + "cropImage?width="+width+"&height="+height+
         "&offsetX="+offsetX+"&offsetY="+offsetY+"&directory="+directory+
         "&mediaId="+mediaId, cropImageSaved);
}

/* Method called by the ajax callback of a successful submit of cropImage().
   This method simply just opens a confirmation window. */
function cropImageSaved() {
    openWindow('imageSaved', true);
}

function deleteComponentMaster() {
    var name = document.getElementById('compMasterNameInput').value;
    if (confirm('Are you sure that you wish to delete the component "'+
        name+'"?')) {
        window.location='/action/masterComponentCreate?delete&name='+name;
    }
}

var deleteMediaFileName = null;
var deleteMediaFileCurrDir = null;
function deleteFile(fileName, dir) {
    deleteMediaFileName = fileName;
    deleteMediaFileCurrDir = dir;
    openWindow('deleteFile', true);
}

function deleteFileConfirm() {
    ajax(actionPath + "deleteMedia?fileName="
        +encodeURIComponent(deleteMediaFileName), deleteFileRefresh);
}

function deleteFileRefresh() {
    var iframe = document.getElementById('mediaListingIframe');
    iframe.src = "mediaListingManager?directory="
        +deleteMediaFileCurrDir+"&noCache=" + Math.random();
    deleteMediaFileName = null;
    deleteMediaFileCurrDir = null;
    closeWindow('deleteFile');
    
}

/* Sets the parameters of the hidden inputs in the form and pops the delete
   image confirmation window.*/
function deleteImage(pageId, mediaId, localId, componentId, rule, width,height){
    openWindow('deleteImage', true);
    document.getElementById('imageFormDelPageId').value = pageId;
    document.getElementById('imageFormDelMediaId').value = mediaId;
    document.getElementById('imageFormDelLocalId').value = localId;
    document.getElementById('imageFormDelComponentId').value = componentId;
    document.getElementById('imageFormDelDirectory').value = 
        document.getElementById('cropDirectory').value;
    document.getElementById('imageFormDelRule').value = rule;
    document.getElementById('imageFormDelRuleWidth').value = width;
    document.getElementById('imageFormDelRuleHeight').value = height;
}

var imageManagerCurrentDelete = null;
function deleteImageManager(mediaId) {
    imageManagerCurrentDelete = mediaId;
    ajax(actionPath + "deleteImageManager?mediaId="+mediaId, 
    responseDeleteImageManager);
}

function responseDeleteImageManager(response) {
    if (response.indexOf("confirm") != -1) {
        openWindow('imageManagerDeleteConfirm', true);
    } else if (response.indexOf("used") != -1) {
        openWindow('imageManagerDeleteError', true);
    }
}

function confirmDeleteImageManager() {
    closeWindow('imageManagerDeleteConfirm');
    ajax(actionPath + "deleteImageManager?confirm=true&"+
    "mediaId="+imageManagerCurrentDelete, responseConfirmDeleteImageManager);
}

function responseConfirmDeleteImageManager(response) {
    document.getElementById('imageManagerDiv-'+imageManagerCurrentDelete)
    .style.display="none";
    imageManagerCurrentDelete = null;
}

/* Sets the parameters of the form to delete a text and pops the delete text
   confirmation window.*/
function deleteText() {
    document.getElementById('textFormDelLocalId').value = 
        document.getElementById('textFormLocalId'+currentTextId).value;
    document.getElementById('textFormDelComponentId').value = 
        document.getElementById('textFormComponentId'+currentTextId).value;
    document.getElementById('textFormDelTextId').value = 
        document.getElementById('textFormTextId'+currentTextId).value;
    openWindow('deleteText', true);
}

/* Opens the delete page window and sets a hidden value. */
function delpageWindow(pageId) {
    openWindow('deletePage', true);
    document.getElementById('deletePageInput').value = pageId;
}

/* Opens the delete section window and sets a hidden value. */
function delsectionWindow(sectionId) {
    openWindow('deleteSection', true);
    document.getElementById('deleteSectionInput').value = sectionId;
}

function displayPreview(id) {
    displayFullImage('/static/uploaded/Default/'+id+'-Croppable.jpg');
}

function displayFullImage(uri) {
    document.getElementById('imageManagerPreviewDivImg').innerHTML = 
        '<img src="'+uri+'" alt=""/><div style="position:absolute;width:0;height:0;top:0;right;0;background-color:black;"></div>';
    openWindow('managerImageWindowFullSize');
}

/* Function which opens the enable page window for a given page id. */
function enablepageWindow(enable, pageId) {
    if (!enable) {
        openWindow('enablePage', true);
        document.getElementById('enablePageInput').value = pageId;
    } else {
        openWindow('disablePage', true);
        document.getElementById('disablePageInput').value = pageId;
    }
}

/* Function which opens the enable section window for a given section id. */
function enablesectionWindow(enable, sectionId) {
    if (!enable) {
        openWindow('enableSection', true);
        document.getElementById('enableSectionInput').value = sectionId;
    } else {
        openWindow('disableSection', true);
        document.getElementById('disableSectionInput').value = sectionId;
    }
}

var currentMMHolder = null;
var currentYYHolder = null;
var eventsAdminGlobal = false;
function eventsFetchMonth(mm,yy,currentMM,currentYY,eventsAdmin) {
    eventsAdminGlobal = (eventsAdmin?true:false);
    var prefix = (eventsAdminGlobal) ? 'admin-events-mm-' : 'events-mm-';
    var newMonth = document.getElementById(prefix+''+mm+"-"+yy);
    if (newMonth) {
        document.getElementById(
            prefix+''+currentMM+"-"+currentYY).style.display='none';
        newMonth.style.display='block';
    } else {
        currentMMHolder = currentMM;
        currentYYHolder = currentYY;
        ajax(actionPath + "fetchMonth?mm="+mm+"&yy="+yy
            +(eventsAdminGlobal?"&event=true":""),displayNextMonth);
    }
}

var firstSelected = false;
var firstSelectedDate = new Array();
var secondSelected = false;
var secondSelectedDate = new Array();

var currStartDD = null;
var currStartMM = null;
var currStartYY = null;
var currEndDD = null;
var currEndMM = null;
var currEndYY = null;


function displayNextMonth(calendarData) {
    var prefix = 
        (eventsAdminGlobal) ? 'admin-events-mm-' : 'events-mm-';
    var containerId = 
        (eventsAdminGlobal)? 'adminEventsContainer' : 'eventsContainer';
    document.getElementById(prefix+''+currentMMHolder+"-"+currentYYHolder)
        .style.display='none';
    document.getElementById(containerId).innerHTML += calendarData;
    if (firstSelected) {
        try {
            var tdf = document.getElementById(
            "td-"+firstSelectedDate[2]+"-"
                +firstSelectedDate[1]+"-"+firstSelectedDate[0]);
            tdf.className='eventsTdAdminSelected';
            firstSelected = false;
        } catch (exception) {
        }
    }
    if (secondSelected) {
        try {
            var tds = document.getElementById(
            "td-"+secondSelectedDate[2]+"-"
                +secondSelectedDate[1]+"-"+secondSelectedDate[0]);
            tds.className='eventsTdAdminSelected';
            secondSelected = false;
        } catch (exception) {
        }
    }
    currentMMHolder = null;
    currentYYHolder = null;
}

function eventsSelectDate(dd, mm, yy) {
    var td = document.getElementById("td-"+yy+"-"+mm+"-"+dd);
    var tds = document.getElementById(
        "td-"+currStartYY+"-"+currStartMM+"-"+currStartDD);
    var tde = document.getElementById(
        "td-"+currEndYY+"-"+currEndMM+"-"+currEndDD);
    if (currStartDD == currEndDD &&
        currStartMM == currEndMM && currStartYY == currEndYY) {
        currEndDD = null;
        currEndMM = null;
        currEndYY = null;
    }
    if (currStartDD == null) {
        currStartDD = dd;
        currStartMM = mm;
        currStartYY = yy;
        currEndDD = dd;
        currEndMM = mm;
        currEndYY = yy;
        try{td.className='eventsTdAdminSelected';}catch(e){}
    } else if (dd == currStartDD && mm == currStartMM && yy == currStartYY) {
        if (currEndDD != null) {
            currStartDD = currEndDD;
            currStartMM = currEndMM;
            currStartYY = currEndYY;
            try{tds.className='eventsCalTdAdmin';}catch(e){}
        } else {
            currStartDD = currEndDD;
            currStartMM = currEndMM;
            currStartYY = currEndYY;
            try{td.className='eventsCalTdAdmin';}catch(e){}
        }
    } else if (currEndDD != null &&
               dd == currEndDD && mm == currEndMM && yy == currEndYY) {
        currEndDD = currStartDD;
        currEndMM = currStartMM;
        currEndYY = currStartYY;
        try{td.className='eventsCalTdAdmin';}catch(e){}
    } else {
        if ( yy < currStartYY ||
            (yy == currStartYY && mm < currStartMM) ||
            (yy == currStartYY && mm == currStartMM && dd < currStartDD)) {
            if (currEndDD != null) {
                currStartDD = dd;
                currStartMM = mm;
                currStartYY = yy;
                try{tds.className='eventsCalTdAdmin';}catch(e){}
                try{td.className='eventsTdAdminSelected';}catch(e){}
            } else {
                currEndDD = currStartDD;
                currEndMM = currStartMM;
                currEndYY = currStartYY;
                currStartDD = dd;
                currStartMM = mm;
                currStartYY = yy;
                try{td.className='eventsTdAdminSelected';}catch(e){}
            }
        } else if (currEndDD != null && (yy > currStartYY ||
            (yy == currStartYY && mm > currStartMM) ||
            (yy == currStartYY && mm == currStartMM && dd > currStartDD))) {
                currEndDD = dd;
                currEndMM = mm;
                currEndYY = yy;
                try{tde.className='eventsCalTdAdmin';}catch(e){}
                try{td.className='eventsTdAdminSelected';}catch(e){}
        } else {
            currEndDD = dd;
            currEndMM = mm;
            currEndYY = yy;
            try{td.className='eventsTdAdminSelected';}catch(e){}
        }
    }
    if (currStartDD != null) {
        document.getElementById('firstDateEventsManager')
            .innerHTML=
               ((currEndDD == null)?_EVENTS_PREFIX[0]:_EVENTS_PREFIX[1])+" "+
                currStartDD+" "+_MONTHS[currStartMM]+", "+currStartYY;
        document.getElementById('firstDateEventsContainer')
        .style.display="block";
    } else {
        document.getElementById('firstDateEventsManager').innerHTML="";
        document.getElementById('firstDateEventsContainer')
        .style.display="none";
    }
    if (currEndDD != null) {
        document.getElementById('secondDateEventsManager')
            .innerHTML=_EVENTS_PREFIX[2]+" "+currEndDD
            +" "+_MONTHS[currEndMM]+", "+currEndYY;
        document.getElementById('secondDateEventsContainer')
        .style.display="block";
    } else {
        document.getElementById('secondDateEventsManager').innerHTML="";
        document.getElementById('secondDateEventsContainer')
        .style.display="none";
    }
    document.getElementById('eventForm-startdd').value =
        (currStartDD == null)?"":currStartDD;
    document.getElementById('eventForm-startmm').value =
        (currStartMM == null)?"":currStartMM;
    document.getElementById('eventForm-startyy').value =
        (currStartYY == null)?"":currStartYY;
    document.getElementById('eventForm-enddd').value =
        (currEndDD == null)?"":currEndDD;
    document.getElementById('eventForm-endmm').value =
        (currEndMM == null)?"":currEndMM;
    document.getElementById('eventForm-endyy').value =
        (currEndYY == null)?"":currEndYY;
}

function eventsSubmitForm() {
    var startDD = parseInt(document.getElementById('eventForm-startdd').value);
    var startmm = parseInt(document.getElementById('eventForm-startmm').value);
    var startYY = parseInt(document.getElementById('eventForm-startyy').value);
    var startHH = parseInt(document.getElementById('eventForm-starthh').value);
    var startMM = parseInt(document.getElementById('eventForm-startMM').value);
    var endDD = parseInt(document.getElementById('eventForm-enddd').value);
    var endmm = parseInt(document.getElementById('eventForm-endmm').value);
    var endYY = parseInt(document.getElementById('eventForm-endyy').value);
    var endHH = parseInt(document.getElementById('eventForm-endhh').value);
    var endMM = parseInt(document.getElementById('eventForm-endMM').value);
    if ((startDD == endDD && startmm == endmm && startYY == endYY) &&
        ((startHH == endHH && startMM > endMM) || startHH > endHH)) {
          popError('errorMessageAjax');
          document.getElementById('errorMessageAjax').innerHTML =
            _EVENTS_ERRORS[2];
    } else if (document.getElementById('eventForm-startdd').value == "") {
          popError('errorMessageAjax');
          document.getElementById('errorMessageAjax').innerHTML =
            _EVENTS_ERRORS[0];
    } else if (document.getElementById('eventForm-title').value == ""
        || document.getElementById('eventForm-location').value == "") {
          popError('errorMessageAjax');
          document.getElementById('errorMessageAjax').innerHTML =
            _EVENTS_ERRORS[1];
    } else {
        document.getElementById('addEventForm').submit();
    }
}

function eventsModifyEvent(id) {
    openWindow('eventsManager');
    document.getElementById('eventForm-eventId').value=id;
    var startDD = document.getElementById('mod-eventForm-startdd').innerHTML;
    var startmm = document.getElementById('mod-eventForm-startmm').innerHTML;
    var startYY = document.getElementById('mod-eventForm-startyy').innerHTML;
    var startHH = document.getElementById('mod-eventForm-starthh').innerHTML;
    var startMM = document.getElementById('mod-eventForm-startMM').innerHTML;
    var endDD = document.getElementById('mod-eventForm-enddd').innerHTML;
    var endmm = document.getElementById('mod-eventForm-endmm').innerHTML;
    var endYY = document.getElementById('mod-eventForm-endyy').innerHTML;
    var endHH = document.getElementById('mod-eventForm-endhh').innerHTML;
    var endMM = document.getElementById('mod-eventForm-endMM').innerHTML;
    document.getElementById('eventForm-startdd').value=startDD;
    document.getElementById('eventForm-startmm').value=startmm;
    document.getElementById('eventForm-startyy').value=startYY;
    document.getElementById('eventForm-starthh').selectedIndex=startHH;
    var indexStartMM = 0;
    switch (parseInt(startMM)) {
        case 15:
            indexStartMM = 1;
            break;
        case 30:
            indexStartMM = 2;
            break;
        case 45:
            indexStartMM = 3;
            break;
        default:
            break;
    }
    document.getElementById('eventForm-startMM').selectedIndex=indexStartMM;
    eventsSelectDate(startDD, startmm, startYY);
    firstSelected = true;
    firstSelectedDate[0] = startDD;
    firstSelectedDate[1] = startmm;
    firstSelectedDate[2] = startYY;
    if (startDD != endDD || startmm != endmm || startYY != endYY) {
        document.getElementById('eventForm-enddd').value=endDD;
        document.getElementById('eventForm-endmm').value=endmm;
        document.getElementById('eventForm-endyy').value=endYY;
        document.getElementById('eventForm-endhh').selectedIndex=endHH;
        var indexEndMM = 0;
        switch (parseInt(endMM)) {
            case 15:
                indexEndMM = 1;
                break;
            case 30:
                indexEndMM = 2;
                break;
            case 45:
                indexEndMM = 3;
                break;
            default:
                break;
        }
        document.getElementById('eventForm-endMM').selectedIndex=indexEndMM;
        eventsSelectDate(endDD, endmm, endYY);
        secondSelected = true;
        secondSelectedDate[0] = endDD;
        secondSelectedDate[1] = endmm;
        secondSelectedDate[2] = endYY;
    }
    document.getElementById('eventForm-title').value=
        document.getElementById('mod-eventForm-title').innerHTML;
    document.getElementById('eventForm-host').value=
        document.getElementById('mod-eventForm-host').innerHTML;
    document.getElementById('eventForm-location').value=
        document.getElementById('mod-eventForm-location').innerHTML;
    tinyMCE.get('eventForm-description').setContent(
        document.getElementById('mod-eventForm-description').innerHTML);
    eventsFetchMonth(startmm,startYY,_EVENTS_CURRENT_MM,_EVENTS_CURRENT_YY,true);
}

function eventsDeleteEvent(id) {
    openWindow('deleteEvent',true);
    document.getElementById('eventId-deleteEvent').value=id;
}

/* Function which highlights or un-highlights a given menu item. */
function highlightMenu(menuItem, id, on) {
    if (on) {
        if (!openedMenus[id]) {
            menuItem.className = 'topMenuItem';
        }
    } else {
        menuItem.className = 'topMenuItem topMenuItemH';
    }
}

function lockPageWindow(id) {
    document.getElementById('restrictPageInput').value = "true";
    document.getElementById('restrictPageIdInput').value = id;
    openWindow('lockPage',true);
}

function makeFloatPageWindow(id) {
    document.getElementById('floatPageIdInput').value = id;
    openWindow('makeFloatPage',true);
}

function unlockPageWindow(id) {
    document.getElementById('restrictPageInput').value = "false";
    document.getElementById('restrictPageIdInput').value = id;
    openWindow('unlockPage',true);
}

/* Returns the mouse offset coordinates (x,y) based on a given target 
   and event. */
function getMouseOffset(target, ev){
    ev = ev || window.event;
    
    var docPos    = getPosition(target);
    var mousePos  = mouseCoords(ev);
    return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

/* Returns the position (x:left, y:top) of the given element e. */
function getPosition(e){
    var left = 0;
    var top  = 0;
    
    while (e.offsetParent){
        left += e.offsetLeft;
        top  += e.offsetTop;
        e     = e.offsetParent;
    }
    
    left += e.offsetLeft;
    top  += e.offsetTop;
    
    return {x:left, y:top};
}

/* Returns the x,y coordinates of the scrolling in the page's view pane. */
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft 
      || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft 
      || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

/* Returns the size (width, height) of the browser's view pane. */
function getViewPaneSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth 
      || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth 
      || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [ myWidth, myHeight ];
}

function imageManagerSize(select) {
    var div = document.getElementById('imageManagerContainer');
    var val = document.getElementById('imageManagerCurrentSize');
    var newVal = select.options[select.selectedIndex].value;
    div.innerHTML = (""+div.innerHTML).split("-"+val.innerHTML).join("-"+newVal);
    val.innerHTML = newVal;
}

/* Function which makes a given item draggable. There is also an additional
   optional parameter that allows to set a clickable source to drag the
   original item. This can be useful if you don't want the entire item to
   be clickable, but rather have a selected region clickable while still 
   being able to drag the entire item. */
function makeDraggable(item, dragSource){  
    if(!item) {
        return;
    }
    if (dragSource) {
        dragSource.onmousedown = function(ev){
            setFocus(item);
            dragObject  = item;
            mouseOffset = getMouseOffset(this, ev);
            return false;
        }
    } else {
        item.onmousedown = function(ev){
            setFocus(this);
            dragObject  = this;
            mouseOffset = getMouseOffset(this, ev);
            return false;
        }
    }
}

/* Opens the make home page window and sets a hidden value. */
function makeHomeWindow(id) {
    openWindow('makeMainPage', true);
    document.getElementById('makeMainPageId').value = id;
}

var currentMediaDir = null;
function mediaMngrAddDirectoryOpen(dir) {
    currentMediaDir = dir;
    document.getElementById('addMediaDirectoryInput').value = "";
    openWindow('mediaListAddDirectory',true);
}

function mediaMngrAddDirectory() {
    var dir = document.getElementById('addMediaDirectoryInput').value;
    dir = currentMediaDir + "/" + dir;
    ajax(actionPath + "addMediaDirectory?dir="+dir, mediaMngrRefreshAdd);
}

function mediaMngrRefreshAdd() {
    var iframe = document.getElementById('mediaListingIframe');
    iframe.src = "mediaListingManager?directory="
        +currentMediaDir+"&noCache=" + Math.random();
    currentMediaDir = null;
    closeWindow('mediaListAddDirectory');
}

var parentMediaDir = null;
function mediaMngrDeleteDirectoryOpen(dir, parentDir) {
    currentMediaDir = dir;
    parentMediaDir = parentDir;
    openWindow('mediaListDeleteDirectory',true);
}

function mediaMngrDeleteDirectory() {
    ajax(actionPath + "deleteMediaDirectory?dir="+currentMediaDir, 
          mediaMngrRefreshDelete);
}

function mediaMngrRefreshDelete() {
    var iframe = document.getElementById('mediaListingIframe');
    iframe.src = iframe.src+"?dir="+parentMediaDir+"&noCache=" + Math.random();
    currentMediaDir = null;
    parentMediaDir = null;
    closeWindow('mediaListDeleteDirectory');
}

function mediaMngrUpload(dir) {
    document.getElementById('mediaManagerUploadFile').src = 'mediaManagerUploadFile?dir='+dir;
    openWindow('uploadFile', true);
}

function modifyCSS(localId, type, css) {
    document.getElementById('modCSS-div').style.display = "block";
    document.getElementById('modCSS-localId').value = localId;
    document.getElementById('modCSS-type').value = type;
    document.getElementById('modCSS-style').value = css;
}

/* Sets the hidden values to modify a label based on the given parameters and
   opens the window to prompt the editing of the label. */
function modifyLabel(key, domElement, maxlength) {
    document.getElementById('currentLabelKeyInput').value = key;
    var input = document.getElementById('currentLabelValueInput');
    input.value = domElement.innerHTML;
    input.maxLength = maxlength;
    currentEditDom = domElement;
    openWindow('addSiteLabel');
}

/* Returns the coordinations (x,y) of the mouse based on a given event. */
function mouseCoords(ev){
    if(ev.pageX || ev.pageY){
        return {x:ev.pageX, y:ev.pageY};
    }
    try {
      return {
          x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
          y:ev.clientY + document.body.scrollTop  - document.body.clientTop
      };
    }catch (exception) { 
        
    }
}

/* Function that is binded to the document's mouse move event, in the case 
   that there is an element being dragged, then it will follow the mouse. */
function mouseMove(ev){
    ev = ev || window.event;
    var mousePos = mouseCoords(ev);
    mouseCoordsXY = mousePos;
    if(dragObject){      
        dragObject.style.position = 'absolute';
        dragObject.style.top      = mousePos.y - mouseOffset.y + "px";
        dragObject.style.left     = mousePos.x - mouseOffset.x + "px";
        return false;
    }
}

/* Event which indicates the mouse button has been released, we therefore
   "release" the object being dragged by setting the reference to it to null.*/
function mouseUp(){
    dragObject = null;
}

function mailinglistSubmit() {
    var email = document.getElementById('mailinglist-email').value;
    if (email == "" || email.indexOf('@') == -1 
        || email.indexOf('.') == -1 || email.length < 7) {
        //do nothing invalid email
    } else {
      var code = document.getElementById('mailinglist-code').value;
      ajax(actionPath + "newsletter?email="+email+"&code="+code, 
          onmailinglistSubmitResponse);
    }
}

function onmailinglistSubmitResponse() {
    addCookie("mailinglist", "true");
    document.getElementById('mailinglist-form').style.display="none";
    document.getElementById('mailinglist-thankyou').style.display="block";
}

/* Opens a window based on its given id. The blackout is a boolean optional
   parameter which will put a black out behind the window if set to true. */
function openWindow(id, blackout, blackoutcloseable) {
    if (disableApp && id != 'errorMsg' && id != 'siteErrorMsg') {
        popErrorSite('errorMessageDivIE6');
        return;
    }
    if (blackout) {
      openedWindows[id] = "blackout";
      var blackoutDiv = document.getElementById('blackout');
      blackoutDiv.style.display = "block";
      setFocus(blackoutDiv);
      if (blackoutcloseable) {
          blackoutDiv.onlick = function() {closeWindow(id);}
      }
    } else {
      openedWindows[id] = id;
    }
    closeAllMenu();
    var tbar = document.getElementById(id+'_titlebar');
    if (tbar) {
        //We have a draggable window, make it so!
        makeDraggable(document.getElementById(id), tbar);
    }
    var elem = document.getElementById(id);
    elem.style.display = "block";
    setFocus(elem);
    centerElement(id);
}

/* This function pops up the window to select a component and filters the
   choices by only displaying those in the given allowed list. This method
   will also "select" the first component in the allowed list to provide
   the user with a default value and prevent errors for empty value submits. */
function popComponentSelect(id, allowed, name) {
    var allowedList = allowed.split(",");
    var selectDiv = document.getElementById('componentPreviews-select');
    document.getElementById('nameSelectComponent').value = allowedList[0];
    document.getElementById('compPreview_'+
        allowedList[0]+"_firstChild").style.borderColor = "red";
    selectDiv.innerHTML = "";
    for (var i in allowedList) {
        if (i != 0) {
          document.getElementById('compPreview_'+
              allowedList[i]+"_firstChild").style.borderColor = "white";
        }
        var n = allowedList[i];
        selectDiv.innerHTML = selectDiv.innerHTML 
            + document.getElementById('compPreview_'+n).innerHTML;
    }
    document.getElementById('componentIdInput').value = id;
    document.getElementById('componentNameInput').value = name;
    openWindow('componentSelect', true);
}

/* Opens the delete component window and sets a hidden value. */
function popDeleteComponent(id, name) {
    openWindow('deleteComponent', true);
    document.getElementById('componentIdDeleteInput').value = id;
    document.getElementById('componentNameDeleteInput').value = name;
}

/* Function which pops the error window and sets the proper error message
   to be displayed based on the given id. */
function popError(errorDivId) {
    openWindow('errorMsg');
    document.getElementById('errorMessageDivOriginal').style.display = "none";
    document.getElementById('errorMessageDivEmptyForm').style.display  ="none";
    document.getElementById('errorMessageDivInvalidSwap').style.display="none";
    document.getElementById('errorMessageDivNoSelGroup').style.display="none";
    document.getElementById('errorMessageAjax').style.display = "none";
    document.getElementById(errorDivId).style.display = "block";
}

function popErrorSite(errorDivId) {
    openWindow('siteErrorMsg',true);
    document.getElementById('errorMessageSite').style.display = "none";
    document.getElementById('errorMessageDivSearchTooShort').style.display  ="none";
    document.getElementById('errorMessageDivIE6').style.display="none";
    document.getElementById('errorMessageEmptyFields').style.display="none";
    document.getElementById('errorMessageInvalidEmail').style.display = "none";
    document.getElementById('errorMessageAjaxSite').style.display = "none";
    document.getElementById(errorDivId).style.display = "block";
}

/* Pops the based on a given id. The parent is a reference to the main menu
   item which is calling this function. Both parameters are necessary. */
function popMenu(parent, id) {
    var menu = document.getElementById(id);
    if (openedMenus[id]) {
        openedMenus[id] = false;
        menu.style.display = "none";
    } else {
        openedMenus[id] = true;
        menu.style.display = "block";
        menu.style.left = parent.offsetLeft + 'px';
    }
    for (var i in openedMenus) {
        if (i != id) {
        openedMenus[i] = false;
        var openedMenu = document.getElementById(i);
        openedMenu.style.display="none";
        document.getElementById('parent_'+i).className = 
            'topMenuItem';
        }
    }
}

/* Makes the ajax call to remove a user from the selected group. */
function removeUserGroup() {
    ajax(actionPath + "removeGroupUser?userId="+swapUpId+"&groupId="
        +selectedGroup, accessCompleteSwapUp);
}

function sendContactFormEmail(validate, count) {
    var subject = document.getElementById('contactForm-subject').value;
    var email = document.getElementById('contactForm-email').value;
    var content = null;
    try {
        content = tinyMCE.get('contactForm-content').getContent();
    } catch (exception) { 
        content = document.getElementById('contactForm-content').value;
    }

    var appendField="";
    if(document.getElementById('fieldName1')!=null) {
        var total = 9;
        if (count) {
            total = count;
        }
        for (var i = 1; i < total; i++) {
            appendField+="&fieldName"+i+"="+
                encodeURIComponent(document.getElementById('fieldName'+i).value);
            if(document.getElementById('field'+i).type == "checkbox") {
                if (document.getElementById('field'+i).checked) {
                    appendField+="&field"+i+"=checked.";
                } else {
                    appendField+="&field"+i+"=not checked.";
                }
            } else {
              appendField+="&field"+i+"="+
                  encodeURIComponent(document.getElementById('field'+i).value);
            }
        }
        appendField+="&count="+total;
    }
    var form = document.getElementById('contactForm-Container');
    var inputs = form.getElementsByTagName("input");
    var validForm = true;
    for (i in inputs) {
        if (inputs[i].type=="text" && inputs[i].value=="") {
            validForm = false;
            break;
        }
    }
    if (!validForm && validate) {
        popError('errorMessageDivEmptyForm');
    } else {
        ajax(actionPath + "contactUs?subject="+encodeURIComponent(subject)
            +"&email="+encodeURIComponent(email)
            +"&content="+encodeURIComponent(content)
            +appendField, sendContactFormEmailConfirm);
    }
}

function sendContactFormEmailProdentia() {
    var subject = document.getElementById('contactForm-subject').value;
    var email = document.getElementById('contactForm-email').value;
    var content = tinyMCE.get('contactForm-content').getContent();
    var appendField="";
    if(document.getElementById('fieldName1')!=null) {
        for (var i = 1; i < 9; i++) {
            appendField+="&fieldName"+i+"="
                +encodeURIComponent(document.getElementById('fieldName'+i).value);
            if(document.getElementById('field'+i).type == "checkbox") {
                if (document.getElementById('field'+i).checked) {
                    appendField+="&field"+i+"=checked.";
                } else {
                    appendField+="&field"+i+"=not checked.";
                }
            } else {
              appendField+="&field"+i+"="
                  +encodeURIComponent(document.getElementById('field'+i).value);
            }
        }
    }
    var form = document.getElementById('prodentiaContactForm');
    var inputs = form.getElementsByTagName("input");
    var validForm = true;
    for (i in inputs) {
        if (inputs[i].type=="text" && inputs[i].value=="") {
            validForm = false;
            break;
        }
    }
    if (!validForm) {
        popError('errorMessageDivEmptyForm');
    } else {
        ajax(actionPath + "contactUs?subject="+encodeURIComponent(subject)
            +"&email="+encodeURIComponent(email)
            +"&content="+encodeURIComponent(content)
            +appendField, sendContactFormEmailConfirm);
    }
}

function sendContactFormEmailConfirm() {
    document.getElementById('contactForm-Container').style.display = "none";
    document.getElementById('contactForm-sent').style.display = "block";
}

function selectComponent(type) {
    var nodes = document.getElementById('componentPreviews-select').childNodes;
    for (var i in nodes) {
        var node = nodes[i];
        if (node.nodeType == 1) {
          node.style.borderColor = "white";
        }
    }
    document.getElementById('nameSelectComponent').value = type;
    document.getElementById('compPreview_'+
        type+"_firstChild").style.borderColor = "red";
}

/* Simulates the selection of a previously uploaded media by surrounding it
   with a border of appropriate color (and de-selecting the previous one).
   This function also, of course, stores the the selection in a hidden input. */
function selectImageUpload(img, id) {
    if ((img.style.borderColor + "").indexOf("black") != -1) {
        if (selectedImageUpl) {
            selectedImageUpl.style.border = "2px solid black";
        }
        img.style.border = "2px solid red";
        selectedImageUpl = img;
        document.getElementById('mediaIdUploadForm').value = id;
        document.getElementById('uploadType2').checked = true;
    } else {
        img.style.border = "2px solid black";
        selectedImageUpl = null;
        document.getElementById('mediaIdUploadForm').value = "unselected";
    }
}

/* Selects the template and sets the hidden input to the proper value as well
   as updates the images on screen. */
function selectTemplate(name, source) {
    var input = document.getElementById('templateSelectInput_'+source);
    var oldImg = document.getElementById(
        'templateImg_' + source + '_' + input.value);
    var newImg = document.getElementById('templateImg_' + source + '_' + name);
    oldImg.src = oldImg.src.split("_sel").join("");
    newImg.src = newImg.src.split(".jpg").join("_sel.jpg");
    input.value = name;
}

/* This function brings the given DOM Object visual priority over all other
   Objects in the page. */
function setFocus(selectedWindow) {
    zIndex = zIndex + 1;
    selectedWindow.style.zIndex = zIndex;
}

/* This function submits the form associated with the given id. If there are
   inputs of type text that are empty, this function will call the error
   window to be popped up to advise the user to fill all the inputs. */
function submitForm(id) {
    var form = document.getElementById(id);
    var inputs = form.getElementsByTagName("input");
    var validForm = true;
    for (i in inputs) {
        if (inputs[i].type=="text" && inputs[i].value=="") {
            validForm = false;
            break;
        }
    }
    if (!validForm) {
        popError('errorMessageDivEmptyForm');
    } else {
        form.submit();
    }
}

/* Ajax callback when a label has been modified on the back-end, make sure to
   update the proper dom element. */
function submitLabelModified(text) {
    currentEditDom.innerHTML = text;
    currentEditDom = null;
    closeWindow('addSiteLabel');
}

/* Makes the Ajax call to save the label being modified. */
function submitModifyLabel() {
    ajax(actionPath + "addSiteLabel?key="+
        document.getElementById('currentLabelKeyInput').value+"&value="+
        encodeURIComponent(
            document.getElementById('currentLabelValueInput').value), 
            submitLabelModified);
}

/* Submits the form for the current text being edited. */
function submitText() {
    document.getElementById('formSaveText'+currentTextId).submit();
}

/* Swaps the language in the url and loads the new url. This function requires
   that both the previous and new language be given as parameters or nothing
   will happen. */
function swapLang(oldlang, newlang) {
    addCookie("foxone.lang", newlang);
    var loc = ""+window.location;
    if (oldlang && newlang) {
        window.location = loc.split("/"+oldlang+"/").join("/"+newlang+"/");
    }
}

var componentSwapFirstDiv = null;
var componentSwapSecondDiv = null;
var componentSwapPos = null;
var componentSwapNextPos = null;

function swapComponents(name, id, up, pageId, max) {
    var index = id.indexOf('Component')+9;
    componentSwapPos = id.substring(index);
    componentSwapNextPos = 
        (up ? parseInt(componentSwapPos) - 1 : parseInt(componentSwapPos) + 1);
    var firstId = 'componentDiv_'+name+'-Component'+componentSwapPos;
    var secondId = 'componentDiv_'+name+'-Component'+(componentSwapNextPos);
    if ((componentSwapPos == 1 && up) || (componentSwapPos == max && !up)) {
        componentSwapPos = null;
        componentSwapNextPos = null;
        return;
    }
    try {
      componentSwapFirstDiv = document.getElementById(firstId);
      componentSwapSecondDiv = document.getElementById(secondId);
      componentMouseOver(id,true,false);
      componentMouseOver(id.split('Component'+componentSwapPos)
          .join('Component'+componentSwapNextPos),true,false);
      ajax(actionPath+"swapComponent?pageId="+pageId+"&componentId="+id+"&name="
          +name+"&up="+up, swapComponentSuccess());
    } catch (exception) { 
      //Trying to move beyond the scope.
    }
}

function swapComponentSuccess() {
    var temp = componentSwapFirstDiv.innerHTML
    .split('Component'+componentSwapPos).join('Component'+componentSwapNextPos);
    componentSwapFirstDiv.innerHTML = componentSwapSecondDiv.innerHTML
    .split('Component'+componentSwapNextPos).join('Component'+componentSwapPos);
    componentSwapSecondDiv.innerHTML = temp;
    componentSwapFirstDiv = null;
    componentSwapSecondDiv = null;
    componentSwapPos = null;
    componentSwapNextPos = null;
}

/* Alows the swapping of two elements in the tree view window. */
function swapTreeElement(id) {
    var div = document.getElementById(id);
    var img = document.getElementById('img_'+id);
    if (id.indexOf('page') != -1) {
        var pageId = id.substring(13);
        if (swapPage) {
            if (swapPage == pageId) {
                swapPage = null;
                div.style.backgroundColor = swapOldBgColor;
                img.src = img.src.split("_on").join("_off");
            } else {
                openWindow('swapPage', true);
                document.getElementById('swapFirstPageId').value = swapPage;
                document.getElementById('swapSecondPageId').value = pageId;
            }
        } else if (swapSection) {
            popError('errorMessageDivInvalidSwap');
        } else {
            swapOldBgColor = div.style.backgroundColor;
            div.style.backgroundColor = '#6FB7F2';
            img.src = img.src.split("_off").join("_on");
            swapPage = pageId;
        }
    } else {
        var sectionId = id.substring(16);
        if (swapSection) {
            if (swapSection == sectionId) {
                swapSection = null;
                div.style.backgroundColor = swapOldBgColor;
                img.src = img.src.split("_on").join("_off");
            } else {
                openWindow('swapSection', true);
                document.getElementById('swapFirstSectionId').value=swapSection;
                document.getElementById('swapSecondSectionId').value=sectionId;
            }
        } else if (swapPage) {
            openWindow('movePage', true);
            document.getElementById('movePageId').value = swapPage;
            document.getElementById('moveSectionId').value = sectionId;
        } else {
            swapOldBgColor = div.style.backgroundColor;
            img.src = img.src.split("_off").join("_on");
            div.style.backgroundColor = '#6FB7F2';
            swapSection = sectionId;
        }
    }
}

/* This method pops the window to edit a text based on the given parameters.
   This method also sets a few hidden inputs for the form. */
function textWindow(id, localId, componentId) {
    if (currentTextId != null) {
        closeTextWindow();
    }
    currentTextId = id;
    document.getElementById('textFormLocalId'+id).value = localId;
    document.getElementById('textFormComponentId'+id).value = componentId;
    var form = document.getElementById('formSaveText'+id);
    if (id != '') {
        document.getElementById('textFormTextId'+id).value = id;
        form.action = actionPath + "updateText";
    } else {
        form.action = actionPath + "createText";
    }
    openWindow('textWindow'+id);
}

/* This method sets the url for the iframe of the upload image form based
   on the given parameters then opens the image uploading/editing window. */
function uploadImage(id, localId, componentId, 
    directory, pageId, rule, width, height) {
    var iframe = document.getElementById('uploadImageIframe');
    var source = "crop?content&";
    if (id != '') {
        source += "mediaId="+id+"&";
    }
    source += "localId=" + localId;
    source += "&componentId=" + componentId;
    source += "&directory=" + directory;
    source += "&pageId=" + pageId;
    source += "&rule=" + rule;
    source += "&ruleWidth=" + width;
    source += "&ruleHeight=" + height;
    source += "&noCache=" + Math.random();
    iframe.src = source;
    openWindow('imageWindow', true);
}

/* This method checks to make sure that there are at least three characters
   in the search query.*/
function validateSearch(form, input) {
    if (document.getElementById(input).value.length < 3) {
        popErrorSite('errorMessageDivSearchTooShort');
    } else {
        document.getElementById(form).submit();
    }
}

function versionCheck() {
    var v = (""+navigator.appVersion).indexOf('MSIE 6');
    if (v > -1) {
        try {
            document.getElementById('topMenuBar').style.display="none";
        } catch (exception) { 
        }
        disableApp = true;
        popErrorSite('errorMessageDivIE6');
    }
}

function submitComplexForm(id, cnt) {
    var form = document.getElementById(id);
    var errors = false;
    for (var i = 1; i < (cnt+1); i++) {
        try {
            var currField = document.getElementById('field'+i);
            var fieldName = 'fieldName'+i;
            if (document.getElementById(fieldName).value.indexOf("*") != -1) {
                if (currField.value == "") {
                    errors = true;
                    currField.className = 'formBorderWrong';
                } else {
                    currField.className = '';
                }
            } else {
                currField.className = '';
            }
            if (currField.value.indexOf("checkbox-") != -1 && !errors) {
                var localCnt = parseInt(currField.value.substring(9));
                currField.value = "";
                for (var j = 1; j < localCnt; j++) {
                    var f = document.getElementById('f'+i+'-'+j);
                    if (f.checked) {
                        if (currField.value != "") {
                            currField.value += ",";
                        }
                        currField.value += f.value;
                    }
                }
            }
        } catch (e) { }
    }

    if (errors) {
        popErrorSite('errorMessageEmptyFields');
    } else {
        form.submit();
    }
}

var currentSourceDirForFileMove = null;
var currentSourceFileForFileMove = null;
function moveFile(filename, srcDir) {
    currentSourceDirForFileMove = srcDir;
    currentSourceFileForFileMove = filename;
    openWindow('moveFile', true);
}

function doMoveFile(target) {
    var tarDir = document.getElementById(target).innerHTML;
    window.location = actionPath + "moveFile?currentDir="
        //+encodeURIComponent(currentSourceDirForFileMove)
        + "&filename="
        +encodeURIComponent(currentSourceFileForFileMove) + "&targetDirectory="
        +tarDir;
}

function toggleBannerForm(sel) {
    document.getElementById('bannerForm-upload').style.display='none';
    document.getElementById('bannerForm-imageurl').style.display='none';
    document.getElementById('bannerForm-flashurl').style.display='none';
    document.getElementById('bannerForm-html').style.display='none';
    document.getElementById('bannerForm-design').style.display='none';
    document.getElementById('bannerForm-'
        +sel.options[sel.selectedIndex].value).style.display='block';
}

function addBannerForm(zoneId) {
    document.getElementById('bannerAddModForm').reset();
    document.getElementById('bannerForm').style.display='block';
    document.getElementById('bannerIdMod').value='';
    document.getElementById('zoneIdMod').value=zoneId;
}

function cancelBannerForm() {
    document.getElementById('bannerAddModForm').reset();
    document.getElementById('bannerForm-upload').style.display='block';
    document.getElementById('bannerForm-imageurl').style.display='none';
    document.getElementById('bannerForm-flashurl').style.display='none';
    document.getElementById('bannerForm-html').style.display='none';
    document.getElementById('bannerForm-design').style.display='none';
    document.getElementById('bannerForm').style.display='none';
}

function deleteBannerConfirm(id) {
    document.getElementById('deleteBannerBannerId').value = id;
    openWindow('deleteBanner', true);
}

var subscribeIdsTemp = new Array();
function updateSubscribe(id, checkbox) {
    if (checkbox.checked) {
        subscribeIdsTemp[id] = true;
    } else {
        subscribeIdsTemp[id] = false;
    }
}

function subscribeToBlog() {
    var email = document.getElementById('subscribeEmail');
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(email.value)) {
        popErrorSite('errorMessageInvalidEmail');
    } else {
        ajax(actionPath + "subscribeBlog?email="+encodeURIComponent(email.value), subscribeToBlogComplete);
    }
}

function subscribeToBlogComplete() {
    addCookie('mailinglist','true');
    document.getElementById('newsletterFormFields').style.display="none";
    document.getElementById('newsletterConfirm').style.display="block";
}

function refreshPage(name) {
    window.location=name+'?ok'+Math.random();
}

var tlMenuIdStored = 0;
var tlPageIdStored = 0;
var tlPageNameStored = null;
var currentExtraDiv = 1;
var tlItemCount = 0;
var tlCurrentPosition = 0;
var tlMoveUpTag = "right";
var tlMoveDownTag = "left";

function tlAddMenuWindow(menuId,count,moveUp,moveDown) {
    document.getElementById('tlAddMenuIdDiv').innerHTML = menuId;
    if (tlItemCount == 0) {
        tlItemCount=count;
        tlMoveUpTag=moveUp;
        tlMoveDownTag=moveDown;
    }
    openWindow('tlAddMenu', true);
}

function tlAddMenu() {
    var select = document.getElementById('tlAddMenuSelect');
    var pageId = select.options[select.selectedIndex].value;
    var menuId = document.getElementById('tlAddMenuIdDiv').innerHTML;
    tlMenuIdStored = menuId;
    tlPageIdStored = pageId;
    tlPageNameStored = select.options[select.selectedIndex].text;
    ajax(actionPath + "tlAddMenu?pageId="+pageId+
        "&menuId="+menuId, tlAddMenuComplete);
    closeWindow('tlAddMenu');
}

function tlAddMenuComplete() {
    var div = document.getElementById('tlExtraDiv'+currentExtraDiv);
    currentExtraDiv = parseInt(currentExtraDiv) + 1;
    tlItemCount = parseInt(tlItemCount) + 1;
    div.id = "tlMenuItem"+tlItemCount;
    div.className = "extMenuItem";
    div.style.display="block";
    div.innerHTML = '<div class="extMenuLeft"></div><div class="extMenuCenter">'+tlPageNameStored+'</div><div class="extMenuRight"></div><div style="clear: both;"/><div class="extMenuOptions"><div class="extMenuOption"><a href="/action/tlChangeOrderMenu?menuId='+tlMenuIdStored+'&pageId='+tlPageIdStored+'&move=down" style="text-decoration: none;"><img src="/shared/img/tl/tl_'+tlMoveDownTag+'_arrow.png" alt="" style="border:0;"/></a></div><div class="extMenuOption"><a href="/action/tlChangeOrderMenu?menuId='+tlMenuIdStored+'&pageId='+tlPageIdStored+'&move=up" style="text-decoration: none;"><img src="/shared/img/tl/tl_'+tlMoveUpTag+'_arrow.png" alt="" style="border:0;"/></a></div><div class="extMenuOption"><a href="javascript:tlDeleteMenuWindow(\''+tlMenuIdStored+'\',\''+tlPageIdStored+'\',\''+tlItemCount+'\');" style="text-decoration: none;"><img src="/shared/img/tl/tl_delete.png" alt="" style="border:0;"/></a></div><div style="clear: both;"/></div>';
    if(currentExtraDiv>8) {
        window.location=window.location+'?rf'+Math.random();
    }
}

function tlDeleteMenuWindow(menuId,pageId,position) {
    tlCurrentPosition = position;
    document.getElementById('tlDeleteMenuIdDiv').innerHTML = menuId;
    document.getElementById('tlDeletePageIdDiv').innerHTML = pageId;
    openWindow('tlDeleteMenu', true);
}

function tlDeleteMenu() {
    var menuId = document.getElementById('tlDeleteMenuIdDiv').innerHTML;
    var pageId = document.getElementById('tlDeletePageIdDiv').innerHTML;
    ajax(actionPath + "tlDeleteMenu?pageId="+pageId+
        "&menuId="+menuId, tlDeleteMenuComplete);
    closeWindow('tlDeleteMenu');
}

function tlDeleteMenuComplete() {
    document.getElementById('tlMenuItem'+tlCurrentPosition).style.display='none';
}
function rfBlogPercentage() {
    ajax('/action/getBlogSentPerc', updateBlogPercentage, true);
}
function updateBlogPercentage(response) {
    var div = document.getElementById('blogPercBar');
    div.style.width = response + 'px';
    if ((""+response).indexOf('100') == -1) {
        window.setTimeout(rfBlogPercentage, 2500);
    }
    div.title = response + "%";
}
function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

