
/**
 * Copyright (c) 2008: Booreiland. All rights reserved.
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * This code was lovingly handcrafted by our mighty staff.
 */

function init()
{
    if ($('formInput')) {
        Form.focusFirstElement('formInput');
    }

    setTitles();
    fadeMessage.delay(6);
    preprocessUpload();

    new Slideshow().start();
}

function contact(name)
{
    var domain = window.location.host;
    if (domain.substr(0, 4) == 'www.') {
        domain = domain.substr(4); // Remove name
    }
    var position = domain.lastIndexOf(':');
    if (position != -1) {
        domain = domain.substr(0, position); // Remove port
    }
    var mailto = [109, 97, 105, 108, 116, 111, 58];
    var address = '';
    for (var i = 0; i < mailto.length; ++i){
        address += String.fromCharCode(mailto[i]);
    }
    address += name + String.fromCharCode(8 * 8) + domain;
    window.location.replace(address);

    return false;
}

function feedback()
{
    return contact('feedback');
}

function helpdesk()
{
    return contact('helpdesk');
}

function info()
{
    return contact('info');
}

function abuse()
{
    return contact('abuse');
}

function preprocessUpload()
{
    if (Prototype.Browser.WebKit) {
        var fields = $$('input.upload');
        var size = fields.length;
        for (var i = 0; i < size; ++i) {
            fields[i].style.color = '#fff';
        }
    }
}

function fadeMessage()
{
    var messages = $$('p.info');
    if (messages && messages.length == 1) {
        Effect.Fade(messages[0], {duration: .5});
    }
}

function search()
{
    var form = document.getElementById('formSearch');

    // Store the form's values
    var params = $H();
    params.set('query', form.query.value);

    // Assemble the URL and redirect
    var url = Url.join(form.action, Url.toQueryParams(params));
    Url.redirect(url);

    return false;
}

function setTitle(id, width, text)
{
    swfobject.embedSWF(
        Url.getBase() + 'swf/site/headline.swf',
        id,
        width, '22',
        '9.0.1',
        Url.getBase() + 'swf/site/expressInstall.swf',
        {text: text},
        {wmode: 'transparent'}
    );
}

function setTitles()
{
    var titles = $$('h2.title').concat($$('h2.titleLong')).concat($$('h2.titleMedium')).concat($$('h2.titleShort'));
    var size = titles.length;

    for (var i = 0; i < size; ++i) {
        var element = titles[i];
        if (!element.id) {
            element.id = 'title_' + i;
        }
        var text = element.firstChild.data;

        var width = 320; // Default
        if (element.className == 'titleLong') {
            width = 750;
        } else if (element.className == 'titleMedium') {
            width = 406;
        } else if (element.className == 'titleShort') {
            width = 200;
        }
        setTitle(element.id, width, text);
    }
}

function toggleFaq(link)
{
    var section = link.parentNode.parentNode;
    var parts = section.getElementsByTagName('p');

    var question = parts[0];
    var answer = parts[1];

    var src = Url.getBase() + 'images/site/misc/';
    if (!Element.visible(answer)) {
        src += 'faqArrowDown.gif';
    } else {
        src += 'faqArrowRight.gif';
    }
    question.style.backgroundImage = 'url("' + src + '")';

    Element.toggle(answer);
}

Event.observe(window, 'load', init);

// --------------------------------------------------

var Url = Class.create();

Url.base = null;

Url.getBase = function()
{
    if (Url.base != null) {
        return Url.base;
    }
    var head = document.getElementsByTagName('head')[0];
    var scripts = head.getElementsByTagName('script');

    // Find the base href, e.g. "http://www.example.com/subdir"
    var base = null;
    var size = scripts.length;
    for (var i = 0; i < size; ++i) {
        var name = scripts[i].src;
        var position = name.indexOf('js/site/scripts.js');
        if (position != -1) {
            base = name.substr(0, position);
            break; // Got it; now get out
        }
    }
    return (Url.base = base || Url.getHost()); // Fallback
}

Url.getHost = function()
{
    // E.g. "http://www.example.com"
    return window.location.protocol + '//' + window.location.host;
}

Url.getBasePath = function()
{
    // Find the base path, e.g. "/admin"
    var url = Url.getBase();
    if (url.startsWith(Url.getHost())) {
        url = url.substr(Url.getHost().length);
    }
    if (!url.startsWith('/')) {
        url = '/' + url;
    }
    return url;
}

Url.redirect = function(url)
{
    window.location.href = url;
}

Url.join = function(/* ... */)
{
    var path = [];
    var size = arguments.length;
    for (var i = 0; i < size; ++i) {
        var value = arguments[i];

        // Trim leading and trailing slashes
        value = value.replace(/^\/+/, '');
        value = value.replace(/\/+$/, '');

        if (value.length) {
            path.push(value); // Keep non-empty
        }
    }

    // Create the path; prepend slash if needed
    path = path.join('/');
    if (!path.startsWith('http://') && !path.startsWith('/')) {
        path = '/' + path;
    }
    return path;
}

Url.encode = function(value)
{
    value = value.replace(/\\|\//g, ''); // Remove slashes
    value = encodeURIComponent(value);

    return value;
}

Url.toQueryParams = function(params)
{
    var args = [];
    params.each(function(pair) {
        var key = Url.encode(pair.key);
        var value = Url.encode(pair.value);

        if (key.length && value.length) {
            args.push(key + '/' + value); // Keep non-empty
        }
    });
    return args.join('/');
}

// --------------------------------------------------

var Slideshow = Class.create({

    initialize: function()
    {
    },

    start: function()
    {
        if (!Slideshow.url || !Slideshow.size) {
            return;
        }

        // Fix prefix, if necessary
        if (!window.location.host.startsWith('www.') &&
             Slideshow.url.startsWith('http://www.')) {
                Slideshow.url = 'http://' + Slideshow.url.substr(11);
        }

        if (swfobject.hasFlashPlayerVersion('9.0.1')) {
            swfobject.embedSWF(
                Url.getBase() + 'swf/site/monoslideshow.swf',
                'slideshow',
                Slideshow.size, Slideshow.size,
                '9.0.1',
                '',
                {dataFile: Slideshow.url},
                {base: Url.getBasePath() + 'swf/site', bgcolor: '#090705'}
            );
            return; // Has Flash!
        }

        this.entries = [];
        this.index = 0;
        this.timer = null;
        this.loader = this.onLoad.bindAsEventListener(this);
        this.title = '';
        this.description = '';
        this.image = new Image();
        Event.observe(this.image, 'load', this.loader);

        this.reload();
    },

    stop: function()
    {
        Event.stopObserving(this.image, 'load', this.loader);
        if (this.timer) {
            window.clearTimeout(this.timer);
        }
    },

    parseData: function(transport)
    {
        var entries = [];
        var images = transport.responseXML.getElementsByTagName('image');
        for (var i = 0; i < images.length; ++i) {
            var source = images[i].getAttribute('source');
            var title = images[i].getAttribute('title');
            var description = images[i].getAttribute('description');

            entries.push([source, title, description]);
        }
        this.entries = entries;
        this.index = 0;
        this.next();
    },

    reload: function()
    {
        new Ajax.Request(Slideshow.url, {
            method: 'get',
            onSuccess: this.parseData.bindAsEventListener(this),
            onFailure: this.stop.bindAsEventListener(this)
        });
    },

    next: function()
    {
        if (this.entries.length == 0) {
            this.stop();
            return;
        } else if (this.index >= this.entries.length) {
            this.index = 0;
        }
        this.image.src = this.entries[this.index][0];
        this.title = this.entries[this.index][1];
        this.description = this.entries[this.index][2];
        this.index++;
    },

    onLoad: function()
    {
        if (this.timer) {
            window.clearTimeout(this.timer);
        }
        var slideshow = $('slideshow');
        var photoTitle = $('photoTitle');
        var photoDescription = $('photoDescription');

        slideshow.style.background = 'url(' + this.image.src + ') center';

        if (!this.title) { // May be null
            photoTitle.style.visibility = 'hidden';
            photoTitle.update('');
        } else {
            photoTitle.style.visibility = 'visible';
            photoTitle.update(this.title);
        }

        if (!this.description) { // May be null
            photoDescription.style.visibility = 'hidden';
            photoDescription.update('');
        } else {
            photoDescription.style.visibility = 'visible';
            photoDescription.update(this.description);
        }

        this.timer = window.setTimeout(this.next.bind(this), 4000);
    }

});

Slideshow.url = null;
Slideshow.size = null;
