/* Modernizr custom build of 1.7: csstransitions | hashchange | history */
;window.Modernizr=function(a,b,c){function G(){}function F(a,b){var c=a.charAt(0).toUpperCase()+a.substr(1),d=(a+" "+p.join(c+" ")+c).split(" ");return!!E(d,b)}function E(a,b){for(var d in a)if(k[a[d]]!==c&&(!b||b(a[d],j)))return!0}function D(a,b){return(""+a).indexOf(b)!==-1}function C(a,b){return typeof a===b}function B(a,b){return A(o.join(a+";")+(b||""))}function A(a){k.cssText=a}var d="1.7",e={},f=!0,g=b.documentElement,h=b.head||b.getElementsByTagName("head")[0],i="modernizr",j=b.createElement(i),k=j.style,l=b.createElement("input"),m=":)",n=Object.prototype.toString,o=" -webkit- -moz- -o- -ms- -khtml- ".split(" "),p="Webkit Moz O ms Khtml".split(" "),q={svg:"http://www.w3.org/2000/svg"},r={},s={},t={},u=[],v,w=function(a){var c=b.createElement("style"),d=b.createElement("div"),e;c.textContent=a+"{#modernizr{height:3px}}",h.appendChild(c),d.id="modernizr",g.appendChild(d),e=d.offsetHeight===3,c.parentNode.removeChild(c),d.parentNode.removeChild(d);return!!e},x=function(){function d(d,e){e=e||b.createElement(a[d]||"div");var f=(d="on"+d)in e;f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=C(e[d],"function"),C(e[d],c)||(e[d]=c),e.removeAttribute(d))),e=null;return f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),y=({}).hasOwnProperty,z;C(y,c)||C(y.call,c)?z=function(a,b){return b in a&&C(a.constructor.prototype[b],c)}:z=function(a,b){return y.call(a,b)},r.hashchange=function(){return x("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},r.history=function(){return !!(a.history&&history.pushState)},r.csstransitions=function(){return F("transitionProperty")};for(var H in r)z(r,H)&&(v=H.toLowerCase(),e[v]=r[H](),u.push((e[v]?"":"no-")+v));e.input||G(),e.crosswindowmessaging=e.postmessage,e.historymanagement=e.history,e.addTest=function(a,b){a=a.toLowerCase();if(!e[a]){b=!!b(),g.className+=" "+(b?"":"no-")+a,e[a]=b;return e}},A(""),j=l=null,e._enableHTML5=f,e._version=d,g.className=g.className.replace(/\bno-js\b/,"")+" js "+u.join(" ");return e}(this,this.document);


function go(href) { window.location.href = href; }

function init_tabindex() {
    var tabindex = 0,
        setindex = function() { this.setAttribute('tabindex', ++tabindex); };

    $('fieldset').each(function() {
        var $this = $(this),
            $elems = $this.find('input, select, textarea');

        if ($this.hasClass('vertical')) {
            $elems.filter(':even').each(setindex);
            $elems.filter(':odd').each(setindex);
        } else {
            $elems.each(setindex);
        }
    });
}

// TODO use something else
var el = document.getElementsByTagName('html')[0];
var supports = {
    hashchange: el.className.indexOf('no-hashchange') == -1,
    history: el.className.indexOf('no-history') == -1,
    transitions: el.className.indexOf('no-csstransitions') == -1
    };

var FH = {
    on_document_ready: function () {

        var $slides = $('.slides');
        var moodboard_cfg = {
            slide_time: 3500,
            controls: false,
            _init_controls: function($mb, data) {
                // call default implementation
                //$.fn.moodboard.defaults._init_controls($mb, data);

                var $toc = $('<div class="toc">');
                for (var i=data.count - 1; i >= 0; i--) {
                    $toc.append('<a rel="s' + i + '">' + (i + 1) + '</a>');
                }

                $toc.appendTo($mb).find('a[rel=s0]').addClass('current');
                $mb.delegate('.toc a', 'click', (function($mb, data) {
                    return function() {
                        $mb.find('.toc a').removeClass('current');
                        $mb.moodboard('jump', parseInt(this.rel.substr(1)));
                    };
                })($mb, data));
            },
            _reveal: function($mb, data, newidx) {
                $.fn.moodboard.defaults._reveal($mb, data, newidx);
                $mb.find('.toc a').removeClass('current').filter('a[rel=s' + newidx + ']').addClass('current');
            }
        };

        if (!supports.transitions) {
            moodboard_cfg._reveal = function($mb, data, newidx) {
                data.slides[data.current].css({'z-index': 100}).animate({opacity: 0}, 400);
                data.slides[newidx].css({'z-index': 101}).animate({opacity: 1}, 400);
                data.current = newidx;
            };

            // move div behind img, so that missing cleartext support in IE CSS
            // filters does not produce ugly artifacts
            $('.flip span').show().css('z-index', 99);
            $('.flip img').css('position', 'absolute').show().css({
                'z-index': 110,
                'opacity': 0.1
                });

            // hide image instead of revealing colored layer on mouseover
            $('.flip').hover(function() {
                $('img', this).stop(true, true).animate({opacity:1}, 'fast');
            }, function() {
                $('img', this).stop(true, true).animate({opacity:0.1});
            });
        }

        $slides.moodboard(moodboard_cfg);
        // TODO this is really ugly
        if ($slides.find('.slide').length == 1)
            $slides.find('.slide').show().css('opacity', 1);

        if (!supports.transitions) {
            var $controls = $slides.find('.controls');
            $controls.hover(function() {
                $controls.animate({opacity: 0.8}, 300);
            }, function() {
                $controls.animate({opacity: 0}, 300);
            });

            setTimeout(function() { $controls.animate({opacity: 0}, 300); }, 1000);
        }
    }
}


function str_repeat(input, multiplier) {
    return new Array(multiplier + 1).join(input);
}

var Voting = {
    submit: function() {
        var $form = $('#vote'),
            $input = $form.find('#id_vote_query');

        $.getJSON(window.bosg_voting.search, {term: $input.val()}, function(data) {
            if (data.length == 1) {
                Voting.open(window.bosg_voting.base + 'vote/' + data[0].id + '/');
            } else if (data.length == 0) {
                alert('Wir konnten zu deiner Angabe leider nichts finden. \nVersuch es bitte noch einmal.');
            } else {
                window.location.href = '/guide/?query=' + $input.val();
            }
        });
        return false;
    },

    open: function(url) {
        $.colorbox({
            href: url,
            opacity: 0.5,
            onComplete: Voting.init_form,
            scrolling: false
            });
    },

    init_form: function() {
        $('#votingform').bind('submit', function() {
            $.post(this.action, $(this).serialize(), function (data, textStatus, jqXHR) {
                $.colorbox({
                    html: data,
                    opacity: 0.5,
                    onComplete: Voting.init_form,
                    scrolling: false
                    });
                Voting.init_form();
            });
            return false;
        });

        $('#votingform button[value]').bind('click', function() {
            var $form = $('#votingform'),
                data = $form.serialize() + '&clicked=' + this.value;

            var handler = function() {
                $.post($form.attr('action'), data, function (data, textStatus, jqXHR) {
                    $.colorbox({
                        html: data,
                        opacity: 0.5,
                        onComplete: Voting.init_form,
                        scrolling: false
                        });
                    Voting.init_form();
                });
                return false;
            }

            handler();
            return false;
        });

        var count = 6;
        $('#votingform input[name=score]').not('.processed').addClass('processed').each(function() {
            $(this).after(str_repeat('<span>+</span>', count));
            count--;
        });

        $('#votingform .detailscore').each(function() {
            var $this = $(this),
                $inputs = $this.find('label:gt(0)');

            // show value which might be already there
            $inputs.find('input:checked').parent().addClass('selected').prevAll().addClass('selected');

            $inputs.hover(function() {
                $(this).addClass('hovered').prevAll().addClass('hovered');
            }, function() {
                $(this).removeClass('hovered').prevAll().removeClass('hovered');
            }).bind('mousedown', function() {
                $(this).find('input').trigger('click').end().addClass('selected').prevAll().addClass('selected').end().nextAll().removeClass('selected');
                return false;
            });
        });
    }
};


$(function() {
    FH.on_document_ready();


    $('#vote form').bind('submit', Voting.submit);
    $('#vote #id_vote_query').autocomplete({
        source: window.bosg_voting.locations,
        select: function(event, ui) {
            $('#vote #id_vote_query').val(ui.item.value);
            Voting.submit();
        },
        autoFocus: true
    });

    if ('placeholder' in document.createElement('input'))
        $('#loginform label').css('visibility', 'hidden');
});



function reload_css(filename) {
    var l = document.getElementsByTagName('link');
    for (var i = 0; i < l.length; i++) {
        var ss = l[i];
        if (ss.href && ss.href.indexOf(filename) != -1) {
            try {
                ss.href = (ss.href.split("?")[0]) + "?" + Math.random();
            } catch (e) {
                console.log(e);
            }
        }
    }
}

