// ---------------------------------------------------------------------
// $Id: urlpixie.js 567 2008-11-07 00:03:55Z eric $
// ---------------------------------------------------------------------
// Urlpixie.com JavaScript Functions
// Requires Prototype and Scriptaculous
// 
// (c) 2008 Eric McCarthy  <http://limulus.net/>
// ---------------------------------------------------------------------

/*@cc_on @*/


Event.observe(document, "dom:loaded", function () {
    addUrlFormSetup();
    ajaxifyForms();
    ajaxifyUrlitems();
    addToggles();
    fixIE();
});

// ---------------------------------------------------------------------

function addUrlFormSetup() {
    var addDiv = $("AddUrl");
    if (!addDiv) return;
    
    // Get the form and keep it from submitting directly.
    var form = addDiv.down("form");
    form.onsubmit = function () { return false; };
    
    // Toggle the "http://" in the url input.
    var input = form.down("input[type=text]");
    input.observe("focus", function (e) {
        if (this.value == "http://") this.value = "";
    });
    input.observe("blur", function (e) {
        if (this.value == "") this.value = "http://";
    });
        
    // Kick off the animation and the AJAX request when the form is submitted.
    form.observe("submit", function (e) {
        if (!$F(input).match(/^https?:\/\/[\w\.\-]+\.\w{2,}/)) {
            window.alert("Sorry, that's not a valid URL!");
            return;
        }
        
        new Ajax.Request("/ajax.php", { method: "post",
            parameters: { action: "add_url", url: $F(input) },
            onFailure: function (r) {
                var msg = r.responseJSON.message;
                window.alert("Sorry! An error was encountered: " + msg);
            },
            onSuccess: function (r) {
                var json = r.responseJSON;
                var urlDiv = $("PixieUrl");
                var urlpixie = "http://urlpixie.com/" + json.pixie;
                
                flashCopy(urlpixie);
                urlDiv.update(urlpixie);
                
                if (form.visible()) {
                    setTimeout(function () {
                        urlDiv.appear({ duration: 0.2 });
                    }, 600);
                }
                else {
                    urlDiv.appear({ duration: 0.2 });
                }
            }
        });
        
        var dustDiv = $("PixieDust");
        dustDiv.show();
        animatePixieDust(dustDiv);
        
        form.fade({ duration: 0.6 });
    });
};

// ---------------------------------------------------------------------

function animatePixieDust (div) {
    var div = $(div);
    var iw = 320;
    var ih = 200;
    var mw = 3;
    var mh = 7;
    
    animatePixieDust.x = 0;
    animatePixieDust.y = 0;
    
    animatePixieDust.interval = setInterval(function () {
        var x = animatePixieDust.x;
        var y = animatePixieDust.y;
        
        var newx = (iw + x) % (iw * mw);
        var newy = (newx == 0) ? (ih + y) % (ih * mh) : y;
        
        div.style.backgroundPosition = "-" + newx + "px " + "-" + newy + "px";
        
        if (!(newx || newy)) {
            clearInterval(animatePixieDust.interval);
            div.hide();
        }
        
        animatePixieDust.x = newx;
        animatePixieDust.y = newy;
    }, 60);
};

// ---------------------------------------------------------------------
// http://urlpixie.com/BQI

function flashCopy (text) {
    Element.insert(document.body, '<embed src="/clipboard.swf"' +
        'FlashVars="clipboard=' +
        encodeURIComponent(text) +
        '" width="0" height="0" type="application/x-shockwave-flash"></embed>'
    );
};

// ---------------------------------------------------------------------

function ajaxifyForms () {
    $$("form.ajaxify").each(function (form) {
        form.select("input").invoke("observe", "change", function (e) {
            var status = form.down("div.status");
            status.update("Saving…").show();
            
            form.request({
                onSuccess: function () {
                    status.update("Saved!").fade({ duration: 0.5, delay: 1 });
                },
                onFailure: function () {
                    window.alert("Sorry, there was an error saving!");
                }
            });
        });
    });
};

// ---------------------------------------------------------------------

function ajaxifyUrlitems () {
    $$("li.urlitem span.form").each(function (span) {
        ajaxifyUrlitemForm(span);
    });
};

function ajaxifyUrlitemForm (span) {
    var form = $(span).down("form");
    var submitFunc = function () {
        var params = {};
        form.select("input[type=submit]").each(function (input) {
            var name = input.readAttribute("name");
            var value = params[name] || '';
            if (input.readAttribute("data-wasClicked")) {
                value = input.value;
                input.writeAttribute("data-wasClicked", '');
            }
            params[name] = value;
        });
        
        $(span).down("form").request({
            parameters: params,
            onSuccess: function (r) {
                $(span).update(r.responseText);
                ajaxifyUrlitemForm(span);
                fixIE();
            },
            onFailure: function () {
                window.alert("Sorry, there was an error saving!");
            }
        });
        $(span).update("<strong>Saving…</strong>");
        
        return false;
    };
    
    form.onsubmit = function () { return false; };
    form.observe("submit", submitFunc);
    
    form.select("input[type=submit]").invoke("observe", "click", function () {
        $(this).writeAttribute("data-wasClicked", "1");
    });
    
    var delurl = $(span).down("input[name=delurl]");
    if (delurl) {
        delurl.onclick = function () {
            return window.confirm("Disown this URL?");
        }
    }
    
    form.select("input[type=checkbox]").invoke("observe", "change", function () {
        $(this).up("form").select("input[type=submit]").invoke(
            "writeAttribute",
            "data-wasClicked",
            ""
        );
        submitFunc();
    });
};

// ---------------------------------------------------------------------

function fixIE () {
    /*@if (@_win32)
    $$("li.urlitem input[name=delurl], li.urlitem input[name=addurl]").invoke(
        "writeAttribute", "value", " "
    );
    @end @*/
}

// ---------------------------------------------------------------------

function addToggles () {
    $$('a.toggle[href^="#"]').each(function (a) {
        var name = a.href.replace(/.*#/, "");
        var target = a.up("div").down('a[name="'+name+'"]').up('[style*="none"]');
        
        a.onclick = function () {
            Effect.toggle(target, "appear", { duration: 0.4 });
            return false;
        };
    });
}

// ---------------------------------------------------------------------