var csssprites = {

    moreFields: function() {
        var mf = YAHOO.util.Dom.get('more-fields');
        var initial = mf.parentNode.getElementsByTagName('div')[0];
        var new_div = document.createElement('div');
        var new_input = document.createElement('input');
        new_input.type = 'file';
        new_input.name = 'img[]';
        new_div.appendChild(new_input);
        new_div.appendChild(document.createTextNode('\u00A0'));
        new_div.appendChild(new_input.cloneNode(true));
        new_div.appendChild(document.createTextNode('\u00A0'));
        new_div.appendChild(new_input.cloneNode(true));
        var inserted = initial.parentNode.insertBefore(new_div, mf);
    },

    createTable: function(sprite, res) {

        // creates <table> and <tbody> elements
        var table     = document.createElement("table");
        var tablebody = document.createElement("tbody");
        var thediv, im;

        var current_row = document.createElement("tr");
        var current_cell = document.createElement("th");
        current_cell.appendChild(document.createTextNode('To display this image...'));
        current_row.appendChild(current_cell);
        current_cell = document.createElement("th");
        current_cell.appendChild(document.createTextNode('...use this style'));
        current_row.appendChild(current_cell);
        tablebody.appendChild(current_row);

        var the_background = "url(results/"+ sprite.id +".png?a"+ Math.random(0, 1000) + '=' + Math.random(0, 1000) + ")";

        // creating all cells
        for(var i = 0; i < sprite.images.length; i++) {
            // creates a <tr> element
            current_row = document.createElement("tr");

            // creates a <td> element
            current_cell = document.createElement("td");

            thediv = document.createElement('div');
            im = sprite.images[i];
            thediv.style.background = the_background;
            thediv.style.backgroundPosition = "-"+ im[0] +"px -"+ im[1] +"px";
            thediv.style.width = im[2] +"px";
            thediv.style.height = im[3] +"px";
            thediv.appendChild(document.createTextNode('\u00A0'));
            current_cell.appendChild(thediv);
            current_row.appendChild(current_cell);


            current_cell = document.createElement("td");

            currenttext = document.createTextNode("background-position: -"+ im[0] +"px -"+ im[1] +"px;");

            current_cell.appendChild(currenttext);
            // appends the cell <td> into the row <tr>
            current_row.appendChild(current_cell);

            // appends the row <tr> into <tbody>
            tablebody.appendChild(current_row);
        }

        // appends <tbody> into <table>
        table.appendChild(tablebody);
        // appends <table>
        res.appendChild(table);

    },

    showResults: function(sprite) {

        var res = YAHOO.util.Dom.get('results');
        res.style.display = 'none';
        if (res.getElementsByTagName('table')[0]) {
            var tab = res.getElementsByTagName('table')[0];
            tab.parentNode.removeChild(tab);
        }

        var link, i = 0, links = res.getElementsByTagName('a');
        for (i = 0; i < links.length; i++) {
            link = links[i];
            link.innerHTML = link.innerHTML.replace(/SID/, sprite.id);
            link.href      = link.href.replace(/SID/, sprite.id);

        }

        var thecode = res.getElementsByTagName('code')[0];
        thecode.innerHTML = thecode.innerHTML.replace(/SID/, sprite.id);

        csssprites.createTable(sprite, res);

        res.style.display = 'block';
        res.style.backgroundColor = '#feff8f';

        var myAnim = new YAHOO.util.ColorAnim(res, {backgroundColor: { to: '#ffffff' } });
        myAnim.animate();

    },

    uploadCallback: {
        'upload': function(o) {
            if (console && console.log) {console.log(o);}
            csssprites.addUploadListener();
            try {
                var sprite = o.responseText.parseJSON();
            } catch (e) {
                alert('Wacky response from the spriting server, sorry it didn\'t work out.');
                return false;
            }
            csssprites.showResults(sprite);

        },
        'failure': function(o) {
            alert('Sorry, something went wrong, cross your fingers and try again');
        }


    },

    addUploadListener: function() {
        var the_form = document.getElementsByTagName('form')[0];
        YAHOO.util.Event.removeListener(the_form, 'submit', csssprites.makeRequest);
        the_form.target = "";
        YAHOO.util.Connect.setForm(the_form, true);
        YAHOO.util.Event.addListener(the_form, 'submit', csssprites.makeRequest);
    },

    makeRequest: function (e) {
        var cnt = 0, i, els = document.getElementsByName('img[]');
        for (i=0; i < els.length; i++) {
            if (els[i].value != '') {
                cnt++;
            }
        }

        if (cnt < 2){
            alert('Please upload at least two images to create a CSS sprite');
            csssprites.addUploadListener();
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                e.cancelBuble = true;
            }
            return false;
        }

        YAHOO.util.Connect.asyncRequest('POST', 'upload.php', csssprites.uploadCallback);
    }

}

YAHOO.util.Event.addListener('more-fields', 'click', csssprites.moreFields);
csssprites.addUploadListener();

