var nofreight = 500;

function checkFreight(totalint, freightid) {
    var update = false;

    if (totalint < nofreight && !($.cookie("ShopCart").match("freight"))) {
        update = add_freight(freightid, 1, "freight");
    } else if ((totalint - 80) >= nofreight && $.cookie("ShopCart").match("freight")) {
        update = remove_freight(freightid);
    }
    if (update == true) {
        window.location.reload();
    }
}



// -------------  COOKIE FUNCTIONS ------------- //

function add_freight(productid, quantity, data) {

    //DOES COOKIE EXIST?
    if ($.cookie("ShopCart") && !($.cookie("ShopCart").match("freight"))) {

        var currentcookiestr = $.cookie("ShopCart");
        var newcookie = "";
        newcookie = currentcookiestr + "|" + productid + "|" + quantity + ",0," + data;

        createCookie("ShopCart", newcookie, 7);
        return true;
    } else {
        return false;
    }

}

function remove_freight(productid) {
    var changed = false;
    if ($.cookie("ShopCart")) {
        var currentcookie = $.cookie("ShopCart").split("|");
        var newcookie = "";
        for (var i = 0; i < currentcookie.length; i++) {
            if (parseInt(currentcookie[i]) == productid) {
                //this is the product that should be removed = ignore it
                changed = true;
            } else {
                newcookie += currentcookie[i] + "|" + currentcookie[i + 1] + "|";
            }
            i = i + 1;
        }
        var newcookielength = newcookie.length;
        newcookie = newcookie.substring(0, newcookielength - 1);
        createCookie("ShopCart", newcookie, 7);
    }
    return changed;
}


// -------------  GENERAL COOKIE FUNCTIONS ------------- //

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}
