jQuery(document).ready(function() {
    pollstation();
    //refresh the data every 30 seconds
    setInterval(pollstation, 30000);
});

// Accepts a url and a callback function to run.  
function requestCrossDomain( callback ) {  
    // Take the provided url, and add it to a YQL query. Make sure you encode it!  
    var yql = 'http://s7.viastreaming.net/scr/yql.php?port='+port+'&username='+user+'&callback=?';
    // Request that YSQL string, and run a callback function.  
    // Pass a defined function to prevent cache-busting.  
    jQuery.getJSON( yql, cbFunc );
  
    function cbFunc(data) {  
    // If we have something to work with...  
    if ( data ) {  
        // Strip out all script tags, for security reasons. there shouldn't be any, however
        data = data[0].results.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
        data = data.replace(/<html[^>]*>/gi, '');
        data = data.replace(/<\/html>/gi, '');
        data = data.replace(/<body[^>]*>/gi, '');
        data = data.replace(/<\/body>/gi, '');
  
        // If the user passed a callback, and it  
        // is a function, call it, and send through the data var.  
        if ( typeof callback === 'function') {  
            callback(data);  
        }  
    }  
    // Else, Maybe we requested a site that doesn't exist, and nothing returned.  
    else throw new Error('Nothing returned from getJSON.');  
    }  
}  

function pollstation() {
    requestCrossDomain(function(stationdata) {
        
        var lines = stationdata.split('|+|');
        
        jQuery('#sname').html(lines[0]);
		
		jQuery('#sgenre').html(lines[1]);
		
        jQuery('#clisteners').html(lines[2]);
		
		jQuery('#bitrate').html(lines[3]);
       
        jQuery('#currentsong').html('' + jQuery.trim(lines[4]) + '');

		var prev = lines[5].split('+|+');
		jQuery('#prevsong').html('');
		
        for (var i = 0; i < 9; i++) 
		{    
			if(typeof(prev[i]) != 'undefined')
			{			
				jQuery('#prevsong').append(''+ prev[i] + '<br>');
			}
		}	
		
		jQuery('#mplayers').html(lines[6]);	

		jQuery('#mobile').html(lines[7]);
    } );
}
