/**
Project:        kubusmedia.com
Author:         Sebastian Wohlrab for kubus media
Date:           2008-04-03
Update:         2008-04-04

ToDo:           - Paginglink functionality should be optimized
                - Link Events (internal Links, Footer)
                - Channel-Search (articles)
                - Testing and Debug
*/

/**
description:    empty() clears the Fallback-HTML Content
date:           2008-04-03 | SW
return:         boolean
*/
function empty()
{
    $$('input').remove();
    if ($(navigationel).empty() && $(topel).empty())
    {
        if(document.getElementById('submit'))
        {
            $('submit').remove();
            return true;
        }
        else
        {
            return true;
        }
    }
    else
    {
        return false;
    }
}

/**
description:    buildBase(id) builds the Basic Site-Layout
date:           2008-04-03 | SW
args:           int id, int contentid
return:         boolean
*/
function buildBase(id, contentid)
{
    /*
    id will be used for the channel-tree-fetching (buildChannel(id))
    contentid will be used for the main-content (buildContent(contentid))
    */
    if(buildNavigation())
    {
        // getRemoteHTML(starturl, contentel)
        return true;
    }
    else
    {
        return false;
    }
}

/**
description:    buildNavigation(id) builds the Main Content at navigationel
date:           2008-04-03 | SW
return:         boolean
*/
function buildNavigation()
{
    // Get the Request-Data
    var navigation = $(navigationel);

    getRemoteJson(jsonnavurl).addEvent(
        'onComplete', function(data) {
        // Loop through the Items and Inject them into the html
        for (var i = 0; i < data.childs.length; i++)
        {
            new Element('a',
            {
                'href':data.childs[i].alias,
                'class': navigationclass
            }).setHTML(data.childs[i].title).injectInside(navigation);

            // Include the delimiter, if its not the last element
            if ((i+1) < data.childs.length) 
            {
                new Element('span').setHTML(delimiter).injectInside(navigation);
            }
        }
        var element = 'a.' + navigationclass;
        setEvent(element, mainel);
        // TODO: Check, if succeded
        return true;
    });
}

/**
description:    getChannel(id) builds the Channel-Tool at channelel
date:           2008-04-04 | SW
args:           int id
return:         boolean
*/
function getChannel(id)
{
    function fn() {
        fadeOut(channelel);
        
        getRemoteJson(jsontreeurl, id).addEvent('onComplete', function(items) {
            $(channelel).empty();
            items.childs.each(function(item) {
                buildSideBarLink(item.id, item.title, item.alias);
            });
            
            fadeIn(channelel);
            setEvent("a." + sidebarclass, 'content');
            setPaging(items);
            
            function fn() {
                fadeIn('bbar');
            }
            fn.delay(smoothness);
        });
    }
    fn.delay(smoothness);
    // Request JSON and Rebuild the filtered Channel
}

/**
description:    buildSideBarLink(id, title, alias) creates a Link inside channelel
date:           2008-04-07 | SW
args:           int id, string title, string alias
*/
function buildSideBarLink(id, title, alias)
{
    var li = new Element('li').injectInside(channelel);
    new Element('a', {
        'id':id,
        'href':alias,
        'class': sidebarclass
    }).setHTML(title).injectInside(li);
}

/**
description:    getRemoteJson(rurl, id) will request Json Data from an URL
date:           2008-04-03 | SW
args:           string rurl, int id
return:         object / boolean
*/
function getRemoteJson(rurl, id)
{
    var url = rurl;

    if (id)
    {
        url = rurl + "?f=" + id;
    }
    return new Json.Remote(url).send();
}

/**
description:    getRemoteHTML(url, el) will request Data from an URL and render it into el
date:           2008-04-03 | SW
args:           string rurl, string id
return:         object / boolean
*/
function getRemoteHTML(url, el)
{
    var check = false;
    if (url)
    {
        var transurl = getURLTranslation(url);
        if (transurl)
        {
            fadeOut(el);
            // rollOut(footerel);
            fadeOut(footerel);
            function appear()
            {
                fadeIn(el);
                // rollIn(footerel);
                fadeIn(footerel);
            }
            new Ajax(transurl, {
                method: 'get',
                update: $(el),
                onComplete: function() {
                    handlePage(el);
                    appear.delay(smoothness);
					setEvent("a.clink", contentel);
                }
            }).request();
        }
    }
}

/**
description:    getURLTranslation(url) will request Date via XHTTPRequest from an URL
date:           2008-04-03 | SW
args:           string url
return:         string / false

ToDo:           This should be working in English also
*/
function getURLTranslation(url)
{
    if (url)
    {
        url = url.replace("/" + access + "/", "/request_" + access + "/");
        return url;
    } else {
        return false;
    }
    
}

/**
description:    setNavigationEvent(el) will add the Link-Event to el
date:           2008-04-03 | SW
args:           string el
return:         boolean

ToDo:           -- fixed -- Fix fadeOut on Filter Event
*/
function setEvent(el, target)
{
    function switchit()
    {
        switchKubus("white", kubus);
    }

    if (el && target)
    {
        // The following Loop could be replaced with a "for" (ggf. IE)
        $$(el).each(function(item)
        {
            item.addEvent('click',
                function(e)
                {
                    switchit.delay(smoothness);

                    e = new Event(e).stop();

                    fadeOut(topel);

                    function fn()
                    {
                        if(item.getProperty('id'))
                        {
                            getMedia(item.getProperty('id').replace("lid_", ""))
                        }
                        else
                        {
                            $(topel).empty();
                        }
                        fadeIn(topel);
                    }
                    fn.delay(smoothness);

                    // Set Active-Link Class
                    $$('a').each(function(item) {
                        item.removeClass('active');
                    });
                    item.addClass('active');

                    // get The Content
                    getRemoteHTML(item.getProperty('href'), target);
                }
            );
        });
    }
    else
    {
        return false;
    }
}

/**
description:    handlePage(el) controls some Events.
date:           2008-04-03 | SW
args:           string el
*/
function handlePage(el)
{
    if (el == mainel)
    {
        var element = 'a.' + sidebarclass;
        setEvent(element, 'content');
    }
    if (document.getElementById(listel))
    {
        var sidebarelements = "a."+sidebarclass;
    }
    if (document.getElementById("choose"))
    {
        setFilterEvent("choose");
    }
    if (document.getElementById(contactel))
    {
        new Element('input', {
            'type'  : 'hidden',
            'name'  : 'access',
            'value' : access
        }).injectInside(contactel);

        $(contactel).setProperty('action', '/contact.php');
        setFormEvent(contactel);
    }
    if (document.getElementById('bbar'))
    {
        setPagingEvent(forwardel);
        setPagingEvent(backwardel);
    }
}

/**
description:    setFormEvents(el) sets the Form-Event and submits the data
date:           2008-04-03 | SW
args:           string el
ToDo:           The Form must be processed by a external script :-(
*/
function setFormEvent(el)
{
    $(el).addEvent('submit', function(e) {
        e = new Event(e).stop();
        var error = [];
    
        $$('fieldset').each(function(item, i) {
            var items = item.getChildren();
            
            items.each(function(element, j) {
                if ( ( (element.getTag() == "input") && (element.getProperty('type') == "text") ) || (element.getTag() == "textarea"))
                {
                    element.setProperty( 'name', element.getProperty('id') );

                    if (!element.value)
                    {
                        switchColor( "#ead8d5", element);
                        error[i] = 1;
                    }
                    else
                    {
                        switchColor( "#ffffff", element);
                        // element.removeClass('inputerror');
                    }
                }
            });
        });

        if (error.length == 0)
        {
             this.send({
                 update: $(contentel)
             });
        }
    });
}

function getPaging(url) {
    getRemoteJson( url ).addEvent('onComplete', function(items) {
       $(channelel).empty();
       
       // Building the List-Links
       items.childs.each(function(item, i) {
           buildSideBarLink(item.id, item.title, item.alias);
       });

       setPaging(items);
       fadeIn(channelel);
       setEvent("a." + sidebarclass, 'content');
   });
}

/**
description:    setPaging(items) creates (if needed) the Backward Link and implements the Paging-Logic
date:           2008-04-07 | SW
args:           string items
*/
function setPaging(items)
{
    var actual      = parseInt(items.page);
    var max         = Math.ceil( parseInt(items.count) / pageflip - 1);
    var filter      = $('choose').value;

    // Backward-Link, including Creation if not exists
    if (actual >= 1) {
        if (!document.getElementById(backwardel))
        // Create the Backward-Link, if not existing
        {
            var backward = $('bbar_left');
            new Element("a", {
                'id': backwardel,
                'class': 'bbar_link',
                'href': '?f=' + filter + '&p=' + (actual - 1)
            }).setHTML( (actual) + "/" + (max + 1)).injectInside(backward);
            setPagingEvent(backwardel);
        }
        else
        // Set Styles, href and Text of the "new" Paging-Link
        {
            fadeIn(backwardel);
            $(backwardel).setProperty('href', '?f=' + filter + '&p=' + (actual - 1));
            $(backwardel).setHTML( (actual) + "/" + (max + 1));
        }
    }
    else
    {
        if ( document.getElementById(backwardel))
        // fade Out the Element, if the first Page appears
        {
            fadeOut(backwardel);
        }           
    }

    if ((actual + 1) <= max) {
        fadeIn(forwardel);
        $(forwardel).setHTML( (actual + 2) + "/" + (max + 1));
        $(forwardel).setProperty( 'href', '?f=' + filter + '&p=' + (actual + 1));
    } else {
        fadeOut(forwardel);
    }
}

/**
description:    setPagingEvent(el) sets the Event of the Paging Links
date:           2008-04-07 | SW
args:           string el
*/
function setPagingEvent(el) {
    if (document.getElementById(el))
    {
        $(el).addEvent('click', function(e) {
            e = new Event(e).stop();

            fadeOut(listel);

            function fn()
            {
                getPaging(jsontreeurl + $(el).getProperty( 'href' ));
            }
            fn.delay(smoothness);
        });
    }
}

/**
description:    setFilterEvent(el) sets the Event of Channel Filter
date:           2008-04-04 | SW
args:           string el
*/
function setFilterEvent(el)
{
    $(el).addEvent('change', function (e) {
        fadeOut('bbar');
        e = new Event(e).stop();
        getChannel($(el).value);
    });
}

/**
description:    fadeOut(element) fades out the given Element
date:           2008-04-03 | SW
args:           string el
*/
function fadeOut(element)
{
    var fadeout = new Fx.Styles(element, {
        duration: smoothness
    });

    fadeout.start({
        'opacity': 0
    });
}

/**
description:    fadeIn(element) fades in the given Element
date:           2008-04-03 | SW
args:           string el
*/
function fadeIn(element)
{
    var fadein = new Fx.Styles(element, {
        duration: smoothness
    });

    fadein.start({
        'opacity': 1
    });
}

/**
Description:    rollIn(element) rolls in an Element with zero-opacity and a setted margin-top
Date:           2008-04-04 | SW
args:           string element
*/
function rollIn(element)
{
    var rollin = new Fx.Styles(element, {
        duration: smoothness
    });
    
    rollin.start({
        'opacity': 1,
        'margin-top': 0
    });    
}

/**
Description:    rollOut(element) rolls out the given Element to bottom
Date:           2008-04-04 | SW
args:           string element
*/
function rollOut(element)
{
    var rollout = new Fx.Styles(element, {
        duration: smoothness
    });
    
    rollout.start({
        'opacity': 0,
        'margin-top': 50
    });
}

/**
Description:    appearList(el) will fadeIn every element of el
Date:           2008-04-04 | SW
args:           string el
*/
function appearList(el)
{
    var timer = 0;
    var showfx = [];
    
    function appear() {
        $$(el).each(function(item, i)
        {
            timer += timingvalue;
            showfx[i] = new Fx.Styles(item, {
                duration: smoothness
            });

            function showit() {
                showfx[i].start({
                    'opacity': 1
                });
            }
            showit.delay(timer+100);
        });
    }
    appear.delay(smoothness);
}