var configChoices = {'donut_flavor': {'label': 'Donut Flavor', 'choices': ['Plain', 'Chocolate', 'Blueberry', 'Coconut', 'Strawberry', 'Marble']},
                     'donut_type': {'label': 'Donut Type', 'choices': ['Hollow', 'Filled']},
                     'donut_coating': {'label': 'Donut Coating', 'choices': ['Plain', 'Powdered', 'Dipped']},
                     'icing': {'label': 'Icing', 'choices': ['Banana', 'Blueberry', 'Bubble Gum', 'Caramel', 'Chocolate', 'Cinnamon', 'Coffee', 'Lemon', 'Maple', 'Marshmallow', 'Mint', 'Peanut Butter', 'Strawberry', 'Vanilla']},
                     'filling': {'label': 'Filling', 'choices': ['Banana', 'Blueberry', 'Blackberry', 'Caramel', 'Chocolate', 'Cinnamon', 'Coconut', 'Coffee', 'Grape', 'Mint', 'Vanilla', 'Lemon', 'Orange', 'Strawberry']},
                     'sprinkles': {'label': 'Toppings', 'choices': ['Blueberry Sprinkles', 'Chocolate Sprinkles', 'Halloween Sprinkles', 'Lemon Sprinkles', 'Mint Sprinkles', 'Rainbow Sprinkles', 'Red White and Blue Sprinkles', 'Strawberry Sprinkles', 'Vanilla Sprinkles', 'Candy Corn', 'Chocolate Chips', 'Toffee Crunch', 'Peppermint', 'Raisins', 'Redhots', 'Granola']}
}

var configToKey = {'donut_flavor': {'Plain': 'a', 'Chocolate': 'b', 'Blueberry': 'c', 'Coconut': 'd', 'Strawberry': 'e', 'Marble': 'f', '': '0'},
                   'donut_type': {'Hollow': 'a', 'Filled': 'b', '': '0'},
                   'donut_coating': {'Plain': 'a', 'Powdered': 'b', 'Dipped': 'c', '': '0'},
                   'icing': {'Banana': 'a', 'Blueberry': 'b', 'BubbleGum': 'c', 'Caramel': 'd', 'Chocolate': 'e', 'Cinnamon': 'f', 'Coffee': 'g', 'Lemon': 'h', 'Maple': 'i', 'Marshmallow': 'j', 'Mint': 'k', 'PeanutButter': 'l', 'Strawberry': 'm', 'Vanilla': 'n', '': '0'},
                   'filling': {'Banana': 'a', 'Blueberry': 'b', 'Blackberry': 'c', 'Caramel': 'd', 'Chocolate': 'e', 'Cinnamon': 'f', 'Coconut': 'g', 'Coffee': 'h', 'Grape': 'i', 'Mint': 'j', 'Vanilla': 'k', 'Lemon': 'l', 'Orange': 'm', 'Strawberry': 'n', 'NA': '9', '': '0'},
                   'sprinkles': {'BlueberrySprinkles': 'a', 'ChocolateSprinkles': 'b', 'HalloweenSprinkles': 'c', 'LemonSprinkles': 'd', 'MintSprinkles': 'e', 'RainbowSprinkles': 'f', 'RedWhiteandBlueSprinkles': 'g', 'StrawberrySprinkles': 'h', 'VanillaSprinkles': 'i', 'CandyCorn': 'j', 'ChocolateChips': 'k', 'ToffeeCrunch': 'l', 'Peppermint': 'm', 'Raisins': 'n', 'Redhots': 'o', 'Granola': 'p', '': '0'}
}

var keyToConfig = {'donut_flavor': {'a':'Plain', 'b': 'Chocolate', 'c': 'Blueberry', 'd': 'Coconut', 'e': 'Strawberry', 'f': 'Marble', '0': ''},
                   'donut_type': {'a': 'Hollow', 'b': 'Filled', '0': ''},
                   'donut_coating': {'a': 'Plain', 'b': 'Powdered', 'c': 'Dipped', '0': ''},
                   'icing': {'a': 'Banana', 'b': 'Blueberry', 'c': 'BubbleGum', 'd': 'Caramel', 'e': 'Chocolate', 'f': 'Cinnamon', 'g': 'Coffee', 'h': 'Lemon', 'i': 'Maple', 'j': 'Marshmallow', 'k': 'Mint', 'l': 'PeanutButter', 'm': 'Strawberry', 'n': 'Vanilla', '0': ''},
                   'filling': {'a': 'Banana', 'b': 'Blueberry', 'c': 'Blackberry', 'd': 'Caramel', 'e': 'Chocolate', 'f': 'Cinnamon', 'g': 'Coconut', 'h': 'Coffee', 'i': 'Grape', 'j': 'Mint', 'k': 'Vanilla', 'l': 'Lemon', 'm': 'Orange', 'n': 'Strawberry', '9': 'NA', '0': ''},
                   'sprinkles': {'a': 'BlueberrySprinkles', 'b': 'ChocolateSprinkles', 'c': 'HalloweenSprinkles', 'd': 'LemonSprinkles', 'e': 'MintSprinkles', 'f': 'RainbowSprinkles', 'g': 'RedWhiteandBlueSprinkles', 'h': 'StrawberrySprinkles', 'i': 'VanillaSprinkles', 'j': 'CandyCorn', 'k': 'ChocolateChips', 'l': 'ToffeeCrunch', 'm': 'Peppermint', 'n': 'Raisins', 'o': 'Redhots', 'p': 'Granola', '0': ''}
}

var config = {
    opts : ['donut_flavor', 'donut_type', 'donut_coating', 'icing', 'filling', 'sprinkles'],
    donut_flavor : '',
    donut_type : '',
    donut_coating : '',
    filling : '',
    icing : '',
    sprinkles : '',

    key: '',

    get : function(name, dflt) {
        if (this[name]) {
            return this[name];
        } else if (dflt) {
            return dflt;
        } else {
            return ''
        }
    },

    set : function(name, val) {
        this[name] = val;
    },

    makeKey : function() {
        var parts = [];
        for (var i in this.opts) {
            parts[i] = configToKey[this.opts[i]][this.get(this.opts[i])];
        }
        return parts.join('');
    },
    
    load: function(key) {
        this.key = key;
        for (var i in this.opts) {
            this.set(this.opts[i], keyToConfig[this.opts[i]][key.charAt(i)]);
        }
    },

    loadFromObj : function(loadObj) {
        for (var i in this.opts) {
            this.set(this.opts[i], loadObj[this.opts[i]]);
        }
        this.key = this.makeKey();
    },
    
    save : function() {
        this.key = this.makeKey();
    }
}

//******************* donut config handling **************//

function showChoices() {
    hideDeleteButton();
    var choices = this.nextSibling;
    choices.style.display = "block";
}

function onChoiceClick () {
    setChoice(this.parentNode.previousSibling, this.parentNode.getAttribute("name"), this.innerHTML);
}

function setChoice (label, config_key, choice) {
    if (!choice) { return }
    label.innerHTML = choice;
    label.onclick = onLabelClick;
    label.nextSibling.style.display = "none"; // hide choices
    config.set(config_key, choice.replace(/ /g, ''));
    setPicked(config_key, choice.replace(/ /g, ''));
}

function onLabelClick () {
    hideDeleteButton();
    clearChoice(this);
    this.nextSibling.style.display = "block"; // show choices
}

function clearChoice (label) {
    var config_key = label.nextSibling.getAttribute("name");
    label.innerHTML = configChoices[config_key]['label'];
    label.onclick = showChoices;
    config.set(config_key, '');
    clearPicked(config_key);
}

function choiceHover() {
    this.style.color = "#ef666d";
}

function choiceUnHover() {
    this.style.color = "#333333";
}

function setImage(id, path) {
    document.getElementById(id).innerHTML = makePngString("", path, 304, 210, "", "");
}

function setImageIf(picked, id, path) {  // set image if config option has been selected
    if (picked) {
        setImage(id, path);
    }
}

function clearImage(id) {
    document.getElementById(id).innerHTML = "";
}

function setPicked (config_key, choice, showOnly) {
    if (config_key == "donut_type") {
        setImage("shellDiv", '/images/bakery/donuts/' + choice + '/' + config.get("donut_coating", "Plain") + '/' + config.get("donut_flavor", "Wire"));
        setImageIf(config.get("icing"), "icingDiv", '/images/bakery/icings/' + choice + '/' + config.get("icing"));
        setImageIf(config.get("sprinkles"), "sprinklesDiv", '/images/bakery/sprinkles/' + choice + '/' + config.get("sprinkles"));

        if (choice == "Hollow") {
            clearImage("fillingDiv");
            setChoice(document.getElementById("filling_label"), "filling", "NA");
        } else if (choice == "Filled" && config.get("filling") == "NA") {
            clearChoice(document.getElementById("filling_label"));
        }
    } else if (config_key == "filling") {
        setImage("fillingDiv", '/images/bakery/fillings/' + choice);
        if (config.get("donut_type") != "Filled" && choice != "NA") {
            setChoice(document.getElementById("donut_type_label"), "donut_type", "Filled");
        }
    } else if (config_key == "donut_coating") {
        setImage("shellDiv", '/images/bakery/donuts/' + config.get("donut_type", "Hollow") + '/' + choice + '/' + config.get("donut_flavor", "Wire"));
    } else if (config_key == "donut_flavor") {
        setImage("shellDiv", '/images/bakery/donuts/' + config.get("donut_type", "Hollow") + '/' + config.get("donut_coating", "Plain") + '/' + choice);
    } else if (config_key == "icing") {
        setImage("icingDiv", '/images/bakery/icings/' + config.get("donut_type", "Hollow") + '/' + choice);
    } else if (config_key == "sprinkles") {
        setImage("sprinklesDiv", '/images/bakery/sprinkles/' + config.get("donut_type", "Hollow") + '/' + choice);
    }
}
 
function clearPicked (config_key) {
    if (config_key == "donut_type") {
        setImage("shellDiv", '/images/bakery/donuts/Hollow/' + config.get("donut_coating", "Plain") + '/' + config.get("donut_flavor", "Wire"));
        if (config.get("filling") == "NA") {
            clearChoice(document.getElementById("filling_label"));
        }
    } else if (config_key == "filling") {
        clearImage("fillingDiv");
    } else if (config_key == "donut_coating") {
        setImage("shellDiv", '/images/bakery/donuts/' + config.get("donut_type", "Hollow") + '/Plain/' + config.get("donut_flavor", "Wire"));
    } else if (config_key == "donut_flavor") {
        setImage("shellDiv", '/images/bakery/donuts/' + config.get("donut_type", "Hollow") + '/' + config.get("donut_coating", "Plain") + '/Wire');
    } else if (config_key == "icing") {
        clearImage("icingDiv");
    } else if (config_key == "sprinkles") {
        clearImage("sprinklesDiv");
    }
}
 
function resetDonut() {
    hideDeleteButton();
    for (var i in config.opts) {
        clearChoice(document.getElementById([config.opts[i], "_label"].join('')));
    }
    //document.getElementById("shellDiv").innerHTML = makePngString("", "/images/bakery/donuts/Hollow/Plain/Wire", 304, 210, "", "");
    hideForms();
}

function loadDonut(key, index) {
    resetDonut();
    config.load(key);
    
    setChoice(document.getElementById("donut_type_label"), "donut_type", config.get("donut_type", "Hollow"));
    setChoice(document.getElementById("donut_flavor_label"), "donut_flavor", config.get("donut_flavor", "Wire"));
    setChoice(document.getElementById("donut_coating_label"), "donut_coating", config.get("donut_coating", "Plain"));
    setChoice(document.getElementById("filling_label"), "filling", config.get("filling"));
    setChoice(document.getElementById("icing_label"), "icing", config.get("icing"));
    setChoice(document.getElementById("sprinkles_label"), "sprinkles", config.get("sprinkles"));

    // add delete button
    if (!isNaN(index)) {
        showDeleteButton(index);
    }
}

function showDeleteButton(index) {
    var del = document.getElementById("deleteDonut");
    del.innerHTML = ['<img src="/images/bakery/delete.gif" onclick="deleteDonutFromDoz(', index, ');" />'].join('');
    del.style.display = "block";
}

function hideDeleteButton() {
    var del = document.getElementById("deleteDonut");
    del.innerHTML = "";
    del.style.display = "none";
}

//**************** My Dozen functions **************************//

function getMyDozen() {
    var myDoz;
    var dozCookie = LL_get_cookie("myDoz");
    if (!dozCookie) {
        myDoz = [];
    } else {
        myDoz = dozCookie.split(',');
    }
    return myDoz
}

function initMyDozen() {
    var myDoz = getMyDozen();
    var dozLinks = [];
    for (var i=0; i < 12; i++) {
        if (i < myDoz.length) {
            dozLinks[i] = ['<img class="dozLinkOn" src="/images/bakery/dozOn.gif" onclick="loadDonut(\'', myDoz[i], '\', ', i, ');" />'].join('');
        } else { 
            dozLinks[i] = '<img class="dozLinkOff" src="/images/bakery/dozOff.gif" />';
        }
    }
    document.getElementById("myDozen").innerHTML = dozLinks.join('');
}

function updateMyDozen() {
    var myDoz = getMyDozen();
    if (myDoz.length < 12) {
        myDoz[myDoz.length] = config.get("key");
    }
    LL_set_cookie("myDoz", myDoz.join(','));
    initMyDozen();
}

function deleteDonutFromDoz(index) {
    var myDoz = getMyDozen();
    myDoz.splice(index, 1);
    LL_set_cookie("myDoz", myDoz.join(','));
    initMyDozen();
    resetDonut();
}

//****************** form functions **************//

function showForm(name, msg) {
    if (msg) {
        var msgObj = document.getElementById('regMesg');
        msgObj.innerHTML = msg;
    }
    document.getElementById(name).style.display = "block";
}

function showThanks(i) {
    var thnx = document.getElementById('thanksDiv');
    var msgs = thnx.getElementsByTagName('div');
    for (var j=0; j < msgs.length; j++) {
        msgs[j].style.display = (i == j) ? 'block' : 'none';
    }
    thnx.style.display = 'block';
}

function hideForm(name) {
    document.getElementById(name).style.display = "none";
}

function hideForms() {
    var forms = ['regFormDiv', 'sendFormDiv', 'thanksDiv'];
    for (var i in forms) {
        hideForm(forms[i]);
    }
}

var submittedRegAlready = false;

function verifyReg(isNew) {
    var status = false;
    hideForms();
    if (LL_get_cookie("hdauth")) {
       status = true;
    } else {
        var msg = '';
        if (submittedRegAlready) {
            msg = 'Have you checked your email? <b>You should receive an email shortly.</b> Just click the "Verify My Dozen Account" link in that email to activate your account. Then you can begin baking and sharing your donuts!';
        } else if (isNew) {
            msg = 'Your "My Dozen" account lets you save up to 12 donuts and allows you to send donut email to your friends. Just complete and submit this form to get going! We\'ll send an account activation link to the email address you provide.';
        } else {
            msg = 'Hi. Looks like your cookies may have been cleared since you opened your "My Dozen" account.  Sorry for any inconvenience. Please re-submit the form to reactivate your account.';
        }
        showForm('regFormDiv', msg);
    }
    initHeaderControls();
    return status;
}

function submitReg(name) {
    var formObj = document.forms[name];
    if (formObj.first.value && formObj.last.value && formObj.email.value) {
        hideForm('regFormDiv');
        showThanks(0);
        formObj.risitor_id.value = LL_risitor_id;
        formObj.dstr.value = config.makeKey();
        ajaxSubmit("GET", "/proxy/bakery_proxy.php", "form_id=151&" + serializeForm("regForm"), alertReg);
        submittedRegAlready = true;
        formObj.reset();
    } else {
        showThanks(6);
    }
}

function alertReg(result) {
    if (result == "success") {
        showThanks(1);
    } else {
        showThanks(4);
    }
}

function submitSend(formObj) {
    if (!formObj.toAddress.value) {
        showThanks(7);
    } else if (verifyReg()) {
        showThanks(2);
        formObj.risitor_id.value = LL_risitor_id;
        formObj.hdauth.value = LL_get_cookie("hdauth");
        formObj.dstr.value = config.makeKey();
        ajaxSubmit("POST", "/proxy/bakery_proxy.php?form_id=152", serializeForm("sendForm"), alertSend);
    }
}

function alertSend(result) {
    if (result == "success") {
        showThanks(3);
    } else if (result == "failure") {
        LL_del_cookie("hdauth");
        verifyReg();
    } else {
        showThanks(4);
    }
}

function saveDonut() {
    var isNew = (!LL_get_cookie("myDoz") && !LL_get_cookie("hdauth"));
    config.save(); // make donut string
    if (config.key[0] == "0" || config.key[1] == "0" || config.key[2] == "0") {
        showThanks(5);
    } else if (verifyReg(isNew)) {
        var data = ["form_id=153", "risitor_id=" + LL_risitor_id, "hdauth=" + encodeURIComponent(LL_get_cookie("hdauth")), "dstr=" + config.makeKey()].join('&');
        ajaxSubmit("GET", "/proxy/bakery_proxy.php", data, alertSave);
    }
}

function alertSave(result) {
    // server errors can be ignored
    if (result == "success") {
        // cookie donut string
        updateMyDozen();
    }
}

//************************  email setup functions ******************//

function showCard() {
    var mesg = ['<p>Dear friend,</p>'];
    mesg.push('<p>[YOUR NAME HERE] made a Honey Dew donut just for you! See your <a href="#" onclick="return false;">special donut</a> and sign up for your very own Honey Dew Donuts&reg; "My Dozen" account.</p>');
    mesg.push('<p>Message from [YOUR NAME HERE]:</p>');
    mesg.push(document.sendForm.note.value.replace(/\n/g, '<br>'));
    document.getElementById("note_card").innerHTML = mesg.join('');
    document.getElementById("card").style.display = "block";
}

function hideCard() {
    document.getElementById("note_card").innerHTML = '';
    document.getElementById("card").style.display = "none";
}

//***************** init functions **********************/

function initBakery() {
    initControls();

    // check authorization and setup header controls
    initHeaderControls();

    // load donut config if param present
    var loadKey = LL_get_param("d");
    if (loadKey) {
        loadDonut(loadKey);
    } else {
        document.getElementById("shellDiv").innerHTML = makePngString("", "/images/bakery/donuts/Hollow/Plain/Wire", 304, 210, "", "");
    }
    document.getElementById("lines").innerHTML = makePngString("", "/images/bakery/lines", 369, 173, "", "");

    preloadImages();
}

function initControls () {
    var controls = document.getElementById("controls");
    for (var config in configChoices) {
        var opts = document.createElement("div");
        opts.className = "opts";
        opts.setAttribute("id", config);
        var label = document.createElement("label");
        label.setAttribute("id", [config, "_label"].join(''));
        label.innerHTML = configChoices[config]['label'];
        label.onclick = showChoices;
        opts.appendChild(label);
        var choices = document.createElement("div");
        choices.className = "choices";
        choices.setAttribute("name", config);
        choices.setAttribute("id", [config, "_choices"].join(''));
        // add choices
        for (var i in configChoices[config]['choices']) {
            var choice = document.createElement("div");
            choice.className = "donut_opt";
            choice.innerHTML = configChoices[config]['choices'][i];
            choice.onmouseover = choiceHover;
            choice.onmouseout = choiceUnHover;
            choice.onclick = onChoiceClick;
            choices.appendChild(choice);
        }
        opts.appendChild(choices);
        controls.appendChild(opts);
    }
}

function initHeaderControls() {
    var ris = LL_get_param("ris");
    var auth = LL_get_param("hdauth");
    var dstr = LL_get_param("dstr");
    if (auth && ris) { // coming from reg verification email
        if (ris == LL_get_cookie("visitor_id")) {
            LL_set_cookie('hdauth', auth);
        }
        var loc = ["/bakery/bakery.html"];
        if (dstr) {
            loc.push("?d=");
            loc.push(dstr);
        }
        window.location = loc.join(''); // authorized. refresh bakery and load donut
    }

    // check cookies
    if (LL_get_cookie("hdauth") && LL_get_cookie("visitor_id")) {
        // add send/save controls
        initMyDozen();
        document.getElementById("sendControls").style.display = "block";
        document.getElementById("myDozen").style.display = "block";
    } else {
        // hide send/save controls
        document.getElementById("sendControls").style.display = "none";
        document.getElementById("myDozen").style.display = "none";
    }
}

function preloadImages() {
    var img = new Image();
    for (var key in configToKey["donut_flavor"]) {
        img.src = ["/images/bakery/donuts/Filled/Plain/", key, ".png"].join('');
        img.src = ["/images/bakery/donuts/Hollow/Plain/", key, ".png"].join('');
        img.src = ["/images/bakery/donuts/Filled/Powdered/", key, ".png"].join('');
        img.src = ["/images/bakery/donuts/Hollow/Powdered/", key, ".png"].join('');
        img.src = ["/images/bakery/donuts/Filled/Dipped/", key, ".png"].join('');
        img.src = ["/images/bakery/donuts/Hollow/Dipped/", key, ".png"].join('');
    }
    for (var key in configToKey["filling"]) {
        img.src = ["/images/bakery/fillings/", key, ".png"].join('');
    }
    for (var key in configToKey["icing"]) {
        img.src = ["/images/bakery/icings/Filled/", key, ".png"].join('');
        img.src = ["/images/bakery/icings/Hollow/", key, ".png"].join('');
    }
    for (var key in configToKey["sprinkles"]) {
        img.src = ["/images/bakery/sprinkles/Filled/", key, ".png"].join('');
        img.src = ["/images/bakery/sprinkles/Hollow/", key, ".png"].join('');
    }
}

initBakery();
