// extended effects leveraging scriptaculous.js

Effect.PhaseIn = function(element) {
    element = $(element);
    new Effect.BlindDown(element, arguments[1] || {});
    new Effect.Appear(element, arguments[2] || arguments[1] || {});
}

Effect.PhaseOut = function(element) {
    element = $(element);
    new Effect.Fade(element, arguments[1] || {});
    new Effect.BlindUp(element, arguments[2] || arguments[1] || {});
}

Effect.Phase = function(element) {
    element = $(element);
    if (element.style.display == 'none')
        new Effect.PhaseIn(element, arguments[1] || {}, arguments[2] || arguments[1] || {});
    else new Effect.PhaseOut(element, arguments[1] || {}, arguments[2] || arguments[1] || {});
}


Effect.Center = function(element) {
    try
    {
        element = $(element);
    }
    catch(e)
    {
        return;
    }

    var my_width = 0;
    var my_height = 0;

    if (typeof( window.innerWidth ) == 'number')
    {

        my_width = window.innerWidth;
        my_height = window.innerHeight;
    }
    else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ))
    {

        my_width = document.documentElement.clientWidth;
        my_height = document.documentElement.clientHeight;
    }
    else if (document.body && ( document.body.clientWidth || document.body.clientHeight ))
    {

        my_width = document.body.clientWidth;
        my_height = document.body.clientHeight;
    }


    element.style.zIndex = 99;

    var scrollY = 0;

    if (document.documentElement && document.documentElement.scrollTop)
    {
        scrollY = document.documentElement.scrollTop;
    }
    else if (document.body && document.body.scrollTop)
    {
        scrollY = document.body.scrollTop;
    }
    else if (window.pageYOffset)
    {
        scrollY = window.pageYOffset;
    }
    else if (window.scrollY)
    {
        scrollY = window.scrollY;
    }

    var elementDimensions = Element.getDimensions(element);

    var setX = ( my_width - elementDimensions.width  ) / 2;
    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

    setX = ( setX < 0 ) ? 0 : setX;
    setY = ( setY < 0 ) ? 0 : setY;

    element.style.left = setX + "px";
    element.style.top = setY + "px";

}


// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize() {

    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;
    if (self.innerHeight) {    // all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth) {
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }


    return new Array(pageWidth, pageHeight, windowWidth, windowHeight)
}


function setShimSize() {
    var arrayPageSize = getPageSize();
    document.getElementById('shim').style.height = "1500px";
    document.getElementById('shim').style.width = (arrayPageSize[0] + 'px');
}


// toggle or set layer display
function toggleDisp(theLayer, dispType) {
    if (!dispType) dispType = "block"

    if (document.getElementById(theLayer).style.display == dispType || document.getElementById(theLayer).style.display == "") setDisp(theLayer, 'none');
    else setDisp(theLayer, dispType);
}
function setDisp(theLayer, dispType) {
    document.getElementById(theLayer).style.display = dispType
}

function togglePopup(theLayer) {
    if (document.getElementById(theLayer).style.display == "block" || document.getElementById(theLayer).style.display == "") {
        new Effect.PhaseOut($(theLayer), { duration: .3});
        setDisp('shim', 'none');
    }
    else {
        setShimSize();
        new Effect.Appear($('shim'), { duration: .1, from: 0, to: .5});
        new Effect.Center($(theLayer));
        new Effect.Appear($(theLayer), { duration: .3});
    }
}

//SHOW/HIDE LAYER FUNCTION
function toggleVis(theLayer) {
    if (document.getElementById(theLayer).style.visibility == "visible") {
        document.getElementById(theLayer).style.visibility = "hidden";

    }
    else {
        document.getElementById(theLayer).style.visibility = "visible";
    }
}


// ALLOW "TIP" TEXT IN TEXT ENTRY BOXES

function clickclear(thisfield, defaulttext) {
    if (thisfield.value == defaulttext) {
        thisfield.value = "";
    }
}

function clickrecall(thisfield, defaulttext) {
    if (thisfield.value == "") {
        thisfield.value = defaulttext;
    }
}


/***********************************************
 * Fixed ToolTip script- © Dynamic Drive (www.dynamicdrive.com)
 * This notice MUST stay intact for legal use
 * Visit http://www.dynamicdrive.com/ for full source code
 ***********************************************/
var tipwidth = 275
var vertical_offset = "0" //horizontal offset of tooltip from anchor link
var horizontal_offset = "-75px" //horizontal offset of tooltip from anchor link

/////No further editting needed

var ie4 = document.all
var ns6 = document.getElementById && !document.all
var lastX = 0
var lastY = 0

function getposOffset(what, offsettype) {
    var totaloffset = (offsettype == "left") ? what.offsetLeft : what.offsetTop;
    var parentEl = what.offsetParent;
    while (parentEl != null) {
        totaloffset = (offsettype == "left") ? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
        parentEl = parentEl.offsetParent;
    }
    return totaloffset;
}


function iecompattest() {
    return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge) {
    var edgeoffset = (whichedge == "rightedge") ? parseInt(horizontal_offset) * -1 : parseInt(vertical_offset) * -1
    if (whichedge == "rightedge") {
        var windowedge = ie4 && !window.opera ? iecompattest().scrollLeft + iecompattest().clientWidth - 15 : window.pageXOffset + window.innerWidth - 15
        dropmenuobj.contentmeasure = dropmenuobj.offsetWidth
        if (windowedge - dropmenuobj.x < dropmenuobj.contentmeasure) edgeoffset = dropmenuobj.contentmeasure
    }
    else {
        var windowedge = ie4 && !window.opera ? iecompattest().scrollTop + iecompattest().clientHeight - 15 : window.pageYOffset + window.innerHeight - 18
        dropmenuobj.contentmeasure = dropmenuobj.offsetHeight
        if (windowedge - dropmenuobj.y < dropmenuobj.contentmeasure) edgeoffset = dropmenuobj.contentmeasure + obj.offsetHeight
    }
    return edgeoffset
}


var cursorOvr = 0
var dropmenu

function showDropdown(obj, e, objID, vert, horiz) {
    cursorOvr = 1
    if (window.event) event.cancelBubble = true
    else if (e.stopPropagation) e.stopPropagation()
    vertical_offset = vert
    horizontal_offset = horiz
    dropmenuobj = document.getElementById ? document.getElementById(objID) : objID
    dropmenuobj.x = getposOffset(obj, "left") - 120
    dropmenuobj.y = getposOffset(obj, "top")
    var version = parseFloat(navigator.appVersion.split("MSIE")[1]);
    if (version == 7) {
        //IE7
        dropmenuobj.x -= 120
    }
    dropmenuobj.style.left = dropmenuobj.x - clearbrowseredge(obj, "rightedge") + "px"
    dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, "bottomedge") + obj.offsetHeight + "px"
    new Effect.Appear($(objID), {duration: .3})
}

function hideCalendar() {
    delayhideDropdown('calendar')
}

function addAction() {
    document.getElementById('calendar').attachEvent("onmouseout", hideCalendar)
}

function hideDropdown(objID) {
    clearTimeout(dropmenu)
    if (cursorOvr != 1) {
        new Effect.Fade($(objID), {duration: .3})
    }

}

function delayhideDropdown(objID) {
    cursorOvr = 0;
    dropmenu = setTimeout("hideDropdown('" + objID + "')", 800)
}

var baseURL = window.location.href.match(/https?:\/\/.*?\/.*?\//);

function doRequest(url, data, onReady) {
    var xmlhttp = false;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }

    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }

    data = data.replace(" ", "+");
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            //alert("Response " + xmlhttp.responseText);
            if (onReady == "getListComplete") Collection.getListComplete(eval(xmlhttp.responseText));
            if (onReady == "collectionAddComplete") Collection.collectionAddComplete();
            if (onReady == "openTabComplete") Collection.openTabComplete(eval(xmlhttp.responseText));
            if (onReady == "getCollectionComplete") Collection.getCollectionComplete(eval(xmlhttp.responseText));
            if (onReady == "savePathComplete") Collection.savePathComplete();
            if (onReady == "indexComplete") Collection.indexComplete();
            if (onReady == "getScannerComplete") Collection.getScannerComplete(eval(xmlhttp.responseText));
            if (onReady == "saveSettingsComplete") Collection.saveSettingsComplete();
            if (onReady == "saveScheduleComplete") Collection.saveScheduleComplete();
            if (onReady == "collectionDeleteComplete") Collection.collectionDeleteComplete();
            if (onReady == "getReportListComplete") Report.getReportListComplete(eval(xmlhttp.responseText));
            if (onReady == "getQueryComplete") Report.getQueryComplete(eval(xmlhttp.responseText));
            if (onReady == "getTopComplete") Report.getTopComplete(eval(xmlhttp.responseText));
            if (onReady == "getZeroComplete") Report.getZeroComplete(eval(xmlhttp.responseText));
            if (onReady == "changePasswordComplete") Admin.changePasswordComplete(eval(xmlhttp.responseText));
            if (onReady == "searchPagesGetListComplete") SearchPagesCollection.searchPagesGetListComplete(eval(xmlhttp.responseText));
            if (onReady == "tabbedGetListComplete") TabbedResults.tabbedGetListComplete(eval(xmlhttp.responseText));
            if (onReady == "categoryGetListComplete") CategoryResults.categoryGetListComplete(eval(xmlhttp.responseText));
            if (onReady == "getTemplatesListComplete") CreateObject.getTemplatesListComplete(eval(xmlhttp.responseText));
            if (onReady == "saveTemplateComplete") CreateObject.saveTemplateComplete(eval(xmlhttp.responseText));
            if (onReady == "saveTmpTemplateComplete") CreateObject.saveTmpTemplateComplete(eval(xmlhttp.responseText));
            if (onReady == "getLogoImagesComplete") CreateObject.getLogoImagesComplete(eval(xmlhttp.responseText));
            if (onReady == "deleteTemplateComplete") deleteTemplateComplete(eval(xmlhttp.responseText));
            if (onReady == "setTemplatesList") setTemplatesList(eval(xmlhttp.responseText));
            if (onReady == "saveOrUpdateComplete") saveOrUpdateComplete(eval(xmlhttp.responseText));
            if (onReady == "deleteAdComplete") deleteAdComplete(eval(xmlhttp.responseText));
            if (onReady == "getAdListComplete") getAdListComplete(eval(xmlhttp.responseText));
            if (onReady == "changeAdStatusComplete") changeAdStatusComplete(eval(xmlhttp.responseText));
        }
    }
    //alert("To send: " + url + " " + data);
    xmlhttp.send(data);
}

function trim(str) {
    var s = str.replace(/^(\s)*/, '');
    s = s.replace(/(\s)*$/, '');
    return s;
}

function getTimeString(date, hours, minutes, secs, convert) {
    if (date == '') return '';
    if (hours < 12 && convert == 'pm') {
        hours = Number(hours) + 12;
    }
    return date + ' ' + hours + ':' + minutes + ':' + secs;
}

function makeTime(timeString) {
    var pattern = /^(\d+\-\d+\-\d+)\s+(\d+)\:(\d+)\:(\d+)$/
    if (pattern.exec(timeString)) {
        var hours = RegExp.$2;
        var min = RegExp.$3;
        var convert = 'am';

        if (hours > 12) {
            hours = Number(hours) - 12;
            convert = 'pm';
        }
        if (hours == 12) convert = 'pm';
        if (hours == 0) hours = 12;
        return new Array(RegExp.$1, hours, min, RegExp.$4, convert);
    }
    return new Array('', '', '', '', '');
}

function validateDate(dateString) {
    var re_date = /^(\d+)\-(\d+)\-(\d+)$/;
    return (re_date.exec(dateString) || trim(dateString) == '');
}

function showHelp(helpType) {
    var header = '', overview = '', body = '';
    if (helpType == "list") {
        header = "Collections to Crawl";
        overview = "This screen provides an overall view of all collections";
        body = "<p><b>Name</b><br/>"
                + "The unique name assigned to this collection. The collection type icon is displayed next to the collection name."
                + "There are 4 possible collection types: HTTP, Filesystem, RSS or Custom.</p>"
                + "<p><b>Status</b><br/>"
                + "A collection can be in either one of 2 states, Ready (green circle icon) or Indexing/Refreshing (updating circle icon)."
                + " You can search the collection during both these states.</p>"
                + "<p><b>Last Updated</b><br/>"
                + "The last updated time stamp for the collection.</p>"
                + "<p><b>Queries</b><br/>"
                + "The number of search queries that were submitted to this collection.</p>"
                + "<p><b>Docs</b><br/>"
                + "The number of documents in this collection.</p>"
                + "<p><b>Index</b><br/>"
                + "Index may be held in Memory or Disk. &quot;Disk&quot; is best used when the amount of"
                + " physical RAM in the server is low or when indexing a very large document collection."
                + " &quot;Memory&quot; is best used when the number of documents is small or very fast search response times are required.</p>"
                + "<p><b>Language</b><br/>"
                + "Language of the content that can be indexed in this collection.</p>";
    }
    if (helpType == "add") {
        header = "Add Collection";
        overview = "To create a new collection, choose/fill-in the required values for each field.";
        body = "<p><b>Collection Name</b><br/>"
                + "Enter a unique name for your collection. </p>"
                + "<p><b>Collection Type</b><br/>"
                + "Choose one of the 4 possible types: HTTP, Filesystem, Feed or Custom."
                + " Pick the collection type based on the application requirements:<br/><br/>"
                + "HTTP - Websites, Intranets or Portals. Use to index urls that can be accessed by http.<br/><br/>"
                + "Filesystem - File/Documents from a filesystem/file share. Use to index files that can be accessed by drive mappings like c:\\ or \\\\fileshare etc.<br/><br/>"
                + "RSS - Blogs, News feeds, job feeds, product feeds. Use to index files that are available through a RSS/Atom/XML feeds.<br/><br/>"
                + "Custom - Content that needs to contructed from multiple sources and index within SearchBlox. Use to index custom content that is created by external applications.</p>"
                + "<p><b>Language </b><br/>"
                + "Choose the language of the contentthat you are about to index.</p>"
                + "<p><b>Index Type</b><br/>"
                + "Index may be held in Memory or Disk. &quot;Disk&quot; is best used when the amount of"
                + " physical RAM in the server is low or when indexing a very large document collection."
                + " &quot;Memory&quot; is best used when the number of documents is small or very fast search response times are required."
                + " Memory-based indexes will also be saved on disk but searching will be in-memory. <br/></p>";

    }
    if (helpType == "C" || helpType == "H" || helpType == "R") {
        header = "Collection Paths";
        overview = "Filters configure the crawler/spider to include or exclude URLs / "
                + "documents in the index.";
        body = "<p><b>Root URLs</b><br/>"
                + "Enter the starting URLs where the crawler/spider will begin indexing content.</p>"
                + "<p><b>Allow Paths </b><br/>"
                + "The URL path or pattern that will matched with every URL that gets indexed into this collection.</p>"
                + "<p><b>Disallow Paths</b><br/>"
                + "The URL path or pattern of URLs that should not be indexed in this collection.</p>"
                + "<p><b>Allowed Formats</b><br/>"
                + "The file formats that are permitted to be indexed into this collection.</p>";

    }
    if (helpType == "F") {
        header = "Collection Paths";
        overview = "The Directory Path is the starting path for the crawler. The crawler recursively "
                + "indexes content within the folders.";
        body = "<p><b>Directory Paths </b><br/>"
                + "Enter at least one Directory path for the collection. <br/>"
                + "<p><b>Mapping File system paths to HTTP URLs </b><br/>"
                + "When you enter the directory path for a FileSystem Collection, you can"
                + "optionally set an URL mapping for each directory. For example, C:\\ProgramFiles\\Apache Group\\Tomcat\\webapps\\tomcat-docs "
                + "can be mapped to http://localhost:8080/tomcat-docs so that even though SearchBlox indexed the "
                + "content from the file system, when a user clicks on the search result, the web document is served from the web server."
                + "<p><b>Allowed Paths </b><br/>"
                + "The URL path or pattern that will matched with every URL that gets indexed into this collection.</p>"
                + "<p><b>Disallowed Paths</b><br/>"
                + "The URL path or pattern of URLs that should not be indexed in this collection.</p>"
                + "<p><b>Allowed Formats</b><br/>"
                + "The file formats that are permitted to be indexed into this collection.</p>";
    }
    if (helpType == "docs") {
        header = "Collection Documents";
        overview = "Individual documents can be added/updated/deleted from a collection in real time.";
        body = "<p><b>Add/Update</b><br/>"
                + "Add to new document for indexing or update an existing individual document in the collection"
                + "<p><b>Delete </b><br/>"
                + "Delete an individual document from the collection"
                + "<p><b>Status </b><br/>"
                + "Get the status of a document from the selected"
                + "collection. The Title, Description, Keywords, Size, URL, Last Modified Date, Index Date of a document"
                + "can be seen using the Status function</p>";
    }
    if (helpType == "settings") {
        header = "Collection Settings";
        overview = "The Settings sub-tab holds tunable parameters for the crawler/spider. "
                + "SearchBlox comes pre-configured with some parameters when you create a new collection. "
                + "Please clear and re-index the collection to ensure the changes you make take effect. ";
        body = "<p><b>Keyword-in-Context Display</b><br/>"
                + "The Keyword-in-Context feature returns search results where the description is displayed from areas of content where the search term occurs.</p>"
                + "<p><b>HTML Parser Settings </b><br/>"
                + "This setting configures the HTML parser to read the description for a document "
                + "from one of the following html tags:"
                + "<br/><br/>Meta - &lt;META name=&#39;description &#39; content= &#39;some description here&#39; &gt;"
                + "<br/>H1 - &lt;H1&gt; some content here&lt;H1&gt;"
                + "<br/>H2 - &lt;H2&gt; some content here&lt;H2&gt;"
                + "<br/>H3 - &lt;H3&gt; some content here&lt;H3&gt;"
                + "<br/>H4 - &lt;H4&gt; some content here&lt;H3&gt;"
                + "<br/>H5 - &lt;H5&gt; some content here&lt;H5&gt;"
                + "<br/>H6 - &lt;H6&gt; some content here&lt;H6&gt;"
                + "<br/><br/>If the Keyword-in-Context feature is disabled, the description will be obtained "
                + "from one of the above tags. If the description parameter is not set "
                + "and Keyword-in-Context is disabled, the description will be set "
                + "to the first 200 characters in the document content."
                + "<p><b>Scanner Settings </b><br/>"
                + "These settings configure the http scanner/spider with values to be used when requesting the content<br/><br/>"
                + "<i>Maximum Document Age - </i>(In days) specifies the maximum allowable age of a document in the collection<br/>"
                + "<i>Maximum Document Size - </i>(In kilobytes) specifies the maximum allowable size of a document in the collection<br/>"
                + "<i>Maximum Spider Depth - </i>Specifies the maximum depth the spider is allowed to proceed to index documents<br/>"
                + "<i>Spider Delay - </i>Specifies the wait time in milliseconds for the spider between http requests to a web server<br/>"
                + "<i>User Agent - </i>The name under which the spider requests documents from a web server.<br/>"
                + "<i>Referrer - </i>Is a URL value set in the request headers to specify where the user agent previously visited<br/>"
                + "<i>Ignore Robots - </i>This value is set to Yes or No to tell the spider whether or to obey the robot rules<br/>"
                + "<i>Follow Redirects - </i>This value is set to Yes or No to instruct the spider whether or not to automatically follow redirects<br/>"
                + "<p><b>HTTP Basic Authentication</b><br/>"
                + "The spider can index secure content by authenticating to web servers protected by HTTP Basic Authentication."
                + " Specify the username and password to be presented when indexing secure content.</p>"
                + "<p><b>HTTP Form Authentication</b><br/>"
                + "The spider can access documents protected by form-based authentication. "
                + "The spider can login in and access the documents by presenting the values set in these fields.</p>"
                + "<p><b>HTTP Proxy Server Settings</b><br/>"
                + "The spider can index content by passing through Proxy Servers. The Proxy Server settings need to be entered in these fields. </p>"
                + "<p><b>Boosting</b><br/>"
                + "Boosting improves the relevancy of search results when search terms are found in the Title, Description, Keywords or Body by a factor of the value set for each field.</p>"
                + "<p><b>Remove Duplicates</b><br/>"
                + "The indexer can determine if the content found in 2 different URLs is the same and prevent the second URL from getting into the index if this value is set to Yes.</p>"
                + "<p><b>Stemming</b><br/>"
                + "Stemming is the process for reducing inflected words to their stem, base or root form. Stemming is enabled by default."
                + "<p><b>Spelling Suggestions</b><br/>"
                + "Spelling suggestions are created at the end of the index process for each collection."
                + "The search results include the &#39;Did you mean?&#39; suggestion if there is a match to the user's query.</p>"
                + "<p><b>Enable Logging</b><br/>"
                + "You can set the Logging to DEBUG mode to view the detailed spider/indexer activity within the index.log within the /searchblox folder.</p>";
    }
    if (helpType == "schedule") {
        header = "Index";
        overview = "Indexer Activity is controlled from this section. ";
        body = "<p><b>Current Status</b><br/>"
                + "Indicates the current status of the indexer for this collection.</p>"
                + "<p><b>Manual</b><br/><br/>"
                + "<i>Index - </i>Index a collection. In case of a collection which has existing documents, the documents will be indexed regardless of whether the document timestamp has changed.<br/><br/>"
                + "<i>Clear  - </i>Clear the index of any documents. This does not clear the settings for a collection. After this action, the number of documents in a collection will be 0.<br/><br/>"
                + "<i>Refresh   - </i>Index only the documents that have changed since the last indexing activity. The indexer uses the time stamp in the header of web page to determine if a file has changed."
                + "In case of filesystem documents, the time stamp is read from the last modified date of file on the disk.</p>"
                + "<p><b>Scheduled Activity</b><br/><br/>"
                + "<i>Index - </i>Set the frequency and the start date/time for indexing a collection.<br/><br/>"
                + "<i>Clear - </i>Set the frequency and the start date/time for clearing a collection.<br/><br/>"
                + "<i>Refresh - </i>Set the frequency and the start date/time for refreshing a collection.<br/><br/>"
                + "<i>Optimize - </i>Set the frequency and the start date/time for optimizing a collection.</p>";
    }

    if (helpType == "result") {
        header = "Settings";
        overview = "This screen provides an overall view of the settings that control the Search Results page. Please click the Save button to make sure your changes take effect.";
        body = "<p><b>Results per Page</b><br/>"
                + "Sets the default number of search results to display in a page. This value can also be changesd dynamically at user search time by passing the pagesize parameter.</p>"
                + "<p><b>Sorting</b><br/>"
                + "Results can be sorted by relevance of the search term, modified date on the document or by alphabetical order of the page title.</p>"
                + "<p><b>Hit-Highlighting</b><br/>"
                + "Enables hightlighting of search terms within the title and description on the search results page.</p>"
                + "<p><b>Search Form</b><br/>"
                + "Sets the display of the search form on every page or only on the first page of the search results.</p>"
                + "<p><b>Cluster Search Results</b><br/>"
                + "Dynamically clusters search results into folders. This can also be enabled by passing the parameter cluster=true as part of the search query.</p>"
                + "<p><b>Cache Search Results</b><br/>"
                + "Caches both standard search results and clustered search results for performance. This can also be enabled by passing the parameter cache=true as part of the search query.</p>"
                + "<p><b>Default Template</b><br/>"
                + "Sets the default XSL stylesheet to be used for all collections. The XSL stylesheet can also be changed"
                + " dynamically at user search time by passing the xsl parameter. The XSL templates can be found under /searchblox/stylesheets "
                + "folder within the SearchBlox installation.</p>";
    }

    if (helpType == "preview") {
        header = "Preview";
        overview = "Please enter a search term and choose the XSL template to preview the look&amp;feel of the search results page.";
    }

    if (helpType == 'replication') {
        header = 'Replication';
        overview = 'To make this installation into a replica of another SearchBlox installation, please click the On radio button and enter the settings.';
        body = "<p><b>Server URL</b><br/>"
                + "Enter the URL of the server you are replicating. http://&lt;hostname:port&gt;/searchblox</p>"
                + "<p><b>Username</b><br/>"
                + "Enter the Username of the Server Admin Console that you are replicating</p>"
                + "<p><b>Password</b><br/>"
                + "Enter the Password of the Server Admin Console that you are replicating</p>"
                + "<p><b>Confirm</b><br/>"
                + "Confirm the Password of the Server Admin Console that you are replicating</p>"
                + "<p><b>Check for Updates</b><br/>"
                + "Enter the frequency of how often the main server should be checked for updates"
                + "<p><b>Starting</b><br/>"
                + "Enter the start date/time for the replication process</p>";
    }
    if (helpType == 'user') {
        header = 'Change Password';
        overview = 'Use this screen to change your existing password to a new password.';
    }
    if (helpType == 'license') {
        header = 'License';
        overview = 'License information is displayed here.';
        body = "<p><b>Version</b><br/>"
                + "Your current SearchBlox version</p>"
                + "<p><b>Edition</b><br/>"
                + "The SearchBlox Edition you are running</p>"
                + "<p><b>Licensed to</b><br/>"
                + "Licensee name</p>"
                + "<p><b>Document Limit</b><br/>"
                + "The total number of documents you can index</p>"
                + "<p><b>Days Remaining</b><br/>"
                + "If you are running the evaluation version of SearchBlox, the number of remaining days to evaluate this version will be displayed here"
                + "<p><b>IP Address</b><br/>"
                + "The IP address that is being used for the License will be displayed here"
                + "<p><b>Subscription Expires</b><br/>"
                + "Displays the date until your support and upgrades are active with SearchBlox</p>";
    }
    if (helpType == 'base') {
        header = 'SearchBlox Context Sensitive Help';
        body = "<p>SearchBlox provides context-sensitive help "
                + "to enable users to effectively use SearchBlox. <br/><br/> "
                + "To access the context-sensitive help, please click on the ? symbol on the page or the section of the page in the SearchBlox Admin Console.</p>"


    }
    if (helpType == 'report') {
        header = 'Dashboard';
        overview += 'This screen provides a real-time dashboard view of the number of search queries that were submitted against each collection within a 7 day, 24 hour and 60 minute period.';
    }

    if (helpType == 'query') {
        header = 'Query';
        overview += 'This is screen provides the ability to select a collection and a time period to see the top search terms with and without search results.';
    }

    if (helpType == 'search') {
        header = 'Search';
        overview += 'This screen provides the ability to search the collections and to see what search results are returned.';
    }

    if (helpType == 'ads') {
        header = 'Featured Results';
        body = "<p><b>Type</b><br/>"
                + "Type: text or graphic (banner)</p>"
                + "<p><b>Title</b><br/>"
                + "Title to display. For text-type featured results, it will be displayed as header. For graphic it will be image title</p>"
                + "<p><b>Description</b><br/>"
                + "Text to display for text-type featured results</p>"
                + "<p><b>URL</b><br/>"
                + "Target URL</p>"
                + "<p><b>Key Word Content</b><br/>"
                + "Search keywords source</p>"
                + "<p><b>Keywords</b><br/>"
                + "Keywords</p>"
                + "<p><b>Keyword URL</b><br/>"
                + "Keywords document URL</p>"
                + "<p><b>Autogenerated ID</b><br/>"
                + "Identifier</p>"
                + "<p><b>Expiry Date</b><br/>"
                + "Expiration date</p>"
                + "<p><b>Number Times to Display</b><br/>"
                + "Display counter</p>"
                + "<p><b>Priority</b><br/>"
                + "Display priority</p>"
                + "<p><b>Graphic URL</b><br/>"
                + "Banner image URL</p>"
                + "<p><b>State</b><br/>"
                + "Active/inactive. Only active feautured results will be found</p>"
    }

    if (helpType && helpType.custom) {
        header = helpType.header || '';
        overview = helpType.overview || '';
        body = helpType.body || '';
    }

    document.getElementById("helpHeader").innerHTML = header;
    document.getElementById("helpOverview").innerHTML = overview;
    document.getElementById("helpBody").innerHTML = body;
    togglePopup('help');
}

//File input
var W3CDOM = (document.createElement && document.getElementsByTagName);

function init() {
    if (!W3CDOM) return;
    var fakeFileUpload = document.createElement('div');
    fakeFileUpload.className = 'fakefile';
    fakeFileUpload.appendChild(document.createElement('input'));
    var image = document.createElement('img');
    image.src = '../images/fileupload_btn.jpg';
    fakeFileUpload.appendChild(image);
    var x = document.getElementsByTagName('input');
    for (var i = 0; i < x.length; i++) {
        if (x[i].type != 'file') continue;
        if (x[i].getAttribute('noscript')) continue;
        if (x[i].parentNode.className != 'fileinputs') continue;
        x[i].className = 'file hidden';
        var clone = fakeFileUpload.cloneNode(true);
        x[i].parentNode.appendChild(clone);
        x[i].relatedElement = clone.getElementsByTagName('input')[0];
        if (x[i].value)
            x[i].onchange();
        x[i].onchange = x[i].onmouseout = function () {
            this.relatedElement.value = this.value;
        }
    }
}

function getXsl(form) {
    for (var i = 0; i < form.elements['template'].length; i++) {
        if (form.elements['template'][i].checked) {
            return form.elements['template'][i].value;
        }
    }
    return 'default.xsl';
}

function showMessage(message) {
    clearMessages();
    $("notificationTitle").innerHTML = message.header || '';
    $("notificationMessage").innerHTML = message.body || '';
    $("notificationButtons").innerHTML = message.buttons || '<span><a onclick="new Effect.SwitchOff($(\'notification\'));" href="javascript: void(0);">OK</a></span>';
    new Effect.BlindDown('notification', {duration: .3});
    new Effect.ScrollTo('masthead', {duration: .3});
}

function showError(error) {
    clearMessages();
    $("errorTitle").innerHTML = error.header || '';
    $("errorMessage").innerHTML = error.body || '';
    new Effect.BlindDown('error', {duration: .3});
    new Effect.ScrollTo('masthead', {duration: .3});
}

function clearMessages() {
    $('notification').style.display = 'none';
    $('error').style.display = 'none';
}
