// Thanks to http://www.w3schools.com/PHP/php_ajax_database.asp for this code!

var xmlhttp;

function AddSongToInvoiceInDB (sSong, sDIV, sPrice)
{
    var sURL = "ajax/add_song.php?invoice=" + gup("invoice") + "&song=" + sSong + "&div=" + sDIV + "&price=" + sPrice;
    db(sURL);
}

function AddAlbumToInvoiceInDB (sAlbum, sAlbumDIV, sPrice, sSongsAndDIVs)
{
    var sURL = "ajax/add_album.php?invoice=" + gup("invoice") + "&album=" + sAlbum + "&albumdiv=" + sAlbumDIV + "&price=" + sPrice;
    var i;
    var aSongAndDIV;
    var aSongAndDIVs;

    // Add all the songs & song divs as their own parameters
    // Format is:  song`song_div~song`song_div~
    aSongsAndDIVs = sSongsAndDIVs.split("~");
    for (i in aSongsAndDIVs)
    {
        if (aSongsAndDIVs[i].length > 2)
        {
            aSongsAndDIV = aSongsAndDIVs[i].split("`");
            sURL += "&song" + i + "=" + aSongsAndDIV[0] + "&songdiv" + i + "=" + aSongsAndDIV[1];
        }
    }

    // Call the function that inserts stuff into the DB
    db(sURL);
}

function DeleteSongFromInvoiceInDB (sSong)
{
    var sURL = "ajax/delete_song.php?invoice=" + gup("invoice") + "&song=" + sSong;
    db(sURL);}

function DeleteAlbumFromInvoiceInDB (sAlbum)
{
    var sURL = "ajax/delete_album.php?invoice=" + gup("invoice") + "&album=" + sAlbum;
    db(sURL);
}

function db(sURL)
{
    // Get an xmlhttp object
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null)
    {
        alert ("Browser does not support HTTP Request");
        return;
    }

    // Add the random "session ID" onto the URL (to mostly prevent using a cached request)
    sURL += "&sid=" + Math.random();

    // Send the xml+http request
    xmlhttp.onreadystatechange = stateChanged;
    xmlhttp.open ("GET", sURL, true);
    xmlhttp.send (null);
}


function stateChanged()
{
    if (xmlhttp.readyState==4)
    {
        if (xmlhttp.status==200)
        {
//            alert("URL Exists!");
//        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
        else
        {
            if (xmlhttp.status==404)
            {
                alert("The URL " + url + " doesn't exist!");
            }
            else
            {
                alert("There's a strange AJAX status :  " + xmlhttp.status);
            }
        }
    }
}

function GetXmlHttpObject()
{
    if (window.XMLHttpRequest)
    {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
    }
    if (window.ActiveXObject)
    {
        // code for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}


