/**
 * Slider object.
 *
 * @var     object
 * @access  private
 */
var slider = false;

/**
 * Intervall time for sliding action.
 *
 * @var     object
 * @access  private
 */
var scrollInterval = false;


/**
 * Registers observers for mouse wheel events.
 *
 * In order to obtain a valid observer for both IE and Mozilla compatible
 * browser we need to register the 'scroll' event for mozilla and IE. The
 * 'mousewheel' event needs to be registered for Opera Browsers.
 *
 * @return  void
 *
 * @access  public
 */
function registerElementObserver()
{
    var box = $('content_main_box');
    var down = $('sb_button_down');
    var up = $('sb_button_up');

    setContentAreaHeight();
    showContentElements();

    // only register mousewheel event if we do have an opera browser
    if ( isBrowserType('opera') ){
        Event.observe(box, 'mousewheel', observeSearchElementsPosition);
        Event.observe(up, 'mousedown', observeSearchElementsPosition);
        Event.observe(down, 'mousedown', observeSearchElementsPosition);
    } else {
        Event.observe(box, 'scroll', observeSearchElementsPosition);

        Event.observe(down, 'mousedown', startScrollEventByMouseClick);
        Event.observe(down, 'mouseup', stopScrollEventByMouseClick);
        Event.observe(document, 'mouseup', stopScrollEventByMouseClick);

        Event.observe(up, 'mousedown', startScrollEventByMouseClick);
        Event.observe(up, 'mouseup', stopScrollEventByMouseClick);
        Event.observe(document, 'mouseup', stopScrollEventByMouseClick);
    }

    Event.observe(box, 'keypress', observeSearchElementsPosition);

    registerElementsForPreview();
}



/**
 * Observes if we need to load (add) new search results.
 *
 * Function looks if the user has scrolled down the results page
 * down to 90 percent of the results list. In this case we need
 * to reload new results.
 *
 * @return  void
 *
 * @access  public
 */
function observeSearchElementsPosition( event )
{
    var box = $('content_main_box');

    // Opera 9.x onmousewheel bug
    if ( isBrowserType('opera') ){
        if ( event && event.wheelDelta < 0 ){
            box.scrollTop = box.scrollTop + event.wheelDelta;
        }
    }

    if( $('content_loading_status') && box.scrollTop != 0 ){
        if ( lastScrollPosition < box.scrollTop ){
            // moving down
            box.scrollTop = box.scrollTop - 25;
        }
        else if ( lastScrollPosition > box.scrollTop ) {
            // moving up
            box.scrollTop = box.scrollTop + 25;
        }
    }

    lastScrollPosition = box.scrollTop;

    // loads new search results if search is active
    loadNewSearchResults();

    // sets slider to content position
    setSliderPositionByContentPosition();
}



/**
 * Start scrolling action for scroll button.
 *
 * @return  boolean
 *
 * @access  public
 */
function startScrollEventByMouseClick( event )
{
    if( Event.isLeftClick(event) ) {
        var id = Event.element(event).id;

        if ( id == 'sb_button_down' ){
            scrollResultsBy(10);
            scrollInterval = setInterval("scrollResultsBy(15)", 20);
            return true;
        }

        if ( id == 'sb_button_up' ){
            scrollResultsBy(-10);
            scrollInterval = setInterval("scrollResultsBy(-15)", 10);
            return true;
        }
    }

    return false;
}



/**
 * Stops scrolling action.
 *
 * @return  boolean
 *
 * @access  public
 */
function  stopScrollEventByMouseClick( event )
{
    if( Event.isLeftClick(event) ) {
        clearInterval(scrollInterval);
    }
}



/**
 * Scrolls results list.
 *
 * @return  boolean
 *
 * @access  public
 */
function scrollResultsBy( pos )
{
    var box = $('content_main_box');

    var new_pos = box.scrollTop + pos;
    box.scrollTop = new_pos;
}



/**
 * Scales and sets the size of the search results box.
 *
 * @return  void
 *
 * @access  public
 */
function setContentAreaHeight()
{

    // set size of results box
    var w = WindowUtilities.getPageSize();

    //var width  = w.windowWidth - 300;
    var height = w.windowHeight - 120;

    Element.setStyle( 'content_main_box'  , {'height': height + 'px'} );
    Element.setStyle( 'content_scrollbar' , {'height': height + 'px'} );

    var up_h    = Element.getHeight( 'sb_button_up' );
    var down_h  = Element.getHeight( 'sb_button_down' );

    var slide_h = height - up_h - down_h;
    Element.setStyle( 'sb_slidebar'       , {'height': slide_h + 'px'} );

    //setFooterPosition(w.windowHeight - 62);

    initSlider();
    setSliderPositionByContentPosition();
}


/**
 * Enables slider or creates new slider object.
 *
 * @return  void
 *
 * @access  public
 */
function initSlider()
{
    var box  = $('content_main_box');

    if ( box.scrollHeight >  Element.getHeight(box) ){
        enableSlider();
    } else {
        disableSlider();
    }
}


/**
 * Enables slider or creates new slider object.
 *
 * @return  void
 *
 * @access  public
 */
function enableSlider()
{
    if ( slider != false ){
        slider.dispose();
    }

    slider = new Control.Slider('sb_slider','sb_slidebar', {axis:'vertical',
        onSlide:setSliderPosition, onChange:setSliderPosition});
}


/**
 * Disables the slider.
 *
 * @return  void
 *
 * @access  public
 */
function disableSlider()
{
    if ( slider != false ){
        slider.setDisabled();
    }
}


/**
 * Sets the sliders position based on the content position.
 *
 * @return  void
 *
 * @access  public
 */
function setSliderPositionByContentPosition()
{
    var box = $('content_main_box');
    var bar = $('sb_slidebar');
    var sld = $('sb_slider');

    var s = box.scrollTop;
    var h = Element.getHeight(box);

    var slider_height = Element.getHeight(bar);
    var bar_height = Element.getHeight(sld);

    var scroll_height = box.scrollHeight;
    var top = Math.round((s * (slider_height - bar_height)) / (scroll_height - h));

    Element.setStyle( sld, {'top' : top + 'px'} );
}



/**
 * Callback Function: Sets sliders y position.
 *
 * Function gets called by the Control.Slider event viewer and set
 * the vertical position of the slider element.
 *
 * @return  void
 *
 * @access  public
 */
function setSliderPosition( position )
{
    var box = $('content_main_box');

    var scroll_height = box.scrollHeight;
    var h = Element.getHeight(box);

    position = Math.round((scroll_height - h) * position);
    box.scrollTop = position;
}



/**
 * Function shows up (activates) all search elements.
 *
 * @return  void
 *
 * @access  public
 */
function showContentElements()
{
    href = window.location.href;
    query = href.substr(href.lastIndexOf("/") + 1, href.length);

    if ( $('page_content') ){
        Element.setStyle($('page_content'),{'visibility' : 'visible'});
    }
}



/**
 * Checks which browser do we have.
 *
 * @return  boolean
 *
 * @access  public
 */
function isBrowserType( string )
{
    var detect = navigator.userAgent.toLowerCase();
    var place = detect.indexOf(string) + 1;

    return place;
}



/**
 * Get Domain name from URL.
 *
 * @return  string      domain_name
 *
 * @access  public
 */
function getDomainName()
{
    if ( location.href.lastIndexOf('//') != -1 ){
        var split = new Array();
        split = location.href.split("://");

        var domain = split[1].substr(0, split[1].indexOf('/'));
        domain = split[0] + '://' + domain;

        return domain;
    }

    return location.href.substr(0,location.href.lastIndexOf("/"));
}



/**
 * Returns the subdomain from the URL
 *
 */
function getSubDomain()
{
    var split = new Array();
    split_ = location.href.split(".");
    return split_[0].substr(7, 4);
}



/**
 * Return channel based on URL parameter
 *
 */
function getChannel()
{
    var url = location.href;
    var filename = url.split("/");
    var name = filename[3];

    var search_pattern = /search_string/;

    if (url.match(search_pattern))
    {
        return "search";
    }

    if (name.length == 0)
    {
        return "homepage";
    }
    if (name)
    {
        if (checkNumber(name))
        {
            return "publication";
        }
        else
        {
            return "author";
        }
    }
    return "publication";
}



/**
 * Show AdBox
 *
 */
function showAdBox()
{
    var parent      = $('content_nav_box');
    var subdomain   = getSubDomain();
    var channel     = getChannel();
    var zones       = getZoneDef();

    var adbox = appendNode(parent, 'div', 'adbox');
    adbox.innerHTML = '<iframe src="http://ads.scientificcommons.org/adbox/' + zones[subdomain + "_" + channel] + '" border="0" frameborder="0" scrolling="auto"  width="300" height="270"></iframe>';
}



/**
 * Reload AdBox
 *
 */
function reloadAdbox()
{
    var adbox       = $('adbox');
    var subdomain   = getSubDomain();
    var channel     = getChannel();
    var zones       = getZoneDef();

    adbox.src = 'http://ads.scientificcommons.org/adbox/' + zones[subdomain + "_" + channel];
}



/**
 * Get Zone Definitions
 *
 */
function getZoneDef()
{
    var zones = new Array();

    zones["de_author"]      = 5;
    zones["de_publication"] = 4;
    zones["de_search"]      = 3;
    zones["de_homepage"]    = 9;

    zones["en_author"]      = 6;
    zones["en_publication"] = 7;
    zones["en_search"]      = 8;
    zones["en_homepage"]    = 10;

    zones["www_homepage"]   = 10;

    return zones;
}



/**
 * Checks if string only consists of numbers
 *
 */
function checkNumber(str)
{
    var validChars = "0123456789";
    var isNumber = true;
    var c;

    for (i = 0; i < str.length && isNumber == true; i++)
    {
        c = str.charAt(i);
        if (validChars.indexOf(c) == -1)
        {
            isNumber = false;
        }
    }
    return isNumber;
}



//
// Start core event observer handler
//
Event.observe(window, 'resize', setContentAreaHeight);
Event.observe(window, 'load', showAdBox);