var psURI = new URI();

ordine=[1, 2, 3, 4];
i=0;
opp=0;
b=1;
w=1;
callingajax = 0;
fc = new Array();
lasturl = psURI.get('fragment')


//<input type="text" name="denominazione_sociale" value="" class="required">
function fada(el)
{
	if(fc[el]==4)
	{
		$$('ul#rotator_'+el+' li').fade('show');
		fc[el] = 1;
		fada(el);
		return;
	}
	else
	{
		$(el+fc[el]).fade('out')
		setTimeout("fada('"+el+"')",4000);
	}
fc[el]++;
}


function addwork()
{
	if(w<=10)
	{
		work = new Element('textarea', {'name': 'portfolio[]'});
		work.inject($('portfolio'));	
	}
	w++;
}

function calendario(mese,anno)
{

	$('cal').destroy();
	//$('calendario').load('/inc/php/maggiordomo.php?op=calendario&mese='+mese+'&anno='+anno);
		var cal = new Request.HTML({
		url: '/inc/php/maggiordomo.php?op=calendario&mese='+mese+'&anno='+anno,
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
			$('calendario').set('html',responseHTML);
			link_ajax()
			myTips = new Tips('.tip', {offset:{'x':-265,'y':75},fixed: true, hideDelay: 0});		
		}	
	}).get();	

}

function like_fb()
{
	if($('like_fb'))
	{
		if (lasturl != "") {
			lasturlfb = lasturl;
		} else {
			lasturlfb = psURI.get('directory');
		}
		$('like_fb').empty();
		var fbsharelink = new Element('a', {
			'target': 'blank',
			'href': 'http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.pugliasounds.it'+lasturlfb
		})
		var fbshare = new Element('img', {
			'src': '/images/condividi.png'
		})
		var fblike = new Element('iframe', {
			'src': 'http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.pugliasounds.it'+lasturlfb+'&amp;layout=standard&amp;show_faces=true&amp;width=350&amp;action=like&amp;font=trebuchet+ms&amp;colorscheme=light&amp;height=80',
			'scrolling': 'no',
			'allowTransparency': 'true',
			'frameborder': '0'
		});
		fbshare.inject(fbsharelink)
		$('like_fb').adopt(fbsharelink,fblike)
	}
}

function link_ajax()
{
			$$('.link, #b_pugl a').addEvent("click", function(e){
			e.stop();
			lasturl = this.get('href')
			if (this.get('href') != "") {
				lasturl = lasturl.replace('http://www.pugliasounds.it','')
				var urlarray = lasturl.split("/");
				
				if (this.hasClass("aprichiudi")) {
					aprichiudi(urlarray[2]);
				} 
			
				if (urlarray[1] == "d") {
					where = urlarray[2] == "0" ? "home" : "interna";
					caricapagina(urlarray[2], urlarray[4], urlarray[5], urlarray[3], where,"si")
				}
			}
		})
	like_fb();
	Mediabox.scanPage();
}

function aprichiudi(item) {
	elem=document.getElementById('m'+item);
	visibile=(elem.style.display!="none")
	if (visibile) { elem.style.display="none"; } 
	else { elem.style.display="block"; }
}

function preanima()
{
	ordine.sort(function(){
	return 0.5 - Math.random()
	});
	anima(i);
	setTimeout("preanima()",13000);
}

function anima(n) {

	myFx = new Fx.Tween('uno'+ordine[n], {duration: 1000, transition: Fx.Transitions.Elastic.easeOut}).addEvent('start', function(e){

		if(i==3) {
			if(b==6) b=-1;
			b++;
			i=0;
			return false;
		}
		i++;
		setTimeout("anima("+i+")",300);
	});
	myFx.start('margin-top', (b*(-207)));
}	

function accordion_fixed(corrente)
{
	if(window.ie6) var heightValue='100%';
	else var heightValue='';
	if(corrente<0) corrente = -1; 
	window.addEvent('domready', function() {
		
		
	var myAccordion = new Accordion($$('.toggler'), $$('.element'), {
		   display: corrente,
		   alwaysHide: true,
		onActive: function(toggler){ toggler.addClass('active');},
		onComplete: function() {
		   var element=$(this.elements[this.previous]);
		   if(element && element.offsetHeight>0) element.setStyle('height', heightValue);         
		},
		onBackground: function(toggler){ toggler.removeClass('active');}
	});
	});
}


function invia(top){
	
$('div_expo').fade('out');

$('messaggio').morph({display: 'block', height: 200, 'margin-top': 100});


	var ajax = new Request.HTML({
		url: $('ajaxform').get("action"),
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
						$('messaggio').set('html',responseHTML);
		},
		onFailure: function(){
			$('messaggio').set('text', 'Richiesta fallita.');
		}		
	}).post($('ajaxform'));
		
}
function homepage(){

	//		$('col1').adopt($('b_evid'), $('b_play'));
	
	if (interna == 1) {
		$('corntopcal').dispose();
		$('col1').set('class', 'colonna colonna-double');
		$('col2').set('class', 'colonna colonna-double');
		$('col2').inject($('col1'), 'after');
		$('riservata').set('class', 'box');
		$('b_evid').set('class', 'box double bianco');
		$('b_cale').set('class', 'box verde-scuro h-190 calendario');
		$('b_rass').set('class', 'box grigio-medio rassegna');
		$('b_arti').set('class', 'box-right verde-chiaro artisti');
		$('b_play').set('class', 'box double grigio-chiaro player');
		$('col2').adopt($('b_pugl'), $('b_rass'), $('b_arti'));
		$('col1').adopt($('b_evid'),$('b_news_clear'),$('b_news'), $('b_play'));
		$('col3').adopt($('b_cale'), $('riservata'));
		$('b_pugl').setStyle("display", "block");
		$('col3').setStyle("display", "block");
		$('b_news').setStyle("display", "block");
		$('b_news_clear').setStyle("display", "block");		
		//$('titolo').set("text","PUGLIA SOUNDS - The music system"); 	
		interna = 0;
	}
	
}

function paginainterna(titolo){
	
	// effettua il morphing dei box del layout
	//$('col1').morph('.colonna-cinque');
	if (interna == 0) {
		new Element("div", {
			'id': 'corntopcal',
			'class': 'corntop-20'
		}).inject('b_cale');

		$('col1').set('class', 'colonna colonna-cinque');
		$('col2').set('class', 'colonna-right-pages');
		$('riservata').set('class', 'box-right');
		$('b_evid').set('class', 'box double bianco h-380 quattro37');
		$('b_cale').set('class', 'box verde-scuro h-190 calendario right9 topzero padd-top-40');
		$('b_rass').set('class', 'box grigio-medio rassegna left_rass');
		$('b_arti').set('class', 'box-right verde-chiaro artisti right9');
		$('b_play').set('class', 'box-right double grigio-chiaro player meno35');
		$('col2').adopt($('riservata'), $('b_cale'), $('b_arti'));
		$('col1').adopt($('col2'), $('b_rass'));
		$('b_pugl').setStyle("display", "none");
		$('col3').setStyle("display", "none");
		$('b_news').setStyle("display", "none");
		$('b_news_clear').setStyle("display", "none");
		interna = 1;		
	}
	//$('titolo').set("text","PUGLIA SOUNDS - "+titolo); 
}

function scegli_genere()
{
	caricapagina('91', 'genere', '1', 'genere', 'genere','si');
}

function caricapagina(cat, id, pag, pagina, tipo, animazione) {

	if(callingajax == 1)
	{
		HTMLRequest.cancel();
	}
	phpage = "inc_pagine.php";


	if(tipo=="genere")
	{
		phpage = "inc_pagine.php?cat=91&id="+id+"&pag="+pag;
		paginainterna("genere");
	}
	if(tipo=="cercaevento")
	{
		phpage = "inc_pagine.php?cat=98&id="+id+"&pag="+pag;
		paginainterna("cercaevento");
	}
	if(tipo=="cerca")
	{
		phpage = "inc_pagine.php?cat=93&id="+id+"&pag=1";
		paginainterna("cerca");
	}
	else if(tipo=="form")
	{
		phpage = "inc_contatti.php";
		paginainterna("form");
	}
	else if(tipo=="home")
	{
		homepage();
		phpage = "inc_home.php";
	} else {paginainterna(pagina);}
		
	//$('custom_content').empty();
	$('custom_content').addClass("loading");
	var variabili = {"pag":pag, "cat":cat, "id":id, "key": pagina};

	HTMLRequest = new Request.HTML({evalScripts: false,
		onRequest: function()
		{
			callingajax = 1;
		},
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {

			$('custom_content').removeClass("loading");
			$('custom_content').innerHTML = responseHTML;
			
			cat=null;
			eval(responseJavaScript);
			$$('.link, #b_pugl a, #custom_content a').removeEvents('click');
		/*	if(Browser.Engine.name!="trident"){ 
			$$('form.ajax').removeEvents('submit');       
			}
			*/
			link_ajax();
			
			$$('a[rel=blank]').set('target','_blank');
			callingajax = 0;
			like_fb();
			pageTracker._trackPageview(lasturl);
		}
	});
	if (tipo != "form" && tipo!="cerca" && tipo!="cercaevento" && tipo!="genere") {
		HTMLRequest.get("/" + phpage, variabili);
		
	} else
	{
		HTMLRequest.post("/" + phpage, $(id));
	}
	var fragments = ""; 
	if(id!="") fragments = id+"/";
	if(pag>0) fragments += pag+"/";
	if (animazione == "si") {

		psURI.set('fragment', '/d/' + cat + '/' + pagina + '/' + fragments);
		psURI.go();
	}
			var vaisu = new Fx.Scroll($(document.body)).toTop();
			
			
			
	aggiorna_banner();
	/*
	if (animazione != "no") { 
	
		//ordine.sort(function(){
		//	return 0.5 - Math.random()
		//});
	
			
			var vaisu = new Fx.Scroll($(document.body), {
			    onComplete: function(){
					//setTimeout("anima("+i+")",1000);
			    }
			}).toTop();

	}
	*/
	
}
	

function aggiorna_banner()
{
	var ajax = new Request.HTML({
		url: '/inc/php/banner.php',
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
						$('banner').set('html',responseHTML);
		}	
	}).get();
}

var validate = new Class({
	
	getOptions: function(){
		return {
			validateOnBlur: true,
			errorClass: 'error',
			errorMsgClass: 'errorMessage',
			dateFormat: 'dd/MM/yy',
			_onFail: $empty,
			_onSuccess: 'invia()',
			showErrorsInline: true,
			label: 'Please wait...',
			form2: false,
			replay: false,
			top_servizi: true
		};
	},

	initialize: function(form, options){
		this.setOptions(this.getOptions(), options);
		this.form = $(form);
		this.elements = this.form.getElements('.required');			
		
		this.list = [];
		
		this.elements.each(function(el,i){
			if(this.options.validateOnBlur){
				el.addEvent('blur', this.validate.bind(this, el));
			}
		}.bind(this));
		
		if(this.options.replay == false)
		{
		
			this.form.addEvent('submit', function(e){
				var event = new Event(e);
				var doSubmit = true;
				var classe = "required"
				this.elements.each(function(el, i){
	
					if (el.hasClass(classe)) {
						if (!this.validate(el)) {
							event.stop();
							doSubmit = false;
							this.list.include(el);
							$("errorMessage").set('html', errore_txt);
							$("errorMessage").set('style','display:block');
							//setTimeout(function() {new Fx.Scroll(window).toElement('form_ap');}, 1500); 
						}
						else {
							this.list.erase(el);
						}
					}
					
				}
.bind(this));
				
				if (doSubmit) {
					if (this.options._onSuccess) {
						event.stop();
						
						invia(this.options.top_servizi);
					//this.options._onSuccess(this.form);
					}
					else {
						this.form.getElement('input[type=submit]').setProperty('value', this.options.label);
					}
				}
				else {
					this.options._onFail(this.getList());
				}
				
				return false;
				
			}
.bind(this));
		}
		
	},
	getList: function(){
		var list = new Element('ul');
		this.list.each(function(el,i){
			if(el.title != ''){
			var li = new Element('li').inject(list);
			new Element('label').set({
				'for': el.id,
				'text': el.title
			}).inject(li);
			}
		});
		return list;
	},
	
	validate: function(el){
		var valid = true;
		this.clearMsg(el);
		
		switch(el.type){
			case 'text':
			case 'textarea':
			case 'select-one':
				if(el.value != ''){
					if(el.hasClass('email')){
						var regEmail = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
						if(el.value.toUpperCase().match(regEmail)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el);
							//this.setMsg(el, 'Please enter a valid email address');
						}
					}
					
					if(el.hasClass('number')){
						var regNum = /[-+]?[0-9]*\.?[0-9]+/;
						if(el.value.match(regNum)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el);
						}
					}
					
					if(el.hasClass('postcode')){
						var regPC = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/
						if(el.value.match(regPC)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, 'Please enter a valid postcode');
						}
					}
					
					if(el.hasClass('date')){
						var d = Date.parseExact(el.value, this.options.dateFormat);
						if(d != null){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, 'Please enter a valid date in the format: '+this.options.dateFormat.toLowerCase());
						}
					}
					
				}else{
					valid = false;
					this.setMsg(el);
				}
				break;
				
				
				
				case 'checkbox':

				if(!el.checked){
					valid = false;
					this.setMsg(el);	
					$(el.get("name")).addClass('error');	
				}else{
					valid = true;
					$(el.get("name")).removeClass('error');	
				}
				break;
				
				
				
			case 'radio':
				var rad = $A(this.form[el.name]);
				var ok = false;
				rad.each(function(e,i){
					if(e.checked){
						ok = true;
					}
				});
				if(!ok){
					valid = false;
					this.setMsg(rad.getLast(), '');
				}else{
					valid = true;
					this.clearMsg(rad.getLast());
				}
				break;
				
		}
		return valid;
	},
	
	setMsg: function(el, msg){
		if(msg == undefined){
			msg = el.title;
		}
		el.addClass("error");
	},
	
	clearMsg: function(el){
		el.removeClass("error");
	}
	
});

validate.implement(new Options);
validate.implement(new Events);


/*************************************************************/


function ptp(what,idartista)
{
	$$('ul#tabs li').removeClass('active');
	what2 = what=='init' ? 'shuffle' : what;
	switch(what)
	{
		case 'init':
		case 'shuffle': $('shuffle').set("class","active"); break;
		case 'play_count': $('play_count').set("class","active"); break;
		case 'play_new': $('play_new').set("class","active"); break;
		case 'play_artist':
		case 'play_dinamic': opp = 5; break;
	}

	new Request.JSON({
	url: '/inc/php/maggiordomo.php?op=player&id_artista='+idartista+'&w='+what2,
	onComplete: function(jsonObj) {
		
			addplaylist(jsonObj.playlist);
			
	myFxp = new Fx.Tween('t0');
if(what=='init')
{
	$f("huluPlayer", 
	{
		src: 'http://player.ccbclab.it/flowplayer.commercial-3.1.5.swf', 
		wmode: 'transparent'
	},
	 {
			key: '#@7fba45c43d2b0774e2a', 
	
		clip: {   
	        autoPlay: false, 
	        autoBuffering: false,
	        onBegin: function() { v($f("huluPlayer").getClip().index,opp) },
	        onLastSecond: function() {
				var actclip = $f("huluPlayer").getClip().index;
				new Request.JSON({url: '/inc/php/maggiordomo.php?op=conta&id_audio='+$("t"+actclip).get('rid')}).send();}
		},
		playlist: newplaylist,
	   
			plugins: {
			controls: {
			playlist: true,
	        all: false,
	        play: true, 
	        scrubber: true,
	        mute: true,
	        
	      tooltipColor: '#ffffff',
	      sliderColor: '#5e5e5e',
	      sliderGradient: 'none',
	      timeBgColor: '#555555',
	      progressGradient: 'none',
	      buttonColor: '#4C4C4C',
	      bufferGradient: 'none',    
	      progressColor: '#0397f9',
	      bufferColor: '#4C4C4C', 
	      backgroundColor: '#222222', 
	      tooltipTextColor: '#0296f8',
	      buttonOverColor: '#0296f8',
	      borderRadius: '0',
	      volumeSliderColor: '#000000',
	      volumeSliderGradient: 'none',
	      timeColor: '#5E5E5E',
	      backgroundGradient: 'none',
	      durationColor: '#ffffff',
	      height: 21,
	      opacity: 1.0
			},
			        audio: { 
			        url: 'flowplayer.audio-3.1.2.swf'
			    } 
	
			}
	 	});			
}			 
else
{
	$f("huluPlayer").setPlaylist(newplaylist);
	$f("huluPlayer").play();
}			
			
			            
		}    
	}).send();
}

function v(videoid,op)
{
	//alert("schermata "+(videoid/3).toInt());
	if (op != 5) {
		if (videoid != 0 && videoid != 5) 
			myFxp.start('margin-top', (-42 * videoid) + 42);
	}
	 if (op != 3) {
	 	$f("huluPlayer").play(videoid.toInt());
	 }
	$$("ul#playlist li").removeClass("active");
	$("t"+videoid).addClass("active");
} 


var addplaylist = function(tracks) {
		$('playlist').empty();
		newplaylist = new Array;
		d=0;
		tracks.each(function(track) {
		autoplay = d == 0 ? false:true;
		newplaylist[d] = {
			'url': track.file,
			'autoPlay': autoplay
		};
		var classe = d%2 == 1 ? "chiara":"";
		lileft = new Element("div",{'class':'left'});
		lis = new Element("span",{'class':'cover', 'html': '&nbsp;'});    
		lib = new Element("span",{'class':'songname', 'text': track.branonome});
		lib.adopt(lis)
		lispann = new Element("a",{'href':'/d/91/Artisti/'+track.artistaid+'/', 'class':'link','text':track.artistanome})
		libr = new Element("br");
		libr.inject(lileft,"top");
		lib.inject(lileft,"top");
		lispann.inject(lileft);
		divs = new Element("div",{'class':'song', 'style':'background-image: url('+track.img+')'});
		divm = new Element("div",{'class':'song-mask'});
		divm.inject(divs);
		librano = new Element("li", {'id': 't'+d, 'rid': track.branoid, 'vid': d, 'class': classe, 'events': {
        'click': function(){
            v(this.get("vid"),opp);
        }}}).adopt(lileft,divs).inject($('playlist'));	
		d++;
		});
		link_ajax();
	};

/*

window.onhashchange = function() {
		var urlarray = location.hash.split("/");
		if (urlarray[1] == "d") {
			where = urlarray[2] == "0" ? "home" : "interna";
			caricapagina(urlarray[2], urlarray[4], urlarray[5], urlarray[3], where, "no")
		}
}


*/

window.onload = function() {

	if (Browser.Engine.name != "trident") {
		
		$('ajaxnewsletter').addEvent("submit", function(e){
			e.stop();
			caricapagina('85', 'ajaxnewsletter', '2', 'CONTATTI', 'form',"si");
		})
		$('cerca').addEvent("submit", function(e){
			e.stop();
			caricapagina('93', 'cerca', '1', 'CERCA', 'cerca',"si");
		})

	}	
	
	//link_ajax();

	if (psURI.get('fragment') != "") {
		var urlarray = psURI.get('fragment').split("/");
		if (urlarray[1] == "d") {
			where = urlarray[2] == "0" ? "home" : "interna";
			caricapagina(urlarray[2], urlarray[4], urlarray[5], urlarray[3], where, "si")
		}
	}

 	$$('.gohome').addEvent("click", function(e){
		e.stop();
		caricapagina(0,0,0, "HOMEPAGE", "home","si");
	})

	ptp('init');
		
	setTimeout("preanima()",2000);
	$$('a').set('target','_blank');


	$$('ul#tabs li').addEvent('click', function(event){
		opp = 2;
		ptp(this.get('id'))
	});

	$('newsl').addEvent('focus', function(){
		if (this.get("value") == 'your@email.here') 
		{	
			this.set('value', '');
		}
	});
	$('newsl').addEvent('blur', function(){
		if (this.get("value") == '') 
		{	
			this.set('value', 'your@email.here');
		}
	});

new Asset.css('/inc/mediabox/mediaboxAdvBlack.css');

};


window.addEvent('hashload',function(data) {
		if ("/"+data.hash+"/" != lasturl) {
			var urlarray = data.hash.split("/");
			if (urlarray[0] == "d") {
				where = urlarray[1] == "0" ? "home" : "interna";
				if(urlarray[1]==85) where = "form";
				if(urlarray[1]==93) where = "cerca";
				if(urlarray[1]==98) where = "cercaevento";
				if(urlarray[1]==91) where = "genere";
				caricapagina(urlarray[1], urlarray[3], urlarray[4], urlarray[2], where, "no")
			}
		}
});

