IriSP.Widgets.MusitagAnnotator = function(player, config) {
    IriSP.Widgets.Widget.call(this, player, config);
};

IriSP.Widgets.MusitagAnnotator.prototype = new IriSP.Widgets.Widget();

IriSP.Widgets.MusitagAnnotator.prototype.defaults = {
    min_left: -90,
    max_right: 900,
    width: 870,
    record_swf: "",
    show_play_arrow: false,
    api_serializer: "ldt_annotate",
    api_endpoint_template: "",
    api_method: "PUT",
    close_widget_timeout: 4000,
    annotation_type: "contributions",
    creator_name: "musitag",
    emoticons: [
        { tag: "happy", name: "content"},
        { tag: "unhappy", name: "mécontent"},
        { tag: "laughing", name: "rigolard"},
        { tag: "surprised", name: "étonné"}
    ],
    colors: [
        { tag: "red", name: "rouge"},
        { tag: "yellow", name: "jaune"},
        { tag: "green", name: "vert"},
        { tag: "blue", name: "bleu"}
    ],
};

IriSP.Widgets.MusitagAnnotator.prototype.template =
    '<div class="Musitag-Annotator-PositionBar"></div><div class="Musitag-Annotator-Main">'
    + '<div class="Musitag-Annotator-MainScreen">'
    + '<div class="Musitag-Annotator-section"><h2>1</h2>'
    + '    <h3>Choisis<br />une couleur</h3>'
    + '    <div class="Musitag-Annotator-selector">'
    + '{{#colors}}'
    + '        <div class="Musitag-container-80 Musitag-Annotator-tagInSelector" title="{{name}}">'
    + '            <div class="Musitag-shadow"></div>'
    + '            <div class="Musitag-color"></div>'
    + '            <div class="Musitag-color Musitag-{{tag}}"></div>'
    + '        </div>'
    + '{{/colors}}'
    + '    </div>'
    + '</div>'
    + '<div class="Musitag-Annotator-separator"></div>'
    + '<div class="Musitag-Annotator-section">'
    + '    <h2>2</h2>'
    + '    <h3>Choisis<br />une émotion</h3>'
    + '    <div class="Musitag-Annotator-selector">'
    + '{{#emoticons}}'
    + '        <div class="Musitag-container-80 Musitag-Annotator-tagInSelector" title="{{name}}">'
    + '            <div class="Musitag-shadow"></div>'
    + '            <div class="Musitag-color"></div>'
    + '            <div class="Musitag-emoticon Musitag-{{tag}}"></div>'
    + '        </div>'
    + '{{/emoticons}}'
    + '    </div>'
    + '</div>'
    + '<div class="Musitag-Annotator-separator"></div>'
    + '<div class="Musitag-Annotator-section">'
    + '    <h2>3</h2>'
    + '    <h3>Enregistre<br />ta voix</h3>'
    + '    <div class="Musitag-Annotator-record">'
    
    + '    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="220" height="160" id="record_mic" align="middle">'
    + '        <param name="movie" value="{{record_swf}}" />'
    + '        <param name="quality" value="high" />'
    + '        <param name="bgcolor" value="#ffffff" />'
    + '        <param name="play" value="true" />'
    + '        <param name="loop" value="true" />'
    + '        <param name="wmode" value="transparent" />'
    + '        <param name="scale" value="showall" />'
    + '        <param name="menu" value="true" />'
    + '        <param name="devicefont" value="false" />'
    + '        <param name="salign" value="" />'
    + '        <param name="allowScriptAccess" value="always" />'
    + '        <param name="allowFullScreen" value="true" />'
    + '        <param name="flashvars" value="playVisible={{show_play_arrow}}">'
    + '        <embed src="{{record_swf}}"" quality="high" bgcolor="#ffffff"'
    + '             width="220" height="160" name="ExternalInterfaceExample" align="middle"'
    + '             play="true" loop="false" quality="high" allowScriptAccess="always" '
    + '             type="application/x-shockwave-flash" allowFullScreen="true" wmode="transparent" '
    + '             flashvars="playVisible={{show_play_arrow}}"'
    + '             pluginspage="http://www.macromedia.com/go/getflashplayer">'
    + '        </embed>'
    + '    </object>'
    
    
    +'</div>'
    + '</div>'
    + '<div class="Musitag-Annotator-separator"></div>'
    + '<div class="Musitag-Annotator-section">'
    + '    <h2>4</h2>'
    + '    <h3>Envoie<br />ton Musitag</h3>'
    + '    <div class="Musitag-Annotator-Note">'
    + '        <div class="Musitag-container-80 Musitag-Annotator-tagInSend">'
    + '            <div class="Musitag-shadow"></div>'
    + '            <div class="Musitag-color"></div>'
    + '            <div class="Musitag-emoticon"></div>'
    + '        </div>'
    + '    </div>'
    + '</div>'
    + '<div class="Musitag-Annotator-close"></div>'
    + '</div><div class="Musitag-Annotator-EndScreen Musitag-Annotator-TextMessage">Ton Musitag a bien été enregistré :-)</div>'
    + '<div class="Musitag-Annotator-ErrorScreen Musitag-Annotator-TextMessage">Nous n\'avons pas réussi à envoyer ton Musitag :-(</div>'
    + '<div class="Musitag-Annotator-WaitScreen Musitag-Annotator-TextMessage">Nous sommes en train d\'envoyer ton Musitag</div>'
    + '</div></div>';

IriSP.Widgets.MusitagAnnotator.prototype.draw = function() {
    this.renderTemplate();
    this.position_bar = this.$.find(".Musitag-Annotator-PositionBar");
    this.position_bar.hide();
    this.position_width = this.position_bar.outerWidth();
    this.main_div = this.$.find(".Musitag-Annotator-Main");
    this.$.hide();
    this.main_width = this.main_div.outerWidth();
    this.bindPopcorn("timeupdate","onTimeupdate");
    this.bindPopcorn("IriSP.MusitagAnnotator.hide","hide");
    this.bindPopcorn("IriSP.MusitagAnnotator.show","show");
    this.recorder = this.$.find("embed")[0];
    
    var _this = this;
    
    this.$.find('.Musitag-Annotator-tagInSelector').click(function() {
        var _class = IriSP.jQuery(this).children(':last-child').attr('class'),
            _classes = _class.split(' '),
            _type = _classes[0].replace(/^\w+-/,""),
            _value = _classes[1].replace(/^\w+-/,"");
        _this.annotation[_type] = _value;
        _this.checkAnnotation();
        IriSP.jQuery('.Musitag-Annotator-tagInSend .' + _classes[0]).attr('class',_class);
        IriSP.jQuery(this).siblings().removeClass('down')
            .children(':last-child').css('opacity',.35);
        IriSP.jQuery(this).addClass('down')
            .children(':last-child').css('opacity',1);
    });
    
    this.$.find('.Musitag-Annotator-close').click(function() {
        _this.recorder.stopRecord();
        _this.hide();
    });
    
    this.$.find('.Musitag-Annotator-Note').click(function() {
        if (_this.checkAnnotation) {
            _this.recorder.stopRecord();
            _this.sendAnnotation();
        }
    });
    
    window.setAudioUrl = function(_url) {
        _this.annotation.audio_url = _url;
    }
}

IriSP.Widgets.MusitagAnnotator.prototype.onTimeupdate = function() {
    var _x = Math.floor(this.width * this.player.popcorn.currentTime() / this.source.getDuration().getSeconds());
    this.position_bar.css("margin-left", (_x - this.position_width / 2)+"px");
    this.main_div.css("margin-left",Math.max(this.min_left, Math.min(this.max_right - this.main_width, _x - this.main_width / 2))+"px");
}

IriSP.Widgets.MusitagAnnotator.prototype.checkAnnotation = function() {
    var _res = this.annotation.emoticon && this.annotation.color;
    this.$.find('.Musitag-Annotator-Note').css("opacity", _res ? 1 : .5);
    return _res;
}

IriSP.Widgets.MusitagAnnotator.prototype.showScreen = function(_screenName) {
    this.$.find('.Musitag-Annotator-' + _screenName + 'Screen').show()
        .siblings().hide();
}

IriSP.Widgets.MusitagAnnotator.prototype.show = function() {
    if (!this.player.popcorn.media.paused) {
        this.player.popcorn.pause();
    }
    this.$.show();
    this.showScreen('Main');
    this.$.find('.Musitag-Annotator-tagInSelector').removeClass("down");
    this.$.find(".Musitag-Annotator-tagInSend .Musitag-color").attr("class","Musitag-color");
    this.$.find(".Musitag-Annotator-tagInSend .Musitag-emoticon").attr("class","Musitag-emoticon hidden");
    this.annotation = {
        timecode: Math.floor(this.player.popcorn.currentTime() * 1000),
        audio_url: false,
        emoticon: false,
        color: false
    };
    this.checkAnnotation();
    this.position_bar.slideDown(200);
}

IriSP.Widgets.MusitagAnnotator.prototype.hide = function() {
    var _this = this;
    this.player.popcorn.trigger("IriSP.MusitagAndYou.show");
    this.position_bar.slideUp(200, function() {
        _this.$.hide();
    });
}

IriSP.Widgets.MusitagAnnotator.prototype.sendAnnotation = function() {
    var _exportedAnnotations = new IriSP.Model.List(this.player.sourceManager);
        _export = this.player.sourceManager.newLocalSource({serializer: IriSP.serializers[this.api_serializer]}),
        _annotation = new IriSP.Model.Annotation(false, _export),
        _annotationTypes = this.source.getAnnotationTypes().searchByTitle(this.annotation_type),
        _annotationType = (_annotationTypes.length ? _annotationTypes[0] : new IriSP.Model.AnnotationType(false, _export)),
        _color = new IriSP.Model.Tag(false, _export),
        _emoticon = new IriSP.Model.Tag(false, _export),
        _url = Mustache.to_html(this.api_endpoint_template, {id: this.source.projectId});
    
    if (!_annotationTypes.length) {
        _annotationType.dont_send_id = true;
    }
    
    _color.title = this.annotation.color;
    _emoticon.title = this.annotation.emoticon;

    _annotationType.title = this.annotation_type;
    _annotation.setBegin(this.annotation.timecode);
    _annotation.setEnd(this.annotation.timecode);
    _annotation.setMedia(this.source.currentMedia.id);
    _annotation.setAnnotationType(_annotationType.id);
    _annotation.created = new Date();
    _annotation.description = this.annotation.color + " " + this.annotation.emoticon;
    _annotation.setTags([_color.id, _emoticon.id]);
    
    if (this.annotation.audio_url) {
        _annotation.audio = {
            src: "mic",
            mimetype: "audio/mp3",
            href: this.annotation.audio_url
        };
    }
    
    _export.creator = this.creator_name;
    _export.created = new Date();
    _exportedAnnotations.push(_annotation);
    _export.addList("annotation",_exportedAnnotations);
    
    var _this = this;
    IriSP.jQuery.ajax({
        url: _url,
        type: this.api_method,
        contentType: 'application/json',
        data: _export.serialize(),
        success: function(_data) {
            _this.showScreen('End');
            window.setTimeout(_this.functionWrapper("hide"),_this.close_widget_timeout);
            _export.getAnnotations().removeElement(_annotation, true);
            _export.deSerialize(_data);
            _this.source.merge(_export);
            _this.player.popcorn.trigger("IriSP.MusitagAnnotations.redraw");
        },
        error: function(_xhr, _error, _thrown) {
            IriSP.log("Error when sending annotation", _thrown);
            _export.getAnnotations().removeElement(_annotation, true);
            _this.showScreen('Error');
            window.setTimeout(function(){
                _this.showScreen("Main");
            },
            _this.close_widget_timeout);
        }
    });
    this.showScreen('Wait');
}
