window.addEvent('domready', function() {

    new Request.JSON({   
        url: 'other-psychic-readers-available.php',
        onSuccess: function(json) {
            parse_json(json);
        },
        method: 'get',
        initialDelay: 2000,
        delay: 15000,
        limit: 60000
    }).startTimer({json: 1});
    
});

function parse_json( json_readers) {
    var dom_readers = $$('.Reader');    
    var template_html = $('template');
    
    var pin_array = $A(new Array());
    
    //loop through xml and update the readers. if they don't exist in the dom, then add them
    json_readers.each(function(json) {        
        pin_array.include(json.pin);
        
        //it does not exist, so create it
        if(!$(json.pin)) {
            var new_reader_html = template_html.clone();
            new_reader_html.setProperty('id', json.pin);
            new_reader_html.removeProperty('style');
            
            image_url = json.picture;
            if(image_url != 'None') {
                new_reader_html.getElement('.Picture img').setProperty('src', image_url);
            }
            
            new_reader_html.getElement('.Description').set('text', json.description);
            new_reader_html.getElement('.Name').set('text', json.name); 
            new_reader_html.getElement('.Pin').set('text', json.pin); 
            new_reader_html.getElement('.Status').set('text', json.status); 

            new_reader_html.inject('content');
        } else {
            $(json.pin).getElement('.Status').set('text', json.status);
        }
        
    });
    
    //loop throught he dom and remove any readers that are not in the xml
    dom_readers.each(function(el) {
        var dom_pin = el.id;
        var found = pin_array.indexOf(dom_pin);

        //it's not found in the xml any more, so remove them from the dom
        if(found == -1 && el.id != 'template') {
            el.dispose();
        }    
    });
    
}