

/* runs on page load */
var loadCPCMenu = function() {

    // binding to 'change' events, in honor of Obama
    $('#cpcsel1').bind('change', cpcHandler.showCPCSub);
    $('#cpcSubCategory').bind('change', cpcHandler.showCPCProducts);
    $('#cpcProduct').bind('change', cpcHandler.showCPCDetail);

    if (curr_product) { // show menu/select to match this product and category nest
        var curr_cat;
        for (var cat in cpcCategories) { // find top-level category working from bottom up
            for (var subcat in cpcCategories[cat].subcats) {
                if (subcat == curr_subcat) {
                    curr_cat = cat;
                    break;
                }
            }
        }
        if (curr_cat) { // set 3 selects to appropriate values
            $('#cpcsel1').val(curr_cat).trigger('change');
            $('#cpcSubCategory').val(curr_subcat).trigger('change');
            $('#cpcProduct').val(curr_product);
        }
    }
};

var cpcHandler = {

    showCPCSub : function () {
        var selected = $(this).val();
        if (selected != "") {
            $('#cpcSubCategory').empty().append('<option value="" class="prompt"> -- select one -- </option>');
            for (var id in cpcCategories[selected].subcats) {
                $('#cpcSubCategory').append('<option value="'+ id  +'">'+ cpcCategories[selected].subcats[id] +'</option>');
            }
            $('#cpcmenu_sub').show();
            $('#cpcmenu_products').hide();
        }
    },

    showCPCProducts : function() {
        var selected = $(this).val();
        if (selected != "") {
            $('#cpcProduct').empty().append('<option value="" class="prompt"> -- select one -- </option>');
            if (cpcApps[selected]) {
                for (var id in cpcApps[selected]) {
                    $('#cpcProduct').append('<option value="'+ id  +'">'+ cpcApps[selected][id].title +'</option>');
                }
                $('#cpcmenu_products').show();
            }
        }
    },

    showCPCDetail : function () {
        var selected = $(this).val();
        if (selected != "") {
            for (var i=0; i<this.options.length; i++) {
                if (this.options[i].value == selected) {
                    var txt = $(this.options[i]).text(); 
                    break;
                }
            }
            document.location = "/products/covers/cpc/" + selected + "/" + escape(txt.substring(0,16).replace(/\s+/g, '-')) + ".html";
        }
    }
};

$(loadCPCMenu);

