<html>
    <head>

        <link rel="stylesheet" href="../css/style.css" type="text/css" />

        <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />

        <script type="text/javascript" src="../js/jquery.js"></script>
        <script type="text/javascript" src="../js/jquery-ui.js"></script>
        <script type="text/javascript" src="../js/handlebars.js"></script>
        <script type="text/javascript" src="../js/ember.js"></script>
        <script type="text/javascript" src="../js/common.js"></script>
        <title>Dynamuse</title>
        <style>

            body { overflow: hidden; margin: 0; }

            .tiny-text { font-size: 10px; font-family: sans-serif; font-weight: bold; -webkit-user-select: none;
                text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black }

            .content { width: 750px; height: 600px; webkit-user-select: text; }

            .play_controls {
                float: left;
                margin-left: 20px;
            }

            .ui-state-highlight { height: 1.5em; line-height: 1.2em; }
            .select_group {
                float: left;
                border-style: solid;
                border-radius: 4px;
                border-width: 2px;
                margin: 2px 6px 2px 12px;
                background-color: white;
                max-height: 504px;
            }
            .select_group.flow {
                overflow-x: hidden;
                overflow-y: scroll;
            }

            .select_title { }
            .select_list {
                list-style-type: none;
            }
            .select_option {
                background-color: white;
                border-style: solid;
                border-radius: 4px;
                border-width: 2px;
                margin: 0px 2px 2px -38px;
                position: relative;
                width: 180px;
                height: 70px;
            }
            .select_option.condition {
                width: 240px;
                height: 50px;
            }
            .option_content {
                margin: 4px;
            }

            button.ui-button-icon-only.add_button {
                width: 24px;
            }
            button.ui-button-icon-only.delete_button {
                width: 17px;
                border-radius: 8px;
                position: absolute;
                top: 0px;
                right: 0px;
            }

            .number_field {
                width: 50px;
                text-align: right;
            }

            .number_field.long {
                width: 70px;
            }

            .condition_area {
                list-style: none;
                margin: 0;
                position: relative;
            }
            .condition_select {
                text-decoration: none;
            }
            .compare_text {
                width: 10px;
            }

            .condition_area .subnav {
                list-style: none;
                position: absolute;
                left: 0px;
                top: 20px;
                background: #333;
                margin: 0;
                padding: 0;
                display: none;
                float: left;
                width: 100px;
                border: 1px solid #111;
                z-index: 10;
            }

            .condition_area .subnav li {
                margin: 0;
                padding: 0;
                border-top: 1px solid #252525;
                border-bottom: 1px solid #444;
                clear: both;
                width: 100px;
            }

            .condition_area .subnav li span {
                float: left;
                width: 80px;
                background: #333;
                padding-left: 20px;
                color: #EEE;
            }

            .select_handle {
                margin-right: 3px;
                border-radius: 8px 0 0 8px;
                background-color: blue;
                width: 10px;
                height: 100%;
                float: left;
            }
            .select_handle.selected {
                background-color: green;
            }

            .edit_field {
                width: 100px;
                display: none;
            }
        </style>
    </head>
    <body>

        <div id="dynamuse" class="window" data-handle="Dynamuse">

        <script data-template-name="compose-template" type="text/x-handlebars">
            <div>
                <div style="float:left;">
                    {{#view App.EditField contentBinding="App.dynamuse.track.name"}}
                        <span>{{view.content}}</span>
                        {{view Ember.TextField class="edit_field" valueBinding="view.content"}}
                    {{/view}}
                    <label>
                    {{view Ember.TextField type="number" class="number_field long" valueBinding="App.dynamuse.track.bar"}}
                    Bar Time
                    </label>
                    <button onclick="App.createTrack();">New</button>
                    <button onclick="App.saveTrack();">Save</button>
                    <button onclick="App.loadTrack();">Load</button>
                </div>
                <div class="play_controls">
                    <button onclick="App.playTrack();">{{App.dynamuse.playStopText}}</button>
                    <div>
                        <span>Intensity</span>
                        {{view App.RangeField class="range_field" max="10" valueBinding="App.dynamuse.intensity"}}
                        <span>{{App.dynamuse.intensity}}</span>
                    </div>
                    <div>
                        <span>Daytime</span>
                        {{view App.RangeField class="range_field" max="24" valueBinding="App.dynamuse.daytime"}}
                        <span>{{App.dynamuse.daytime}}</span>
                    </div>
                </div>
                <div style="clear:both;"></div>
            </div>
            <div>
                {{#if App.dynamuse.track}}
                    <div id="samples" class="select_group flow">
                        <span class="select_title">Samples</span>
                        {{view App.AddButton classBinding=":add_button" target="App.dynamuse" action="addSample"}}
                        <ul class="select_list">
                        {{#each sample in App.dynamuse.track.samples}}
                            {{#view App.SampleView contentBinding="sample"}}
                                <li class="select_option">
                                    <button {{bindAttr class="sample.isSelected:selected :select_handle"}} {{action "select"}}>
                                    </button>
                                    <div class="option_content">
                                        {{#view App.EditField contentBinding="sample.name"}}
                                            <span>{{view.content}}</span>
                                            {{view Ember.TextField class="edit_field" valueBinding="view.content"}}
                                        {{/view}}
                                        <span {{action "selectFile" target="sample"}}>{{sample.filename}}</span>
                                        {{#view Ember.Button classBinding=":preview" target="view" action="preview"}}
                                            <label {{bindAttr for="view.elementId"}}></label>
                                        {{/view}}
                                        {{#view Ember.Checkbox classBinding=":solo" checkedBinding="sample.solo"}}
                                            <label {{bindAttr for="view.elementId"}}></label>
                                        {{/view}}
                                        {{#view Ember.Button classBinding=":mute" target="view" action="mute"}}
                                            <label {{bindAttr for="view.elementId"}}></label>
                                        {{/view}}
                                    </div>
                                    {{view Ember.Button classBinding=":delete_button" target="view.content" action="destroy"}}
                                </li>
                            {{/view}}
                        {{/each}}
                        </ul>
                    </div>
                {{/if}}
                {{#if App.dynamuse.sample}}
                    <div id="triggers" class="select_group flow">
                        <span class="select_title">Triggers</span>
                        {{view App.AddButton classBinding=":add_button" target="App.dynamuse" action="addTrigger"}}
                        <ul class="select_list">
                        {{#each trigger in App.dynamuse.sample.triggers}}
                            {{#view App.TriggerView contentBinding="trigger"}}
                                <li class="select_option">
                                    <button {{bindAttr class="trigger.isSelected:selected :select_handle"}} {{action "select"}}>
                                    </button>
                                    <div>
                                        <div class="option_content">
                                            <span class="select_label">Plays:</span>
                                            {{view Ember.TextField type="number" class="number_field" valueBinding="trigger.plays"}}
                                            {{#view Ember.Checkbox classBinding=":restart" checkedBinding="trigger.restart"}}
                                                <label {{bindAttr for="view.elementId"}}></label>
                                            {{/view}}
                                        </div>
                                        <div>
                                            <span class="select_label">Fade In: </span>
                                            {{view Ember.TextField type="number" class="number_field" valueBinding="trigger.fadeIn"}}
                                        </div>
                                    </div>
                                    {{view Ember.Button classBinding=":delete_button" target="view.content" action="destroy"}}
                                </li>
                            {{/view}}
                        {{/each}}
                        </ul>
                    </div>
                {{/if}}
                {{#if App.dynamuse.trigger}}
                    <div id="conditions" class="select_group">
                        <span class="select_title">Conditions</span>
                        {{view App.AddButton classBinding=":add_button" target="App.dynamuse" action="addCondition"}}
                        <ul class="select_list">
                        {{#each condition in App.dynamuse.trigger.conditions}}
                            {{#view App.ConditionView contentBinding="condition"}}
                                <li class="select_option condition">
                                    <div class="condition_area option_content">
                                        <span class="condition_select select_label">{{condition.type.name}}</span>
                                        <ul id="subnav" class="subnav">
                                            {{#each conditionType in App.conditions}}
                                                {{#view App.ConditionTypeView contentBinding="conditionType"}}
                                                    <li><span>{{conditionType.name}}</span></li>
                                                {{/view}}
                                            {{/each}}
                                        </ul>
                                        {{view Ember.Button classBinding=":delete_button" target="view.content" action="destroy"}}
                                    </div>
                                    <div class="condition_area option_content">
                                        {{#view App.CompareTextView}}
                                            <span>{{condition.compareText}}</span>
                                        {{/view}}
                                        <ul class="subnav">
                                            {{#each conditionSample in App.dynamuse.track.samples}}
                                                {{#view App.SampleSelectView contentBinding="conditionSample"}}
                                                    <li><span>{{conditionSample.name}}</span></li>
                                                {{/view}}
                                            {{/each}}
                                        </ul>
                                        <span class="condition_select">{{condition.compare}}</span>
                                        <ul class="subnav">
                                            {{#each option in condition.comparisionOptions}}
                                                {{#view App.ComparisonView contentBinding="option"}}
                                                    <li><span>{{option.text}}</span></li>
                                                {{/view}}
                                            {{/each}}
                                        </ul>
                                        {{#unless condition.isSelectStatus}}
                                            {{view Ember.TextField type="number" class="number_field" valueBinding="condition.lower"}}
                                            {{view Ember.TextField type="number" class="number_field" valueBinding="condition.upper"}}
                                        {{/unless}}
                                    </div>
                                </li>
                            {{/view}}
                        {{/each}}
                        </ul>
                    </div>
                {{/if}}
                <div style="clear: both;"></div>
            </div>
        </script>

        <div id="content" class="content"></div>

        </div>


        <script type="text/javascript">
            App = Ember.Application.create();

            $(document).ready(function() {

                App.AddButton = Ember.Button.extend({
                    didInsertElement: function() {
                        this.$().button({icons: {primary: "ui-icon-plus"}, text: false });
                    }
                });

                App.RangeField = Ember.TextField.extend({
                    attributeBindings: ["min", "max", "step"],
                    type: 'range',
                    min: 0,
                    max: 10,
                    step: 1
                });

                App.ConditionType = Ember.Object.extend({
                    getId: 0,
                    name: ""
                });

                App.ConditionTypeView = Ember.View.extend({
                    content: null,
                    click: function() {
                        var condition = App.dynamuse.condition;
                        condition.set('type', this.content);
                        if (condition.get('useSampleSelect') && condition.sample == null) {
                            condition.set('sample', App.dynamuse.track.samples.content[0]);
                        }
                    }
                });

                App.Comparison = Ember.Object.extend({
                    text: ""
                });

                App.ComparisonView = Ember.View.extend({
                    content: null,
                    click: function() {
                        App.dynamuse.condition.set('compare', this.content.text);
                    }
                });

                App.CompareTextView = Ember.View.extend({
                    tagName: 'span',
                    classNames: ["compare_text"],
                    click: function() {
                        if (App.dynamuse.condition.get('useSampleSelect')) {
                            var nav = this.$('span').parent().next('.subnav');
                            if (nav.is(':visible')) {
                                nav.slideUp(200).show();
                            } else {
                                nav.slideDown(200).show();
                            }
                            this.$('span').parent().parent().mouseleave(function() {}, function() {
                                if (nav.is(':visible')) {
                                    nav.slideUp(200).show();
                                }
                            });
                        }
                    }
                });

                App.SampleSelectView = Ember.View.extend({
                    content: null,
                    click: function() {
                        console.log(this.content);
                        App.dynamuse.condition.set('sample', this.content);
                    }
                });


                App.Track = Ember.Object.extend({
                    name: '',
                    path: '',
                    samples: null,
                    bar: 0,
                    init: function() {
                        this.samples = Ember.ArrayController.create({content: []});
                    },
                    barChanged: function() {
                        Crea.invoke("barChanged", this.bar);
                    }.observes('bar')
                });

                App.Sample = Ember.Object.extend({
                    name: '',
                    path: '',
                    triggers: null,
                    isSelected: false,
                    isPreviewing: false,
                    solo: false,
                    mute: false,
                    init: function() {
                        this.triggers = Ember.ArrayController.create({content: []});
                    },
                    destroy: function() {
                        if (this == App.dynamuse.sample) {
                            App.dynamuse.set('sample', null);
                            App.dynamuse.set('trigger', null);
                            App.dynamuse.set('condition', null);
                        }
                        App.dynamuse.track.samples.removeObject(this);
                        Crea.invoke('removeSample', this.name);
                    },
                    selectFile: function() {
                        Crea.invoke('selectSample', this.name, false);
                    },
                    filename: function() {
                        var filename = this.path.replace(/^.*[\\\/]/, '');
                        if (filename.length >= 20) {
                            filename = filename.substr(0, 17) + "..."
                        }
                        return filename;
                    }.property('path'),
                    nameWillChange: function() {
                        this.previousName = this.name;
                    }.observesBefore('name'),
                    nameChanged: function() {
                        if (this.previousName !== this.name) {
                            Crea.invoke('sampleNameChanged', this.previousName, this.name);
                        }
                    }.observes('name'),
                    soloChanged: function() {
                        Crea.invoke('solo', this.name, this.solo);
                    }.observes('solo'),
                    muteChanged: function() {
                        Crea.invoke('mute', this.name, this.mute);
                    }.observes('mute')
                });

                App.Trigger = Ember.Object.extend({
                    plays: 1,
                    restart: false,
                    fadeIn: 0,
                    conditions: null,
                    isSelected: false,
                    init: function() {
                        this.conditions = Ember.ArrayController.create({content: []});
                    },
                    getId: function() {
                        return App.dynamuse.sample.triggers.indexOf(this);
                    },
                    destroy: function() {
                        if (this == App.dynamuse.trigger) {
                            App.dynamuse.set('trigger', null);
                            App.dynamuse.set('condition', null);
                        }
                        Crea.invoke('removeTrigger', App.dynamuse.sample.name, this.getId());
                        App.dynamuse.sample.triggers.removeObject(this);
                    },
                    playsChanged: function() {
                        Crea.invoke('playsChanged', App.dynamuse.sample.name, this.getId(), this.plays);
                    }.observes('plays'),
                    restartChanged: function() {
                        Crea.invoke('restartChanged', App.dynamuse.sample.name, this.getId(), this.restart);
                    }.observes('restart'),
                    fadeInChanged: function() {
                        Crea.invoke('fadeInChanged', App.dynamuse.sample.name, this.getId(), this.fadeIn);
                    }.observes('fadeIn')
                });

                App.Condition = Ember.Object.extend({
                    type: null,
                    sample: null,
                    compare: "<",
                    lower: 0,
                    upper: 1,
                    init: function() {
                        if (this.type == null) {
                            this.type = App.conditions.findProperty('name', 'Intensity');
                        }
                    },
                    getId: function() {
                        return App.dynamuse.trigger.conditions.indexOf(this);
                    },
                    typeChanged: function() {
                        Crea.invoke('typeChanged', App.dynamuse.sample.name, App.dynamuse.trigger.getId(), this.getId(), this.type.name);
                    }.observes('type'),
                    sampleChanged: function() {
                        if (sample != null) {
                            Crea.invoke('sampleChanged', App.dynamuse.sample.name, App.dynamuse.trigger.getId(), this.getId(), this.sample.name);
                        }
                    }.observes('sample'),
                    compareChanged: function() {
                        if (this.get('isSelectStatus')) {
                            Crea.invoke('statusChanged', App.dynamuse.sample.name, App.dynamuse.trigger.getId(), this.getId(), this.compare);
                        } else {
                            Crea.invoke('compareChanged', App.dynamuse.sample.name, App.dynamuse.trigger.getId(), this.getId(), this.compare);
                        }
                    }.observes('compare'),
                    lowerChanged: function() {
                        if (this.lower > this.upper) {
                            this.set('upper', this.lower);
                        }
                        Crea.invoke('lowerChanged', App.dynamuse.sample.name, App.dynamuse.trigger.getId(), this.getId(), this.lower);
                    }.observes('lower'),
                    upperChanged: function() {
                        if (this.lower > this.upper) {
                            this.set('lower', this.upper);
                        }
                        Crea.invoke('upperChanged', App.dynamuse.sample.name, App.dynamuse.trigger.getId(), this.getId(), this.upper);
                    }.observes('upper'),
                    useSampleSelect: function() {
                        return this.type.name === "Sample Status" || this.type.name === "Status Changed";
                    }.property('type'),
                    compareText: function() {
                        if (this.get('useSampleSelect')) {
                            if (this.sample == null) {
                                this.set('sample', App.dynamuse.track.samples.content[0]);
                            }
                            return this.sample.name;
                        } else {
                            return this.type.name;
                        }
                    }.property('type', 'sample'),
                    destroy: function() {
                        if (this == App.dynamuse.condition) {
                            App.dynamuse.set('condition', null);
                        }
                        Crea.invoke('removeCondition', App.dynamuse.sample.name, App.dynamuse.trigger.getId(), this.getId());
                        App.dynamuse.trigger.conditions.removeObject(this);
                    },
                    isSelectStatus: function() {
                        return this.type.name === "Sample Status";
                    }.property('type'),
                    comparisionOptions: function() {
                        if (this.get("isSelectStatus")) {
                            if (App.statuses.findProperty('text', this.compare) == null) {
                                this.set('compare', App.statuses.content[0].text);
                            }
                            return App.statuses;
                        } else {
                            if (App.comparisons.findProperty('text', this.compare) == null) {
                                this.set('compare', App.comparisons.content[0].text);
                            }
                            return App.comparisons;
                        }
                    }.property('type')
                });

                App.Dynamuse = Ember.Object.extend({
                    track: null,
                    sample: null,
                    trigger: null,
                    condition: null,
                    sampleNumber: 0,
                    intensity: 5,
                    daytime: 12,
                    isPlaying: false,
                    addSample: function() {
                        do {
                            this.sampleNumber += 1;
                        } while (this.track.samples.findProperty("name", "Sample " + this.sampleNumber) != null);
                        Crea.invoke('selectSample', "Sample " + this.sampleNumber, true);
                    },
                    addTrigger: function() {
                        var trigger = App.Trigger.create();
                        this.sample.triggers.pushObject(trigger);
                        this.selectTrigger(trigger);
                        Crea.invoke('addTrigger', this.sample.name);
                    },
                    addCondition: function() {
                        var condition = App.Condition.create();
                        this.trigger.conditions.pushObject(condition);
                        this.selectCondition(condition);
                        Crea.invoke('addCondition', this.sample.name, this.trigger.getId(), condition.type.name);
                    },
                    selectSample: function(sample) {
                        if (this.sample != sample) {
                            if (this.sample != null) {
                                this.sample.set('isSelected', false);
                                if (this.trigger != null) {
                                    this.trigger.set('isSelected', false);
                                }
                            }
                            this.set('sample', sample);
                            this.set('trigger', null);
                            this.set('condition', null);
                            this.sample.set('isSelected', true);
                        }
                    },
                    selectTrigger: function(trigger) {
                        if (this.trigger != trigger) {
                            if (this.trigger != null) {
                                this.trigger.set('isSelected', false);
                            }
                            this.set('trigger', trigger);
                            this.set('condition', null);
                            this.trigger.set('isSelected', true);
                        }
                    },
                    selectCondition: function(condition) {
                        if (this.condition != condition) {
                            this.set('condition', condition);
                        }
                    },
                    playStopText: function() {
                        if (this.isPlaying) {
                            return "Stop";
                        } else {
                            return "Play";
                        }
                    }.property("isPlaying"),
                    onIntensityChange: function() {
                        Crea.invoke('setIntensity', this.intensity);
                    }.observes('intensity'),
                    onDaytimeChange: function() {
                        Crea.invoke('setDaytime', this.daytime);
                    }.observes('daytime')
                });
                App.dynamuse = App.Dynamuse.create();


                App.SampleView = Ember.View.extend({
                    content: null,
                    select: function() {
                        App.dynamuse.selectSample(this.content);
                    },
                    didInsertElement: function() {
                        this.$('.preview').button({icons: {primary: "ui-icon-play"}, text: false });
                        this.$('.solo').button({icons: {primary: "ui-icon-heart"}, text: false });
                        this.$('.mute').button({icons: {primary: "ui-icon-volume-on"}, text: false });
                        this.$('.delete_button').button({icons: {primary: "ui-icon-close"}, text: false });
                    },
                    preview: function() {
                        this.content.set('isPreviewing', !this.content.get('isPreviewing'));
                        if (this.content.isPreviewing) {
                            this.$(".preview").button("option", "icons", {primary: "ui-icon-stop"});
                        } else {
                            this.$(".preview").button("option", "icons", {primary: "ui-icon-play"});
                        }
                        Crea.invoke("preview", this.content.name);
                    },
                    mute: function() {
                        this.content.set('mute', !this.content.get('mute'));
                        if (this.content.get('mute')) {
                            this.$(".mute").button("option", "icons", {primary: "ui-icon-volume-off"});
                        } else {
                            this.$(".mute").button("option", "icons", {primary: "ui-icon-volume-on"});
                        }
                    }
                });

                App.TriggerView = Ember.View.extend({
                    content: null,
                    select: function() {
                        App.dynamuse.selectTrigger(this.content);
                    },
                    didInsertElement: function() {
                        this.$('.restart').button({icons: {primary: "ui-icon-arrowrefresh-1-w"}, text: false });
                        this.$('.delete_button').button({icons: {primary: "ui-icon-close"}, text: false });
                    }
                });

                App.ConditionView = Ember.View.extend({
                    content: null,
                    click: function() {
                        App.dynamuse.selectCondition(this.content);
                    },
                    didInsertElement: function() {
                        this.$('.delete_button').button({icons: {primary: "ui-icon-close"}, text: false });
                        //Setup functions to handle category drop down menu
                        this.$(".condition_select").click(function() {
                            var nav = $(this).next('.subnav');
                            //var nav = $("#subnav");
                            if (nav.is(':visible')) {
                                nav.slideUp(200).show();
                            } else {
                                nav.slideDown(200).show();
                            }
                            $(this).parent().mouseleave(function() {}, function() {
                                if (nav.is(':visible')) {
                                    nav.slideUp(200).show();
                                }
                            });
                        });
                        $(".subnav").click(function() {
                            $(this).slideUp(100).show();
                        });
                    }
                });

                App.ComposeView = Ember.View.extend({
                    templateName: 'compose-template',
                });

                App.statuses = Ember.ArrayController.create({content: []});
                App.comparisons = Ember.ArrayController.create({content: []});
                App.conditions = Ember.ArrayController.create({content: []});

                App.composeView = App.ComposeView.create();
                App.composeView.appendTo('#content');

                App.EditField = Ember.View.extend({
                    content: null,
                    click: function() {
                        var label = this.$('span');
                        var input = this.$('input');
                        if (!input.is(":visible")) {
                            label.hide();
                            input.show();
                            input.select();
                            input.focus();
                            input.blur(function() {
                                $(this).hide();
                                $(this).prev('span').show();
                            });
                        }
                    }
                });

                App.createTrack = function() {
                    //Save the current track first
                    App.saveTrack();
                    Crea.invoke('new');
                };
                App.saveTrack = function() {
                    if (App.dynamuse.track) {
                        Crea.invoke('save');
                    }
                };
                App.loadTrack = function() {
                    //Save the current track first
                    App.saveTrack();
                    Crea.invoke('load');
                };

                App.playTrack = function() {
                    if (App.dynamuse.track) {
                        if (App.dynamuse.isPlaying) {
                            Crea.invoke('stop');
                        } else {
                            //Syncs the track and plays it
                            Crea.invoke('play');
                        }
                        App.dynamuse.set('isPlaying', !App.dynamuse.isPlaying);
                    }
                }

                Crea.resize(800, 660);
                populate();
            });
        </script>
    </body>
</html>