// If we have an Ajax hash link, redirect to the real page
if (window.location.hash[1] == '/') {
    window.location = window.location.hash.substr(1);
}

/** This implementation was copied from
 ** http://garbageburrito.com/blog/entry/555/slideshow-clearing-all-javascript-timers
 **/
var timers = new Array();
var oldSetTimeout = window.setTimeout;
window.setTimeout = function(code, interval) {
    timers.push(oldSetTimeout(code, interval));
}

function resetTimeouts() {
    timers = new Array();
}

function clearTimeouts() {
    for (var i = 0; i < timers.length; i++) {
        clearTimeout(timers[i]);
    }
    resetTimeouts();
}


var FiveStreet = {
    videoPlayList: [
        /*
         please update jquery.jcarousel.skin.css#40
         width = num items * 110px
         */
        { url: '5street_512x288_kesaspotti.flv', title: '<span>Kesäspotti</span>'},
        { url: 'Ghetto.flv',        title: "<span>Koululla</span>" },
        //<span class=\"date\">12.3.2010</span>
        { url: 'Hidas_tanssi.flv',  title: "<span>Tanssilattialla</span>" },
        { url: 'Romanssi.flv',      title: "<span>Kaksistaan</span>" },
        { url: 'Skottimekkotanssi.flv', title: "<span>Vauhdikkaasti</span>" },
        { url: 'Vaatteet.flv',      title: "<span>Valintoja</span>" }
    ],

    prettifySubmitButtons:
            function(root) {
                root.find('form.formtastic input[type=submit]').each(FiveStreet.prettifySubmitButton);
            },

    prettifySubmitButton: function() {
        var target = $(this);
        target.clone().attr('id', target.attr('id') + '_hover')
                .css('background-image', target.css('background-image').replace('.png', '_hover.png'))
                .css('opacity', 0).css('position', 'absolute').css('top', target.position().top)
                .css('left', target.position().left).css('z-index', -10).insertAfter(target);
        target.hover(function(e) {
            $(e.target).fadeTo('slow', 0).next().fadeTo('slow', 1);
            e.preventDefault();
        }, function(e) {
            $(e.target).fadeTo('slow', 1).next().fadeTo('slow', 0);
            e.preventDefault();
        });
    },

    prepareCarousels: function() {
        /**
         * we need to clear timeouts
         * because we are loading content via AJAX
         * and it causes unwanted behavior
         * when going from Shop to Front
         * as they both have autoscrolls
         */
        clearTimeouts();
        $('.musicScrollable').scrollable({
            size: 1,
            circular: true,
            clickable: false,
            onSeek: function() {
                var band = $(this.getItems()[this.getIndex()]);//getVisibleItems();
                var a = $('p.storeLink a');
                var img = band.find('img');
                var href = img.closest('a').attr('href');
                if (href) {
                    a.attr('href', href);
                } else {
                    a.removeAttr('href');
                }
                a.html($.trim(img.attr('alt')));
            }
        }).autoscroll(5000);

        $('.shopScrollable').scrollable({
            size: 1,
            circular: true,
            clickable: false
        }).autoscroll(5000);

    },

    renderFromJson: function(data) {
        if (data.flash) {
            FiveStreet.undimContent();
            alert(data.flash);
        }

        // We want to flash before redirecting
        if (data.location) {
            window.location = data.location
        }

        if (data.location || data.flash) {
            return;
        }

        pageTracker._trackPageview(this.url);

        // If user registers...
        if (this.url == '/2' && !data.errors && this.type == 'POST') {
            OmnsendPage('5street  Rekisteröityminen');
        }

        if (data.errors) {
            FiveStreet.undimContent();
            FiveStreet.displayRemoteErrors(data.errors);
            return;
        }

        document.title = data.title + ' : 5Street';
        $('#areaLeft').html(data.html.body);
        $('#areaRight').html(data.html.sidebar);
        $('body').attr('id', data.body_id);
        eval(data.callback);

        $('#naviTop li.active').removeClass('active');
        if (this.url === '/') {
            $('#naviTop li a[href=/]').closest('li').addClass('active');
        } else {
            $('#naviTop li a[href^=/' + this.url.split('/')[1] + ']').closest('li').addClass('active');
        }

        FiveStreet.prepareCarousels();

        $('#bannerTop').html($('<iframe border="0" frameborder="0"></iframe>')
                .attr('src', '/banners/bannerTop' + (data.body_id === 'front_index' ? 'Front' : '') + '.html'));

        //FiveStreet.prettifySubmitButtons($('#areaContent'));

        var anchor = this.url.split('--')[1];
        if (anchor) {
            FiveStreet.scrollTo(anchor);
        }

        FiveStreet.undimContent();
    },

    displayRemoteErrors: function(errors) {
        $.each(errors, function(model, errors_in_model) {
            var input;
            $('form.formtastic.' + model).removeClass('new').find('li.error').removeClass('error')
                    .find('p.inline-errors').html('');
            $.each(errors_in_model, function(i, error) {
                var field = error[0].split('.');
                if (field.length > 1) {
                    // For fields_for and accepts_nested_attributes_for
                    input = $('#' + model + '_' + field[0] + '_attributes_' + field[1] + '_input');
                } else {
                    input = $('#' + model + '_' + field + '_input');
                }
                input.addClass('error');
                input.find('p.inline-errors').html(error[1]);
                var color = input.css('background-color');

                input.find('input').effect('highlight', { color: '#E84459' }, 2500);
            });
        });
    },

    displayServerError: function(xhr, textStatus, errorThrown) {
        if (xhr.status === 200) {
            return;
        }
        if (xhr.status === 404) {
            window.location = '/400.html';
        } else {
            window.location = '/500.html';
        }
    },

    getJson: function(href) {
        // Everything actually happens int the address change trigger.
        $.address.value(href);
    },

    postJson: function(form) {
        FiveStreet.dimContent();
        $('#naviTop li.active').removeClass('active');
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: form.serialize(),
            dataType: 'json',
            success: FiveStreet.renderFromJson,
            error: FiveStreet.displayServerError,
            beforeSend: function(xhr) {
                xhr.setRequestHeader('Accept', 'application/json');
            }
        });
    },

    dimContent: function() {
        $('#areaContent').fadeTo('fast', 0);
    },

    undimContent: function() {
        $('#areaContent').fadeTo('fast', 1);
    },

    scrollTo: function(anchor) {
        if (anchor[0] !== '#') {
            anchor = '#' + anchor;
        }
        $('html, body').animate({ scrollTop: $(anchor).offset().top }, 'slow');
    },

    // Ugly hack to prevent instant redirection when entering page.
    skipPageLoad: true
}

$(document).ready(function() {
    $('a[href^=http://][href*=5street][href*=downloader][href$=.exe]').live('click', function(e) {
        pageTracker._trackPageview($('a[href^=http://][href*=5street][href*=downloader][href$=.exe]').attr('href').split('/').pop());
        OmnsendPage('5street  Pelin lataus');
    });

    $('a[rel^=popup]').live('click', function(e) {
        var a = $(e.target).closest('a');
        var options = a.attr('rel').split('|');
        window.open(a.attr('href'), options[1], options[2]);
        e.preventDefault();
    });

    // We only want to use magical JavaScript navigation for non-logged in users
    if (!$('body').hasClass('loggedIn')) {

        $.address.change(function(e) {
            if (FiveStreet.skipPageLoad) {
                FiveStreet.skipPageLoad = false;
                return;
            }
            FiveStreet.dimContent();
            $.ajax({
                type: 'GET',
                url: e.path,
                dataType: 'json',
                success: FiveStreet.renderFromJson,
                error: FiveStreet.displayServerError,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('Accept', 'application/json');
                }
            });
        });

        $('#naviTop li').bind('click', function(e) {
            var li = $(e.target).closest('li');
            var href = li.find('a').attr('href');
            $('#naviTop li.active').removeClass('active');
            li.addClass('active');
            FiveStreet.getJson(href, true);
            e.stopPropagation();
            e.preventDefault();
        });

        $('a:not([href^=http://]):not([target=_blank]):not(:not([href]))').live('click', function(e) {
            if ($(e.target).closest('#naviTop').length) {
                return;
            }
            e.preventDefault();
            var a = $(e.target).closest('a');

            if (a.attr('rel') !== '') {
                if (a.closest('div').attr('id') !== 'areaLeft' && !a.hasClass('back')) {
                    FiveStreet.skipPageLoad = true;
                    return;
                }
            }

            if (a.attr('href')[0] === '#') {
                FiveStreet.scrollTo(a.attr('href'));
                return;
            }

            FiveStreet.getJson(a.attr('href').replace('#', '--')); // We don't want multiple #'s in the URL
        });

        $('form').live('submit', function(e) {
            var form = $(e.target).closest('form');
            if (form.attr('action').substr(0, window.location.protocol.length) === window.location.protocol || form.hasClass('nojax')) {
                return;
            }
            e.preventDefault();
            FiveStreet.skipPageLoad = true;
            FiveStreet.postJson(form);
        });
    }

    FiveStreet.prepareCarousels();
    //FiveStreet.prettifySubmitButtons($('body'));
});
