/**
 * Index of last mouse over preview position.
 * 
 * @var     int
 * @access  private
 */
var mouseOverIndex = false;


/**
 * Download URL
 *
 * @var     string
 * @access  public
 */
var download_url = "http://download.scientificcommons.org";


/**
 * Preview json object cache: This object is caching 
 * the json answers.
 *
 * @var     int
 * @access  private
 */
var prevobj_cache = new Array();



/**
 * Starts the preview task.
 *
 * When you move the mouse over a search element than the function
 * will got called by the mouseover event handler. This function
 * will call the ajax rpc task function "doPreview".
 * 
 * @return  void
 *
 * @access  public 
 */
function startPreviewTask(event)
{
    if ( event ){
        if ( Event.element ){
            var node = Event.element(event);
        }
    }

    if ( typeof getIdOfParentElement == "function" ){
        if ( id = getIdOfParentElement(node) ){
            Element.addClassName($(id), 'selected-element');
            mouseOverIndex = id; // set global index to current mouseover position
            window.setTimeout( function () { 
                if ( typeof getIdOfParentElement == "function" ) doPreview(id, 'preview', showPreviewResponse); 
                }, 400);
        }
    }
}


/**
 * Gets parent element on mouseclick.
 *
 * @return  void
 *
 * @access  public 
 */
function getIdOfParentElement(node)
{
    if (node.id){
        return node.id;
    } 
    else {
        return getIdOfParentElement(node.parentNode);
    }
}



/**
 * Does the preview task.
 *
 * The preview task will be called if the user has still
 * the mouse pointer on the same search element.
 * 
 * @param   int         id          publication id
 * @param   string      action      action to perform (e.g. preview, doccache)
 * @param   string      callback    callback function after ajax request
 *
 * @return  void
 *
 * @access  public 
 */
function doPreview(id, action, callback)
{
    var a = { 'function': action , 'pubid': id };
    var params = $H(a).toQueryString();
    
    if ( action == 'preview' ){
        if (mouseOverIndex == id){
            var prev = $('content_prev_box');
            
            // if preview box doesnt exist we need to create it
            if ( !prev ){
                var navbox = $('content_nav_box');
                var prev = appendNode(navbox, 'div', 'content_prev_box');
                
                if ( Element.setStyle ){
                    Element.setStyle(prev,{'display' : 'none'});
                }
            }
            
            if ( prev.name != id ){
                // is object already in cached?
                if ( prevobj_cache[id] && prevobj_cache[id].id ){
                    showPreviewResponse(1, prevobj_cache[id]);
                }
                else {
                    prevobj_cache[id] = id;
                    prev.name = id;
                                        
                	var myAjax = new Ajax.Request(url, {
                	    method:        'get', 
                	    parameters:    params, 
                	    onComplete:    callback 
                        });
                }
            }
        }
    }
    else {        
        var myAjax = new Ajax.Request(url, { 
            method:         'get', 
            parameters:     params, 
            onComplete:     callback
            });
    }
}



/**
 * Clears the mouse index.
 *
 * If you move the mouse out of a search element then the index
 * gets reseted. This will prevent the preview box from loads of
 * tasks tp perform.
 * 
 * @return  void
 *
 * @access  public 
 */
function clearMouseOverIndex(node)
{
    if (mouseOverIndex){
        Element.removeClassName($(mouseOverIndex), 'selected-element');
    }
    
    mouseOverIndex = false;
}



/**
 * Shows preview box content.
 *
 * @return  void
 *
 * @access  public 
 */
function showPreviewResponse(originalRequest, json)
{
    var prev = $('content_prev_box');
    
    if ( json && mouseOverIndex ) {
        if (mouseOverIndex == json.id){
            prev.name = json.id
            prevobj_cache[json.id] = json; // cache result
    
            if($('content_prev_main')){
                Effect.Fade('content_prev_box', { duration: 0.05 });
                window.setTimeout(function () { showPreview(json); }, 100);
                //showPreview(json);
            } else {
                showPreview(json);
            }
        }
    }
}



/**
 * Shows preview box content.
 *
 * @return  void
 *
 * @access  public 
 */
function showPreview(json)
{
    if ( typeof $ == "function" ){
        var domain = getDomainName();   

        if( $('content_prev_main') ){
            $('content_prev_main').parentNode.removeChild($('content_prev_main'));
        }
    
        var prev = $('content_prev_box');
        
        var parent = appendNode(prev, 'div', 'content_prev_main');
        Element.setStyle(prev,{'display' : 'none'});
        
    
        
        appendNode(parent, 'h2', false, language['preview_title']);
         
        if (json.subject) {
            var name  = appendNode(parent, 'p', false, language[json.subject.name]);
            Element.addClassName(name, 'name');
            var child = appendNode(parent, 'p', false, json.subject.value);
            Element.addClassName(child, 'value');
        }
            
        if (json.creator) {
            if (json.creator.value.length){
                var head  = appendNode(parent, 'p', false, language[json.creator.name]);
                Element.addClassName(head, 'name');
                
                var ul = appendNode(parent, 'p');
                Element.addClassName(ul, 'value');
                
                for(i=0; i < json.creator.value.length; i++){
                    if (i != 0) {
                        ul.innerHTML += '<BR />';
                    }
                                    
                    if (json.creator.value[i].url) {
                        ul.innerHTML += '<a href="' + domain + json.creator.value[i].url + 
                            '">' + json.creator.value[i].name + '</a>';
                    }
                    else {
                        ul.innerHTML += json.creator.value[i].name;
                    }
                }
            }
        }
        
        if (json.repository) { 
            var name  = appendNode(parent, 'p', false, language[json.repository.name]);
            Element.addClassName(name, 'name');
            var child = appendNode(parent, 'p', false, false);
            Element.addClassName(child, 'value');
            var value = appendNode(child, 'a', false, json.repository.value);
            value.href = json.repository.url;
        }
    
        Effect.Appear('content_prev_box', { duration: 0.4 });
    }
}



/**
 * Registers elements for preview.
 *
 * @return  void
 *
 * @access  public 
 */
function registerElementsForPreview()
{
    var elements = document.getElementsByClassName('content_element', 'content_elements');
    
    elements.each( function(item)
        {
            Event.observe(item, 'mouseover', startPreviewTask);
            Event.observe(item, 'mouseout', clearMouseOverIndex);
            //Event.observe(item, 'click', killElementEvents);
        } 
   )
}



/**
 * On page loading the function initializes the preview 
 * of the cached fulltext documents.
 *
 * @return  void
 *
 * @access  public
 */
function loadDownloadCache()
{
    if ( $('publication_id') ){
        var id = $('publication_id').innerHTML;
        doPreview(id, 'download', showDownloadResponse);
    }
    else {
        loadRefExportLinks();
    }
}



/**
 * Displays the ajax response for the fulltext download
 * request on page loading.
 *
 * @param   string          originalRequest         uri of the original request
 * @param   array           json                    json result array
 *
 * @return  void
 *
 * @access  public
 */
function showDownloadResponse(originalRequest, json)
{
    if (json.length >= 1){
        var prev = $('content_nav_box');

        for (i=0; i<json.length; i++) {
            var parent = appendNode(prev, 'div', 'content_prev_box_download');
            
            if ( json.length > 1 ){
                var title = language['download_cache'] + ' (' + (i+1) + ')';
            }
            else {
                var title = language['download_cache'];
            }
            
            appendNode(parent, 'h2', false, title);
            
            var name  = appendNode(parent, 'p', false, language['date_cache']);
            Element.addClassName(name, 'name');
            var child = appendNode(parent, 'p', false, json[i].date);
            Element.addClassName(child, 'value');
            
            var name  = appendNode(parent, 'p', false, language['type']);
            Element.addClassName(name, 'name');
            var child = appendNode(parent, 'p', false, json[i].mime);
            Element.addClassName(child, 'value');
            
            if ( json[i].filename ){
                if (json[i].filename.length > 25) {
                    json[i].filename = json[i].filename.substr(0, 25) + "...";
                }

                var name  = appendNode(parent, 'p', false, language['file']);
                Element.addClassName(name, 'name');
                var child = appendNode(parent, 'p', false, json[i].filename);
                Element.addClassName(child, 'value');
            }
            
            var url = download_url + '/' + json[i].id
            var link = '<a class="' + json[i].mime + '" href="' + url + '">' 
                + language['download_pub'] + '</a>';
            
            var child  = appendNode(parent, 'p', false, link);
        }
    }
    
    loadRefExportLinks();
}



/**
 * Shows the links to export bibliographic data of the meta data entry
 * 
 * @return  void
 *
 * @access  public
 */
function loadRefExportLinks() 
{
    if ($('publication_id')){
        var prev   = $('content_nav_box');
        var parent = appendNode(prev, 'div', 'content_prev_box');
        appendNode(parent, 'h2', false, language['export_references']);

        var publication_id = $('publication_id').innerHTML;

        
        var ris    = '<a class="ris" href="/export/ris/' + publication_id + 
            '">EndNote Download</a> (RIS Format)';
        appendNode(parent, 'p', false, ris);
        
        var bibtex = '<a class="bibtex" href="/export/bibtex/' + publication_id + 
            '">BibTex Download</a> (Tex Format)';
        appendNode(parent, 'p', false, bibtex);
    }
}


//
// Initializing Download Cache Preview and Export Links
//
Event.observe(window, 'load', loadDownloadCache);
