var player = null;
function playerReady(thePlayer) {
	player = window.document[thePlayer.id];
}

$(document).ready(function() {
	$("#playerspace_holder").corner();

	if($.browser.msie && parseInt(jQuery.browser.version)<=6) {
		alert("On vas amb aquesta versió tan vella d'Internet Explorer?\n\n\n"+
				"Ho sentim, aquesta pàgina no es visualitza bé amb la versió "+jQuery.browser.version+"\n"+
				"Si us plau, instal.la la darrera versió del teu navegador.\n"+
				"T'aconsellem Firefox, que el pots baixar en català amb corrector automàtic d'ortografia en català i tot.");
	}

	resetThumbsHandlers();
	
	if($("#notLoggedHeader:visible").length==1) {
		openModal("#dragDropHint");
		setTimeout(function() {
			if($("#dragDropHint:visible").length>0) {
				$.modal.close();
			}
		},20*1000);
	}
});

var draggedRadio=null;
function resetThumbsHandlers() {
	var thumbDivs = $(".icon_holder");
	thumbDivs.unbind();
	thumbDivs.hover(
		function(evt) {	// in
			if(!dragging) {
				var radioImg=$(this).find("img");
				radioImg.fadeTo(200, 0.4);
			}
		}, 
		
		function(evt) {	// out
			var radioImg=$(this).find("img");
			if(!dragging) {
				radioImg.fadeTo(200, 1);
			}
		}
	);
	thumbDivs.click(radioClicked);

	thumbDivs.draggable({
    	revert: true,
    	revertDuration: 0,
    	cursorAt: {left: 30, top: 30}, 
		start: function() {
    		dragging=true;
    		draggedRadio=$(this).find("img");
    		if(!$.browser.msie) {
    			draggedRadio.unreflect();
    		}
    		draggedRadio.fadeTo(0,1);
		},
		stop: function() {
			setTimeout(function() {
				dragging=false;
			},10);
    		draggedRadio=$(this).find("img");
    		if(!$.browser.msie) {
    			draggedRadio.reflect();
    		}
		}
	});
	
	if($.browser.msie) {
		thumbDivs.find("img").removeClass("reflect");
		setTimeout(function() {
			thumbDivs.find("img").unreflect();
		},500);
	}

	thumbDivs.droppable({
		accept: '.draggable',
		hoverClass: "draggedOver",
		drop: function(event, ui) {
			var doppableImg=$(this).find("img");
			var idDroppable=doppableImg.attr("id").substring("idImg_".length);
			if(draggedCarouselRadio!=null) {
				// a radio from the carousel was dropped 
				var idDraggable=draggedCarouselRadio.attr("id").substring("carouselItem".length);
				
				swapAttributes(doppableImg,draggedCarouselRadio.find("img"),"src");
				doppableImg.attr("id","idImg_"+idDraggable);
				draggedCarouselRadio.attr("id","carouselItem"+idDroppable);
				
				replaceInArray(carouselRadioIds, idDraggable, idDroppable);
				replaceInArray(radioIconIds, idDroppable, idDraggable);
				draggedCarouselRadio=null;
			} else {
				// a radio from the upper radios was dropped 
				var idDraggable=draggedRadio.attr("id").substring("idImg_".length);
				
				swapAttributes(doppableImg, draggedRadio, "src");
				swapAttributes(doppableImg, draggedRadio, "id");
				
				swapInArray(radioIconIds, idDraggable, idDroppable);
				draggedRadio=null;
			}
    		if(!$.browser.msie) {
    			doppableImg.reflect();
    		}
			sendRadiosToServer();
		}
	});

	$("#playerspace_holder").droppable({
		accept: '.draggable',
		hoverClass: "playerDraggedOver",
		drop: function(event, ui) {
			if(draggedCarouselRadio!=null) {
				// a radio from the carousel was dropped 
				var idDraggable=draggedCarouselRadio.attr("id").substring("carouselItem".length);
				draggedCarouselRadio=null;
			} else {
				// a radio from the upper radios was dropped 
				var idDraggable=draggedRadio.attr("id").substring("idImg_".length);
				draggedRadio=null;
			}
			playRadio(idDraggable);
		}
	});
}
	
function goToChannel(url) {
	window.open(url,'mywindow','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=yes,resizable=yes');
}
		
function createPlayer(ur) {
	var flashvars = { file: ur, autostart:"true", type:"sound", duration: "14400" };
	var params = { allowfullscreen:"false", allowscriptaccess:"always", wmode: "opaque" };
	var attributes = { id:"playerspace_main", name:"playerspace_main" };
	swfobject.embedSWF("player.swf", "playerspace_main", "260", "125", "7", null, flashvars, params, attributes, function(e) {
		if(!e.success) {
			var playerVersion = swfobject.getFlashPlayerVersion();
			if(playerVersion.major<7) {
				alert("On vas amb aquesta versió tan vella de Flash? Tu ara tens la versió "+playerVersion.major+". Passa't a la versió de Flash actual.");
			} else {
				alert("Hi havía un problema desconegut amb el flash-player que tens instalat.");
			}
		}
	});
}

function radioClicked(evt) {
	if(dragging) {
		dragging=false;
		return;
	}
	var divElem = $(evt.target);
	var elementId=divElem.attr("id").substring("idImg_".length);

	// check if play or info button was pressed
	var x=evt.pageX-$(divElem).offset().left;
	var y=evt.pageY-$(divElem).offset().top;
	if(x+y>65) {
		if(typeof pageTracker != "undefined") {
			var radio = radios[elementId];
			pageTracker._trackEvent('Radios', 'Info', 'id: '+elementId+" ("+radio.title+")");
		}
		openModal("#info_id_"+elementId);
	} else {
		playRadio(elementId);
	}
}

function playRadio(elementId) {
	var radio = radios[elementId];
	
	if(typeof pageTracker != "undefined") {
		pageTracker._trackEvent('Radios', 'Play', 'id: '+elementId+" ("+radio.title+")");
	}

	if(radio.works=="STREAM") {
		updateEstasEscoltant(radio,elementId);
		createPlayer(radio.url);
	} else {
		$("#current_radio_title").html("");
		$("#current_radio_icon").html("");
		if(player!=null) {
			player.sendEvent('STOP');
		}
		if(radio.works=="POPUP") {
			var width="80%";
			var height="80%";
			if(typeof radio.size != "undefined") {
				width=radio.size.width;
				height=radio.size.height;
			}
			$.fn.colorbox({width:width, height:height, iframe:true, href:radio.url});
		} else if(radio.works=="WINDOW") {
			goToChannel(radio.url);
		} else if(radio.works=="PLS") {
			$.ajax({
				url: "getURLContent.php",
				data: {url: radio.url},
				type: "POST",
				dataType: "text",
				processDataBoolean: false,
				success: function(data) {
		        	var idx=data.indexOf("File1=");
		        	var url=data.substring(idx+"File1=".length);
		        	var eof=url.indexOf("\n");
		        	if(eof!=-1) {
		        		url=url.substring(0,eof);
		        	}
		        	if(!url.endsWith("/")) {
		        		url=url+"/";
		        	}
		    		updateEstasEscoltant(radio,elementId);
					createPlayer(url+";stream.nsv");
		      	}
			});
		}
	}
}

function updateEstasEscoltant(radio,radioId) {
	$("#current_radio_title").html("Estàs escoltant:<br/>"+radio.title);
	$("#current_radio_icon").html("<img src='img/icons2/"+radioId+".png' width='32' height='32'/>");
}


function addBookmark(url,title) {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url, "");
	} else if (window.external) { // IE Favorite
		window.external.AddFavorite(url, title);
	} else if (window.opera) { // Opera 7+
		return false; // do nothing - the rel="sidebar" should do the trick
	} else { // for Safari, Konq etc - browsers who do not support
				// bookmarking scripts (that i could find anyway)
		alert("Aquest navegador no suporta aquesta acció, si us plau, afegeix-nos manualment a les teves adreces d'interès.");
	}
}

function openModal(ele){
	$(ele).modal({	
		closeClass: "modalCloseImg",
		closeHTML: "<a href='#' id='modalCloseImg'></a>",
		
		containerCss:{
			backgroundColor:"#222",
			borderColor:"#FFF",
			//width: 500,
			height: "auto",
			margin: "0 auto",
			position:"relative",
			padding:0,
			display:"none",
			border:"10px solid #FFF"
		},

		onOpen: function (dialog) {
			dialog.overlay.fadeIn('fast', function () {
				dialog.container.corner();
				dialog.data.hide();
				dialog.container.fadeIn('fast', function () {
					dialog.data.fadeIn('fast');
					
				});
			});
		},
		
		onClose: function (dialog) {
			dialog.data.fadeOut('fast', function () {
				dialog.container.fadeOut('fast', function () {
					dialog.overlay.fadeOut('fast', function () {
						$.modal.close();
					});
				});
			});
		},
		
		opacity:80,
		overlayCss: {backgroundColor:"#000"},
		overlayClose:true,
		escClose:true
	});
}

function openTellFriend() {
	$("#friend_name, #name, #friend_email, #email, #comment").val("");

	openModal('#tellfriend');
	setTimeout(function() {
		document.getElementById("friend_name").focus();
	},1000);
}

function tellFriendSubmit() {
	var friendEmail=$("#friend_email");
	if(friendEmail.val()=="") {
		friendEmail.focus();
		alert("Has d'introduir el correu electrònic del destinatari.");
		return false;
	}
	setTimeout(function() {
		$.modal.close();
		setTimeout(function() {
			openModal('#sent');
		},800);
	},500);
	
	return true;
}		

function replaceInArray(theArray, val1, val2) {
	for(var i=0; i<theArray.length; i++) {
		if(theArray[i]==val1) {
			theArray[i]=val2;
			break;
		}
	}
}

function swapInArray(theArray, val1, val2) {
	replaceInArray(theArray, val1, "_dummy");
	replaceInArray(theArray, val2, val1);
	replaceInArray(theArray, "_dummy", val2);
}

function swapAttributes(jQueryObj1, jQueryObj2, attribute) {
	var attrVal1=jQueryObj1.attr(attribute);
	jQueryObj1.attr(attribute, jQueryObj2.attr(attribute));
	jQueryObj2.attr(attribute, attrVal1);
}

/**
 * @return null if the emailStr is a parseable email, an error string otherwise
 */
function checkEmail(emailStr) {
	var emailPat=/^(.+)@(.+)$/;
  	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		return "Email seems to be incorrect";
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	var i=0;
	for (i=0; i < user.length; i++) {
		if (user.charCodeAt(i)>127) {
			return "The email contains illegal characters";
		}
	}
	for (i=0; i < domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			return "The domain of the email is incorrect";
	   }
	}
	if (user.match(userPat)==null) {
		return "The email seems to be incorrect";
	}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
				return "The IP of the email is incorrect";
		    }
	    }
	    return true;
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i < len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			return "The domain of the email is incorrect";
		}
	}
	
	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>6) {
		return "The domain of the email is too long or too short";
	}
	
	if (len<2) {
		return "The email does not have a domain";
	}
	return null;
}

String.prototype.endsWith = function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
};


/* Radio stations have three different work states:
- STREAM, can be played directly with embedded player
- POPUP, radio's web page can be loaded in javascript popup
- WINDOW, radio's web page needs to be opened in new browser window
*/
var radios={
	1: {url:"http://players40.iccbroadcast.com/players/GUMFM/reproductor_radio_gum.php", works:"POPUP", size: {width:"550px", height:"400px"}, title:"GUM FM"},
	2: {url:"http://stream.franclr.fr/lecteur.php?id=8", works:"POPUP", size: {width:"280px", height:"260px"}, title:"Arrels"},
	3: {url:"http://www.rtva.ad/difusio/Rna.htm", works:"POPUP", size: {width:"360px", height:"360px"}, title:"RNA Andorra"},
	4: {url:"http://www.radiovilafant.net/endirecte", works:"POPUP", size: {width:"710px", height:"190px"}, title:"Radio Vilafant"},
	5: {url:"http://www.radiobanyoles.cat/streaming_finestra.php", size: {width:"400px", height:"400px"}, works:"POPUP", title:"Radio Banyoles"},
	6: {url:"http://www.laradioactivitat.com/reproductor.html", works:"POPUP", size: {width:"600px", height:"400px"}, title:"La radio activa"},
	7: {url:"http://www.begur.cat/web/cat/radio.php", works:"POPUP", size: {width:"450px", height:"260px"}, title:"Radio Begur"},
	8: {url:"http://www.comunicaciopalafrugell.cat/modules/mod_ngs_shoutcast/singleplaylist.php?ip=217.126.88.182&port=8000&format=PLS", works:"PLS", title:"Palafrugell"},
	9: {url:"http://213.98.133.85:8000/;stream.nsv", works:"STREAM", title:"IIR Llagostera"},
	10: {url:"http://www.emisorasonline.net/conexion/v5.0/player50/index.php?cc=000686&cont=000396", works:"POPUP", size: {width:"450px", height:"360px"}, title:"Arenys de Munt"},
	11: {url:"http://www.novaradiolloret.org", works:"POPUP", title:"Nova Radio Lloret"},
	12: {url:"http://streaming01.ib3radio.com:8000/ib3radio.mp3", works:"STREAM", title:"IB3"},
	13: {url:"http://www.proxima.cat/radio/index.html", works:"POPUP", size: {width:"650px", height:"450px"}, title:"Pròxima fm"},
	14: {url:"http://www.ona-fm.cat/streaming/streaming.php", works:"POPUP", size: {width:"360px", height:"500px"}, title:"Radio Ona"},
	15: {url:"http://87.98.148.253/castcontrol/playlist.php?id=14", works:"PLS", title:"STYL FM"},
	16: {url:"http://www.icatfm.cat", works:"WINDOW", title:"iCat fm"},
	17: {url:"http://www.catradio.cat/endirecte", works:"POPUP", title:"Catalunya Radio"},
	18: {url:"http://rac1.org/wp-content/plugins/rac-player/reproductor.php", works:"POPUP", size: {width:"585px", height:"300px"}, title:"RAC 1"},
	19: {url:"http://www.rac105.cat/player/rac105-fm", works:"POPUP", size: {width:"510px", height:"295px"}, title:"RAC 105"},
	20: {url:"http://radio.boothosting.com:8058/;stream.nsv", works:"STREAM", title:"Alcudia Radio"},
	21: {url:"http://www.canalblau.cat/cb4/online/radiopop.asp", works:"POPUP", size: {width:"450px", height:"450px"}, title:"Canal Blau"},
	22: {url:"http://radiotime.com/WebTuner.aspx?StationId=80764", works:"POPUP", size: {width:"460px", height:"310px"}, title:"Radio Vic 90.3"},
	23: {url:"http://www.radioflaixbac.cat/seccions/directe/content/irc/index.php", size: {width:"455px", height:"455px"}, works:"POPUP", title:"Radio Flaixbac"},
	24: {url:"http://www.rtve.es/radio/radio4-endirecto", works:"POPUP", size: {width:"410px", height:"320px"}, title:"Ràdio 4"},
	25: {url:"http://www.catradio.cat/reproductor/catinfo", works:"POPUP", size: {width:"710px", height:"510px"}, title:"Catalunya informació"},
	26: {url:"http://www.comradio.com/flash/index.asp", works:"POPUP", size: {width:"950px", height:"650px"}, title:"Com Radio"},
	27: {url:"http://comradioblocs.com/latincom/", works:"POPUP", size: {width:"950px", height:"450px"}, title:"LatinCom"},
	28: {url:"http://88.2.136.150:8000/;stream.nsv", works:"STREAM", title:"Som i Serem"},
	29: {url:"http://www.cugat.cat/directe/index.php", works:"POPUP", size: {width:"390px", height:"350px"}, title:"Cugat ràdio 91.5 FM"},
	30: {url:"http://www.radiosabadell.fm/layout/set/radio", works:"POPUP", size: {width:"330px", height:"250px"}, title:"Radio Sabadell 94.6"},
	31: {url:"http://www.flaixfm.cat/seccions/directe/content/irc/index.php", works:"POPUP", size: {width:"470px", height:"500px"}, title:"Flaix fm"},
	32: {url:"http://www.radiosio.com", works:"WINDOW", title:"Ràdio Sió Agramunt"},
	33: {url:"http://www.emisorasonline.net/conexion/v5.0/player50/index.php?cc=001004&cont=000551", works:"POPUP", size: {width:"450px", height:"390px"}, title:"ONA FM"},
	34: {url:"http://stream.giss.tv:8000/r90.mp3", works:"STREAM", title:"Ràdio 90"},
	35: {url:"http://rcb.cat/player.htm", works:"POPUP", size: {width:"450px", height:"440px"}, title:"Badalona"},
	36: {url:"http://www.catclassica.cat/flash/player_directe_cc.swf?streamUrl=catclassica.directe-flv.emissio.catradio.cat/live|@|CatClassica_FLV_1@1246", works:"POPUP", size: {width:"280px", height:"160px"}, title:"Cat Clàssica"},
	37: {url:"http://www.catmusica.cat/flash/player_directe_cm.swf?streamUrl=catmusica.directe-flv.emissio.catradio.cat/live|@|CatMusica_FLV_1@1599", works:"POPUP", size: {width:"280px", height:"160px"}, title:"Cat Mùsica"},
	38: {url:"http://www.radiointerdominios.com:8040/;stream.nsv", works:"STREAM", title:"El Prat Radio"},
	39: {url:"http://www.elive5.es/player/?i=2&elive=RA222", works:"POPUP", size: {width:"430px", height:"450px"}, title:"L'H'"},
	40: {url:"http://www.rtvmallorca.cat/#radio", works:"POPUP", size: {width:"500px", height:"510px"}, title:"ona Mallorca 98.0 fm"},
	41: {url:"http://www.rap107.fm:18000/;stream.nsv", works:"STREAM", title:"Rap 107 fm 107.8"},
	42: {url:"http://www.rtvvilafranca.cat/radio-en-directe.html", works:"POPUP", title:"Radio Vilafranca"},
	43: {url:"http://www.punt6radio.cat:8500/listen.pls", works:"PLS", title:"99.8 punt sis radio"},
	44: {url:"http://www.tarragonaradio.cat/stream.asp", works:"POPUP", size: {width:"550px", height:"450px"}, title:"Tarragona radio 96.7"},
	45: {url:"http://panel.soydigital.fm/tunein.php/totmusica/playlist.pls", works:"PLS", title:"TOT Musica 105.1 fm"},
	46: {url:"http://www.ciutatdigital.cat:8000/ampostaradio", works:"STREAM", title:"Amposta radio"},
	47: {url:"http://server1.beatproducciones.com:8038/;stream.nsv", works:"STREAM", title:"Imagina ràdio"},
	48: {url:"http://www.canalgv.com/app/player/default.cfm?int_ElementId=1502&int_LanguageId=1", works:"POPUP", size: {width:"700px", height:"450px"}, title:"Radio Nou Castelló"},
	49: {url:"http://www.rtvv.es/va/directo/radio9valencia.html", works:"POPUP", size: {width:"850px", height:"450px"}, title:"Radio Nou València"},
	50: {url:"http://www.canalgv.com/app/player/default.cfm?int_ElementId=1501&int_LanguageId=1", works:"POPUP", size: {width:"700px", height:"450px"}, title:"Radio Nou Alacant"},
	51: {url:"http://www.canalgv.com/app/player/default.cfm?int_ElementId=1499&int_LanguageId=1", works:"POPUP", size: {width:"700px", height:"450px"}, title:"Radio Nou SisRadio"},
	52: {url:"http://www.radioaktivat.org", works:"WINDOW", title:"Ràdio Aktiva"},
	53: {url:"http://www.radioarenys.cat/php/directeplayer.php", works:"POPUP", size: {width:"470px", height:"300px"}, title:"Arenys de Mar"},
	54: {url:"http://91.121.92.186:8002/;stream.nsv", works:"STREAM", title:"Capital de l'Emporda"},
	55: {url:"http://tunein.com/tuner/?StationId=115601", works:"POPUP", size: {width:"620px", height:"475px"}, title:"Voltregà"},
	56: {url:"http://sites.google.com/site/radiosantasusanna", works:"POPUP", size: {width:"720px", height:"520px"}, title:"Ràdio Santa Susanna 91.7 FM"},
	57: {url:"http://www.solsonafm.cat/", works:"WINDOW", title:"Solsona"},
	58: {url:"http://radio.vilassardemar.cat/wp-content/vila.html", works:"POPUP", size: {width:"450px", height:"480px"},  title:"Vilassar"},
	59: {url:"http://www.radiocassa.cat", works:"POPUP", size: {width:"800px", height:"250px"}, title:"Ràdio Cassà"},
	60: {url:"http://www.totradio.com:8000/128kbps", works:"STREAM", title:"Tot ràdio"},
	61: {url:"http://www.igualada.cat/cat/Radio", works:"POPUP", size: {width:"550px", height:"300px"}, title:"Igualada"},
	62: {url:"http://www.constantiradio.cat", works:"WINDOW", title:"Constantí Ràdio"},
	63: {url:"http://stream.zuperdns.net:9110/;stream.nsv", works:"STREAM", title:"Ràdio Tot Bisbal"},
	64: {url:"http://www.labonaradio.com/index_cat.htm", works:"POPUP", size: {width:"900px", height:"650px"}, title:"La Bona ràdio"},
	65: {url:"http://www.el9nou.cat/el9fm_directe.php", works: "POPUP", size: {width:"400px", height:"320px"}, title:"El 9 FM"},
	66: {url:"http://www.elive5.es/player/? i=2&elive=RA217", works: "POPUP", size: {width:"400px", height:"430px"}, title:"Ràdio Tàrrega"},
	67: {url:"http://www.molinsderei.cat/radio", works: "WINDOW", title:"Molins de rei"},
	68: {url:"http://www.argentonacomunicacio.cat/radio_directe", size: {width:"750px", height:"230px"}, works: "POPUP", title:"Argentona"},
	69: {url:"http://radio1.aasit.net:8000/rvilanova.mp3", works: "STREAM", title:"Ràdio Nova (Vilanova del Camí)"},
	70: {url:"http://www.elive5.es/player/?i=2&elive=RC023", works: "POPUP", size: {width:"410px", height:"425px"}, title:"Canals Ràdio"}
};

