

(function($, undefined) {

    jPlayerPlaylist = function(cssSelector, playlist, options) {
        var self = this;

        this.current = 0;
        this.loop = false; // Flag used with the jPlayer repeat event
        this.shuffled = false;
        this.removing = false; // Flag is true during remove animation, disabling the remove() method until complete.

        this.cssSelector = $.extend({}, this._cssSelector, cssSelector); // Object: Containing the css selectors for jPlayer and its cssSelectorAncestor
        this.options = $.extend(true, {}, this._options, options); // Object: The jPlayer constructor options for this playlist and the playlist options

        this.playlist = []; // Array of Objects: The current playlist displayed (Un-shuffled or Shuffled)
        this.original = []; // Array of Objects: The original playlist

        this._initPlaylist(playlist); // Copies playlist to this.original. Then mirrors this.original to this.playlist. Creating two arrays, where the element pointers match. (Enables pointer comparison.)

        // Setup the css selectors for the extra interface items used by the playlist.
        this.cssSelector.title = this.cssSelector.cssSelectorAncestor + " .jp-title"; // Note that the text is written to the decendant li node.
        this.cssSelector.playlist = this.cssSelector.cssSelectorAncestor + " .jp-playlist";
        this.cssSelector.footer = this.cssSelector.cssSelectorAncestor + " .jp-footer";
        this.cssSelector.next = this.cssSelector.cssSelectorAncestor + " .jp-next";
        this.cssSelector.previous = this.cssSelector.cssSelectorAncestor + " .jp-previous";
        this.cssSelector.shuffle = this.cssSelector.cssSelectorAncestor + " .jp-shuffle";
        this.cssSelector.shuffleOff = this.cssSelector.cssSelectorAncestor + " .jp-shuffle-off";

        // Override the cssSelectorAncestor given in options
        this.options.cssSelectorAncestor = this.cssSelector.cssSelectorAncestor;

        // Override the default repeat event handler
        this.options.repeat = function(event) {
            self.loop = event.jPlayer.options.loop;
        };

        // Create a ready event handler to initialize the playlist
        $(this.cssSelector.jPlayer).bind($.jPlayer.event.ready, function(event) {
            self._init();
        });

        // Create an ended event handler to move to the next item
        $(this.cssSelector.jPlayer).bind($.jPlayer.event.ended, function(event) {
		//console.log("frepetiririririr")
			if(self.loop){
		//console.log("si")
            self.repeat();
			}else{
		//console.log("no")
			 self.next();
			}
        });

        // Create a play event handler to pause other instances
        $(this.cssSelector.jPlayer).bind($.jPlayer.event.play, function(event) {
            $(this).jPlayer("pauseOthers");
        });

        // Create a resize event handler to show the title in full screen mode.
        $(this.cssSelector.jPlayer).bind($.jPlayer.event.resize, function(event) {
            //if(event.jPlayer.options.fullScreen) {
                $(self.cssSelector.title).show();
            /*} else {
                $(self.cssSelector.title).hide();
            }*/
        });

        // Create click handlers for the extra buttons that do playlist functions.
        $(this.cssSelector.previous).click(function() {
            self.previous();
            $(this).blur();
            return false;
        });

        $(this.cssSelector.next).click(function() {
            self.next();
            $(this).blur();
            return false;
        });

        $(this.cssSelector.shuffle).click(function() {
            self.shuffle(true);
            return false;
        });
        $(this.cssSelector.shuffleOff).click(function() {
            self.shuffle(false);
            return false;
        }).hide();

        // Put the title in its initial display state
       /* if(!this.options.fullScreen) {
            $(this.cssSelector.title).hide();
        }*/
         $(this.cssSelector.title).show();

        // Remove the empty <li> from the page HTML. Allows page to be valid HTML, while not interfereing with display animations
        $(this.cssSelector.playlist + " ol").empty();

        // Create .live() handlers for the playlist items along with the free media and remove controls.
        this._createItemHandlers();

        // Instance jPlayer
        $(this.cssSelector.jPlayer).jPlayer(this.options);
    };

    jPlayerPlaylist.prototype = {
        _cssSelector: { // static object, instanced in constructor
            jPlayer: "#jquery_jplayer_1",
            cssSelectorAncestor: "#jp_container_1"
        },
        _options: { // static object, instanced in constructor
            playlistOptions: {
                autoPlay: false,
                loopOnPrevious: false,
                shuffleOnLoop: true,
                enableRemoveControls: false,
                displayTime: 'slow',
                addTime: 'fast',
                removeTime: 'fast',
                shuffleTime: 'slow',
                itemClass: "jp-playlist-item",
                freeGroupClass: "jp-free-media",
                freeItemClass: "jp-playlist-item-free",
                removeItemClass: "jp-playlist-item-remove"
            }
        },
        option: function(option, value) { // For changing playlist options only
            if(value === undefined) {
                return this.options.playlistOptions[option];
            }

            this.options.playlistOptions[option] = value;

            switch(option) {
                case "enableRemoveControls":
                    this._updateControls();
                    break;
                case "itemClass":
                case "freeGroupClass":
                case "freeItemClass":
                case "removeItemClass":
                    this._refresh(true); // Instant
                    this._createItemHandlers();
                    break;
            }
            return this;
        },
         _init: function() {
            var self = this;
            this._refresh(function() {
                if(self.options.playlistOptions.autoPlay) {
                    self.play(self.current);
                } else {
                    self.select(self.current);
                }
            });
			
            this._initFiltro();
        },
        _initFiltro: function(){
            
            if($(this.cssSelector.footer).length < 1){
                return;
            }
            
            
            $(this.cssSelector.footer).find("a.video").hide();
            $(this.cssSelector.footer).find("a.letra").hide();
            
            
            this._loadPluginFilter(this.cssSelector.footer,this.cssSelector.playlist);
            
               
        },
        _loadPluginFilter: function(header,playlist){
             
              jQuery.expr[':'].Contains = function(a,i,m){
                  return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
              };
             
              function filterList(header, list) {
                var form = $("<form>").attr({"class":"filterform","action":"#"}),
                    input = $("<input>").attr({"class":"filterinput","placeholder":"encuentre una canci&oacute;n","type":"text"});
                $(form).append(input).appendTo(header);
             
                $(input)
                  .change( function () {
                    var filter = $(this).val();
                    if(filter) {
             
                      $matches = $(list).find('a:Contains(' + filter + ')').parents('li');
                      $('li', list).not($matches).hide();
                      $matches.show();
             
                    } else {
                      $(list).find("li").show();
                    }
                    return false;
                  })
                .keyup( function () {
                    $(this).change();
                });
              }
             filterList(header, playlist);
             

        },
        _initPlaylist: function(playlist) {
            this.current = 0;
            this.shuffled = false;
            this.removing = false;
            this.original = $.extend(true, [], playlist); // Copy the Array of Objects
            this._originalPlaylist();
        },
        _originalPlaylist: function() {
            var self = this;
            this.playlist = [];
            // Make both arrays point to the same object elements. Gives us 2 different arrays, each pointing to the same actual object. ie., Not copies of the object.
            $.each(this.original, function(i,v) {
                self.playlist[i] = self.original[i];
            });
        },
        _refresh: function(instant) {
            /* instant: Can be undefined, true or a function.
			 *	undefined -> use animation timings
			 *	true -> no animation
			 *	function -> use animation timings and excute function at half way point.
			 */
            var self = this;

            if(instant && !$.isFunction(instant)) {
                $(this.cssSelector.playlist + " ol").empty();
                $.each(this.playlist, function(i,v) {
                    $(self.cssSelector.playlist + " ol").append(self._createListItem(self.playlist[i]));
                });
                this._updateControls();
            } else {
                var displayTime = $(this.cssSelector.playlist + " ol").children().length ? this.options.playlistOptions.displayTime : 0;

                $(this.cssSelector.playlist + " ol").fadeOut(displayTime, function() {
                    var $this = $(this);
                    $(this).empty();
					
                    $.each(self.playlist, function(i,v) {
                        $this.append(self._createListItem(self.playlist[i]));
                    });
                    self._updateControls();
                    if($.isFunction(instant)) {
                        instant();
                    }
                    if(self.playlist.length) {
                        $(this).fadeIn(self.options.playlistOptions.displayTime);
                    } else {
                        $(this).show();
                    }
                });
            }
        },
        _createListItem: function(media) {
            var self = this;

            // Wrap the <li> contents in a <div>
            var listItem = "<li><div>";

            // Create remove control
            listItem += "<a href='javascript:;' class='" + this.options.playlistOptions.removeItemClass + "'>&times;</a>";
           /* 
            if(media.dedicar) {
                listItem += "<span class='opcion dedicar'>";
                listItem += "<a class='hits'>" + media.hits + "</a>";
                listItem += "</span>";
            }*/
            if(media.agregar) {
                listItem += "<span class='opcion agregar'>";        
                listItem += "<a class='tipsy-top opcion agregar' title='Agregar " + media.titleXD + "' onclick=\"lr_c_fav('Proc.Favorito','" + media.id + "'); return false\" href=\"#\" tabindex='1'>agregar</a>";
                listItem += "</span>";
            }
            if(media.dedicar) {
                listItem += "<span class='opcion dedicar'>";
                listItem += "<a class='opcion dedicar' title='Dedicar " + media.titleXD + "' onclick=\"rdc('msj/cancion/" + media.id + "/');return false;\"    href=\"" + media.enlace + "\"  tabindex='1'>dedicar</a>";
                listItem += "</span>";
            }
			if(media.descarga) {
                listItem += "<span class='opcion descarga'>";
                listItem += "<a class='opcion descarga' title='Descargar " + media.titleXD + "' onclick=\"down('" + media.mp3 + "','" + media.titleXD + "'); return false;\" href=\"#\" tabindex='1'>descarga</a>";
                listItem += "</span>";
            }

            /*if(media.enlace) {
                listItem += "<span class='opcion enlace'>";
                listItem += "<a class='opcion enlace' title='Ir a  " + media.title + "'  href='" + media.enlace + "' tabindex='1'>ir a la canción</a>";
                listItem += "</span>";
            }*/
            // Create links to free media
            //			if(media.descarga) {
            //				var first = true;
            //				listItem += "<span class='" + this.options.playlistOptions.freeGroupClass + "'>";
            //				$.each(media, function(property,value) {
            //					if($.jPlayer.prototype.format[property]) { // Check property is a media format.
            //						if(first) {
            //							first = false;
            //						} else {
            //							listItem += " | ";
            //						}
            //						listItem += "<a class='" + self.options.playlistOptions.freeItemClass + "' href='" + value + "' tabindex='1'>" + property + "</a>";
            //					}
            //				});
            //				listItem += "</span>";
            //			}

            // The title is given next in the HTML otherwise the float:right on the free media corrupts in IE6/7
            listItem += "<a href='"+media.enlace+"' class='" + this.options.playlistOptions.itemClass + "' tabindex='1'>" + media.title + (media.artist ? " <span class='jp-artist'>by " + media.artist + "</span>" : "") + "</a>";
            listItem += "</div></li>";

            return listItem;
 
        },
        _createItemHandlers: function() {
            var self = this;
            // Create .live() handlers for the playlist items
            $(this.cssSelector.playlist + " a." + this.options.playlistOptions.itemClass).die("click").live("click", function() {
          //  $(this.cssSelector.playlist + " li").die("click").live("click", function() {
                var index = $(this).parent().parent().index();
              //  var index = $(this).index();
                if(self.current !== index) {
                    self.play(index);
                } else {
                    $(self.cssSelector.jPlayer).jPlayer("play");
                }
                $(this).blur();
                return false;
            });

            // Create .live() handlers that disable free media links to force access via right click
            $(self.cssSelector.playlist + " a." + this.options.playlistOptions.freeItemClass).die("click").live("click", function() {
                $(this).parent().parent().find("." + self.options.playlistOptions.itemClass).click();
                $(this).blur();
                return false;
            });

            // Create .live() handlers for the remove controls
            $(self.cssSelector.playlist + " a." + this.options.playlistOptions.removeItemClass).die("click").live("click", function() {
                var index = $(this).parent().parent().index();
                self.remove(index);
                $(this).blur();
                return false;
            });
        },
        _updateControls: function() {
            if(this.options.playlistOptions.enableRemoveControls) {
                $(this.cssSelector.playlist + " ." + this.options.playlistOptions.removeItemClass).show();
            } else {
                $(this.cssSelector.playlist + " ." + this.options.playlistOptions.removeItemClass).hide();
            }
            if(this.shuffled) {
                $(this.cssSelector.shuffleOff).show();
                $(this.cssSelector.shuffle).hide();
            } else {
                $(this.cssSelector.shuffleOff).hide();
                $(this.cssSelector.shuffle).show();
            }
        },
        _highlight: function(index) {
            if(this.playlist.length && index !== undefined) {
                $(this.cssSelector.playlist + " .jp-playlist-current").removeClass("jp-playlist-current");
                $(this.cssSelector.playlist + " li:nth-child(" + (index + 1) + ")").addClass("jp-playlist-current").find(".jp-playlist-item").addClass("jp-playlist-current");
                $(this.cssSelector.title + " li").html(this.playlist[index].title + (this.playlist[index].artist ? " <span class='jp-artist'>by " + this.playlist[index].artist + "</span>" : ""));
            }
        },
        setPlaylist: function(playlist) {
            this._initPlaylist(playlist);
            this._init();
        },
        add: function(media, playNow) {
            $(this.cssSelector.playlist + " ol").append(this._createListItem(media)).find("li:last-child").hide().fadeIn(this.options.playlistOptions.addTime);
            this._updateControls();
            this.original.push(media);
            this.playlist.push(media); // Both array elements share the same object pointer. Comforms with _initPlaylist(p) system.

            if(playNow) {
                this.play(this.playlist.length - 1);
            } else {
                if(this.original.length === 1) {
                    this.select(0);
                }
            }
        },
        remove: function(index) {
            var self = this;

            if(index === undefined) {
                this._initPlaylist([]);
                this._refresh(function() {
                    $(self.cssSelector.jPlayer).jPlayer("clearMedia");
                });
                return true;
            } else {

                if(this.removing) {
                    return false;
                } else {
                    index = (index < 0) ? self.original.length + index : index; // Negative index relates to end of array.
                    if(0 <= index && index < this.playlist.length) {
                        this.removing = true;

                        $(this.cssSelector.playlist + " li:nth-child(" + (index + 1) + ")").fadeOut(this.options.playlistOptions.removeTime, function() {
                            $(this).remove();

                            if(self.shuffled) {
                                var item = self.playlist[index];
                                $.each(self.original, function(i,v) {
                                    if(self.original[i] === item) {
                                        self.original.splice(i, 1);
                                        return false; // Exit $.each
                                    }
                                });
                                self.playlist.splice(index, 1);
                            } else {
                                self.original.splice(index, 1);
                                self.playlist.splice(index, 1);
                            }

                            if(self.original.length) {
                                if(index === self.current) {
                                    self.current = (index < self.original.length) ? self.current : self.original.length - 1; // To cope when last element being selected when it was removed
                                    self.select(self.current);
                                } else if(index < self.current) {
                                    self.current--;
                                }
                            } else {
                                $(self.cssSelector.jPlayer).jPlayer("clearMedia");
                                self.current = 0;
                                self.shuffled = false;
                                self._updateControls();
                            }

                            self.removing = false;
                        });
                    }
                    return true;
                }
            }
        },
        select: function(index) {
            index = (index < 0) ? this.original.length + index : index; // Negative index relates to end of array.
            if(0 <= index && index < this.playlist.length) {
                this.current = index;
                this._highlight(index);
                $(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[this.current]);
            } else {
                this.current = 0;
            }
        },
        play: function(index) {
            index = (index < 0) ? this.original.length + index : index; // Negative index relates to end of array.
            
			/*if(this.loop && index==this.current){
			
                    this.select(this.current);
                    $(this.cssSelector.jPlayer).jPlayer("play");
					
			}else */if(0 <= index && index < this.playlist.length) {
                if(this.playlist.length) {

                    this.select(index);
                    $(this.cssSelector.jPlayer).jPlayer("play");
                    $(this.cssSelector.title).html(this.playlist[this.current].title);
		    $('#canc01').val(this.playlist[this.current].enlace);

tem = this.playlist[this.current].tema.toUpperCase();
art = this.playlist[this.current].artista.toLowerCase().replace(/\s/g,"-");
gen = this.playlist[this.current].genero.toLowerCase().replace(/\s/g,"-");

function text_corto(cantidad,texto){if(texto.length>cantidad){return texto.substr(0,cantidad)+'...';}else{return texto;}};


$('#ringtone').html("<a href='http://www.ringtonematcher.com/go/?sid=BFBAros&artist=" + this.playlist[this.current].artista + "&song=" + this.playlist[this.current].tema + "' target='_blank' rel='nofollow' style='text-decoration: none; font: bold 13px Arial;'> <img src='./img/phone_left.gif' style='border-style: none; vertical-align: bottom;'> <span style='text-decoration: underline; color: #f00;'>Descargar el tono &quot;" +text_corto(200,this.playlist[this.current].tema)+ "&quot; a tu Movil</span> <img src='./img/phone_right.gif' style='border-style: none; vertical-align: bottom;' /></a> (Ad)");

$('#shared').html("<a href='#compartir' onclick=\"return fbs_shared('" + this.playlist[this.current].enlace + "')\" title='Compartir " + this.playlist[this.current].tema + " en Facebook'><img src='Imagenes/compartirfb.jpg' alt='Compartir " + this.playlist[this.current].tema + " en Facebook' height='17'  style='float:none;border:0;'/></a>");

$('#repro').html("<div class='cr'> <div class='ir'><img src='" + this.playlist[this.current].imagen + "' width='53' height='55' alt='" + this.playlist[this.current].artista + "' title='" + this.playlist[this.current].artista + "' /></div> <div class='dr'> <div class='h1'><a href=" + this.playlist[this.current].enlace + " >" + tem + "</a></div> <div class='h2'><span><b>By: </b><a href='" + art + "'>" + this.playlist[this.current].artista + "</a> </span></div> <div class='h3'><span><b>On: </b><a href='musica/" + gen + "'>" + this.playlist[this.current].genero + "</a></span></div> <div class='rlike'> <div class='voto_c' id='avoto'> <a href='#votar' onClick=\"Votacion('" + this.playlist[this.current].id + "','1'); return false\" title='Votar por " + this.playlist[this.current].tema + "'>&iexcl;votar!</a> </div> <div class='voto_p' id='svoto'></div> <a href='#compartir' onclick=\"return fbs_shared('" + this.playlist[this.current].enlace + "')\" title='Compartir " + this.playlist[this.current].tema + " en Facebook'><img src='Imagenes/compartirfb.jpg' alt='Compartir " + this.playlist[this.current].tema + " en Facebook' height='17'  style='float:none;border:0;'/></a>  </div>    </div> </div>");

var cancion = this.playlist[this.current];
VerVideo(cancion.title);  
                }
            } else if(index === undefined) {
                $(this.cssSelector.jPlayer).jPlayer("play");
            }
        },
        pause: function() {
            $(this.cssSelector.jPlayer).jPlayer("pause");
        },
        next: function() {
            var index = (this.current + 1 < this.playlist.length) ? this.current + 1 : 0;

            if(this.loop) {
                // See if we need to shuffle before looping to start, and only shuffle if more than 1 item.
                if(index === 0 && this.shuffled && this.options.playlistOptions.shuffleOnLoop && this.playlist.length > 1) {
                    this.shuffle(true, true); // playNow
                } else {
                    this.play(index);
                }
            } else {
                // The index will be zero if it just looped round
                if(index > 0) {
                    this.play(index);
                }
            }
        },
        previous: function() {
            var index = (this.current - 1 >= 0) ? this.current - 1 : this.playlist.length - 1;

            if(this.loop && this.options.playlistOptions.loopOnPrevious || index < this.playlist.length - 1) {
                this.play(index);
            }
        },
        repeat: function() {
            var index = this.current;
			this.play(index);
        },
        shuffle: function(shuffled, playNow) {
            var self = this;

            if(shuffled === undefined) {
                shuffled = !this.shuffled;
            }

            if(shuffled || shuffled !== this.shuffled) {

                $(this.cssSelector.playlist + " ol").fadeOut(this.options.playlistOptions.shuffleTime, function() {
                    self.shuffled = shuffled;
                    if(shuffled) {
                        self.playlist.sort(function() {
                            return 0.5 - Math.random();
                        });
                    } else {
                        self._originalPlaylist();
                    }
                    self._refresh(true); // Instant

                    if(playNow || !$(self.cssSelector.jPlayer).data("jPlayer").status.paused) {
                        self.play(0);
                    } else {
                        self.select(0);
                    }

                    $(this).fadeIn(self.options.playlistOptions.shuffleTime);
                });
            }
        }
    };
})(jQuery);
