/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(name,value,options){var expires,date,path,domain,secure,cookieValue,cookies,cookie,i;if(typeof value!=='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}if(options.expires&&(typeof options.expires==='number'||options.expires.toUTCString)){if(typeof options.expires==='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}path=options.path?'; path='+(options.path):'';domain=options.domain?'; domain='+(options.domain):'';secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{cookieValue=null;if(document.cookie&&document.cookie!==''){cookies=document.cookie.split(';');for(i=0;i<cookies.length;i++){cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)===(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

$(function(){
    $("#mainContent :header:first").css("marginTop", "0px");
    $('#searchInput').click(function(){
        $(this).attr('value', '');
    });
    //$('#editMode ul.navLevel1 li:last').remove();
    $('.navLevel2 li:last').css('background', 'none transparent');
});

function animateLayer (id, height) {
    $("#" + id).animate({"height": height}, 300);
}

function toggleForm () {
    var obj = arguments[0];
    var pos = obj.curPos;
    var curId = obj.curId;
    var height = "0px";
    var messagesHeight = "0px";
    if (arguments.length > 1) {
        for (i = 0; i < obj.ids.length; i++) {
            if (obj.layerIsOpen[i]) {
                animateLayer(obj.layerIds[i], "0px");
            }
            if (arguments[1] === obj.triggerIds[i]) {
                pos = i;
                obj.curPos = i;
            }
        }
    }
    if (obj.layerIsOpen[pos]) {
        obj.layerIsOpen[pos] = false;
        if (obj.success) {
            $("#" + obj.successIds[pos]).css({"display": "block"});
            $("#" + obj.errorIds[pos]).css({"display": "none"});
            messagesHeight = obj.successHeights[pos];
            obj.success = false;
            window.setTimeout("animateLayer('" + obj.messageIds[pos] + "', '0px')", 3000);
        }
        else if (obj.error) {
            obj.layerIsOpen[pos] = true;
            $("#" + obj.successIds[pos]).css({"display": "none"});
            $("#" + obj.errorIds[pos]).css({"display": "block"});
            messagesHeight = obj.errorHeights[pos];
            height = $("#" + obj.layerIds[pos]).height() + "px";
        }
    } else {
        height = $("#" + obj.formIds[pos]).height() + "px";
        obj.layerIsOpen[pos] = true;
    }
    $("#" + obj.messageIds[pos]).animate({"height": messagesHeight}, 300)
    $("#" + obj.layerIds[pos]).animate({"height": height}, 300);
}

function swapViews (triggerId) {
    var obj = iw.swapView;
    var groupPos = 0;
    var pos = 0;
    function getPositions(i){
        for (j = 0; j < obj.triggerIds[i].length; j++) {
            if (triggerId === obj.triggerIds[i][j]) {
                groupPos = i;
                pos = j;
            }
        }
    }
    for (i = 0; i < obj.triggerIds.length; i++) {
        getPositions(i);
    }
    var layerIds = obj.layerIds[groupPos];
    var layerStates = obj.layerStates[groupPos];
    var layerHeights = obj.layerHeights[groupPos];
    var triggerLayerId = obj.layerIds[groupPos][pos];
    var triggerLayerState = obj.layerStates[groupPos][pos];
    for (i = 0; i < layerStates.length; i++) {
        if (layerStates[i]) {
            layerStates[i] = false;
            animateLayer(layerIds[i], "0px");
        }
        if (i === layerStates.length - 1) {
            if (!triggerLayerState) {
                layerStates[pos] = true;
                window.setTimeout("animateLayer('" + triggerLayerId + "', '" + obj.layerHeights[groupPos][pos] + "')", 300);
            }
        }
    }
}

function injectTrigger (obj) {
    var img;
    for (i = 0; i < obj.ids.length; i++) {
        img = obj.triggerImages[i];
        if (obj.types[i] === "isComment") {
            $("#" + obj.layerIds[i]).parent().prevAll("div.section:first").addClass("commentMeta").append(img);
        }
        else {
            $(img).addClass("noComment");
            $("#" + obj.layerIds[i]).parent().prevAll("div.section:first").addClass("noComment").append(img);
        }
    }
}

var iw = {
    "debug": true,
    "path2Layout": "",
    "init": function () {
        $(function(){
            iw.inputButtonReplace.init();
            iw.swapView.init();
            iw.reportingForm.init();
            iw.user.init();
            iw.tagForm.init();
            iw.header.init();
            iw.cookie.init();
        });
    },
    "cookie": {
        "init": function () {
            if (!$.cookie('loggedIn')) {
                this.setValue('false');
            }
            else if ($.cookie('loggedIn') && (!iw.user.isUser)) {
                this.setValue('false');
            }
        },
        "setValue": function (value) {
            $.cookie('loggedIn', value, {path: '/'});
        }
    },
    "inputButtonReplace": {
        "type": "image",
        "layerIds": [],
        "imageNames": [],
        "inputNames": [],
        "inputValues": [],
        "addLayerId": function (val) {
            this.addValue(val, this.layerIds);
        },
        "addImageName": function (val) {
            this.addValue(val, this.imageNames);
        },
        "addInputName": function (val) {
            this.addValue(val, this.inputNames);
        },
        "addInputValue": function (val) {
            this.addValue(val, this.inputValues);
        },
        "addValue": function (val, type) {
            for (i = 0; i < val.length; i++) {
                type.push(val[i]);
            }
        },
        "init": function () {
            for (i = 0; i < this.layerIds.length; i++) {
                if (this.type === "image") {
                    var newButton = "<input type='image' src='" + iw.path2Layout + this.imageNames[i] + "' name='" + this.inputNames[i] + "' value='" + this.inputValues[i] + "' />";
                    $(this.layerIds[i]).
                        find("input:submit").
                        remove().
                        end().
                        append(newButton);
                }
                else{

                }
            }
        },
        "reset": function () {
            this.layerIds = [];
            this.imageNames = [];
        }
    },
    "reportingForm": {
        "ids": [],
        "triggerIds": [],
        "layerIds": [],
        "messageIds": [],
        "layerIsOpen": [],
        "errorIds": [],
        "errorHeights": [],
        "successIds": [],
        "successHeights": [],
        "formIds": [],
        "types": [],
        "triggerImages": [],
        "curPos": 0,
        "error": false,
        "success": false,
        "addId": function (id) {
            this.ids.push(id);
        },
        "init": function () {
            for (i = 0; i < this.ids.length; i++) {
                this.layerIsOpen.push(false);
                this.layerIds.push("formLayer" + this.ids[i]);
                if ($("#" + this.layerIds[this.layerIds.length-1]).hasClass("isComment")) {
                    this.types.push("isComment");
                }
                else {
                    this.types.push("noComment");
                }
                this.triggerIds.push("trigger" + this.ids[i]);
                var img = new Image;
                img.src = "/_media/themes/1/layout/buttonReportSomething.gif";
                $(img).attr({"id": iw.reportingForm.triggerIds[i], "class": "reportSomething"});
                this.triggerImages.push(img);
                this.messageIds.push("messageLayer" + this.ids[i]);
                this.errorIds.push("error" + this.ids[i]);
                this.errorHeights.push($("#" + this.errorIds[this.errorIds.length-1]).height() + "px");
                this.successIds.push("success" + this.ids[i]);
                this.successHeights.push($("#" + this.successIds[this.successIds.length-1]).height() + "px");
                this.formIds.push("form" + this.ids[i]);
            }
            for (i = 0; i < this.ids.length; i++) {
                $("#" + this.layerIds[i]).css({"height": "0px"});
                $("#" + this.messageIds[i]).css({"height": "0px"});
                $("#" + this.triggerIds[i]).live("click", function (e) {
                    toggleForm(iw.reportingForm, e.target.id);
                });
            }
            injectTrigger(iw.reportingForm);
        },
        "update": function () {
            toggleForm(iw.reportingForm);
        }
    },
    "swapView": {
        "layerStates": [],
        "layerIds": [],
        "layerHeights": [],
        "triggerIds": [],
        "addLayerIds": function (ids) {
            var tmp = [];
            this.layerIds.push(ids);
            for (i = 0; i < ids.length; i++) {
                tmp.push(false);
            }
            this.layerStates.push(tmp);
        },
        "addTriggerIds": function (id) {
            this.triggerIds.push(id);
        },
        "init": function () {
            // hier event binden
            for (i = 0; i < this.triggerIds.length; i++) {
                var tmp = []
                for (j = 0; j < this.triggerIds[i].length; j++) {
                    $("#" + this.triggerIds[i][j]).bind("click", function (e){
                        swapViews(e.target.id);
                    });
                    tmp.push($("#" + this.layerIds[i][j]).find("form").height() + "px");
                }
                this.layerHeights.push(tmp);
            }
        }
    },
    "player": {
        "wrapperIds": [],
        "controlIds": [],
        "durations": [],
        "type": [],
        "addPlayer": function (arg) {
            this.wrapperIds.push(arg[0]);
            this.controlIds.push(arg[1]);
            this.durations.push(arg[2]);
            this.type.push(arg[3]);
        },
        "init": function () {
            for (i = 0; i < this.wrapperIds.length; i++) {
                $f(this.wrapperIds[i], "/_media/base/flash/flowplayer/flowplayer.unlimited-3.2.3.swf", {
                    "plugins": {
                        "controls": null,
                        "audio": {
                            "url": "/_media/base/flash/flowplayer/flowplayer.audio-3.2.1.swf"
                        }
                    },
                    "clip": {
                        "autoPlay": false,
                        "autoBuffering": false,
                        "duration": this.durations[i]
                    }
                }).
                controls(this.controlIds[i], {"duration": this.durations[i]}).
                onStart(function () {console.log('huhu');});
            }
        }
    },
    "tagForm": {
        "ids": [],
        "triggerIds": [],
        "layerIds": [],
        "messageIds": [],
        "layerIsOpen": [],
        "errorIds": [],
        "errorHeights": [],
        "successIds": [],
        "successHeights": [],
        "formIds": [],
        "curPos": 0,
        "error": false,
        "success": false,
        "addId": function (id) {
            this.ids.push(id);
        },
        "init": function () {
            for (i = 0; i < this.ids.length; i++) {
                this.layerIsOpen.push(false);
                this.layerIds.push("formLayer" + this.ids[i]);
                this.triggerIds.push("trigger" + this.ids[i]);
                this.messageIds.push("messageLayer" + this.ids[i]);
                this.errorIds.push("error" + this.ids[i]);
                this.errorHeights.push($("#" + this.errorIds[this.errorIds.length-1]).height() + "px");
                this.successIds.push("success" + this.ids[i]);
                this.successHeights.push($("#" + this.successIds[this.successIds.length-1]).height() + "px");
                this.formIds.push("form" + this.ids[i]);
            }
            for (i = 0; i < this.ids.length; i++) {
                $("#" + this.layerIds[i]).css({"height": "0px"});
                $("#" + this.messageIds[i]).css({"height": "0px"});
                $("#" + this.triggerIds[i]).bind("click", function (e) {
                    toggleForm(iw.tagForm, e.target.id);
                });
            }
        },
        "update": function () {
            toggleForm(iw.tagForm);
        }
    },
    "user": {
        "isUser": false,
        "init": function () {
            if (this.isUser) {
                $("#userPanelLogin").remove();
                if ($.cookie('loggedIn') === 'false') {
                    iw.cookie.setValue('true');
                }
            }
        }
    },
    "header": {
        "headerLinkIds": ['#headerLinksMixMit', '#headerLinksEinmischen', '#headerLinksAbmischen', '#headerLinksMitmischen'],
        "headerButtonIds": ['#headerButtonRegister', '#headerButtonForum', '#headerButtonMitmischen', '#headerButtonMitmischen2'],
        "fadeLayerIds": ["#headerFadeLayer0", "#headerFadeLayer1", "#headerFadeLayer2", "#headerFadeLayer3"],
        "curFadeLayerPos": 0,
        "fadeHeader": function (pos) {
            if (pos != this.curFadeLayerPos) {
                $(this.headerLinkIds[this.curFadeLayerPos]).toggleClass("active");
                $(this.headerLinkIds[pos]).toggleClass("active");
                $(this.fadeLayerIds[this.curFadeLayerPos]).fadeOut(1000);
                $(this.headerButtonIds[this.curFadeLayerPos]).fadeOut(1000);
                $(this.fadeLayerIds[pos]).fadeIn(1000);
                $(this.headerButtonIds[pos]).fadeIn(1000);
                this.curFadeLayerPos = pos;
            }
        },
        "init": function () {
            if (iw.user.isUser) {
                $("#headerLinkRegister").css("display", "none");
            }
            for (i = 0; i < this.headerLinkIds.length; i++) {
                if (i > 0) {
                    $(this.fadeLayerIds[i]).fadeOut(0);
                    $(this.headerButtonIds[i]).fadeOut(0);
                }
                $(this.headerLinkIds[i]).hover(
                    function(){
                        $(this).toggleClass("hovered");
                    },
                    function(){
                        $(this).toggleClass("hovered");
                    }
                );
                $(this.headerLinkIds[i]).click(function (e) {
                    for (i = 0; i < iw.header.headerLinkIds.length; i++) {
                        if ("#" + e.target.id === iw.header.headerLinkIds[i]) {
                            iw.header.fadeHeader(i);
                        }
                    }
                });
            }
        }
    }
}
$(document).ready(function() {
    var player_active = false;
    if (!iw.user.isUser) {
        $('#userPanel').css('display', 'none');
        $('#userPanelTrigger').attr('class', 'closed');
        $.cookie('panel_status', 'closed');
    }
    if ($.cookie('panel_status') === 'closed') {
        $('#userPanel').css('display', 'none');
        $('#userPanelTrigger').attr('class', 'closed');
    }
    $('#userPanelTrigger, #userPanelTrigger2').click(function () {
        if ($.cookie('panel_status') !== 'closed') {
            $('#userPanel').hide('fast', function () {$('#userPanelTrigger').attr('class', 'closed');});
            $.cookie('panel_status', 'closed');
        }
        else {
            $('#userPanel').show('fast', function () {$('#userPanelTrigger').attr('class', 'open');});
            $.cookie('panel_status', 'open');
        }
        return false;
    });
    if ($.cookie('hide_sequenzer_browser_requirements') === 'true') {
        $('#sequenzer_browser_requirements, #show_sequenzer_browser_requirements').toggleClass('hidden')
    }
    $('#hide_sequenzer_browser_requirements').click(function () {
        $('#sequenzer_browser_requirements, #show_sequenzer_browser_requirements').toggleClass('hidden')
        $.cookie('hide_sequenzer_browser_requirements', 'true', {'expires': 365});
    });

    $('#show_sequenzer_browser_requirements').click(function () {
        $('#sequenzer_browser_requirements, #show_sequenzer_browser_requirements').toggleClass('hidden')
        $.cookie('hide_sequenzer_browser_requirements', 'false', {'expires': 365});
    });

    $('#editTextLayer').
        find('textarea:first').css('height', '50px');

    $('#editTextLayer').
        find('textarea:last').css('height', '200px');

    $('#edit_session').
        click(function(){
        if ($('#session_edit_layer').hasClass('hidden')) {
            $('#session_edit_layer').show();
        }
        else {
            $('#session_edit_layer').hide();
        }
        $('#session_edit_layer').toggleClass('hidden');
    });

    $('#trigger_lb_new_mix').
        fancybox({'hideOnContentClick': false});

    $('#trigger_lb_new_mix').
        click(function () {
            $('#newMixName').attr('value', '');
    });

    $('.trigger_lb_new_mix').
        fancybox({'hideOnContentClick': false});

    $("#feedback").
        click(function(){
            xajax_Cms_getFeedbackForm();
            return false;
        });

    // mix functions in session detail view
    $('.existing_mix').each(function () {
        var mix_id = $(this).attr('id').split('_');
        mix_id = mix_id[mix_id.length - 1];
        if (mix_id === 'new') {
            $('#session_mix_id_' + mix_id + ' .links a').click(function () {
                $('#session_mix_id_' + mix_id + ' form').submit();
            });
        }
        else {
            $('#session_mix_id_' + mix_id + ' .links .start_sequenzer').click(function () {
                window.location.reload();
            });
            $('#editMixData' + mix_id).click(function () {
                var mix_form = '#mixForm' + mix_id;
                if ($(mix_form).hasClass("visible")) {
                    $(mix_form).hide("slow");
                }
                else{
                    $(mix_form).show("slow");
                }
                $(mix_form).toggleClass("visible");
                return false;
            });
            $('#deleteMixData' + mix_id).click(function () {
                if (mk_confirm("Diesen Mix wirklich löschen?")) {
                    $('#session_mix_id_' + mix_id).hide('slow');
                    xajax_Cms_deleteMix(mix_id);
                }
                return false;
            });
        }
    });

    $('.mp3Player').
        each(function () {
            $f($(this).attr('id'), '/_media/base/flash/flowplayer/flowplayer.unlimited-3.2.3.swf', {
                plugins: {
                    controls: {
                        fullscreen: false,
                        autoHide: 'never',
                        height: 34
                    }
                },
                clip: {
                    autoPlay: true
                }
            });
        });

 });


