

/**
 * Open
 *
 * Popup window utility for creating pop up windows without intrusive using any
 * intrusive code.
 *
 * 
 */
(function ($) {

    $.open = {};

    // Default popup window parameters
    $.open.defaultParams = {
        "width":       "800",   // Window width
        "height":      "600",   // Window height
        "top":         "0",     // Y offset (in pixels) from top of screen
        "left":        "0",     // X offset (in pixels) from left side of screen
        "directories": "no",    // Show directories/Links bar?
        "location":    "no",    // Show location/address bar?
        "resizeable":  "yes",   // Make the window resizable?
        "menubar":     "no",    // Show the menu bar?
        "toolbar":     "no",    // Show the tool (Back button etc.) bar?
        "scrollbars":  "yes",   // Show scrollbars?
        "status":      "no"     // Show the status bar?
    };


    // Some configuration properties
    $.open.defaultConfig = {
        autoFocus: true
    };


    // Open popup window static function
    $.open.newWindow = function (href, params, config) {

        // Popup window defaults (don't leave it to the browser)
        var windowParams = $.extend($.open.defaultParams, params);

        // Configuration properties
        var windowConfig = $.extend($.open.defaultConfig, config);

        var windowName = params["windowName"] || "new_window";

        var i, paramString = "";

        for (i in windowParams) {
            if (windowParams.hasOwnProperty(i)) {
                paramString += (paramString === "") ? "" : ",";
                paramString += i + "=";

                // Allow true/false instead of yes/no in params
                if (windowParams[i] === true || windowParams[i] === false) {
                    paramString += (windowParams[i]) ? "yes" : "no";
                }
                else {
                    paramString += windowParams[i];
                }
            }
        }

        var popupWindow = window.open(href, windowName, paramString);

        if (windowConfig.autoFocus) {
            popupWindow.focus();
        }

        return popupWindow;
    };


    // Plugin method: $("...").popup()
    $.fn.open = function (parameters, callback) {

        var params = parameters.params || parameters;
        var config = parameters.config || {};

        // Loop over all matching elements
        this.each(function (){

            // Add an onClick behavior to this element
            $(this).click(function (event) {

                // Prevent the browser's default onClick handler
                event.preventDefault();

                // Use the target attribute as the window name
                if ($(this).attr("target")) {
                    params.windowName = $(this).attr("target");
                }

                // Determine the url to open
                //   Use param.href over element's href
                var href;
                if (params.href) {
                    href = params.href;
                }
                else if ($(this).attr("href")) {
                    href = $(this).attr("href");
                }
                else {
                    return;  // Can't openWindow anything, so stop here
                }

                
                // Pop up the window
                var windowObject = $.open.newWindow(href, params, config);

                if (callback) {
                    callback(windowObject);
                }
            });
        });

        return $;
    };

})(jQuery);

﻿/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/08/13
 *
 * @author Blair Mitchelmore
 * @version 1.1.3
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});

function request_playlist(){

	$.ajax({
		url: '/escucha.xml',
		type: 'GET',
		beforeSend: function(){
			$("#reproductor").unbind("click");
			$("#reproductor").text("");
			$("#reproductor").addClass("cargando");
			$("#reproductor").removeClass("cargado");
			$("#reproductor").removeClass("sincargar");
			$("#reproductor").removeClass("errorcargando");
			$('<span>Cargando...</span>').addClass('entry_name').appendTo('#reproductor');
			$('<span>Espera unos instantes...</span>').addClass('entry_url').appendTo('#reproductor');
			$("#reproductor").attr("title","Espera unos instantes...");
		},
		error: function(){
			$("#reproductor").click(request_playlist);
			$("#reproductor").text("");
			$("#reproductor").removeClass("cargando");
			$("#reproductor").addClass("errorcargando");
			$('<span>¡Error!</span>').addClass('entry_name').appendTo('#reproductor');
			$('<span>Reinténtalo en unos minutos.</span>').addClass('entry_url').appendTo('#reproductor');
			$("#reproductor").attr("title","Pulsa aquí para cargar la radio");
		},
		success: function(xml){
			$("#reproductor").click(request_playlist);
			$("#reproductor").text("");
			$("#reproductor").attr("title","Pulsa aquí para recargar la radio");
        		$(xml).find('entry').each(function(){
				entry_name=$(this).find('name').text();
				entry_url=$(this).find('url').text();
				$('<audio></audio>').attr('type','audio/ogg; codecs=vorbis').attr('autoplay','true').attr('src',entry_url).attr('name',entry_name).appendTo("#reproductor");
				$('<span>Iniciando buffer...</span>').addClass('entry_status').appendTo('#reproductor');
				$('<span>'+entry_name+'</span>').addClass('entry_name').appendTo('#reproductor');
				$('<span>'+entry_url+'</span>').addClass('entry_url').appendTo('#reproductor');
				$(document).everyTime(800, function() {
                    audio=$('audio').get(0);
                    if(audio){
                        if(audio.networkState==1 || audio.networkState==2){
                            $("#reproductor").removeClass("cargando");
                  			$("#reproductor").addClass("cargado");
					        $(".entry_status").each(function(){
						        $(this).text("Reproduciendo...");
					        });
                        }
                        else{
                            $("#reproductor").removeClass("cargado");
                  			$("#reproductor").addClass("cargando");
					        $(".entry_status").each(function(){
						        $(this).text("Recargando buffer...");
					        });
                        }
                    }
				});
			});
		}
	});

}

$(document).ready(function(){
	$('<span>Pulsa aquí para iniciar el reproductor</span>').addClass('entry_name').appendTo('#reproductor');
	$('<span>Requiere un navegador moderno (no Internet Explorer)</span>').addClass('entry_url').appendTo('#reproductor');
	$("#reproductor").addClass("sincargar");
	$("#reproductor").click(request_playlist);
	$("#repopener").open({
	      width: 380,
	      height: 110,
	      scrollbars: false
	   });
});



function java_load(){

	$.ajax({
		url: '/escucha.xml',
		type: 'GET',
		beforeSend: function(){
			$("#javaductor").unbind("click");
			$("#javaductor").text("");
			$('<span>Cargando...</span>').addClass('entry_name').appendTo('#javaductor');
			$('<span>Espera unos instantes...</span>').addClass('entry_url').appendTo('#javaductor');
			$("#javaductor").attr("title","Espera unos instantes...");
		},
		error: function(){
			$("#javaductor").click(java_load);
			$("#javaductor").text("");
			$("#javaductor").removeClass("cargando");
			$("#javaductor").addClass("errorcargando");
			$('<span>¡Error!</span>').addClass('entry_name').appendTo('#javaductor');
			$('<span>Reinténtalo en unos minutos.</span>').addClass('entry_url').appendTo('#javaductor');
			$("#javaductor").attr("title","Pulsa aquí para cargar la radio");
		},
		success: function(xml){
			$("#javaductor").click(java_load);
			$("#javaductor").text("");
			$("#javaductor").removeClass("cargando");
			$("#javaductor").addClass("cargado");
			$("#javaductor").attr("title","Pulsa aquí para recargar la radio");
        		$(xml).find('entry').each(function(){
				entry_name=$(this).find('name').text();
				entry_url=$(this).find('url').text();
				if(entry_url.match("live.radiobattletoads.com")) applet_dir='http://live.radiobattletoads.com:10002/cortado-ovt-stripped-0.2.2.jar';
				else applet_dir='http://www.radiobattletoads.com/cortado/cortado-ovt-stripped-0.2.2.jar';
				$('<applet></applet>').attr('code','com.fluendo.player.Cortado.class').attr('archive',applet_dir).attr('width','300').attr('height','13').append('<param name="url" value="'+entry_url+'"></param>').append('<param name="seekable" value="false"></param>').append('<param name="video" value="false"></param>').append('<param name="audio" value="true"></param>').append('<param name="live" value="true"></param>').append('<param name="debug" value="4"></param>').appendTo("#javaductor");
				$('<span>'+entry_name+'</span>').addClass('entry_name').appendTo('#javaductor');
				$('<span>'+entry_url+'</span>').addClass('entry_url').appendTo('#javaductor');
			});
		}
	});

}

$(document).ready(function(){
	$('<span>Pulsa aquí para iniciar el reproductor</span>').addClass('entry_name').appendTo('#javaductor');
	$('<span>Requiere JAVA instalado y habilitado</span>').addClass('entry_url').appendTo('#javaductor');
	$("#javaductor").addClass("sincargar");
	$("#javaductor").click(java_load);
});



function hide_estadisticas(){
	$("#estadisticas").slideUp("slow",function(){
		$(".estadisticas").removeClass("estd_cargado");
		$(".estadisticas").unbind("click");
		$(".estadisticas").click(request_estadisticas);
	});
	return false;
}

function request_estadisticas(){

	$.ajax({
		url: '/services/estadisticas.php',
		type: 'GET',
		beforeSend: function(){
			$(".estadisticas").unbind("click");
			$("#estadisticas").slideUp("fast",function(){
				$("#estadisticas").text("");
				$(".estadisticas").addClass("estd_cargando");
				$(".estadisticas").removeClass("estd_cargado");
				$("#estadisticas").slideDown("slow");
			});
		},
		error: function(){
			$("#estadisticas").slideUp("fast",function(){
				$("#estadisticas").text("");
				$(".estadisticas").click(request_estadisticas);
				$('<span>Ha habido un error cargando las estadísticas.</span>').appendTo('#estadisticas');
				$("#estadisticas").slideDown("slow");
			});
		},
		success: function(xml){
			$("#estadisticas").slideUp("fast",function(){
				$("#estadisticas").text("");
				$(".estadisticas").attr("title","Haz clic para recargar las estadísticas").click(hide_estadisticas);
				$(".estadisticas").addClass("estd_cargado");
				$(".estadisticas").removeClass("estd_cargando");
				$("<table></table>").css('width','100%').appendTo("#estadisticas");
				$("<tbody></tbody>").appendTo("#estadisticas table");
				$("<tr></tr>").appendTo("#estadisticas table tbody");
				$("<td>Total de oyentes</td>").css('width','24%').appendTo("#estadisticas table tbody tr");
				numOyentes=0;
				$(xml).find('totalNumOyentes').each(function(){
					numOyentes = $(this).text();
				});
				maxOyentes=0;
				$(xml).find('totalMaxOyentes').each(function(){
					maxOyentes = $(this).text();
				});
				$("<td></td>").css('width','39%').appendTo("#estadisticas table tbody tr");
				$("<td>"+numOyentes+" / "+maxOyentes+"</td>").css('width','9%').appendTo("#estadisticas table tbody tr");
				$('<td><img src="/services/progreso.php?num='+numOyentes+'&amp;max='+maxOyentes+'" /></td>').css('padding-left','3px').css('width','28%').css('text-align','center').appendTo("#estadisticas table tbody tr");
				impar=false;
	        		$(xml).find('emisor').each(function(){
					emisor_nombre=$(this).find('nombre').text();
					emisor_numOyentes=$(this).find('numOyentes').text();
					emisor_maxOyentes=$(this).find('maxOyentes').text();
					$("<tr></tr>").appendTo("#estadisticas table tbody");
					$("<td>Emisión de "+emisor_nombre+"</td>").appendTo("#estadisticas table tbody tr:last");
					$("<td>http://live.radiobattletoads.com:10002/"+emisor_nombre+".ogg</td>").css('width','30%').css('font-size','80%').appendTo("#estadisticas table tbody tr:last");
					$("<td>"+emisor_numOyentes+" / "+emisor_maxOyentes+"</td>").appendTo("#estadisticas table tbody tr:last");
					$('<td><img height="11" src="/services/progreso.php?num='+emisor_numOyentes+'&amp;max='+emisor_maxOyentes+'" /></td>').css('padding-left','3px').css('text-align','center').appendTo("#estadisticas table tbody tr:last");
				});
				$("#estadisticas tbody tr:even").addClass("impar");
				$("#estadisticas").slideDown("slow");
			});
		}
	});
	return false;

}

$(document).ready(function(){
	$("#estadisticas").hide();
	$(".estadisticas").click(request_estadisticas);
});



/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "preloadCssImages"
 * by Scott Jehl, scott@filamentgroup.com
 * http://www.filamentgroup.com
 * reference article: http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/
 * demo page: http://www.filamentgroup.com/examples/preloadImages/index_v2.php
 * 
 * Copyright (c) 2008 Filament Group, Inc
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 *
 * Version: 3.0, 06.21.2008
 * Changelog:
 * 	02.20.2008 initial Version 1.0
 *    06.04.2008 Version 2.0 : removed need for any passed arguments. Images load from any and all directories.
 *    06.21.2008 Version 3.0 : Added options for loading status. Fixed IE abs image path bug (thanks Sam Pohlenz).
 * --------------------------------------------------------------------
 */
jQuery.preloadCssImages = function(settings){
	var settings = jQuery.extend({
		statusTextEl: null,
		statusBarEl: null
	}, settings);
	
	var allImgs = [];//new array for all the image urls  
	var k = 0; //iterator for adding images
	var sheets = document.styleSheets;//array of stylesheets
	
	for(var i = 0; i<sheets.length; i++){//loop through each stylesheet
		var cssPile = '';//create large string of all css rules in sheet
		var csshref = (sheets[i].href) ? sheets[i].href : 'window.location.href';
		var baseURLarr = csshref.split('/');//split href at / to make array
		baseURLarr.pop();//remove file path from baseURL array
		var baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
		if(baseURL!="") baseURL+='/'; //tack on a / if needed
		if(document.styleSheets[i].cssRules){//w3
			var thisSheetRules = document.styleSheets[i].cssRules; //w3
			for(var j = 0; j<thisSheetRules.length; j++){
				cssPile+= thisSheetRules[j].cssText;
			}
		}
		else {
			cssPile+= document.styleSheets[i].cssText;
		}
		
		//parse cssPile for image urls and load them into the DOM
		var imgUrls = cssPile.match(/[^\(]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename"
		var loaded = 0; //number of images loaded
		if(imgUrls != null && imgUrls.length>0 && imgUrls != ''){//loop array\
			var arr = jQuery.makeArray(imgUrls);//create array from regex obj	 
			jQuery(arr).each(function(){
				allImgs[k] = new Image(); //new img obj
				allImgs[k].src = (this.charAt(0) == '/' || this.match('http://')) ? this : baseURL + this;	//set src either absolute or rel to css dir
				
				$(allImgs[k]).load(function(){
						loaded++;
						//send updates to status elements if applicable
						if(settings.statusTextEl) {$(settings.statusTextEl).html('<span class="numLoaded">'+loaded+'</span> of <span class="numTotal">'+allImgs.length+'</span> loaded (<span class="percentLoaded">'+(loaded/allImgs.length*100).toFixed(0)+'%</span>) <span class="currentImg">Now Loading: <span>'+allImgs[loaded-1].src.split('/')[allImgs[loaded-1].src.split('/').length-1]+'</span></span>');
					}
					if(settings.statusBarEl) {
						var barWidth = $(settings.statusBarEl).width();
						$(settings.statusBarEl).css('background-position', -(barWidth-(barWidth*loaded/allImgs.length).toFixed(0))+'px 50%');
					}
				});
				k++;
			});
		}
	}//loop
	return allImgs;
}				
		







function showdespues(){

	$(".ydespues").unbind("click");
	$(".cuandoque").animate({width:0},"slow",function(){
		$(".cuandoque").css("display","none")
		$(".tdespues").text("Antes");
		$(".mdespues").text("«");
		$(".cuandoque2").css("display","block");
		$(".cuandoque2").animate({
			width:'80%'
		},"slow",function(){
			$(".ydespues").click(showantes);
		});
	});

	
	

}

function showantes(){

	$(".ydespues").unbind("click");
	$(".cuandoque").css("display","block");
	$(".cuandoque").animate({
		width:antewidth+'px'
	},"slow",function(){
		$(".ydespues").click(showdespues);
	});
	$(".cuandoque2").animate({width:0},"slow",function(){
		$(".cuandoque2").css("display","none")
	});
	$(".tdespues").text("Después");
	$(".mdespues").text("»");

}

$(document).ready(function(){
	$(".ydespues").click(showdespues);
	antewidth=$(".cuandoque").width();
	$(".tdespues").text("Antes");
	tawidth=$(".tdespues").width();
	$(".tdespues").text("Después");
	tdwidth=$(".tdespues").width();
	$(".tdespues").width(0);

	$(".ydespues").hover(
		function(){
			$(".tdespues").css("display","inline");
			if($(".tdespues").text()=="Antes")
				$(".tdespues").animate({width:tawidth+"px"},"fast");
			else
				$(".tdespues").animate({width:tdwidth+"px"},"fast");
		},
		function(){
			$(".tdespues").animate({width:0},"fast",function(){
				$(".tdespues").css("display","none");
			});
		});

});

