$(document).ready(function() {   
    jQuery.post("/stores/getCategories", { }, function(xml) {
        $("category",xml).each(function(id) {
            i_id = $('category',xml).get(id);
            s_id = $('id', i_id).text();
            s_na = $('name', i_id).text();
            
            $('#site-search').append($('<option value="' + s_id + '">' + s_na + '</option>'));
        });
    });
    
    //This handles the site-search box
    $('#site-search').change(function() {
        //Switch the values, request the info from the databse, update the table on the site, colorbox the table
        var catId = $(this).val();
        if(catId == '0') {
            return;
        }
        
        $('#store-table').empty();
        var row1 = $('<tr></tr>').append($('<th bgcolor="#58595d" style="color: white;">store name</th>')).append($('<th bgcolor="#58595d" style="color: white;">phone #</th>'));
        $('#store-table').append(row1);
        
        jQuery.post("/stores/getStores", { g: catId }, function(xml) {
                $("stores",xml).each(function(id) {
                    i_id = $('stores',xml).get(id);
                    s_id = $('id', i_id).text();
                    s_na = $('name', i_id).text();
                    s_ho = $('hours', i_id).text();
                    s_ph = $("phone", i_id).text();
                    
                    addStore(s_id, s_na, s_ho, s_ph);
                });
                populateTable();
        });
    });
    if(runAd == true) {
        var blah = true;
        var path = '';
        jQuery.post("/stores/getAd", { }, function(xml) {
            $("ad",xml).each(function(id) {
                i_id = $('ad',xml).get(id);
                if($('error',i_id).text() == 'false') {
                    blah = false;
                    return;
                }
                s_id = $('id', i_id).text();
                s_na = $('image', i_id).text();
                
                path = s_na;
            });
            if(blah == true) {
                $.colorbox({ innerWidth:'650px', innerHeight: '450px', inline: true, href: '<img width="600" src="' + path + '" alt="' + path + '" />'});
            }
        });
    }
});

function addStore(id, name, hours, phone) {
    var newRow = $('<tr></tr>');
    var col1 = $('<td style="background-color: #d1d3d4"></td>').html(name);
    var col3 = $('<td style="background-color: #d1d3d4"></td>').html(phone);
    
    $(newRow).append(col1).append(col3);
    
    $('#store-table').append(newRow);
}

function populateTable() {
    $('#store-table').show();
    $.colorbox({inline: true, href: '#store-table', onCleanup: function() {$("#store-table").hide();}});
}
