/**
 * Lets users with JS support send async requests to watchlistCtrl.
 * Requires the Bones toolkit (<http://foo.at/bones>).
 *
 * @version  $Id: watchlist.js 177 2009-10-13 19:45:47Z spaceman $
 * @author   Stefan Weiss <weiss@foo.at>
 */

var B = Bones,
    BE = B.event,
    CLS_WATCHED = "green",
    CLS_NEUTRAL = "yellow",
    TXT_WATCHED = "Enfernen",
    TXT_NEUTRAL = "Merken",
    TITLE_WATCHED = "Diese Station von Ihrer Merkliste enfernen",
    TITLE_NEUTRAL = "Diese Station zu Ihrer Merkliste hinzufügen";

function btnWatcher (evt, ele) {
    var isWatched = B.hasClass(ele.parentNode, CLS_WATCHED);
    B.ajax.get("watchlistCtrl.php", btnChanger, {
        task: isWatched ? "remove" : "add",
        s: B.parseQuery(ele.href.split("?")[1]).s,
        async: 1
    });
    BE.prevent(evt);
}

function btnChanger (resp) {
    if (resp && resp.status != "error" && resp.code) {
        var div = B.ele("watch-" + resp.code);
        if (div) {
            setActive(div, resp.status == "added");
        }
    }
}

function setActive (div, active) {
    var a = div.firstChild;
    B.setClass(div, CLS_WATCHED, active);
    B.setClass(div, CLS_NEUTRAL, !active);
    a.firstChild.data = active ? TXT_WATCHED : TXT_NEUTRAL;
    a.href = a.href.replace(/task=\w+/, "task=" + (active ? "remove" : "add"));
    a.title = active ? TITLE_WATCHED : TITLE_NEUTRAL;
}

B.onReady(function () {
    var listDiv = B.ele("station-list");
    if (listDiv && listDiv.className == "list-watchlist") {
        return;  // disable Ajax thingy on the watchlist page to force list update
    }
    B.forEach(B.cls("watch"), function (div) {
        btnWatcher.handle("click", div.firstChild);
    });
});

