YAHOO.namespace('SSDC.api');

YAHOO.SSDC.api.init = function() {
    var D = YAHOO.util.Dom;
    var E = YAHOO.util.Event;
    
    var api = {
        count: 0,
        data: [],
        die: 20,
        state: 'start', // start => reroll
        
        row: function(name, roll, sign, im, total, out) {
            this.name  = name;
            this.roll  = roll;
            this.sign  = sign;
            this.im    = im;
            this.total = total;
            this.out   = out;
        },

        action: function(e) {
            var targetID = E.getTarget(e).id;
            if (D.get(targetID).innerHTML.toLowerCase() == 'out') {
                D.get(targetID).innerHTML = 'IN';
                var id = targetID.replace('action-', '');
                D.addClass('row-' + id, 'row-out');
                api.data[id] = new api.row(api.data[id].name, api.data[id].roll, api.data[id].sign, api.data[id].im, -100, true);
            } else {
                D.get(targetID).innerHTML = 'OUT';
                var id = targetID.replace('action-', '');
                var total = api.calcTotal(api.data[id].sign, api.data[id].roll, api.data[id].im);
                api.data[id] = new api.row(api.data[id].name, api.data[id].roll, api.data[id].sign, api.data[id].im, total, false);
                api.drawTable();
            }
        },
        
        add: function(e) {
            var rowID = api.count - 1;
            var name = D.get('name-' + rowID).value;

            var roll = Math.floor(Math.random() * (api.die)) + 1;

            var s = D.get('sign-' + rowID);
            sign  = s.options[s.selectedIndex].value;

            if ((D.get('im-' + rowID).value.length > 0) && (!isNaN(D.get('im-' + rowID).value))) {
                var im = D.get('im-' + rowID).value;
            } else {
                var im = 0;
            }

            if (sign == 'p') {
                var total = roll + parseInt(im);
            } else {
                var total = roll - parseInt(im);
            }						

            api.data[rowID] = new api.row(name, roll, sign, im, total, false);

            api.drawTable();
        },
        
        /*addAnother: function(e) {
            var limit = 10;
            
            api.count = document.getElementById('count').value;
            
            if (api.count < limit) {
                var nextRow = parseInt(api.count)+1;
                document.getElementById('count').value = nextRow;
                
                if (nextRow >= limit) {
                    // if count hits the limit, then disable button
                    E.removeListener('add-another', 'click', api.addAnother, api, true);
                    var addButton = document.getElementById('add-another');
                    addButton.parentNode.removeChild(addButton);
                }

                var newRow = document.createElement('div');
                D.addClass(newRow, 'im-row');
                var newContent  = '<div class="no">' + nextRow + '</div>';
                    newContent += '<div class="name"><input type="text" id="name-' + (nextRow-1) + '" maxlength="50"/></div>';
                    newContent += '<div class="sign">';
                    newContent += '    <select id="sign-' + (nextRow-1) + '">';
                    newContent += '        <option value="p">+</option>';
                    newContent += '        <option value="n">-</option>';
                    newContent += '    </select>';
                    newContent += '</div>';
                    newContent += '<div class="im">';
                    newContent += '    <input type="text" id="im-' + (nextRow-1) + '" maxlength="3" value="0"/>';
                    newContent += '</div>';

                // shove content into div
                newRow.innerHTML = newContent;

                // existing div
                var imBlock = document.getElementById('im-block');

                // attach/render completed new "row" all at once
                imBlock.appendChild(newRow);
            }
        },*/
        
        calcTotal: function(sign, roll, im) {
            if (sign == 'p') {
                total = parseInt(roll) + parseInt(im);
            } else {
                total = parseInt(roll) - parseInt(im);
            }
            return total;
        },

        change: function(e) {
            var targetID = E.getTarget(e).id;
            var id = targetID.substr(targetID.indexOf('-') + 1);

            if (D.get(targetID)) {
                if (D.get(targetID).innerHTML.toLowerCase() == '+') {
                    D.get(targetID).innerHTML = '-';

                    var total = parseInt(api.data[id].roll) - parseInt(api.data[id].im);

                    D.get('total-' + id).innerHTML = total;

                    api.data[id] = new api.row(api.data[id].name, api.data[id].roll, 'n', api.data[id].im, total, api.data[id].out);
    
                    api.drawTable();

            	} else if (D.get(targetID).innerHTML.toLowerCase() == '-') {
                    D.get(targetID).innerHTML = '+';

                    var total = parseInt(api.data[id].roll) + parseInt(api.data[id].im);

                    D.get('total-' + id).innerHTML = total;

                    api.data[id] = new api.row(api.data[id].name, api.data[id].roll, 'p', api.data[id].im, total, api.data[id].out);

                    api.drawTable();

  	          } else if (targetID.substr(0, 2) == 'im') {
                    var value = D.get(targetID).innerHTML;
                    var parent = D.get(targetID).parentNode;
                    var parentValue = D.get(parent).innerHTML;

                    if (parentValue.indexOf('input') == -1) {
                        D.get(targetID).parentNode.innerHTML = '<input type="text" id="im-' + id + '" maxlength="3" value="' + value + '"/>';
                        E.on(targetID, 'change', api.newIM, api, true);
                    }

                } else if (targetID.substr(0, 6) == 'action') {
                    api.action(e);
                }
            }
        },

        drawTable: function() {
            api.sort(api.data);
            api.preDraw();
            
            var imList  = document.createElement('div');
            imList.setAttribute('id', 'im-wrapper');
            
            // header
            var newList = '';
                newList += '<div class="im-row header">';
                newList += '  <div class="no">No.</div>';
                newList += '  <div class="name">Name</div>';
                newList += '  <div class="im-header">d' + api.die + '</div>';
                newList += '  <div class="im-header">&nbsp;</div>';
                newList += '  <div class="im-header">IM</div>';
                newList += '  <div class="im-header">&nbsp;</div>';
                newList += '  <div class="im-header">Total</div>';
                //newList += '  <div class="action">&nbsp;</div>';
                newList += '</div>';
            
            var num = 0;
            for (var i in api.data) {
                var num = parseInt(i) + 1;
                
                if (api.data[i].out) {
                    newList += '<div class="im-row row-out" id="row-' + i + '">';
                } else {
                    newList += '<div class="im-row" id="row-' + i + '">';
                }
                
                newList += '  <div class="no">' + num + '</div>';
                newList += '  <div class="name">' + api.data[i].name + '</div>';

                //if (api.data[i].out) {
                //    newList += '  <div class="init" id="roll-' + i + '">OUT</div>';
                //} else {
                    newList += '  <div class="init" id="roll-' + i + '">' + api.data[i].roll + '</div>';
                //}
                
                if (api.data[i].sign == 'p') {
                    newList += '  <div class="init symbol mod" title="click to toggle"><span id="sign-' + i + '">+</span></div>';
                } else {
                    newList += '  <div class="init symbol mod" title="click to toggle"><span id="sign-' + i + '">-</span></div>';
                }
                
                newList += '  <div class="init mod" title="click to change"><span id="im-' + i + '">' + api.data[i].im + '</span></div>';
                newList += '  <div class="init symbol">=</div>';

                if (api.data[i].out) {
                    
                    var displayTotal = api.calcTotal(api.data[i].sign, api.data[i].roll, api.data[i].im);
                    
                    //newList += '  <div class="init total" id="total-' + i + '">OUT</div>';
                    newList += '  <div class="init total" id="total-' + i + '">' + displayTotal +  '</div>';
                    newList += '  <div class="action"><span id="action-' + i + '">IN</span></div>';
                } else {
                    newList += '  <div class="init total" id="total-' + i + '">' + api.data[i].total +  '</div>';
                    newList += '  <div class="action"><span id="action-' + i + '">OUT</span></div>';
                }

                newList += '</div>';
                num++;
            }
            api.count = parseInt(num);

            E.on('im-wrapper', 'click', api.change, api, true);

            imList.innerHTML = newList;
            D.get('im-list').appendChild(imList);
            
            // add row
            if (api.count <= 10) {
                var addRow = document.createElement('div');
                    D.addClass(addRow, 'im-row');
                    D.setAttribute(addRow, 'id', 'add-player-row');
                    var addContent  = '<div class="no">' + api.count + '</div>';
                            addContent += '<div class="name"><input type="text" id="name-' + (api.count - 1) + '" maxlength="50"/></div>';
                            addContent += '<div class="sign">';
                            addContent += '    <select id="sign-' + (api.count - 1) + '">';
                            addContent += '        <option value="p">+</option>';
                            addContent += '        <option value="n">-</option>';
                            addContent += '    </select>';
                            addContent += '</div>';
                            addContent += '<div class="im">';
                            addContent += '    <input type="text" id="im-' + (api.count - 1) + '" maxlength="3" value="0"/>';
                            addContent += '</div>';
                            addContent += '<input type="button" id="add" value="Add"/>';
                                            
                    // shove content into div
                    addRow.innerHTML = addContent;
                                            
                    var imList = document.getElementById('im-list');
                    imList.appendChild(addRow);
                    
                    E.on('add', 'click', api.add, api, true);
		}
        },

        newIM: function(e) {
            var targetID = E.getTarget(e).id;
            var id = targetID.substr(targetID.indexOf('-') + 1);
            var parent = D.get(targetID).parentNode;

            var im = D.get(targetID).value;
            if (isNaN(im)) {
                im = 0;
            }

            D.get(parent).innerHTML = '<span id="im-' + id + '">' + im + '</span>';

            var total = api.calcTotal(api.data[id].sign, api.data[id].roll, im);
            
            D.get('total-' + id).innerHTML = total;
            
            api.data[id] = new api.row(api.data[id].name, api.data[id].roll, api.data[id].sign, im, total, api.data[id].out);
            
            api.drawTable();
        },
        
        roll: function(e) {
            // visual feedback the roll started
            document.getElementById('roll').style.backgroundColor = '#9999cc';
            document.getElementById('roll').value = "rolling...";

            if (api.state == 'start') {

                var d = D.get('die');
                if (d.options[d.selectedIndex].value.length > 0) {
                    api.die = parseInt(d.options[d.selectedIndex].value);
                }
    
                api.count = D.get('count').value;
    						var count = 0;
                for (rowID = 0; rowID < api.count; rowID++) {
                    if (D.get('name-' + rowID).value.length > 0) {
                        name = D.get('name-' + rowID).value;
                        roll = Math.floor(Math.random() * (api.die)) + 1;

                        var s = D.get('sign-' + rowID);
                        sign  = s.options[s.selectedIndex].value;
    
                        if ((D.get('im-' + rowID).value.length > 0) && (!isNaN(D.get('im-' + rowID).value))) {
                            im = D.get('im-' + rowID).value;
                        } else {
                            im = 0;
                        }
    
                        total = api.calcTotal(sign, roll, im);
    
                        api.data[rowID] = new api.row(name, roll, sign, im, total, false);
                        count++;
                    }
                }
                api.count = count;
 
                // remove die
                var p = document.getElementById('die').parentNode.parentNode;
                p.removeChild(D.get('die').parentNode);

            } else {

                for (var i in api.data) {
                    if (!api.data[i].out) {
                        name = api.data[i].name;
                        roll = Math.floor(Math.random() * (api.die)) + 1;
                        sign = api.data[i].sign;
                        im   = api.data[i].im;
    
                        total = api.calcTotal(sign, roll, im);
                        
                        api.data[i] = new api.row(name, roll, sign, im, total, false);
                    }
                }

            }
            
            api.drawTable();

            // remove data entry
            if (D.get('im-block')) {
                if (D.get('add-another')) {
                    document.getElementById('add-another').parentNode.removeChild(D.get('add-another'));
                }
                document.getElementById('im-block').parentNode.removeChild(D.get('im-block'));
            }

            // visual feedback the roll completed
            document.getElementById('roll').value = "Roll";
            document.getElementById('roll').style.backgroundColor = '#f0f0f0';            

            if (api.state == 'start') {
                api.state = 'reroll';
            }
        },

        preDraw: function() {
            // remove existing im-list
            if (D.get('im-wrapper')) {
                D.get('im-list').removeChild(D.get('im-wrapper'));
            }
            
            // remove existing add row
            if (D.get('add-player-row')) {
                D.get('im-list').removeChild(D.get('add-player-row'));
            }
	},

        // bubble sort
        sort: function(o) {
            for (var i = (o.length - 2); i >= 0; i--) {
                for (var j = 0; j <= i; j++) {
                    if (o[j+1]['total'] > o[j]['total']) {
                        var temp = new api.row(o[j]['name'], o[j]['roll'], o[j]['sign'], o[j]['im'], o[j]['total'], o[j]['out']);
                        o[j]     = new api.row(o[j+1]['name'], o[j+1]['roll'], o[j+1]['sign'], o[j+1]['im'], o[j+1]['total'], o[j+1]['out']);
                        o[j+1]   = new api.row(temp['name'], temp['roll'], temp['sign'], temp['im'], temp['total'], temp['out']);
                    }
                }
            }
        },

        init: function() {
            //E.on('add-another', 'click', api.addAnother, api, true);
            E.on('roll', 'click', api.roll, api, true);
        }
    };
    
    E.onDOMReady(api.init);
    return api;
}();