function get(name){
    if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
        return decodeURIComponent(name[1]);
}
function selectList(type) {
    var element = document.getElementById(type);
    if (element == undefined) bootbox.alert("no element");
    var option = element.options[element.selectedIndex];
    if (option == undefined) return;
    var value = option.value;
    var avail = document.getElementById(type+"available");
    var item = items[type+":"+value];
    if (item == undefined) {
        bootbox.alert("no item called "+value);
    }
    avail.innerHTML = item.quantity;
}
function hideType(type) {
    var items = document.getElementsByClassName("item_"+type);
    for (var i = 0; i < items.length; i++) {
        var options = jQuery('select > option',items[i]);
        if (options.length === 0) jQuery(items[i]).hide();
        // alert("options"+options.length);
    }
}
function postUpdateItem(name, type, quantity, description, newtype, hidden, toggleHidden, nameElement, hideElement, oldQuantityElement) {
    jQuery.ajax({
        method: "POST",
        url: "/store/update",
        data: {
            name: name,
            type: type,
            quantity: quantity,
            description: description,
            newtype: newtype,
            hidden: hidden
        },
        success: function () {
            oldQuantityElement.val(quantity);
            if (toggleHidden == undefined) {
                setTimeout(function() {
                    bootbox.alert("Update successful", function () {
                    });
                },100);
            } else {
                nameElement.removeClass("hiddenItem");
                nameElement.removeClass("showItem");
                if (hidden) {
                    nameElement.addClass("hiddenItem");
                    hideElement.attr("value", "Show")
                } else {
                    nameElement.addClass("showItem");
                    hideElement.attr("value", "Hide")
                }
                hideElement.disabled = false;
            }
        },
        error: function () {
            bootbox.alert("FAILED to update name=" + name + " type=" + type + " to quantity=" + quantity + " FAILED", function () {
                location.reload();
            });
        }
    });
}
function updateItem(name,type,toggleHidden) {
    var newtype = jQuery(this).parent().parent().find(".type").val();
    var quantity = jQuery(this).parent().parent().find(".quantity").val();
    var oldquantityElement = jQuery(this).parent().parent().find(".oldquantity");
    var oldquantity = oldquantityElement.val();
    var description = jQuery(this).parent().parent().find(".description").val();
    var hiddenText = jQuery(this).parent().parent().find(".tohide").val();
    var hidden = false;
    if (hiddenText == "Show") {
        hidden = true;
    } else if (hiddenText == "Hide") {
        hidden = false;
    }
    var nameElement = jQuery(this).parent().parent().find(".name");
    var hideElement = jQuery(this).parent().parent().find(".tohide");
    hideElement.disabled = true;
    if (toggleHidden != undefined) {
        hidden = !hidden;  // toggle hidden
        quantity = -1;
    }
    jQuery.ajax({
        method: "GET",
        url: "/store/get_item",
        data: {
            name: name,
            type: type
        },
        dataType: "json",
        success: function(result) {
            if (result.quantity == oldquantity) {
                postUpdateItem(name, type, quantity, description, newtype, hidden, toggleHidden, nameElement, hideElement, oldquantityElement);
            } else {
                bootbox.dialog({
                    title: '
Quantity out of date
',
                    message: 'Name: '+result.name+'
' +
                        'Type: '+result.type+'
'+
                        'Quantity found in database: '+result.quantity+'
'+
                        'Quantity on page: '+oldquantity+'
',
                    buttons: {
                        update: {
                            label: 'Override',
                            className: 'btn-success',
                            callback: function() {
                                setTimeout(function() {
                                    postUpdateItem(name, type, quantity, description, newtype, hidden, toggleHidden, nameElement, hideElement, oldquantityElement);
                                },100);
                            }
                        },
                        close: {
                            label: "Cancel",
                            className: 'btn-close',
                            callback: function() {
                            }
                        }
                    }
                })
            }
        },
        error: function() {
            bootbox.alert("FAILED to update item",function () {
                location.reload();
            });
        }
    })
}
function goLive() {
    bootbox.confirm("Are you sure you want to Go Live?", function(result) {
        if (result) {
            jQuery.ajax({
                method: "POST",
                url: "/store/golive",
                data: {},
                success: function () {
                    bootbox.alert("Go Live Successful", function () {
                        location.reload();
                    });
                },
                error: function () {
                    bootbox.alert("FAILED to go live", function () {
                        location.reload();
                    });
                }
            });
        }
    });
}
function hideAll() {
    bootbox.confirm("Are you sure you want to Hide All?", function(result) {
        if (result) {
            jQuery.ajax({
                method: "POST",
                url: "/store/hideall",
                data: {},
                success: function () {
                    bootbox.alert("Hide All Successful", function () {
                        location.reload();
                    });
                },
                error: function () {
                    bootbox.alert("FAILED to hide all", function () {
                        location.reload();
                    });
                }
            });
        }
    });
}
function clearCache() {
    jQuery.ajax({
        method: "POST",
        url: "/store/clearcache",
        data: {},
        success: function () {
            bootbox.alert("Clear cache Successful", function () {
            });
        },
        error: function () {
            bootbox.alert("FAILED to clear cache shop", function () {
            });
        }
    });
}
function closeShop() {
    bootbox.confirm("Are you sure you want to close the shop?", function(result) {
        if (result) {
            jQuery.ajax({
                method: "POST",
                url: "/store/closeshop",
                data: {},
                success: function () {
                    bootbox.alert("Close Shop Successful", function () {
                        location.reload();
                    });
                },
                error: function () {
                    bootbox.alert("FAILED to close shop", function () {
                        location.reload();
                    });
                }
            });
        }
    });
}
function openShop() {
    bootbox.confirm("Are you sure you want to open the shop?", function(result) {
        if (result) {
            jQuery.ajax({
                method: "POST",
                url: "/store/openshop",
                data: {},
                success: function () {
                    bootbox.alert("Open Shop Successful", function () {
                        location.reload();
                    });
                },
                error: function () {
                    bootbox.alert("FAILED to open shop", function () {
                        location.reload();
                    });
                }
            });
        }
    });
}
function deleteItem(name,type) {
    var password = jQuery("input#password").val();
    bootbox.confirm("Are you sure you want to delete name: "+name+" type: "+type+" ?", function(result) {
    if (result) {
            jQuery.ajax({
                method: "POST",
                url: "/store/item/delete",
                data: {
                    name: name,
                    type: type,
                    password: password
                },
                success: function () {
                    bootbox.alert("Deleted name=" + name + " type=" + type + " successfully", function () {
                        //location.reload();
                    });
                },
                error: function () {
                    bootbox.alert("FAILED to delete name=" + name + " type=" + type + " FAILED",function () {
                        location.reload();
                    });
                }
            });
        }
    });
}
function createItem() {
    var password = jQuery("input#password").val();
    var name = jQuery("#createname").val();
    var type = jQuery("#createtype").val();
    var quantity = jQuery("#createquantity").val();
    var price = jQuery("#createprice").val();
    var description = jQuery("#createdescription").val();
    jQuery.ajax({
        method: "POST",
        url: "/store/create",
        data: {
            name: name,
            type: type,
            quantity: quantity,
            price: price,
            description: description,
            password: password,
            hidden: 'true'
        },
        success: function() {
            bootbox.alert("Create name="+name+" type="+type+" to quantity="+quantity+" successfully", function () {
                jQuery.ajax({
                    method: "GET",
                    url: "/store/list_item",
                    data: {
                        name: name,
                        type: type,
                        quantity: quantity,
                        price: price,
                        description: description,
                        password: password,
                        hidden: 'true'
                    },
                    success: function(result) {
                        jQuery(".table tr:nth-child(2)").after(result);
                        jQuery("#createname").val('');
                        jQuery("#createdescription").val('');
                    },
                    error: function() {
                        bootbox.alert("FAILED to create name="+name+" type="+type+" to quantity="+quantity+" it may already exist",function () {
                            location.reload();
                        });
                    }
                });
                jQuery(".table");
            });
        },
        error: function() {
            bootbox.alert("FAILED to create name="+name+" type="+type+" to quantity="+quantity+" it may already exist",function () {
                location.reload();
            });
        }
    });
}
function store_checkout() {
    var answer = confirm("Are you sure you wish to checkout now?");
    var test = true;
    if (answer == false) return;
    if( simpleCart.quantity === 0 ){
        error("Cart is empty");
        return;
    }
    storeCart("checkoutClicked","yes",300);
    window.location = "/reserve.html";
}
function store_checkout2() {
    var answer = confirm("Are you sure you wish to checkout now?");
    var test = true;
    if (answer == false) return;
    if( simpleCart.quantity === 0 ){
        error("Cart is empty");
        return;
    }
    storeCart("checkoutClicked","yes",300);
    window.location = "/reserve2.html";
}
function storeInvokeCheckout() {
    if (readCart('checkoutClicked') == "yes") {
        storeCart('checkoutClicked',"no",300);
        isOpen(function(result) {
            if (result == 'false') {
                bootbox.alert("The shop is currently closed, please check back later.",
                    function () {
                        window.location = "/checkout2.html";
                    });
            } else {
                simpleCart.checkout(failureCheckout);
            }
        });
    } else {
        window.location = "/checkout2.html";
    }
}
function storeInvokeCheckout2() {
    if (readCart('checkoutClicked') == "yes") {
        storeCart('checkoutClicked',"no",300);
        isOpen(function(result) {
            if (result == 'false') {
                bootbox.alert("The shop is currently closed, please check back later.",
                    function () {
                        window.location = "/checkout2.html";
                    });
            } else {
                simpleCart.checkout2(failureCheckout2);
            }
        });
    } else {
        window.location = "/checkout2.html";
    }
}
function isOpen(callback) {
    var isOpen = true;
    jQuery.ajax({
        method: "GET",
        url: "/store/options/get",
        data: {
            name: 'isOpen',
            default: 'true'
        },
        success: function(result) {
            isOpen = result;
        },
        error: function() {
            isOpen = false;
            bootbox.alert("FAILED to find out if the shop is open");
        }
    })
        .done(function() {
            callback(isOpen);
        });
}
function failureCheckout(message) {
    bootbox.alert("Not enough stock available:
"+message+"
Click OK to return to checkout.",
        function () {
            window.location = "/checkout2.html";
        }
    )
}
function failureCheckout2(message) {
    bootbox.alert("Not enough stock available:
"+message+"
Click OK to return to checkout.",
        function () {
            window.location = "/checkout2.html";
        }
    )
}
function showDescription(isSelected, index, id) {
    var link = this;
    var type = jQuery(this).parent().children().eq(0).text();
    var optionElement = jQuery(this).parent().children().eq(5).children().eq(0)[0];
    var option;
    if (isSelected) {
        option = optionElement.options[optionElement.selectedIndex].value;
        index = optionElement.selectedIndex;
    } else {
        if (index >= optionElement.options.length) index = 0;
        if (index < 0) index = optionElement.options.length - 1;
        optionElement.selectedIndex = index;
        option = optionElement.options[index].value;
    }
    var addButton = jQuery(this).parent().find(".item_add");
    //var option = jQuery(this).parent().parent().children().eq(5).children().eq(1).val();
    var shortType = typemap[type].name;
    jQuery.ajax({
        method: "GET",
        url: "/store/get_item",
        data: {
            name: option,
            type: shortType
        },
        dataType: "json",
        success: function(result) {
            var itemDesc = result.description;
            if (itemDesc == undefined) itemDesc = "";
            if (itemDesc.length == 0) itemDesc = "Description coming soon..";
            var message = ''+option+'
'+itemDesc+'
';
            if (result.img !== undefined && result.img != null && result.img.length > 0 && result.img != 'null') {
                var img = '';
                img += 'Image is for illustrative purposes only
';
                message += img;
            }
            bootbox.dialog({
                title: ''+type+'
',
                message: message,
                buttons: {
                    addToCart: {
                        label: 'Add To Cart',
                        className: 'btn-success',
                        callback: function() {
                            addButton[0].click();
                            //bootbox.alert("Success", function() {
                            //});
                        }
                    },
                    next: {
                        label: 'Next',
                        className: 'btn-next',
                        callback: function() {
                            showDescription.call(link,false,index  + 1, id);
                            //bootbox.alert("Success", function() {
                            //});
                        }
                    },
                    previous: {
                        label: 'Previous',
                        className: 'btn-previous',
                        callback: function() {
                            showDescription.call(link,false,index - 1, id);
                            //bootbox.alert("Success", function() {
                            //});
                        }
                    },
                    close: {
                        label: "Close",
                        className: 'btn-close',
                        callback: function() {
                            //bootbox.alert("Close", function () {
                            //});
                        }
                    }
                }
            });
        },
        error: function() {
            bootbox.alert("FAILED to edit item",function () {
                location.reload();
            });
        }
    })
}
function releaseOrder(orderId) {
    bootbox.confirm("Are you sure you want to release the order?", function(result) {
        if (result) {
            jQuery.ajax({
                method: "POST",
                url: "/store/order/release",
                data: {
                    orderId: orderId
                },
                success: function (result) {
                    bootbox.alert("Order " + orderId + " released successfully", function () {
                        location.reload();
                    });
                },
                error: function () {
                    bootbox.alert("FAILED to release order", function () {
                        location.reload();
                    });
                }
            })
        }
    });
}
function editItem(name,type) {
    jQuery.ajax({
        method: "GET",
        url: "/store/get_item",
        data: {
            name: name,
            type: type
        },
        dataType: "json",
        success: function(result) {
            if (result.img == undefined) result.img = "";
            bootbox.dialog({
                title: 'Edit Item
',
                message: 'Name: '+result.name+'
' +
                            'Type: '+result.type+'
'+
                            'Quantity: '+result.quantity+'
'+
                            'Image: 
'+
                            'Description: 
',
                buttons: {
                    update: {
                        label: 'Update',
                        className: 'btn-success',
                        callback: function() {
                            description = jQuery("#editDescription").val();
                            image = jQuery("#editImage").val();
                            updateFields(result.name,result.type,description,image);
                            //bootbox.alert("Success", function() {
                            //});
                        }
                    },
                    close: {
                        label: "Close",
                        className: 'btn-close',
                        callback: function() {
                            //bootbox.alert("Close", function () {
                            //});
                        }
                    }
                }
            })
        },
        error: function() {
            bootbox.alert("FAILED to edit item",function () {
                location.reload();
            });
        }
    });
}
function updateFields(name,type,description,image) {
    jQuery.ajax({
        method: "POST",
        url: "update_fields",
        data: {
            name: name,
            type: type,
            description: description,
            image: image
        },
        success: function(result) {
            //alert("result="+result);
        }
    });
}
function are_cookies_enabled()
{
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;
    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
    {
        document.cookie="testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }
    return (cookieEnabled);
}
function hideItem(name, type) {
    updateItem.call(this,name,type,true);
}
function show_item(name) {
    var spinner = new Spinner().spin();
    jQuery("#spinner").append(spinner.el);
    jQuery.ajax({
        method: "GET",
        url: "/store/list_table",
        data: {
            name: name
        },
        success: function(result) {
            jQuery("#item").children().remove();
            jQuery("#item").append(result);
        },
        error: function() {
            bootbox.alert("FAILED to edit item",function () {
                //location.reload();
            });
        }
    });
}
var guid = (function() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return function() {
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
    };
})();
var archive = function (password) {
    jQuery.ajax({
        method: "POST",
        url: "/store/archive",
        data: {
            password: password
        },
        success: function(result) {
            bootbox.alert("Orders archived.",function () {
                //location.reload();
            });
        },
        error: function() {
            bootbox.alert("FAILED to archive orders",function () {
                //location.reload();
            });
        }
    });
};
clear_txn = function (password) {
    jQuery.ajax({
        method: "POST",
        url: "/store/order/clear_txn",
        data: {
            password: password
        },
        success: function(result) {
            bootbox.alert("Txns cleared.",function () {
                //location.reload();
            });
        },
        error: function() {
            bootbox.alert("FAILED to clear txns",function () {
                //location.reload();
            });
        }
    });
}
var unarchive = function (password) {
    jQuery.ajax({
        method: "POST",
        url: "/store/unarchive",
        data: {
            password: password
        },
        success: function(result) {
            bootbox.alert("Orders unarchived.",function () {
                //location.reload();
            });
        },
        error: function() {
            bootbox.alert("FAILED to archive orders",function () {
                //location.reload();
            });
        }
    });
};