﻿
var resultContainer = null;
var commentContainer = null;
var commentSubmitBt = null;
var commentAddLinkCheck = null;
var waitElement = null;
var itemID = -1;

/* --------------------------------------------------- */
/* Search Utilities----------------------------------- */
/* --------------------------------------------------- */

function Querystring(qs)
{ 
    this.params = {};

    if (qs == null) qs = location.search.substring(1, location.search.length);
    if (qs.length == 0) return;

    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&'); // parse out name/value pairs separated via &

    // split out each name=value pair
    for (var i = 0; i < args.length; i++)
    {
        var pair = args[i].split('=');
        var name = decodeURIComponent(pair[0]);

        var value = (pair.length == 2)
			? decodeURIComponent(pair[1])
			: name;

        this.params[name] = value;
    }
}

Querystring.prototype.get = function(key, default_)
{
    var value = this.params[key];
    return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key)
{
    var value = this.params[key];
    return (value != null);
}

/* --------------------------------------------------- */
function searchKeysMonitor(ev)
{
    var keycode = 0;
    if (ev != null)
    {
        if (ev.keyCode)
        { keycode = ev.keyCode; }
        else if (ev.which)
        { keycode = ev.which; }
    }
    else
    {
        if (window.event)
            keycode = window.event.keyCode;
    }


    if (keycode == 13)
    {
        $('searchInputValue').disabled = true;
        var searchStr = $('searchInputValue').value;
        $('searchInputValue').value = 'searching...';
        submitSearch(searchStr);
        return false;
    }
}

function clickSearch()
{
    $('searchInputValue').disabled = true;
    var searchStr = $('searchInputValue').value;
    $('searchInputValue').value = 'searching...';
    submitSearch(searchStr);
}
function submitSearch(searchStr)
{
    if (searchStr != "type your search here") {
        if (searchPage.indexOf("?", 0) > 0)
            document.location.href = searchPage + "&q=" + escape(removeHtml(searchStr).replace(/ /gi, "+"));
        else
            document.location.href = searchPage + "?q=" + escape(removeHtml(searchStr).replace(/ /gi, "+"));
    }
}
function clickOnSearchText()
{
    if ($('searchInputValue').value == "type your search here")
        $('searchInputValue').value = '';

    $('searchInputValue').style.color = "black";
    $('searchInputValue').onkeypress = searchKeysMonitor;

}
function setSearchTerm(q)
{
    $('searchInputValue').value = q.replace("+", " "); ;
    $('searchInputValue').style.color = "black";
    $('searchInputValue').disabled = false;
}
function outOfFocusSearch()
{
    if ($('searchInputValue').value == "type your search here" || $('searchInputValue').value == "")
    {
        $('searchInputValue').value = 'type your search here';
        $('searchInputValue').style.color = "#aaa";
    }
}


// -------------------------------------------------------------------------------
function renderSearchResult(oExecutor, oEventArgs)
{
    if (!oExecutor.get_responseAvailable())
    {
        if (oExecutor.get_timedOut())
            alert("Request Timed Out. The command could not complete");
        else if (oExecutor.get_aborted())
            alert("Request Aborted. The command could not complete");
        else
            alert("HTTP Error. The command could not complete");

    }

    resultContainer.innerHTML = "done<br/>";
        

    var jsonData = oExecutor.get_responseData();

    //resultContainer.innerHTML = jsonData;
    //return;

    var response = eval("(" + jsonData + ")");
    outputSearchData(response);
}
var g_responseData;
function outputSearchData(response)
{
    g_responseData = response;
    var counter = 0;
    var htmlOut = '<div class="searchResult">';
    var startMatch = 0;
    if (resultPage != null)
        startMatch = 10 * resultPage;

    if (startMatch > response.result.items.length)
        return;

    var endMatch = startMatch + 10;
    if (endMatch > response.result.items.length)
        endMatch = response.result.items.length;

    for (var t = startMatch; t < endMatch; t++)
    {
        htmlOut += '<div class="SearchResult">';
        htmlOut += '<div class="SearchThumbContainer"><center><img src="' + response.result.items[t].thumb + '" /></center></div>';
        htmlOut += '<div class="SearchTitleContainer">';
        htmlOut += '<h3><a href="' + response.result.items[t].siteLink + '">' + response.result.items[t].title + "</a></h3>";
        htmlOut += '<h4>Source: <strong><a href="' + response.result.items[t].siteLink + '">' + response.result.items[t].source.name + '</a></strong></h4>';
        htmlOut += '<div class="SearchResultDesc">';
        htmlOut += '<p>published in <a href="' + response.result.items[t].context.link + '">' + response.result.items[t].context.name + '</a> ' + response.result.items[t].modified + '</p>';
        htmlOut += response.result.items[t].description + '</div>';
        htmlOut += '</div></div>';
        counter++;
    }
    htmlOut += "</div>";

    htmlOut += '<div style="width:250px; text-align:right;">';
    var searchPageUrl = searchPage + "?q=" + removeHtml($('searchInputValue').value).replace(/ /gi, "+");
    if (resultPage > 0)
    {
        //htmlOut += '<a style="float:left;" href="javascript:{resultPage++;outputSearchData(g_responseData);' + searchPageUrl + '&start=' + (resultPage - 1) + '">&laquo; Previous Results</a> ';
        htmlOut += '<a style="float:left;" href="javascript:{scroll(0,0);resultPage--;outputSearchData(g_responseData);}">&laquo; Previous Results</a> ';
    }
    if (endMatch < response.result.items.length)
    {
        //htmlOut += '<a href="' + searchPageUrl + '&start=' + (resultPage + 1) + '">Next Results &raquo;</a>';
        htmlOut += '<a href="javascript:{scroll(0,0);resultPage++;outputSearchData(g_responseData);}">Next Results &raquo;</a> ';
    }
    htmlOut += '</div>';

    if (response.result.items.length > 1)
        resultContainer.innerHTML = "<div style='margin:4px;'><p>" + response.result.items.length + " matches found - Page " + (resultPage + 1) + "</p></div>";
    else
        resultContainer.innerHTML = "<div style='margin:4px;'><p>" + response.result.items.length + " match found</p></div>";

    resultContainer.innerHTML += htmlOut;
}

// Commenting utilities

// -------------------------------------------------------------------------------
function commentSubmitReturn(oExecutor, oEventArgs)
{
    if (oExecutor.get_responseAvailable())
    {
        var responseData = oExecutor.get_responseData();
        displayBoxText(responseData)
    }
    else
    {
        if (oExecutor.get_timedOut())
            alert("Request Timed Out. The command could not complete");
        else if (oExecutor.get_aborted())
            alert("Request Aborted. The command could not complete");
        else
            alert("HTTP Error. The command could not complete");

    }
}

// -------------------------------------------------------------------------------
function renderComments(oExecutor, oEventArgs)
{
    if (oExecutor.get_responseAvailable())
    {
        var xhtmlData = oExecutor.get_responseData();
        resultContainer.innerHTML = xhtmlData;
    }
    else
    {
        if (oExecutor.get_timedOut())
            alert("Request Timed Out. The command could not complete");
        else if (oExecutor.get_aborted())
            alert("Request Aborted. The command could not complete");
        else
            alert("HTTP Error. The command could not complete");

    }
}


// -------------------------------------------------------------------------------
function refreshComments(oExecutor, oEventArgs)
{
    var errorSubmit = false;
    waitElement.style.display = 'none';
    commentSubmitBt.disabled = false;
    if (oExecutor != null && oExecutor.get_responseAvailable())
    {
        var xhtmlData = oExecutor.get_responseData().toString();
        if (xhtmlData.length > 1)
        {
            errorSubmit = true;
            displayFadingBoxText(xhtmlData, 4000);
        }
    }

    if (!errorSubmit)
    {
        actionGetComments(itemID, "XHTML", renderComments);
        tinyMCE.get('userCommentText').setContent('');
    }
}

// -------------------------------------------------------------------------------
function submitComment(itemID, contextFolderID)
{
    tinyMCE.triggerSave();
    var content = tinyMCE.get('userCommentText').getContent();
    tinyMCE.get('userCommentText').setContent('');
    commentSubmitBt.disabled = true;
    waitElement.style.display = 'block';
    actionAddComment(itemID, contextFolderID, commentAddLinkCheck.checked, content, refreshComments);

}

// -------------------------------------------------------------------------------
function deleteComment(itemID, commentID, commentDiv)
{
    commentDiv.style.border = 'solid 1px #c00000';
    commentDiv.style.overflow = 'hidden';
    actionDeleteComment(itemID, commentID);
    setTimeout(function() { smoothCollapse(commentDiv); }, 500);
}


/////////////////////////////////////////////////////////////////////////////////////////////////////
// HIDE//SHOW Full description
/////////////////////////////////////////////////////////////////////////////////////////////////////

var targetDescDiv = null;
var currentBtEl = null;

function updateDescription(oExecutor, oEventArgs)
{
    if (oExecutor.get_responseAvailable() && targetDescDiv != null)
    {
        targetDescDiv.innerHTML = oExecutor.get_responseData();
        targetDescDiv = null;
        if (currentBtEl != null)
            currentBtEl.disabled = false;
    }
}

function hideFullDesc(itemID, descDiv, buttonEl)
{
    targetDescDiv = descDiv;
    targetDescDiv.innerHTML = '<div id="operationInProgress" style="margin:2em auto;"><img alt="progress" src="images/processing.gif" />&nbsp;Switching...</div><br/><br/>';
    actionItemRemoveMeta(itemID, 'AllowLongDesc', function(oEx, oEArgs) { window.setTimeout(function() { actionItemGetPubDesc(itemID, updateDescription) }, 500); });
    buttonEl.onclick = function() { showFullDesc(itemID, descDiv, buttonEl); };
    buttonEl.innerHTML = "Full Text";
    buttonEl.disabled = true;
    currentBtEl = buttonEl;
}

function showFullDesc(itemID, descDiv, buttonEl)
{
    if (!confirm("Warning. Showing the full content of this item here might cause a copyright violation.\nMake sure it is OK to display this content in full here before proceeding."))
        return;
    targetDescDiv = descDiv;
    targetDescDiv.innerHTML = '<div id="operationInProgress" style="margin:2em auto;"><img alt="progress" src="images/processing.gif" />&nbsp;Switching...</div><br/><br/>';
    actionItemAddMeta(itemID, 'AllowLongDesc', 'true', function(oEx, oEArgs) { window.setTimeout(function() { actionItemGetPubDesc(itemID, updateDescription) }, 500); });
    buttonEl.onclick = function() { hideFullDesc(itemID, descDiv, buttonEl); };
    buttonEl.innerHTML = "Short Text";
    buttonEl.disabled = true;
    currentBtEl = buttonEl;
}

