/**
 * Playlist Manager  - handles adding/deleting tracks, 
 * totals and backup, saving and loading of playlists
 *
 * Copyright: (c)2007 CK Web Technologies
 * Author:    Chris Knowles <chris.knowles@ckweb.com.au>
 * Version:   $Id: Playlist.js 29 2007-12-13 23:42:45Z Chris $
 */

var Playlist = function(app)
{
    this.app = app;
    this.html = $D.id('playlist');
    this.saveButton = $D.id('saveButton');
    this.totalTimeHtml = $D.id('total-time');
    this.totalSongsHtml = $D.id('total-songs');
    this.message = false;
    this.saved = true;
    this.totalSongs = 0;
    this.totalTime = 0;
    this.totalTimeString = "00:00:00";
    this.listHtml = "<table border='0' cellpadding='0' cellspacing='0' id='playlist-table'><tr><th>&nbsp;</th><th>&nbsp;</th><th class='stretch'>Interpret</th><th class='stretch'>Titel</th><th class='time'>Dauer</th><th class='delete'>&nbsp;</th><th class='hide'></th></tr><tbody id='list-body'></tbody></table>";
    
    this.moveRow = function(e)
    {
        var element = $E.getTarget(e);
        
        if (element && (element.className == 'arrow_up' || element.className == 'arrow_down')) {
  
            var className = element.className;
            var parent = element.parentNode.parentNode;
            
            var children = [];
                        
            for (var child = parent.firstChild; child != null; child = child.nextSibling) {
                 if (child.nodeType == 1) {
                     children.push(child);
                 }
            }
            
            element = element.parentNode;
            
            if (className == 'arrow_up') {
                children = this.moveElementUp(parent, children, element);
            } else if (className == 'arrow_down') {
                children = this.moveElementDown(parent, children, element);
            }
            for (var i = 0, len = children.length; i < len; i++) {
            
                if (i == 0) {
                    var grandchildren = this.getChildren(children[0]);
                    grandchildren[0].className = 'arrow_down';
                    grandchildren[1].className = "";
                    
                } else if (i == children.length - 1) {
                    var grandchildren = this.getChildren(children[children.length - 1]);
                    grandchildren[0].className = "";
                    grandchildren[1].className = 'arrow_up';
    
                } else {
                    var grandchildren = this.getChildren(children[i]);
                    if (grandchildren[0].className == "") {
                        grandchildren[0].className = 'arrow_down';
                    }
                    if (grandchildren[1].className == "") {
                        grandchildren[1].className = 'arrow_up';
                    }
    
                }
                parent.appendChild(children[i]);
            }
            
            this.setUnsaved();
        
        }
    
    };
    
    this.moveElementUp = function(parent, children, element)
    {
        for (var i = 0; i < children.length; i++) {
            if (children[i] == element) {
                var tmp = children[i-1];
                if (tmp) {
                    children[i-1] = children[i];
                    children[i] = tmp;
                    break;
                }
            }
        }
        return children;
    };
    
    this.moveElementDown = function(parent, children, element)
    {
        for (var i = 0; i < children.length; i++) {
            if (children[i] == element) {
                var tmp = children[i+1];
                if (tmp) {
                    children[i+1] = children[i];
                    children[i] = tmp;
                    break;
                }
            }
        }
        return children;
    };

    this.addFromSonglist = function(songlistId, trackId, cdNo)
    {
        var songlist = this.app.Songlist.songlists.get(songlistId).songlist;
        var track = songlist[trackId];
        if (this.message) {
            this.clearMessage();
            $D.setContent(this.html, this.listHtml);
        }
        var row = $D.id("sl-" + trackId);
        var cells = row.getElementsByTagName('td');
        var artist = $D.getContent(cells[0]);
        var title = $D.getContent(cells[1]);
        var first = false;
        if (this.totalSongs == 1) {
            first = true;
        }
        this.addItem(songlistId, trackId, track.artist, track.title, track.minutes, track.seconds, cdNo, first);
        this.setUnsaved();
        $D.id('printButton').className = "unsaved";
    };
    
    this.addItem = function(songlistId, trackId, artist, title, minutes, seconds, cdNo, first)
    {
        $D.setContent($D.id('print'), "");
        this.updateTotals('add', parseInt(minutes), parseInt(seconds));
        var duration = minutes + ":" + seconds;
        var uid = Math.round((Math.random() + Math.random()) * 1000);
        var list = $D.id('list-body');
        var rows = this.getChildren(list);
        var rowLen = rows.length;
        var row = list.insertRow(rowLen);
        row.id = "pl-" + trackId + uid;
        row.className = "p-" + trackId;
        var cell1 = row.insertCell(0);
        cell1.innerHTML = "&nbsp;";
        var cell2 = row.insertCell(1);
        if (rowLen > 0) {
            cell2.className = 'arrow_up';
        }
        cell2.innerHTML = "&nbsp;";
        var cell3 = row.insertCell(2);
        cell3.innerHTML = artist;
        cell3.className = 'stretch';
        var cell4 = row.insertCell(3);
        cell4.innerHTML = title;
        cell4.className = 'stretch';
        var cell5 = row.insertCell(4);
        cell5.innerHTML = duration;
        var cell6 = row.insertCell(5);
        cell6.innerHTML = "<a href='delete/" + trackId + "/' id='delete-" + trackId + uid + "-" + minutes + "-" + seconds + "'>-</a>";
        cell6.className = "delete";
        var cell7 = row.insertCell(6);
        cell7.innerHTML = cdNo;
        cell7.className = 'hide';
        if (rowLen > 0) {
            // add down arrow to previous row
            var rows = $D.id('list-body').getElementsByTagName('tr');
            var children = this.getChildren(rows[rows.length - 2]);
            children[0].className = 'arrow_down';
        }
    };
    
    this.handleClick = function(e)
    {
        $E.kill(e);
        var evt = $E.get(e);
        var parts = evt.target.id.split("-");
        if (parts.length == 4) {
            parts[1] = parts[1] + "-" + parts[2];
            parts[2] = parts[3];
        }
        if (parts.length == 5) {
            parts[1] = parts[1] + "-0-9";
            parts[2] = parts[4];
        }
        if (parts[0] == 'delete') {
            var bits = parts[1].split("-");
            this.app.Playlist.deleteTrack(bits[0], bits[1], parts[2]);
            
        } else if (parts[0] == 'play') {
      
            this.app.Player.load(parts[1], parts[2]);
            
        }
        
    };
    
    this.clear = function(force)
    {
        $D.setContent($D.id('print'), "");
        if (!force && !window.confirm("Delete all songs from the playlist?\n\nACHTUNG: Dieses kann nicht rückgängig gemacht werden")) {
            return;
        }
        this.saveButton.className = 'saved';
        this.totalSongs = 0;
        this.totalTime = 0;
        this.totalTimeString = "00:00:00";
        var tbody = $D.create('tbody', {id: 'list-body'});
        $D.replace('list-body', tbody);
        this.list = "";
        this.updateTotals();
        if (!force) {
            this.app.Storage.save('force');
        }
        $D.id('printButton').className = 'saved';
        
    };
    
    this.load = function(record)
    {
        this.clear(true);
        if (this.message) {
            this.clearMessage();
            $D.setContent(this.html, this.listHtml);
        }
        var tracks = record.split("||");
        var first = true;
        for (var i = 0, len = tracks.length; i < len; i++) {
            var parts = tracks[i].split("|");
            this.addItem(0, parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], first);
            first = false;
        }
        this.list = this.serialise();
        if (this.list.length > 0) {
            $D.id('printButton').className = "unsaved";
        }
    };
        
    this.deleteTrack = function(id, minutes, seconds)
    {
        $D.setContent($D.id('print'), "");
        this.updateTotals('delete', minutes, seconds);
        var list = $D.id('list-body');
        var rows = $D.tags('tr', list);
        for (var i = 0, len = rows.length; i < len; i++) {
            if (rows[i].id == 'pl-' + id) {
                list.deleteRow(i);
                this.setArrows();
                break;
            }
        }
        this.setUnsaved();
        if (this.list.length == 0) {
            $D.id('printButton').className = "saved";
            if (!this.app.User.loggedIn) {
                this.saveButton.className = 'saved';
            }
        }
    };
    
    this.setMessage = function(message)
    {
        message = "<div class='message'>" + message + "</div>";
        $D.setContent(this.html, message);
        this.message = true;
    };
    
    this.clearMessage = function()
    {
        $D.setContent(this.html, "");
        this.message = false;
    };
    
    this.serialise = function()
    {
        var parent = $D.id('list-body');
       
        var children = this.getChildren(parent);
        var order = [];
        for (var i = 0; i < children.length; i++) {
            var parts = children[i].className.split("-");
            if (parts[1]) {
                order.push(parts[1]);
            }
        }
        return order.toString();
    };
    
    this.getChildren = function(parent)
    {
        var children = [];
        if (parent) {
            for(var child = parent.firstChild; child != null; child = child.nextSibling) {
                 if (child.nodeType == 1) {
                     children.push(child);
                 }
            }
        }
        return children;
    };
    
    this.setUnsaved = function()
    {
        this.saved = false;
        this.unhideSaveButton();
        this.list = this.serialise();
    };
    
    this.unhideSaveButton = function()
    {
        if (!this.saved) {
            this.saveButton.innerHTML = 'Save';
            this.saveButton.className = 'unsaved';
        }
    };
    
    this.hideSaveButton = function()
    {
        if (this.saved) {
            this.saveButton.className = 'saved';
            
        } else {
            this.unhideSaveButton();
        }
    };

    this.updatePlaylistName = function()
    {
        $D.setContent(this.html, "My Playlist : " + this.app.User.email);
    };
    
    this.updateTotals = function(action, minutes, seconds)
    {
        minutes = parseInt(minutes);
        seconds = parseInt(seconds);
        var time = (minutes * 60) + seconds;

        if (action == 'add') {
            this.totalTime = this.totalTime + time;
            this.totalSongs++;
        } else if (action == 'delete') {
            this.totalTime = this.totalTime - time;
            this.totalSongs--;
        }
        var new_hours = this.addLeadingZero(Math.floor(this.totalTime / 3600));
        var remainder = this.totalTime % 3600;
        var new_minutes = this.addLeadingZero(Math.floor(remainder / 60));
        var new_seconds = this.addLeadingZero(remainder % 60);
        
        this.totalTimeString = new_hours + ":" + new_minutes + ":" + new_seconds;
        $D.setContent(this.totalTimeHtml, this.totalTimeString);
        $D.setContent(this.totalSongsHtml, this.totalSongs);
        
        if (this.totalSongs > 0) {
            $D.id('clearButton').className = 'unsaved';
        } else {
            $D.id('clearButton').className = 'saved';
        }
        
    };
    
    this.setArrows = function()
    {
        var rows = $D.tags('tr', this.html);
        var length = rows.length - 1;
        if (length < 0) {
            length = 0;
        }
        if (rows[length]) {
            var children = this.getChildren(rows[length]);
            if (children.length > 0) {
                children[0].className = '';
                children[1].className = 'arrow_up';
            }
        }
        var children = this.getChildren(rows[1]);
        if (children.length > 0) {
            if (length == 1) {
                children[0].className = '';
            } else {
                children[0].className = 'arrow_down';
            }
            children[1].className = '';
        }
    };

    this.addLeadingZero = function(number)
    {
        if (number < 10) {
            return "0" + number;
        }
        return number;
    };
}
