/*

AJAX basket & lightbox button script

(c) 2006 Cambridge Imaging Systems

*/

function get_ajax() {
    if (window.XMLHttpRequest) { // moz, safari
        try {
            var ajax = new XMLHttpRequest();
        }
        catch(e) {
            var ajax = false;
        }
    } else if (window.ActiveXObject) { // MSIE
        try {
            var ajax = new ActiveXObject("Msxml2.XMLHTTP"); // newer versions
        }
        catch(e) {
            try {
                var ajax = new ActiveXObject("Microsoft.XMLHTTP"); // older versions
            }
            catch(e) {
                var ajax = false;
            }
        }
    } else {
        var ajax = false;        
    }
    
    return ajax;
}
    
/*

session is the session cookie, in the form SESSIONNAME=sessionid
note AJAX cookie support is flaky, so we append that to the URL we call.
    
action is "addto" or "removefrom"
target is "basket" or "lightbox"
    
link is the calling link, if any
id is the RecID of the imagen record
    
*/
    
function update_link(link, classname, href, onclick, text, xml) {
    if (link) {
        if (classname) link.className = classname;
        if (href) link.href = href;

        // we could overcomplicate this, but this line works sufficiently well
        if (onclick) link.onclick = new Function(onclick);

        // however this is complicated
        if (text) update_text(link, text, xml);
    }
}
    
function update_text(obj, text, xml) {
    try {
    
    
        if (obj.innerHTML) {
            // the easy way
            obj.innerHTML = text;
        } else if (obj.firstChild) {
            // the right way
            // if we have no DOM tree, try to make one
            if (!xml) {
                xml = document.createDocumentFragment();
                xml.appendChild(document.createTextNode(text));
            }
            //empty the object's existing DOM tree
            while (obj.firstChild) obj.removeChild(obj.firstChild);
            //fill it up with the new one
            while (xml.firstChild) {
                obj.appendChild(xml.firstChild);
                xml.removeChild(xml.firstChild);
            }
        } else return false;
    } catch (e) {
        return false;
    }
    return true;
}

    
function ucfirst(text) {
    return text.substring(0,1).toUpperCase() + text.substring(1);
}

function ajaxdo(session, action, target, link, id) {
    // sanitise input.  If it's invalid, return true and let the PHP page deal with it.
    if (action == "addto") {
        var to = "addto";
        var from = "removefrom";
    } else if (action == "removefrom") {
        var to = "removefrom";
        var from = "addto";
    } else return true;

    var ajax = get_ajax();
    if (ajax) {
        if (link) update_link(
            link,
            "action waitinglink waiting" + target + "link",
            null,
            "return false",
            null,
            null
        )
        
        var ajaxstatechange = function() {
            if (ajax.readyState == 4) {
                if ((ajax.status == 200) && (ajax.responseText.substring(0,9) == "<!--OK-->")) {
                    if (link) update_link(
                        link,
                        "action " + from + target + "link",
                        "?" + from + target + "=" + id + "#b" + id,
                        "return ajaxdo('" + session + "','" + from + "','" + target + "', this, " + id + ")",
                        ajax.responseText,
                        ajax.responseXML
                    );
                } else {
                    //failed for whatever reason - fall back on the old way
                    if (ajax.responseText != "FAILED") alert('ajaxdo failed (' + ajax.responseText + ')');
                    document.location.href='?' + to + target + '='+id;
                }
                // free the AJAX object 
                delete ajax;
            } 
        }
        
        try {
            //ajax cookie support is flaky - use PHPSESSID in URL instead.
            //ajax.setRequestHeader("Set-Cookie", session);
            ajax.open("GET", "ajax.php?action=" + to + target + "&id=" + id + "&order=0&" + session, true);
            ajax.onreadystatechange = ajaxstatechange;
            ajax.send("");
        } catch (e) {
            return true;
        }
        
        // return false so link isn't followed
        return false;
    } else {
        // return true so link is followed
        return true;
    }
}

var order_in_ticket = 0;
var order_out_ticket = 0;

function ajaxdoorder(session, action, link, id, order, message) {
    // sanitise input.  If it's invalid, return true and let the PHP page deal with it.
    if (action == "addto") {
        var to = "addto";
        var from = "removefrom";
        var tick = "tick";
    } else if (action == "removefrom") {
        var to = "removefrom";
        var from = "addto";
        var tick = "cross";
    } else return true;

    var ajax = get_ajax();
    if (ajax) {
        if (link) update_link(
            link,
            "action waitinglink waitingorderlink",
            null,
            "return false",
            "Please wait...",
            null
        )
        
        var totaltd = document.getElementById('ordertotals');
        // if we can't update totals - fall back on the old way
        if (totaltd) {
            if (!update_text(totaltd, "Updating...")) return true;
        }
        
        var order_state_ticket = order_in_ticket++;
        var ajaxstatechange = function() {
            if (ajax.readyState == 4) {
                if ((ajax.status == 200) && (ajax.responseText.substring(0,9) == "<!--OK-->")) {
                    // wait our turn, so that clicks are processed in order
                    while (order_out_ticket < order_state_ticket) {};
                    order_out_ticket = order_state_ticket+1;
    
                    if (link) update_link(
                        link,
                        "action " + tick + "link",
                        "?" + from + "basket=" + id + "#b" + id,
                        "return ajaxdoorder('" + session + "','" + from + "', this, " + id + ", " + order + ", '" + message + "')",
                        '<span class="label">' + message + '</span><span class="check">&nbsp;[' + ((action == "addto")?'X':'&nbsp;') + ']</span>',
                        null
                    );

                    // if there are no outstanding updates, update the order totals
                    if (order_out_ticket == order_in_ticket) {
                        ajaxupdateorder(session, '?' + to + 'basket='+id+'&order='+order);
                    } 
                } else {
                    //failed for whatever reason - fall back on the old way
                    if (ajax.responseText != "FAILED") alert('ajaxdo failed (' + ajax.responseText + ')');
                    document.location.href='?' + to + 'basket='+id+'&order='+order;
                }
                // free the AJAX object 
                delete ajax;
            } 
        }

        try {
            //ajax cookie support is flaky - use PHPSESSID in URL instead.
            //ajax.setRequestHeader("Set-Cookie", session);
            ajax.open("GET", "ajax.php?action=" + to + "basket&id=" + id + "&order=" + order + "&" + session, true);
            ajax.onreadystatechange = ajaxstatechange;
            ajax.send("");
        } catch (e) {
            return true;
        }
        
        // return false so link isn't followed
        return false;
    } else {
        // return true so link is followed
        return true;
    }
}

function ajaxupdateorder(session, failsafeurl) {
    var ajax = get_ajax();
    if (ajax) {
        var totaltd = document.getElementById('ordertotals');
        if (!totaltd) document.location.href=failsafeurl;
        
        var order_state_ticket = order_in_ticket++;
        var ajaxstatechange = function() {
            if (ajax.readyState == 4) {
                if ((ajax.status == 200) && (ajax.responseText.substring(0,9) == "<!--OK-->")) {
                    // wait our turn, so that clicks are processed in order
                    while (order_out_ticket < order_state_ticket) {};
                    order_out_ticket = order_state_ticket+1;

                    // if there are no outstanding updates, update the order totals
                    if (order_out_ticket == order_in_ticket) {
                        if (!update_text(totaltd, ajax.responseText, ajax.responseXML)) document.location.href=failsafeurl;
                    }
                } else {
                    //failed for whatever reason - fall back on the old way
                    if (ajax.responseText != "FAILED") alert('ajaxdo failed (' + ajax.responseText + ')');
                    document.location.href=failsafeurl;
                }
                // free the AJAX object 
                delete ajax;
            } 
        }

        try {
            //ajax cookie support is flaky - use PHPSESSID in URL instead.
            //ajax.setRequestHeader("Set-Cookie", session);
            ajax.open("GET", "ajax.php?action=getorder&" + session, true);
            ajax.onreadystatechange = ajaxstatechange;
            ajax.send("");
        } catch (e) {
            document.location.href=failsafeurl;
        }
    }
}
