//AICI SE PUNE TOT CE NECESITA VERIFICARE DE BODY ONLOAD - !!! SA RAMANA IN TOPUL DOCUMENTULUI !!!

Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;

var iniValInput = new Array();

document.observe('dom:loaded',
	function(event){
		
		//PUNEM BANNERELE INCARCATE IN FOOTER ACOLO UNDE TREBUIE SA APARA

		if($$('div.pubtop').length > 0 && $('banner728')) {
			$$('div.pubtop')[0].appendChild($('banner728'));
		}

		if($$('div.pub350').length > 0 && $('banner300')) {
			$$('div.pub350')[0].appendChild($('banner300'));
		}

		if($$('div.banner300px').length > 0 && $('banner300')) {
			$$('div.banner300px')[0].innerHTML = $('banner300').innerHTML;
		}

		if($$('div.pub160').length > 0 && $('banner160')) {
			$$('div.pub160')[0].appendChild($('banner160'));
		}

		if($$('div.banner125').length > 0 && $('banner125')) {
			$$('div.banner125')[0].appendChild($('banner125'));
		}

		if($$('div.banner125x2').length > 0 && $('banner125x2')) {
			$$('div.banner125x2')[0].appendChild($('banner125x2'));
		}

		if($$('div.box_stiri').length > 0 && $('box_stiri')) {
			$$('div.box_stiri')[0].appendChild($('box_stiri'));
		}


		if($$('div.banner728interior').length > 0 && $('banner728interior')) {
			$$('div.banner728interior')[0].appendChild($('banner728interior'));
		}

		//END PUNEM BANNERELE INCARCATE IN FOOTER ACOLO UNDE TREBUIE SA APARA

		//FUNCTIONALITATE INPUTURI SI TEXTAREA - ASCUNDE LA FOCUS SI ARATA LA BLUR VALOAREA DEFAULT
		inputs = $$('input[type="text"]', 'input[type="password"]', 'textarea');
		inputs.each(function(input, iter){
			iniValInput[iter]=input.value;
			if ( !input.hasClassName('nosel') ) {
				Event.observe(input, 'focus', function(e){this.value=this.value==iniValInput[iter]?'':this.value;});
				Event.observe(input, 'blur', function(e){this.value=this.value==''?iniValInput[iter]:this.value;});
			}
		});
		//END FUNCTIONALITATE INPUTURI SI TEXTAREA - ASCUNDE LA FOCUS SI ARATA LA BLUR VALOAREA DEFAULT


		//NEW HP

		if ($('recnav')) {
			$$('#recnav a').each(function(i){
				Event.observe(i, 'click', function(e){
					e.preventDefault();
					$$("div.recomandari").each(function(j){j.hide()});
					$(i.rel).show();
					$$('#recnav a').each(function(k){k.style.fontWeight = 'normal'});
					i.style.fontWeight = 'bold';
				});
			});
		}

		if ($('eventnav')) {
			$$('#eventnav a').each(function(i){
				Event.observe(i, 'click', function(e){
					e.preventDefault();
					$$("div.events").each(function(j){j.hide()});
					$(i.rel).show();
					$$('#eventnav a').each(function(k){k.removeClassName('here');});
					i.addClassName('here');;
				});
			});
		}

		//END NEW HP

		//CARUSEL
		if ($('roll')) {
			if ($('big_carousel')) {
				rollW = 909;
				padd = 0;
			} else if($('hpRoll'))
			{
				rollW = $('hpRoll').getWidth();
//				alert(rollW);
//				rollW = 612;
				padd = 0;
			}
			else
			{
				rollW = 700;
				padd = 15;
			}

			Event.observe($('back_roll'), 'click', RollEv);
			Event.observe($('front_roll'), 'click', RollEv);

			hrefs = $$('#roll_nav a');
			hrefs.each(function(href, iter){Event.observe(href, 'click', function(e){rollCurr=iter;Roll();e.preventDefault();})});

			carousel = new PeriodicalExecuter(Roll, 5);
//
			Event.observe($('rollCont'), 'mouseover', function(e){carousel.stop()});
			Event.observe($('rollCont'), 'mouseout', function(e){carousel=new PeriodicalExecuter(Roll, 5)});
		}
		//END CARUSEL

		//CARUSEL PLAYLIST VIDEO
		if ($('roll_playlist_video')) {
			rollW = 500;
			padd = 0;

			Event.observe($('back_roll'), 'click', RollEvPlaylistVideo);
			Event.observe($('front_roll'), 'click', RollEvPlaylistVideo);

			hrefs = $$('#roll_nav a');
			hrefs.each(function(href, iter){Event.observe(href, 'click', function(e){rollCurr=iter;RollPlaylistVideo();e.preventDefault();})});
		}
		//END CARUSEL PLAYLIST VIDEO

		//PLAYLIST
		if ($$('a.playlist_add')){
			add_btns = $$('a.playlist_add');
			add_btns.each(function(btn, iter){
				Event.observe(btn, 'click', addToPlaylistEv);
			});
		}

		if ($('playlistList')) {
			buttons = $$('#playlistList input[type="button"]');
			Event.observe(buttons[0], 'click', playlistPush);
		}

		//END PLAYLIST

		//PLAYLIST VIDEO
		if ($$('a.add_video')){
			isVideoTrue = true;
			add_btns = $$('a.add_video');
			add_btns.each(function(btn, iter){
				Event.observe(btn, 'click', addToPlaylistEv);
			});
		}

		//HOVER PT LISTAREA DE VIDEO
		if ($$('.more-stats li')){
			th = $$('.more-stats li');
			th.each(function(t, iter){
				Event.observe(t, 'mouseover', function(e){t.childElements().each(function(a) {a.toggle();})});
				Event.observe(t, 'mouseout', function(e){t.childElements().each(function(a) {a.toggle();})});
			});
		}
		//END HOVER PT LISTAREA DE VIDEO


		//HOVER PT POZITIE TOP
		if ($$('div.list_th')){
			th = $$('div.list_th');
			th.each(function(t, iter){
				Event.observe(t, 'mouseover', function(e){t.addClassName('list_t')});
				Event.observe(t, 'mouseout', function(e){t.removeClassName('list_t')});
			});
		}
		//END HOVER PT POZITIE TOP

		//MARQUE HOME PAGE
		if($('marq')) {
			var myMarq = $('marq');
			var snip = $('snipet');
			var snipEl = $$('#snipet span');
			var marqOff = myMarq.positionedOffset();
			var liMarq = $$('#marq li');
			var aMarq = $$('#marq a');
			var marqW = 0;
			var ef;

			liMarq.each(function(li, iter){
				marqW += li.getWidth();
			});

			var xul = marqW/2;
			myMarq.style.width = marqW+'px';
			myMarq.style.left = 0;

			aMarq.each(function(hr, iter){
				Event.observe(hr, 'mouseover',
					function(e){
						ef.cancel();

						snip.style.left = (Event.pointerX(e)-((document.viewport.getWidth()-990)/2))-100+'px';
						snip.style.display = 'block';
						if (iter < snipEl.length) {
							snipEl[iter].style.display = 'block';
						} else {
							snipEl[iter-snipEl.length].style.display = 'block';
						}
					});
				Event.observe(hr, 'mouseout',
					function(e){
						doEf();

						snip.style.display = 'none';

						if (iter < snipEl.length) {
							snipEl[iter].style.display = 'none';
						} else {
							snipEl[iter-snipEl.length].style.display = 'none';
						}
					});
			});

			function restartMarq() {
				myMarq.style.left = 0;
				doEf();
			}

			function doEf() {
				dimensions = myMarq.style.left;
				dimensions = dimensions.sub('px', '');
				dimensions = dimensions.sub('pt', '');
				durata = (marqW/2+parseInt(dimensions))/60;
				ef = new Effect.Move(myMarq, {afterFinish: restartMarq, duration: durata, fps:100, transition: Effect.Transitions.linear, x: -xul, y: 0, mode: 'absolute'});
			}

			doEf();
		}

		//END MARQUE HOME PAGE

		// box stiri promovate homepage
                 // Register event 'click' and associated call back.
				if($('news_navig'))
				{
					Event.observe('news_navig', 'click', respondToClick);
				}

                // Callback function to handle the event.
                function respondToClick(event) {
                      var element = event.element().parentNode.parentNode;
					  respondToClickFn(element);


                }

				function respondToClickFn(element)
				{
					if (!element.readAttribute('id')){
                    	  element = element.up();
                      }

                      var newsid = element.readAttribute('id');
                      var id = newsid.replace(/link_/,'');
                      var others = $$('#action a:not([id="'+'action_'+id+'"])');
                      for(i = 0; i < others.length; i++) {
                            others[i].hide();
                      }
					  
                      $('action_'+id).appear();

                       var others_li =  element.siblings();
                      for(j = 0; j < others_li.length; j++) {
                            others_li[j].removeClassName('activ');
							var div_id = others_li[j].readAttribute('id').replace(/link_/,'');
							$('op_'+div_id).removeClassName('activ');
							$('op_'+div_id).addClassName('hpn_carusel_op');
                      }
                      element.addClassName('activ');
					  $('op_'+id).removeClassName('hpn_carusel_op');
					  $('op_'+id).addClassName('activ');
					  
					  
				}
		// end box stiri promovate homepage

		//FEED BACK

			if ($('feedBtn')) {
				var feedStat = 0;
				var firstFeed = 0;

				Event.observe($('feedBtn'), 'click', function(e){
					Event.stop(e);
					rollFeed();
					return false;
				});

				Event.observe(window, 'resize', function(e){arangeFeed();});

				if (Prototype.Browser.IE6 || Prototype.Browser.IE7) {
					Event.observe(window, 'scroll', function(e){scrollFeed();});
				}

				function getCap(elem) {
					elem.src = baseURL + 'scripts/image.php?rcode=' + Math.random() + '&vwhn=sfeed';
				}

				function rollFeed(e) {
					if (firstFeed == 0) {
						getCap($('sfeed'));
						firstFeed = 1;
					}

					width = document.viewport.getWidth();

					if (feedStat == 0) {
						width = width-400;
						feedEf = new Effect.Move($('feedback'), {x: width, y: 0, mode: 'absolute'});
						feedStat = 1;
					} else {
						feedEf = new Effect.Move($('feedback'), {x: width, y: 0, mode: 'absolute'});
						feedStat = 0;
					}
				}

				function arangeFeed(e) {
					width = document.viewport.getWidth();

					$('feedback').style.top = '0px';
					if (feedStat == 0) {
						$('feedback').style.left = width + 'px';
					} else {
						$('feedback').style.left = width-400 + 'px';
					}
				}

				function scrollFeed(e) {
					var XY = document.viewport.getScrollOffsets();
					width = document.viewport.getWidth();

					if (feedStat == 0) {
						$('feedback').style.left = width + XY.left + 'px';
					} else {
						$('feedback').style.left = width + XY.left -400 + 'px';
					}

					if (XY.top != $('feedback').style.top) {
						$('feedbackFull').style.top = XY.top+'px';
					}
				}

				function initFeedIE() {
					$('feedbackFull').style.width = document.viewport.getWidth();
					$('feedback').style.height = document.viewport.getHeight();
				}

				scrollFeed();

				if (Prototype.Browser.IE6 || Prototype.Browser.IE7) {
					initFeedIE();
				}

				var feedForm = $('feedbackForm');

				function feedSeTrimite() {
					if (countEx <= 3) {
						countEx++;
						$('feedSubm').value += '.';
					} else {
						countEx = 1;
						$('feedSubm').value = 'Se trimite';
					}
				}

				var countEx = 1;
				var feedTimer;

				function sendFeed() {
					$('feedSubm').value = 'Se trimite';
					feedTimer = new PeriodicalExecuter(feedSeTrimite, 0.3);
					url = document.location.href;
					url = url.gsub(/#.*?/, '')
					new Ajax.Request(url, {
						method: 'post',
						parameters: {
							ajxFeedback: 1,
							security_code: feedForm.security_code.value,
							email: feedForm.email.value,
							mesaj: feedForm.mesaj.value
						},
						onSuccess: feedSucces
					});
				}

				function feedSucces(response) {
					feedTimer.stop();
					$('feedSubm').value = 'Trimite';
					var myObject = response.responseText.evalJSON();
					$('response').innerHTML = myObject['message'];
					getCap($('sfeed'));
				}

				Event.observe(feedForm, 'submit', function(e){Event.stop(e);sendFeed();});
			}

		//END FEED BACK

		//ajx newsletter stiri artisti
			if($('newsletter_subm')) {
				function updateNewsletterBox(response) {
					var status = response.responseText.evalJSON();
					switch (status) {
						case 0:
							mesajN = 'Cererea ta a fost inregistrata. Verifica adresa de e-mail pentru confirmare.';
							break;
						case -3:
							mesajN = 'Esti deja abonat la stirile acestui artist.';
							break;
						case -4:
							mesajN = 'Te rugam sa introduci o adresa de e-mail valida!';
							break;
						default:
							mesajN = 'Cererea nu a fost inregistrata. Mai incearca.';
					}

					$('errNewsletter').innerHTML = mesajN;
				}

				Event.observe($('newsletter_subm'), 'click', function(e){
					Event.stop(e);
					emailNews = $('newsletter_popup').email.value;
					idNews = $('newsletter_popup').artist_id.value;
					new Ajax.Request(
							baseURL + 'index.php?module=newsletter&action=registerNwArtist', {
								method: 'post',
								parameters: {
									ajxF: 1,
									email: emailNews,
									id: idNews,
									responseType: 'json'
								},
								onSuccess: updateNewsletterBox
							});
				});
			}
		//end ajx newsletter stiri artisti

		//ajax topuri HP
		if ($('topselect')) {
			Event.observe($('topselect'), 'change', function(e){
				id = $('topselect').value.split("_")[0];
				type = $('topselect').value.split("_")[1];
				updateHpTops(id, type);
			});
		}
		
		//legatura eventuri de facebook
		
		FB.Event.subscribe('edge.create',
			function(response) {
				if(save_count)
				{	
					var loc = response;
					new Ajax.Request( baseURL + 'index.php?module=gallery2&action=saveImgLikes', {
						method: 'post',
						parameters: {
							sentAjx: 1024,
							link: loc,
							img: img_id
						}
					});
				}
			});
		FB.Event.subscribe('edge.remove',
			function(response) {
			   if(save_count)
				{	
					var loc = response;
					new Ajax.Request( baseURL + 'index.php?module=gallery2&action=saveImgLikes', {
						method: 'post',
						parameters: {
							sentAjx: 1024,
							link: loc,
							img: img_id
						}
					});
				}
			});
	}
)

//END SE PUNE TOT CE NECESITA VERIFICARE DE BODY ONLOAD - !!! SA RAMANA IN TOPUL DOCUMENTULUI !!!


//ajax topuri HP

function updateHpTops(id, type) {
	var params = 'top_id='+id+'&type_id='+type+'&ajx=1';
	new Ajax.Updater('hptops', baseURL+'/index.php?module=top20&action=topEntriesAjax',
		{
			method:'get',
			parameters:params
		}
	)
}

//END ajax topuri HP



//PLAYER

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
    } else {
    	return document[movieName];
    }
}

//END PLAYER


//PLAYLIST

var item_to_add = new Array();
var container_to_add = new Array();

function addToPlaylistEv(e) {
	Event.stop(e);

	if (userLoged) {
		addToPlaylist(this.id);
	} else {
		loginUser();
	}

	return false;
}

function addToPlaylist(id) {
	item_to_add.push(id);
	$('pl_msg').style.display = 'none';
	$('playlistList').style.display = 'block';
	playlistMsg.show();
}

function playlistPush(e) {
	my_form = $('playlistList');
	my_checks = $$('#playlistList input[type="checkbox"]');
	my_checks.each(function(check, iter){
		if(check.checked) {
			container_to_add.push(check.value);
		}
	});

	if(my_form.playlist_create.value != '' && my_form.playlist_create.value != 'Nume playlist') {
		editPlaylist('createPlaylist', '', '', my_form.playlist_create.value);
	} else {
		finalAdd();
	}
}

function finalAdd() {
	if (item_to_add.length > 0 && container_to_add.length > 0) {
		editPlaylist('addElem', item_to_add, container_to_add);

		my_form = $('playlistList');

		item_to_add = new Array();;
		container_to_add = new Array();
		my_form.playlist_create.value = '';

		my_checks = $$('#playlistList input[type="checkbox"]');
		my_checks.each(function(check, iter){
			if(check.checked) {
				check.checked = false;
			}
		});
	}
}

function deletePlaylist(id) {
	editPlaylist('deletePlaylist', id);
	return false;
}

function deleteTrack(id, playlist_id) {
	editPlaylist('deleteElem', id, playlist_id);
}

function refreshPlaylist(actiune, id, playlist_id) {
	if (actiune == 'add') {

	} else if (actiune == 'remove') {
		if ($('item_'+id)) {
			$('item_'+id).remove();
		}
	}
}

function refreshPlaylists(actiune, id, title) {
	container = $('playlists_cont');

	if (actiune == 'add') {
		label = document.createElement('label');
		label.className = 'column first full noleading';
		label.id = 'pl_'+id;
		input = document.createElement('input');
		input.type = 'checkbox';
		input.value = id;
		input.className = 'column first';
		bold = document.createElement('b');
		bold.className = 'column';
		elemText = document.createTextNode(title);

		bold.appendChild(elemText);
		label.appendChild(input);
		label.appendChild(bold);
		container.appendChild(label);

		if ($('playlist_util')) {
			tr = document.createElement('tr');
			tr.id = 'li_'+id;
			td1 = document.createElement('td');
			td2 = document.createElement('td');
			td2.style.padding = "0 2px 0 0";

			span1 = document.createElement('span');
			span1.className = 'title';
			span2 = document.createElement('span');
			span2.className = 'align-right';

			link1 = document.createElement('a');
			link1.href = '#';
			Event.observe(link1, 'click', function(e){
				if (isVideoTrue){
					playlistWindow = window.open(baseURL+'index.php?module=clips&action=myPlaylist&id='+id,'Playlist','menubar=no,width=700,height=800,toolbar=no,status=no,location=no,resizable=no');
				} else {
					playlistWindow = window.open(baseURL+'index.php?module=music&action=myPlaylist&id='+id,'Playlist','menubar=no,width=850,height=530,toolbar=no,status=no,location=no,resizable=no');
				}
				return false;
			});
			link1Text = document.createTextNode(title);
			link1.appendChild(link1Text);

			link2 = document.createElement('a');
			link2.href = '#';
			link2.className = 'delete_a ml_icon';
			Event.observe(link2, 'click', function(e){
				deletePlaylist(id);return false;
			});

			span1.appendChild(link1);
			span2.appendChild(link2);
			td1.appendChild(span1);
			td2.appendChild(span2);
			tr.appendChild(td1);
			tr.appendChild(td2);

			$('playlist_util').appendChild(tr);
		}
	} else if (actiune == 'remove') {
		if ($('pl_'+id)) {
			$('pl_'+id).remove();
		}

		if ($('li_'+id)) {
			$('li_'+id).remove();
		}

		if ($('item_'+id)) {
			$('item_'+id).remove();
		}
	}
}

function editPlaylist(action_type, id_elem, id_playlist, title) {
	// action_type = createPlaylist(nu primeste id), deletePlaylist(primeste id), addElem(primeste id, sau array de id-uri si playlist_id), deleteElem(primeste id si playlist_id), refreshPlaylist(nu primeste id)

	if (action_type) {
		new Ajax.Request(
				baseURL + 'index.php?module=music&action=playlistHandler', {
					method: 'post',
					parameters: {
						ajxF: 1,
						type: action_type,
						id: id_elem,
						playlist_id: id_playlist,
						title: title,
						video: isVideoTrue
					},
					onFailure: playlistErr,
					onSuccess: playlistSucces
				});
	}
}

function playlistErr(response) {
}

function playlistSucces(response) {
	var myObject = response.responseText.evalJSON();

	if (myObject.actiune == 'createPlaylist') {
		container_to_add.push(myObject.raspuns.id);
		finalAdd();

		refreshPlaylists('add', myObject.raspuns.id, myObject.raspuns.title);
	}

	if (myObject.actiune == 'deletePlaylist') {
		refreshPlaylists('remove', myObject.raspuns.id);
	}

	if (myObject.actiune == 'deleteElem') {
		refreshPlaylist('remove', myObject.raspuns.id, myObject.raspuns.playlist_id);
	}

	if (myObject.actiune == 'addElem') {
		$('pl_msg').innerHTML = '<h6>Piesa a fost adaugata cu succes</h6>';
		$('pl_msg').style.display = 'block';
		$('playlistList').style.display = 'none';
	}
}

//END PLAYLIST



//LOGIN BOX

function loginUser(element, position)
{
	loginMsg.show();

	return false;
}

//END LOGIN BOX


//CARUSEL

var rollEf = '';
var rollCurr = 0;
var rollW;
var rollNav = 22.5;
var carousel;
var padd;

function Roll(dir) {
	if (dir == 'front' || dir == carousel) {
		rollCurr++;
		if (rollCurr < 0 || rollCurr > 3) {
			rollCurr = 0;
		}
	} else if (dir == 'back'){

		rollCurr--;
		if (rollCurr < 0 || rollCurr > 3) {
			rollCurr = 0;
		}
	}

	lft = (rollCurr * -rollW)-padd;

	if (rollEf != '') {
		rollEf.cancel();
		rollEf = '';
	}

	ef = new Effect.Move($('roll'), {x: lft, y: 10, mode: 'absolute'});

/*	rollBg = (rollCurr * rollNav)-750;$('roll_nav').style.backgroundPosition = rollBg+'px -153px';*/
}

function RollPlaylistVideo(dir) {
	if (dir == 'front' || dir == carousel) {
		rollCurr++;
		if (rollCurr < 0 || rollCurr > 3) {
			rollCurr = 0;
		}
	} else if (dir == 'back'){

		rollCurr--;
		if (rollCurr < 0 || rollCurr > 3) {
			rollCurr = 0;
		}
	}

	lft = (rollCurr * -rollW)-padd;

	if (rollEf != '') {
		rollEf.cancel();
		rollEf = '';
	}

	ef = new Effect.Move($('roll_playlist_video'), {x: lft, y: 30, mode: 'absolute'});

}

function RollEv(e) {
	if(this.id == 'back_roll') {
		Roll('back');
	} else if (this.id == 'front_roll'){
		Roll('front');
	}

	e.preventDefault();
}

function RollEvPlaylistVideo(e) {
	if(this.id == 'back_roll') {
		RollPlaylistVideo('back');
	} else if (this.id == 'front_roll'){
		RollPlaylistVideo('front');
	}

	e.preventDefault();
}



//general

function RollG(dir) {
	var roll = $$('#radioCarousel .roll').first();
	var screens = Math.ceil(parseFloat(roll.getWidth()/roll.up().getWidth()));
	var padd=0;

	if(screens==1)
	{
		ltr=0;
		screens = Math.ceil(parseFloat(roll.getHeight()/roll.up().getHeight()));
		var rollCurr = Math.abs(parseInt(parseInt(roll.getStyle('top'))/roll.up().getHeight()));
	}
	else
	{
		var rollCurr = Math.abs(parseInt(parseInt(roll.getStyle('left'))/roll.up().getWidth()));
	}



	if(!rollCurr)
	{
		rollCurr=0
	}

	if (dir == 'front' || dir == carousel) {
		rollCurr++;
		if (rollCurr < 0 || rollCurr >= screens) {
			rollCurr = 0;
		}
	} else if (dir == 'back'){

		rollCurr--;
		if (rollCurr < 0 || rollCurr >= screens) {
			rollCurr = 0;
		}
	}


	if(ltr)
	{
		lft = (rollCurr * -roll.up().getWidth());
		top=0;
	}
	else
	{
		lft = 0;
		top = (rollCurr * -roll.up().getHeight());
	}
	if (rollEf != '') {
		rollEf.cancel();
		rollEf = '';
	}

	ef = new Effect.Move(roll, {x: lft, y: top, mode: 'absolute'});

}

function RollEvG(e) {

	if(this.hasClassName('back_roll')) {
		RollG('back');
	} else if (this.hasClassName('front_roll')){
		RollG('front');
	}

	e.preventDefault();
}

//END CARUSEL


//SISTEM VOTARE STELUTE

function sendVote(entity_id,entity_type_id,mark,module,action,response)
{
	
	if(!module)
	{
		module='gallery';
	}

	if(!action)
	{
		action='vote';
	}

	
	var url = baseURL + 'index.php';
	var parameters = '&module='+module+'&action='+action+'&entity_type_id='+entity_type_id+'&entity_id='+entity_id+'&mark='+mark;

	switch( response )
	{
		case 3:
			new Ajax.Request(url,
			{
			method:'get',
			parameters:parameters,
			onSuccess:responseVote3
			
			});

			break;

		default:
			new Ajax.Request(url,
			{
			method:'get',
			parameters:parameters,
			onSuccess:responseVote2

			});

			break;
	}
}

function responseVote2(response)
{
	var objResponse = response.responseText.evalJSON();
	if(objResponse['message'])
	{
		alert(objResponse['message']);
	}
	else
	{
		var value = String(Math.round(objResponse['new_value'] * 20));
		
		if($('item_average'))
		{
			$('item_average').innerHTML = objResponse['new_value'];
			document.getElementById('item_average').style.display = 'inline';
		}
		document.getElementById('current_rating').style.width= value+'%';
		//alert(document.getElementById('current_rating').style.width);
	}
}

function responseVote3(response)
{
	var objResponse = response.responseText.evalJSON();
	if(objResponse['message'])
	{
		alert(objResponse['message']);
	}
	else
	{
		var x = parseInt( $('total_vote').innerHTML );
		x += +objResponse['mark'];

		new Effect.Highlight('total_vote', {restorecolor: '#ffff99'});
		$('total_vote').innerHTML = x;
		Effect.Pulsate('total_vote', {pulses: 1, duration: 1});
	}
}

function sendVoteTop20 (element,entity_id,mark,type)
{
	var url = baseURL + 'index.php';
	var parameters = '&module=top20&action=vote&entity_type_id=17&entity_id='+entity_id+'&mark='+mark+'&type='+type+'&ajx=1';
	updDiv = 'score_'+entity_id;
	new Ajax.Request(url,
	{
		method:'get',
		parameters:parameters,
		onSuccess: function (transport)
		{
			var objResponse = transport.responseText.evalJSON();

			try{
				if(objResponse['msg'] == 'login')
				{
					loginUser(element);
				}
				else if(objResponse['msg'])
				{
					new Effect.Highlight('stars_'+entity_id, {restorecolor: '#ddaaaa'});
					$('stars_'+entity_id).innerHTML = objResponse['msg'];
					Effect.Pulsate('stars_'+entity_id, {pulses: 1, duration: 1});
				}else
				{
					new Effect.Highlight('score_'+entity_id, {restorecolor: '#ffff99'});
					$('score_'+entity_id).innerHTML = objResponse['score'];
					Effect.Pulsate('score_'+entity_id, {pulses: 1, duration: 1});
				}
			}catch(e)
			{
				alert(e);
			}

		}

	});

	return false;
}

function sendVoteTop20FB (element,entity_id,mark,type)
{
	var url = baseURL + 'index.php';
	var parameters = '&module=top20&action=vote&entity_type_id=17&fb=1&entity_id='+entity_id+'&mark='+mark+'&type='+type+'&ajx=1';
	updDiv = 'score_'+entity_id;
	new Ajax.Request(url,
	{
		method:'get',
		parameters:parameters,
		onSuccess: function (transport)
		{
			var objResponse = transport.responseText.evalJSON();

			try{
				if(objResponse['msg'] == 'login')
				{
					loginUser(element);
				}
				else if(objResponse['msg'] == 'already_voted')
				{
					alert('Nu poti vota de doua ori in aceeasi zi!');
				}
				else if(objResponse['msg'])
				{
					new Effect.Highlight('stars_'+entity_id, {restorecolor: '#ddaaaa'});
					$('stars_'+entity_id).innerHTML = objResponse['msg'];
					Effect.Pulsate('stars_'+entity_id, {pulses: 1, duration: 1});
				}else
				{
					new Effect.Highlight('score_'+entity_id, {restorecolor: '#ffff99'});
					$('score_'+entity_id).innerHTML = objResponse['score'];
					Effect.Pulsate('score_'+entity_id, {pulses: 1, duration: 1});
				}
			}catch(e)
			{
				alert(e);
			}

		}

	});

	return false;
}


//END SISTEM VOTARE STELUTE

function updateEventMonth(startDate, monthName)
{
    /* sterge clasa de pe linkul de luna veche */
    var lunile_anului = $('lunile_anului').childElements();
    lunile_anului.each(function(luna)
    {
        luna_link = luna.childElements();
        if(luna_link[0].hasClassName("aleasa"))
        {
            luna_link[0].removeClassName("aleasa");
        }
    });

    $("luna_"+monthName).addClassName("aleasa"); // adauga clasa de selectat la linkul lunii selectate
    currentStartDate = startDate;
	var params = 'module=events&action=calendarMonth&ajx=1&data_start='+startDate;
	new Ajax.Updater('month_content', baseURL+'/index.php',
		{
			method:'get',
			parameters:params
		}
	)

    $('listing_box').empty();
    var params = 'module=events&action=listingMonth&ajx=1&data_start='+startDate+'&lang_id=1';
    new Ajax.Updater('listing_box', baseURL+'index.php',
        {
            method: 'get',
            parameters: params,
            onSuccess: function(transport)
            {
                Effect.SlideDown('listing_box', {duration: 2.0});
            }

        }
    );

	return false;
}

function updateEventDay(day)
{
    $('listing_box').empty();

    current_day = currentStartDate.truncate(2,'');
    ds = currentStartDate.sub(current_day, day);

    $('listing_box').empty();
    var params = 'module=events&action=listingMonth&ajax=1&one_day='+ds+'&lang_id=1';
    new Ajax.Updater('listing_box', baseURL+'index.php',
        {
            method: 'get',
            parameters: params,
            onSuccess: function(transport)
            {
                Effect.SlideDown('listing_box', {duration: 2.0});
            }

        }
    );

    return false;
}


//AICI EMBED GALERII FOTO PE STIRE

function prevPhoto(currentItem,galleryItems,galleryId)
{
	if(currentItem-1<0)
	{
		newCurrentItem = 0;
	}
	else
	{
		newCurrentItem = currentItem-1;
	}

	if(newCurrentItem==0)
	{
		$('prevPhoto_'+galleryId).addClassName("disabled");
	}
	else
	{
		$('prevPhoto_'+galleryId).removeClassName("disabled");
		if(newCurrentItem!=galleryItems.length)
		{
			$('nextPhoto_'+galleryId).removeClassName("disabled");;
		}
	}

	var photoPos = (newCurrentItem+1) + ' / ' + galleryItems.length;
	$('photoPos_'+galleryId).innerHTML = photoPos;

	var tmp = galleryItems[newCurrentItem];

	$('photoFrame_'+galleryId).src=tmp.link;
	$('photoTitle_'+galleryId).href=tmp.href;
	$('photoTitle_'+galleryId).innerHTML=tmp.name;
	$('photoDescription_'+galleryId).innerHTML=tmp.description;

	//revendica
	if ($('revendica')) 
	{
		var img_id= tmp.href.substr(tmp.href.indexOf('itemid=')+7);
		img_id = img_id.slice(0,img_id.indexOf('&'));
		$('revendica').innerHTML='<a onclick="if(!userLoged) loginUser(this,\'right\'); else save_user_image(\''+tmp.href+'\','+img_id+');" class="align-right but_nou_left" style="cursor:pointer;color:#343D42;"><span>Revendica poza</span></a>';
	}


	return newCurrentItem;
}

function nextPhoto(currentItem,galleryItems,galleryId)
{
	//alert(galleryItems.length + '|' +currentItem);

	if((currentItem+1)>=galleryItems.length)
	{
		newCurrentItem = currentItem;
	}
	else
	{
		newCurrentItem = currentItem+1;
	}

	if(newCurrentItem+1>=galleryItems.length)
	{
		$('nextPhoto_'+galleryId).addClassName("disabled");
	}
	else
	{
		$('nextPhoto_'+galleryId).removeClassName("disabled");
		if(newCurrentItem!=0)
		{
			$('prevPhoto_'+galleryId).removeClassName("disabled");
		}
	}

	var photoPosContent = (newCurrentItem+1) + ' / ' + galleryItems.length;
	$('photoPos_'+galleryId).innerHTML = photoPosContent;

	var tmp = galleryItems[newCurrentItem];
	
	$('photoFrame_'+galleryId).src=tmp.link;
	$('photoTitle_'+galleryId).href=tmp.href;
	$('photoTitle_'+galleryId).innerHTML=tmp.name;
	$('photoDescription_'+galleryId).innerHTML=tmp.description;
	
	//revendica
	if ($('revendica')) 
	{
		var img_id= tmp.href.substr(tmp.href.indexOf('itemid=')+7);
		img_id = img_id.slice(0,img_id.indexOf('&'));
		$('revendica').innerHTML='<a onclick="if(!userLoged) loginUser(this,\'right\'); else save_user_image(\''+tmp.href+'\','+img_id+');" class="align-right but_nou_left" style="cursor:pointer;color:#343D42;"><span>Revendica poza</span></a>';
	}

	return newCurrentItem;
}

//PANA AICI EMBED GALERII FOTO PE STIRE


//AICI REPLY COMENTARIU SI VOT COMENTARIU


function sendVoteBW(entity_id,entity_type_id,mark)
{
	var url = baseURL + 'index.php';
	var parameters = '&module=articles&action=vote&entity_type_id='+entity_type_id+'&entity_id='+entity_id+'&mark='+mark;

	new Ajax.Request(url,
	{
	method:'get',
	parameters:parameters,
	onSuccess:responseVoteBW

	});
}

function responseVoteBW(response)
{
	var objResponse = response.responseText.evalJSON();
	try{
	if(objResponse['message'])
	{
		//alert(objResponse['message']+'xxx');

		var newDiv = new Element('div', {'class': 'mCi', id: 'customNotice'}).update('<h1>'+objResponse['message']+'</h1>');

		document.body.appendChild(newDiv);

		var errMsg = new MsgBox;
		errMsg.fullBg = true;
		errMsg.contentId = 'customNotice';
		errMsg.init();
		errMsg.show();

	}
	else
	{
		$('positive_vote_result_'+objResponse['entity_type_id']+'_'+objResponse['entity_id']).innerHTML = objResponse['new_value'];
		$('negative_vote_result_'+objResponse['entity_type_id']+'_'+objResponse['entity_id']).innerHTML = 100-objResponse['new_value'];
	}
	}catch(e)
	{
		alert(e);
	}
}

function reply(messageId)
{
	$('parent_id').value=messageId;
}

function goToPage(pagelink)
{
	if(pagelink!="#")
	{
		var linkParts = pagelink.split("?");
		new Ajax.Updater('commentsDiv',baseURL + 'index.php',{parameters:linkParts[1],method:'GET'});
	}

	return false;
}

//PANA AICI REPLY COMENTARIU SI VOT COMENTARIU


//AICI AUTOCOMPLETE FORM ADAUGA VERSURI

function populateTracks()
{
	var artist_id = $('artist_id').value;
	var url = baseURL + '?module=AmvcArtist&action=getTracks';
	var track = $('track_id').options;

	$('track_id').options.length=0

	params = 'artist_id=' + artist_id;

	new Ajax.Request( url,
	{method: 'post',
	parameters:params,
	onSuccess:  addOptionsTracks

	});
}

function addOptionsTracks(jsonul)
{
	var x=$('track_id').options;
	result = jsonul.responseText;
	//json="{'3':'cucu', '4':'mucu'}".evalJSON();
	json = result.evalJSON();

	x[0]= new Option('Alege melodia...', 0);

	json.each(function(j){
		x[x.length]=new Option(j.t_name, j.t_id)
	})
}

function AjaxAutocompleterUserArtists(from, to, module, action, min_chars)
{
	link = baseURL + 'index.php?module='+module+'&action='+action;
	new Ajax.Autocompleter(from,to,link,
	{
		minChars:min_chars,
		indicator: 'indicator1',
		afterUpdateElement : writeArtist_id
	}
	);
}

function writeArtist_id(text, li)
{

	var artist_id = li.id
	$('artist_id').value = artist_id;

}

//PANA AICI AUTOCOMPLETE FORM ADAUGA VERSURI

function AjaxAutocompleterComunica(from, to, module, action, min_chars)
{
	link = baseURL + 'index.php?module='+module+'&action='+action;
	new Ajax.Autocompleter(from,to,link,
	{
		minChars:min_chars,
		indicator: 'indicator_comunica',
		afterUpdateElement : writeArtist_id_Comunica
	}
	);
}

function writeArtist_id_Comunica(text, li)
{
	
	var artist_id = li.id
	$('com_artist_id').value = artist_id;

}


//SECTIUNE FOTO


var Carousel = function(id, item_width , total_items, items_visible, position, prev, next, srcs)
{
	this.div=id;
	this.item_width = item_width;
	this.total_items = total_items;
	this.slides_left = total_items - items_visible;
	this.total_slides = this.slides_left;
	this.items_visible = items_visible;
	this.nextTb = next;
	this.prevTb = prev;
	this.srcs = srcs;
	if(position)
	{
		this.position = position;
		this.actual_slide = position + 1;
		this.slides_left -= position;
	}
	else
	{
		this.actual_slide = 1;
	}
};

Carousel.prototype = {
	moveNext: function(moveBy)
	{
		if(this.slides_left > 0)
		{
			if(moveBy)
			{
				if(this.slides_left < moveBy)
				{
					moveBy = this.slides_left;
				}
				this.actual_slide += moveBy;
				this.slides_left -= moveBy;
				new Effect.Move(this.div, {x: -this.item_width * (this.actual_slide - 1), mode: 'absolute', duration: 0.4});
			}
			else
			{
				if( this.nextTb && this.actual_slide+10 >= this.nextTb && this.nextTb<this.total_items) {
					$('carousel1Img_' + this.nextTb ).src = this.srcs[this.nextTb];
					this.nextTb++;
				}

				new Effect.Move(this.div, {x: -this.item_width * this.actual_slide, mode: 'absolute', duration: 0.4});
				this.actual_slide++;
				this.slides_left--;
			}
		}
	},

	movePrev: function(moveBy)
	{
		if(this.slides_left < this.total_slides)
		{
			if(moveBy)
			{
				if(this.total_slides % moveBy != 0 && this.slides_left == 0)
				{
					moveBy = this.total_slides % moveBy;
				}
				this.actual_slide -= moveBy;
				this.slides_left += moveBy;
				new Effect.Move(this.div, {x: -this.item_width * (this.actual_slide - 1), mode: 'absolute', duration: 0.4});
			}
			else
			{
				if( (this.prevTb || this.prevTb === 0) && this.actual_slide-3 <= this.prevTb && this.prevTb>=0) {
					$('carousel1Img_' + this.prevTb ).src = this.srcs[this.prevTb];
					this.prevTb--;
				}

				new Effect.Move(this.div, {x: -this.item_width * (this.actual_slide - 2), mode: 'absolute', duration: 0.4});
				this.actual_slide--;
				this.slides_left++;
			}
		}
	},

	updateProgress: function(moveBy)
	{
		var x = Math.ceil(this.actual_slide / moveBy);
		if(this.slides_left == 0 && this.actual_slide % moveBy != 1)
		{
			x++;
		}
		var y = Math.ceil(this.total_items / 3);
		$('span_page').innerHTML = x + ' din ' + y;
	}
}

var CarouselGalerie9 = function(id, item_width , total_items, items_visible, position, prev, next)
{
	this.div=id;
	this.item_width = item_width;
	this.total_items = total_items;
	this.slides_left = total_items - items_visible;
	this.total_slides = this.slides_left;
	this.items_visible = items_visible;
	this.nextTb = next;
	this.prevTb = prev;
	if(position)
	{
		this.position = position;
		this.actual_slide = position + 1;
		this.slides_left -= position;
	}
	else
	{
		this.actual_slide = 1;
	}
	checkEmpyCos( this );
};

CarouselGalerie9.prototype = {
	moveNext: function(moveBy)
	{
		if(this.slides_left > 0)
		{
			if(moveBy)
			{
				if(this.slides_left < moveBy)
				{
					moveBy = this.slides_left;
				}
				this.actual_slide += moveBy;
				this.slides_left -= moveBy;
				new Effect.Move(this.div, {x: -this.item_width * (this.actual_slide - 1), mode: 'absolute', duration: 0.4});
			}
			else
			{
				new Effect.Move(this.div, {x: -this.item_width * this.actual_slide, mode: 'absolute', duration: 0.4});
				this.actual_slide++;
				this.slides_left--;
			}


			if(this.slides_left == 0 && this.nextTb) {
				var url = baseURL + 'index.php?module=gallery2&action=getThumb';
				new Ajax.Request(url,
				{
					method:'post',
					parameters: {tid: this.nextTb, ajx: 1},
					onSuccess: function (transport)
					{
						appendThumb(transport)
					}
				});
			}
		}
	},

	movePrev: function(moveBy)
	{


		if(this.slides_left < this.total_slides)
		{
			if(moveBy)
			{
				if(this.total_slides % moveBy != 0 && this.slides_left == 0)
				{
					moveBy = this.total_slides % moveBy;
				}
				this.actual_slide -= moveBy;
				this.slides_left += moveBy;
				new Effect.Move(this.div, {x: -this.item_width * (this.actual_slide - 1), mode: 'absolute', duration: 0.4});
			}
			else
			{
				new Effect.Move(this.div, {x: -this.item_width * (this.actual_slide - 2), mode: 'absolute', duration: 0.4});
				this.actual_slide--;
				this.slides_left++;
			}

			if(this.slides_left == this.total_slides && this.prevTb){
				var url = baseURL + 'index.php?module=gallery2&action=getThumb';
				new Ajax.Request(url,
				{
					method:'post',
					parameters: {tid: this.prevTb, ajx: 1},
					onSuccess: function (transport)
					{
						shiftThumb(transport)
					}
				});
			}
		}

	},

	updateProgress: function(moveBy)
	{
		var x = Math.ceil(this.actual_slide / moveBy);
		if(this.slides_left == 0 && this.actual_slide % moveBy != 1)
		{
			x++;
		}
		var y = Math.ceil(this.total_items / 3);
		$('span_page').innerHTML = x + ' din ' + y;
	}
}

function appendThumb(transport){
	if (transport.responseText.length){
		var objResponse = transport.responseText.evalJSON();

		carrier = eval(objResponse.carrier);
		var container = $(carrier.div);

		var div9 = document.createElement("li");
	   	div9.innerHTML = objResponse.content;
	   	div9.className = objResponse.clasa;
	   	container.appendChild(div9);

		carrier.total_items++;
		container.style.width = carrier.item_width*carrier.total_items + 'px';
		if(objResponse.nextid || objResponse.nextid==false){
			carrier.nextTb = objResponse.nextid;
		}
		carrier.slides_left++;
		carrier.total_slides++;
	}
}

function shiftThumb(transport)
{
	if (transport.responseText.length){
		var objResponse = transport.responseText.evalJSON();

		carrier = eval(objResponse.carrier);
		var container = $(carrier.div);

		var div9 = document.createElement("li");
	   	div9.innerHTML = objResponse.content;
	   	div9.className = objResponse.clasa;
	   	container.insertBefore(div9,container.childNodes[0]);

	   	carrier.total_items++;
		carrier.total_slides++;
		carrier.actual_slide++;
		if (objResponse.previd || objResponse.previd==false){
			carrier.prevTb = objResponse.previd;
		}

		container.style.left = '-' + carrier.item_width + 'px';
		container.style.width = carrier.item_width*carrier.total_items + 'px';

		}
}

function checkEmpyCos( carrier )
{
	var container = $(carrier.div);
	if( carrier.total_items == 0)
	{
		$( carrier.div + '_msgGol').style.display = 'block';
		$( carrier.div ).style.display = 'none';
		$( carrier.div + '_link_down_postere').style.display = 'none';
	} else {
		$( carrier.div + '_msgGol').style.display = 'none';
		$( carrier.div ).style.display = 'block';
		$( carrier.div + '_link_down_postere').style.display = 'block';
	}

}

function addToCos(item, deliveryType, silent){
	var url = baseURL + 'index.php?module=gallery2&action=addToCos';
	new Ajax.Request(url,
	{
		method:'post',
		parameters: {pid: item, tip: deliveryType, ajx: 1},
		onSuccess: function (transport)
		{
			if (transport.responseText.length){
				var objResponse = transport.responseText.evalJSON();
				if (objResponse.status==1){
					appendThumb(transport);
					$('nrPozeCos').innerHTML++;
					checkEmpyCos( carrier );
				}
				if( !silent ){
					alert(objResponse.message);
				} else {
					if(objResponse.status != 1 && objResponse.status != -2 ) {
						alert(objResponse.message)
					} else {
						GB_showCenter('Download Poster', silent);
					}
				}
/*				if ($cosItem['dispatch'] == 1) {
				$src = mmlinkExt($thumbId,100);
				$output = array(
							'status' => 1,
							'message' => 'OK',
							'content'=>'<div class="thumb-foto carousel_item"><a href="'.AMVC_WEB_PATH.'index.php?module=gallery2&action=view&galleryid='.$cosItem['album_id'].'&amp;itemid='.$cosItem['amvc_item_id'].'&amp;lang_id='.$req->get('lang_id').'" class="left"><img src="'.$src.'" style="margin:0px;padding:0px;height:54px;border: 2px solid #FFFFFF;" /></a><div class="clearAll"></div><a href="#" class="left padd" >Adauga</a></div>'
						);
			} elseif ( $cosItem['dispatch'] == -2 ) {
				$output = array(
							'status' => -2,
							'message' => 'Ai adaugat deja poza in cosul tau',
							'content'=>''
						);
			} elseif ( $cosItem['dispatch'] == -4 ) {
				$output = array(
							'status' => -4,
							'message' => 'Poza nu este cu vanzare',
							'content'=>''
						);
			} elseif ( $cosItem['dispatch'] == 0 ) {
				$output = array(
							'status' => 0,
							'message' => 'Nu poti adauga poza in cosul tau (nu ai drepturi)',
							'content'=>''
						);
			} elseif ( $cosItem['dispatch'] == -1 ) {
				$output = array(
							'status' => -1,
							'message' => 'Poza nu a fost adaugata in cosul tau',
							'content'=>''
						);
			} elseif ( $cosItem['dispatch'] == -3 ) {
				$output = array(
							'status' => -3,
							'message' => 'Cosul tau este plin',
							'content'=>''
						);
			}
*/
			}
		}
	});
}

function removeFromCos(pd_id, lnk){
	var url = baseURL + 'index.php?module=gallery2&action=removeFromCos';
	var copil = lnk.parentNode;
	new Ajax.Request(url,
	{
		method:'post',
		parameters: {pd_id: pd_id, ajx: 1},
		onSuccess: function (transport)
		{
			if (transport.responseText.length){
				var objResponse = transport.responseText.evalJSON();
				if (objResponse.status==1){
					copil.remove();
					$('nrPozeCos').innerHTML--;
					carrier = eval(objResponse.carrier);
					var container = $(carrier.div);

					carrier.total_items--;
					container.style.width = carrier.item_width*carrier.total_items + 'px';
					carrier.slides_left--;
					carrier.total_slides--;
					checkEmpyCos( carrier );
				}
				alert(objResponse.message);

/*
			if ($response['dispatch'] == 1) {
				$output = array(
							'status' => 1,
							'message' => 'Poza a fost stersa din cosul tau',
						);
			} elseif ( $response['dispatch'] == -1 ) {
				$output = array(
							'status' => -1,
							'message' => 'Poza nu a fost stearsa din cosul tau',
						);
			} elseif ( $response['dispatch'] == 0 ) {
				$output = array(
							'status' => 0,
							'message' => 'Nu ai dreptul sa stergi poze deoarece nu esti logat',
						);
			} elseif ( $response['dispatch'] == -2 ) {
				$output = array(
							'status' => 2,
							'message' => 'Poza nu exista in cosul tau',
						);
			}
*/
//starile de mai sus sunt starele posibile de raspuns la stergere
//la status 1 trebuie scos divul cu poza care tocmai a fost stersa si redimensionat divul (width carousel cos -CarouselGalerie9.item_width
			}
		}
	});
}

function downloadPicture(picId){
	var url = baseURL + 'index.php?module=gallery2&action=downloadPicture';
	new Ajax.Request(url,
	{
		method:'post',
		parameters: {item: picId, ajx: 1},
		onSuccess: function (transport)
		{
			var objResponse = transport.responseText.evalJSON();
			if(objResponse.status == 1){
				document.location = baseURL + 'index.php?module=gallery2&action=downloadPicture&item=' + picId;
			} else {
				alert(objResponse.message);
			}
		}
	});
}

function confirmBuy(msg){
	if(!msg){
		msg = 'Descarca poster in format original pe calculatorul tau. 1 credit.';
	}
	if(confirm(msg)){
		return true;
	} else {
		return false;
	}
}

function showPacks(){
	if($('packsList').style.display == 'block'){
		$('packsList').style.display='none';
	} else {
		$('packsList').style.display='block';
	}
	$('telComanda').style.display='none';
}

function requestPhone(packId){
	comanda = $('telComanda_' + packId);

	if (comanda.style.display == 'block') {
		comanda.style.display = 'none';
	} else if ( comanda.style.display == 'none' ) {
		arr = $$('div.phoneRequest');

		for (i=0; i<arr.length; i++) {
			arr[i].style.display = 'none';
		}
		comanda.style.display = 'block';
	}

	$('phoneRequest_' + packId).action = baseURL + 'index.php?module=gallery2&action=registerPay&pack=' + packId + '&send=1';

	return false;
}

//END SECTIUNE FOTO


/* Users Messages */
function deleteMsg(msg_id, user_id)
{
	if(confirm("Sunteti sigur ca vreti sa stergeti acest mesaj?"))
	{
		document.location.href="index.php?module=AmvcMessager&action=delete&id=" + msg_id + "&user_id=" + user_id;
	}
}

function markMessageAsRead(message_id, status)
{
	var div = 'message_content_' + message_id;
	Effect.toggle(div);
	if(status == 1 && $(div).style.display == 'none'){
		$('message-' + message_id).className = 'un_mesaj';
		parameters = 'message_id=' + message_id;
		url = 'index.php?module=AmvcMessager&action=markMessageAsRead&ajx=1';
		new Ajax.Request(
			url,
			{
				method:'post',
				parameters:parameters
			}
		)
	}
	return false;
}

function showActions(showId){
    // allActions, userActions, userFriendsActions
    if(showId != 'allActions'){
        $('allActions').hide();
        $('allActions_tab').removeClassName('tab_right');
    }
    if(showId != 'userActions'){
        $('userActions').hide();
        $('userActions_tab').removeClassName('tab_right');
    }
    if(showId != 'userFriendsActions'){
        $('userFriendsActions').hide();
        $('userFriendsActions_tab').removeClassName('tab_right');
    }
    $(showId).show();
    $(showId+'_tab').addClassName('tab_right');

    return false;
}

function populateCountiesByCountry()
{

	var country = $F('country');
	var url = baseURL + '?module=AmvcUserArtist&action=getCountiesByCountry';
	var city = $('county').options;
	$('county').options.length=0;
	$('city').options.length=0;
	params = 'country_id=' + country;

	new Ajax.Request( url,
	{method: 'post',
	parameters:params,
	onSuccess:  addOptionsCounties

	});
	//	setTimeout("populateCitiesByCounty()", 100);
}

function populateCitiesByCounty()
{
	var county = $F('county');
	var url = baseURL + '?module=AmvcUserArtist&action=getCitiesByCounty';
	var city = $('city').options;
	$('city').options.length = 0;
	//var i;

	$('city').options.length=0;

	params = 'county_id=' + county;
	new Ajax.Request( url,
	{method: 'post',
	parameters:params,
	onSuccess:  addOptions

	});
}

function addOptionsCounties(jsonul)
{
	var x=$('county').options;
	result = jsonul.responseText;
	//json="{'3':'cucu', '4':'mucu'}".evalJSON();
	json = result.evalJSON();

	x[0]= new Option('Alege judetul...', 0);

	json.each(function(j){
		x[x.length]=new Option(j.name, j.id)
	})
}

function addOptions(jsonul)
{

	var x=$('city').options;
	result = jsonul.responseText;
	//json="{'3':'cucu', '4':'mucu'}".evalJSON();
	json = result.evalJSON();

	x[0]= new Option('Alege orasul...', 0);

	json.each(function(j){
		x[x.length]=new Option(j.name, j.id)
	})
}

function check_equals( id1, id2 )
{
	return ( document.getElementById( id1 ).value == document.getElementById( id2 ).value );
}

function validate_passwords_match( id1, id2 )
{
	if ( ! check_equals( id1, id2 ) )
	{
		alert( "Parolele nu coincid!" );
		return false;
	}

	return true;
}

function getPos(obj, reposition)
{
	off = Element.viewportOffset(obj);
	offseturi = document.viewport.getScrollOffsets();

	return {leftOff : off[0], topOff : off[1]+offseturi[1]};
}

function enterFanclub(element)
{

	if($('subscribe_fanclub_content'))
	{
		/*
		$('subscribe_fanclub').style.top = (getPos(element).topOff - 40) + 'px';
		$('subscribe_fanclub').style.left = (getPos(element).leftOff - 340) + 'px';

		Effect.Appear('subscribe_fanclub', {duration: 0.5});
		*/

		this.errMsg = new MsgBox;
		this.errMsg.fullBg = true;
		this.errMsg.contentId = 'subscribe_fanclub_content';
		this.errMsg.init();
		this.errMsg.show();

		return false;
	}
	return true;
}

function closeMsgBox()
{
	if (this.errMsg)
		this.errMsg.hide();

	return false;
}

function acceptFanclub()
{
	Effect.Fade('subscribe_fanclub', {duration: 0.5});
	if($('login_popup'))
	{
		closeMsgBox();
		loginUser($('a_subscribe_fanclub'));
	}
	else
	{
		top.location = $('a_subscribe_fanclub').href;
	}
}

function AjaxAutocompleterUsers(from, to, module, action, min_chars)
{

	link = baseURL + 'index.php?module='+module+'&action='+action;
	new Ajax.Autocompleter(from,to,link,
	{
		minChars:min_chars,
		indicator: 'indicator1',
		afterUpdateElement : writeUserId
	}
	);
}

function writeUserId(text, li)
{
	var user_id = li.id;
	$('id').value = user_id;
	$('searchFriend').submit();
}

function isArray(obj) {
	if (typeof obj[0] != 'undefined')
		return true;
	else
		return false;
}

function emailIsValid( emailField, divId ){
	var match =  $(emailField).value.match( /^[a-zA-Z]([a-zA-Z0-9\._-]*[a-zA-Z0-9])?\@[a-zA-Z0-9]([a-zA-Z0-9\._-]*[a-zA-Z0-9])?\.[a-zA-Z0-9]{2,3}$/ );
	if ( match == null){
		var errMsg = new MsgBox;
		errMsg.fullBg = true;
		errMsg.contentId = divId;
		errMsg.init();
		errMsg.show();
		return false;
	}
	return true;
}

var slugStatus = false;
function getSlug ( text, length, functie, table )
{
	var url = baseURL + 'index.php?action=getSlug';
	new Ajax.Request(url,
	{
		method:'post',
		parameters: {text: text, length: length, table: table, ajxF: 1, responseType: 'json'},
		onSuccess: function (transport)
		{
			eval( functie + '(' + transport.responseText + ');' );
		}
	});

}

function markArtist( responseText )
{
	if(responseText.status !=0 )
	{
		$('artist_nou').style.color = 'red';
	} else {
		$('artist_nou').style.color = 'black';
	}
}

function validate_user_artist_form(count)
{
	var gen = 0;
	var err = '';

	if( $('addArtist').artist_nou.value == '' )
	{
		err = 'Trebuie sa introduci un nume pentru artist/trupa! \n';
	}

	if($('artist_nou').style.color == 'red' )
	{
		alert('Acest artist exidta deja pe site.');
		return false;
	}

	for( i=0;i<count;i++ )
	{
		if( $('genre_'+i).checked)
		{
			gen = 1;
		}
	}

	if ( gen == 0)
	{
		err += 'Trebuie sa selectezi cel putin un gen muzical!';
	}

	if ( err != '' )
	{
		alert( err );
		return false;
	}else{
		return true;
	}
}



function testGetSlug(slug)
{
	alert (slug.slug);
	alert (slug.status);
	alert (slug.message);
}

function check_equals( id1, id2 )
{
	return ( document.getElementById( id1 ).value == document.getElementById( id2 ).value );
}

function validate_passwords_match( id1, id2 )
{
	if ( ! check_equals( id1, id2 ) )
	{
		alert( "Parolele nu coincid" );
		return false;
	}

	return true;
}

var isValid=false;

function validate_register_form(id1, id2, user)
{
	var myRegxp = /^[a-zA-Z0-9_\.]{3,20}$/;

	if ( myRegxp.test($(user).value) == false )
	{
		alert("Username-ul trebuie sa aiba minim 3 caractere: cifre, litere, '_' si '.' !");
		return false;
	}

	if (validate_passwords_match( id1, id2 ) )
	{
		if ( $('agreement').checked != true )
		{
			alert('Trebuie sa accepti conditiile pentru a te inregistra');
			return false;
		}
	}

	// Slug
	url = baseURL + 'index.php?action=getSlug';
	new Ajax.Request(url, {
		method: 'post',
		parameters: {
			ajxF: 1,
			text: $(user).value,
			length: 150,
			table: 'user',
			responseType: 'json'
		},
		onSuccess: registerSlugSuccess,
		asynchronous: false
	});

	return isValid;
}

function registerSlugSuccess(response)
{
	ret=response.responseText.evalJSON();
	status=ret['status'];

	// Error
	if ( status != 0 )
	{
		alert(ret['message']);

		if ($('slug'))
		{
			$('slug').remove();
		}

		isValid=false;

		return false;
	}
	// Ok
	else
	{
		var elem = new Element('input', {'type': 'hidden', 'name': 'slug', 'value': ret['slug'], 'id': 'slug'});

		$('regForm').appendChild(elem);

		isValid=true;

		return true;
	}
}

function redirect(url){
	window.location = baseURL + url;
}

function initFB() {
	FB_RequireFeatures(["XFBML"], function(){
		FB.init('9cfdb80fb708a6a8fa98cd4249fb8408', baseURL + 'facebook/xd_receiver.htm',
                {permsToRequestOnConnect : "email"});
	});
}

function fb_connect(){
	FB.ensureInit(
		function(){
			FB.Connect.requireSession( function(){
					var message = 'Hello world of Facebook!';

					FB.Connect.streamPublish(message);
				}
			);
		}
	);
}


function validate_remote_login(user)
{
	var myRegxp = /^[a-zA-Z0-9_\.]{3,20}$/;
	if ( myRegxp.test($(user).value) == false )
	{
		alert("Username-ul trebuie sa aiba \n minim 3 caractere: cifre, litere, '_' si '.' !");
		return false;
	}

	if ( $('agreement').checked != true )
	{
		alert('Trebuie sa accepti conditiile pentru a te inregistra');
		return false;
	}

	// Slug
	url = baseURL + 'index.php?action=getSlug';
	new Ajax.Request(url, {
		method: 'post',
		parameters: {
			ajxF: 1,
			text: $(user).value,
			length: 150,
			table: 'user',
			responseType: 'json'
		},
		onSuccess: registerSlugSuccess,
		asynchronous: false
	});

	return isValid;
}

function verifyEmail(form){
	var url = document.location;
	var params = {search: $F('n_email'), field: 'n_email', ajxF: 1, chaptcha: $F('n_captcha')};
		new Ajax.Request(url,
		{
			method:'POST',
			parameters:params,
			onSuccess: function (rasp){
				if(rasp.responseText){
					$('nw_statusMessages').innerHTML = eval(rasp.responseText);
				} else {
					form.submit();
				}
			}
		});
}

function sendEditEmail(form, link){
	var url = link.href;
	$(form).action = url;
	$(form).submit();
}

function populateCities()
{
	var tara = $F('country');
	var url = baseURL + '?module=AmvcUser&action=getCities';
	var city = $('city').options;

	$('city').options.length=0


	params = 'country_id=' + tara;

	new Ajax.Request( url,
	{method: 'post',
	parameters:params,
	onSuccess:  addOptions

	});
}


function updateJwArtistTrack(artist_id,track_id)
{
	var params = 'artist_id='+artist_id+'&track_id='+track_id+'&ajx=1';
	new Ajax.Updater('', baseURL+'/index.php?module=AmvcArtist&action=updateJwArtistTrack',
		{
			method:'get',
			parameters:params
		}
	)
}

function adhits_update(id)
{
	var url = baseURL+'index.php?module=radio&action=updateAd';
	var params = {id: id};
	new Ajax.Updater('',url,
		{
			method:'post',
			parameters:params
		}
	);
}
function customplaylistNext()
{
	if(is_ad!=1)
		jwplayer("jw").playlistNext();
}

function toggleVisibility(id,effect, time)
{
	if(!effect)
	{
		var effect = 'appear';
	}

	if(!time && time != 0)
	{
		var time = 0.5;
	}

	Effect.toggle(id, effect,{duration: time});

	return false;
}

function toggleClass(elem, class1,class2)
{
	if(elem.hasClassName(class1))
	{
		elem.removeClassName(class1);
		elem.addClassName(class2);
	}
	else
	{
		elem.removeClassName(class2);
		elem.addClassName(class1);
	}
}



function AjaxAutocompleterTop20(from, to, module, action, min_chars)
{

	link = baseURL + 'index.php?module='+module+'&action='+action;
	new Ajax.Autocompleter(from,to,link,
	{
		minChars:min_chars,
		indicator: 'indicator1',
		afterUpdateElement : writeTrack_id,
		frequency: '1'
	}
	);
}

function writeTrack_id(text, li)
{

	var track_id = li.id
	$('track_id').value = track_id;
	$('message').style.background = '#EEFFEE';

}

function verificaPropunere ()
{
	if ($('track_id').value != '')
	{
		return true;
	}
	else
	{
		alert('Trebuie sa alegi o piesa din lista ca propunere!');
		return false;
	}
}


// Carusel grupuri promo

function clickGenreCarusel(element)
{
	var next_id = element.readAttribute('id');
	var id = next_id.replace(/g_link_/,'');

	var others = $$('#genre_head_ul li:not([id="'+'g_li_'+id+'"])');
	for(i = 0; i < others.length; i++) {
		others[i].removeClassName('portocaliu');
	}

	$('g_li_'+id).addClassName('portocaliu');

	var others = $$('#box_mare_carousel_genuri div.carusel2:not([id="'+'genre_content_'+id+'"])');
	for(i = 0; i < others.length; i++) {
			others[i].hide();
	}

	$('genre_content_'+id).appear({duration : 1.0});

}

function scrollGenres()
{
	var elements = $$('#genre_head_ul li.portocaliu');
	var element = elements[0];

	Tsiblings = element.nextSiblings();
	if(Tsiblings.length)
	{
		var nextElement = Tsiblings[0];
	}
	else
	{
		var elements = $$('#genre_head_ul li');
		var nextElement = elements[0];
	}
	var next_id = nextElement.readAttribute('id');
	var id = next_id.replace(/g_li_/,'');

	var others = $$('#genre_head_ul li:not([id="'+next_id+'"])');
	for(i = 0; i < others.length; i++) {
		others[i].removeClassName('portocaliu');
	}
	nextElement.addClassName('portocaliu');

	var others = $$('#box_mare_carousel_genuri div.carusel2:not([id="'+'genre_content_'+id+'"])');
	for(i = 0; i < others.length; i++) {
			others[i].hide();
	}

	$('genre_content_'+id).appear({duration : 2.0});

	setTimeout('scrollGenres()',8000);
}
// End Carusel grupuri promo


// special Google Adsense

function google_ad_request_done(google_ads) {

var s;


    if (google_ads.length == 0)
      return;

google_num_ads += google_ads.length;
google_last_ad_type = google_ads[0].type;

 s = '<a class="ad_attribution" href="' + google_info.feedback_url + '">Anunturi Google</a><br />';
 if (google_ads[0].type == "image" && google_ads[0].image_width == 468) {s += '<a href="' + google_ads[0].url +                '" target="_top" title="go to ' + google_ads[0].visible_url +                '"><img border="0" src="' + google_ads[0].image_url +                '" width="430" height="' + google_ads[0].image_height + '"></a>';}
else if (google_ads[0].type == "image" && google_ads[0].image_width == 728) {s += '<a href="' + google_ads[0].url +                '" target="_top" title="go to ' + google_ads[0].visible_url +                '"><img border="0" src="' + google_ads[0].image_url +                '" width="640" height="' + google_ads[0].image_height + '"></a>';}
else if (google_ads[0].type == "image") {s += '<a href="' + google_ads[0].url +                '" target="_top" title="go to ' + google_ads[0].visible_url +                '"><img border="0" src="' + google_ads[0].image_url +                '"width="' + google_ads[0].image_width +                '"height="' + google_ads[0].image_height + '"></a>';}
else if (google_ads[0].type == "flash" && google_ad.image_width == 728) {s += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +                ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"' +                ' WIDTH="640" HEIGHT="' + google_ad.image_height + '">' +                '<PARAM NAME="movie" VALUE="' + google_ad.image_url + '">' +                '<PARAM NAME="quality" VALUE="high">' +                '<PARAM NAME="AllowScriptAccess" VALUE="never">' +                '<EMBED src="' + google_ad.image_url +                '" WIDTH="640" HEIGHT="' + google_ad.image_height +                '" TYPE="application/x-shockwave-flash"' +                ' AllowScriptAccess="never" ' +                ' PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>';}
else if (google_ads[0].type == "flash" && google_ad.image_width == 468) {s += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +                ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"' +                ' WIDTH="430" HEIGHT="' + google_ad.image_height + '">' +                '<PARAM NAME="movie" VALUE="' + google_ad.image_url + '">' +                '<PARAM NAME="quality" VALUE="high">' +                '<PARAM NAME="AllowScriptAccess" VALUE="never">' +                '<EMBED src="' + google_ad.image_url +                '" WIDTH="430" HEIGHT="' + google_ad.image_height +                '" TYPE="application/x-shockwave-flash"' +                ' AllowScriptAccess="never" ' +                ' PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>';}
else if (google_ads[0].type == "flash" ) {s += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +                ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"' +                ' WIDTH="' + google_ad.image_width +                '" HEIGHT="' + google_ad.image_height + '">' +                '<PARAM NAME="movie" VALUE="' + google_ad.image_url + '">' +                '<PARAM NAME="quality" VALUE="high">' +                '<PARAM NAME="AllowScriptAccess" VALUE="never">' +                '<EMBED src="' + google_ad.image_url +                '" WIDTH="' + google_ad.image_width +                '" HEIGHT="' + google_ad.image_height +                '" TYPE="application/x-shockwave-flash"' +                ' AllowScriptAccess="never" ' +                ' PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>';}
else if (google_ads[0].type == "html") {s += google_ads[0].snippet;}
else if (google_ads[0].type == "text") {       // Dynamic Resizing: Adjust text sizes to occupy the majority of ad space.

if (google_ads.length == 4) {
ad_title_class = 'ad_title_large';
ad_text_class = 'ad_text_large';
ad_url_class = 'ad_url_large';
      }
         else {
ad_title_class = 'ad_title';
ad_text_class = 'ad_text';
ad_url_class = 'ad_url';
      }

      for(var i=0; i<google_ads.length; i++) {
        s += '<p><a class="' + ad_title_class + '" href="' + google_ads[i].url + '" ><b>' +
google_ads[i].line1 + '</b></a> -' + ' <a class="' + ad_url_class + '" href="' + google_ads[i].url + '" >' +
google_ads[i].visible_url + '</a><br><span class="' + ad_text_class + '">' +
google_ads[i].line2 +
google_ads[i].line3 + '</span><br/></p>';
      }
    }
document.write(s);
    return;
}



function loadTop20Genre(genre)
{
	//var params = 'top_id='+id+'&type_id='+type+'&ajx=1';

	var params = 'genre='+genre;
	new Ajax.Updater('rec_events', baseURL+'/index.php?module=top20&action=topEntriesGenreAjax',
		{
			method:'get',
			parameters:params
		}
	)

	var link = 'link'+genre;
	var mytabs =  $('tabList').childElements();
	mytabs.each(function(node){
		//alert(node.nodeName);
		node.removeClassName('activLi');
		//node.addClassName('test');

	});

	$(link).addClassName('activLi');
}

function loadTopPreturi(event_type)
{
	//var params = 'top_id='+id+'&type_id='+type+'&ajx=1';

	var params = 'event_type='+event_type;
	new Ajax.Updater('rec_preturi', baseURL+'/index.php?module=AmvcArtist&action=top_preturi',
		{
			method:'get',
			parameters:params
		}
	)
}

function loadTopSocial()
{
	if($('rec_social').innerHTML=='')
	{
		var params = 'genre=social';
		new Ajax.Updater('rec_social', baseURL+'/index.php?module=top20&action=loadTopSocial',
			{
				method:'get',
				parameters:params
			}
		)
	}
}



function eventsAjax()
{

	var url=baseURL+"index.php?action=events";
	var control = document.getElementById("cityselect");
	var value=control.options[control.selectedIndex].value;
	var params = {cityselect: value, ajx: 1};
	new Ajax.Updater('hptops_right', url,
		{
            method: 'post',
            parameters: params
        } );
}


function addRating(calitate)
{
	document.getElementById('calitate').value=calitate;
	document.ratingform.submit();
}

/*slider pentru box right pagina artist la statistici*/

var featuredcontentslider={

//3 variables below you can customize if desired:
ajaxloadingmsg: '<div style="margin: 20px 0 0 20px"><img src="loading.gif" /> Fetching slider Contents. Please wait...</div>',
bustajaxcache: true, //bust caching of external ajax page after 1st request?
enablepersist: true, //persist to last content viewed when returning to page?

settingcaches: {}, //object to cache "setting" object of each script instance

jumpTo:function(fcsid, pagenumber){ //public function to go to a slide manually.
	this.turnpage(this.settingcaches[fcsid], pagenumber)
},

ajaxconnect:function(setting){
	var page_request = false
	if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
		try {
		page_request = new ActiveXObject("Msxml2.XMLHTTP")
		}
		catch (e){
			try{
			page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else
		return false
	var pageurl=setting.contentsource[1]
	page_request.onreadystatechange=function(){
		featuredcontentslider.ajaxpopulate(page_request, setting)
	}
	document.getElementById(setting.id).innerHTML=this.ajaxloadingmsg
	var bustcache=(!this.bustajaxcache)? "" : (pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', pageurl+bustcache, true)
	page_request.send(null)
},

ajaxpopulate:function(page_request, setting){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
		document.getElementById(setting.id).innerHTML=page_request.responseText
		this.buildpaginate(setting)
	}
},

buildcontentdivs:function(setting){
	var alldivs=document.getElementById(setting.id).getElementsByTagName("div")
	for (var i=0; i<alldivs.length; i++){
		if (this.css(alldivs[i], "contentdiv", "check")){ //check for DIVs with class "contentdiv"
			setting.contentdivs.push(alldivs[i])
				alldivs[i].style.display="none" //collapse all content DIVs to begin with
		}
	}
},

buildpaginate:function(setting){
	this.buildcontentdivs(setting)
	var sliderdiv=document.getElementById(setting.id)
	var pdiv=document.getElementById("paginate-"+setting.id)
	var phtml=""
	var toc=setting.toc
	var nextprev=setting.nextprev
	if (typeof toc=="string" && toc!="markup" || typeof toc=="object"){
		for (var i=1; i<=setting.contentdivs.length; i++){
			phtml+='<a href="#'+i+'" class="toc">'+(typeof toc=="string"? toc.replace(/#increment/, i) : toc[i-1])+'</a> '
		}
		phtml=(nextprev[0]!=''? '<a href="#prev" class="prev">'+nextprev[0]+'</a> ' : '') + phtml + (nextprev[1]!=''? '<a href="#next" class="next">'+nextprev[1]+'</a>' : '')
		pdiv.innerHTML=phtml
	}
	var pdivlinks=pdiv.getElementsByTagName("a")
	var toclinkscount=0 //var to keep track of actual # of toc links
	for (var i=0; i<pdivlinks.length; i++){
		if (this.css(pdivlinks[i], "toc", "check")){
			if (toclinkscount>setting.contentdivs.length-1){ //if this toc link is out of range (user defined more toc links then there are contents)
				pdivlinks[i].style.display="none" //hide this toc link
				continue
			}
			pdivlinks[i].setAttribute("rel", ++toclinkscount) //store page number inside toc link
			pdivlinks[i][setting.revealtype]=function(){
				featuredcontentslider.turnpage(setting, this.getAttribute("rel"))
				return false
			}
			setting.toclinks.push(pdivlinks[i])
		}
		else if (this.css(pdivlinks[i], "prev", "check") || this.css(pdivlinks[i], "next", "check")){ //check for links with class "prev" or "next"
			pdivlinks[i].onclick=function(){
				featuredcontentslider.turnpage(setting, this.className)
				return false
			}
		}
	}
	this.turnpage(setting, setting.currentpage, true)
	if (setting.autorotate[0]){ //if auto rotate enabled
		pdiv[setting.revealtype]=function(){
			featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id])
		}
		sliderdiv["onclick"]=function(){ //stop content slider when slides themselves are clicked on
			featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id])
		}
		setting.autorotate[1]=setting.autorotate[1]+(1/setting.enablefade[1]*50) //add time to run fade animation (roughly) to delay between rotation
	 this.autorotate(setting)
	}
},

urlparamselect:function(fcsid){
	var result=window.location.search.match(new RegExp(fcsid+"=(\\d+)", "i")) //check for "?featuredcontentsliderid=2" in URL
	return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index
},

turnpage:function(setting, thepage, autocall){
	var currentpage=setting.currentpage //current page # before change
	var totalpages=setting.contentdivs.length
	var turntopage=(/prev/i.test(thepage))? currentpage-1 : (/next/i.test(thepage))? currentpage+1 : parseInt(thepage)
	turntopage=(turntopage<1)? totalpages : (turntopage>totalpages)? 1 : turntopage //test for out of bound and adjust
	if (turntopage==setting.currentpage && typeof autocall=="undefined") //if a pagination link is clicked on repeatedly
		return
	setting.currentpage=turntopage
	setting.contentdivs[turntopage-1].style.zIndex=++setting.topzindex
	this.cleartimer(setting, window["fcsfade"+setting.id])
	setting.cacheprevpage=setting.prevpage
	if (setting.enablefade[0]==true){
		setting.curopacity=0
		this.fadeup(setting)
	}
	if (setting.enablefade[0]==false){ //if fade is disabled, fire onChange event immediately (verus after fade is complete)
		setting.contentdivs[setting.prevpage-1].style.display="none" //collapse last content div shown (it was set to "block")
		setting.onChange(setting.prevpage, setting.currentpage)
	}
	setting.contentdivs[turntopage-1].style.visibility="visible"
	setting.contentdivs[turntopage-1].style.display="block"
	if (setting.prevpage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted)
		this.css(setting.toclinks[setting.prevpage-1], "selected", "remove")
	if (turntopage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted)
		this.css(setting.toclinks[turntopage-1], "selected", "add")
	setting.prevpage=turntopage
	if (this.enablepersist)
		this.setCookie("fcspersist"+setting.id, turntopage)
},

setopacity:function(setting, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between)
	var targetobject=setting.contentdivs[setting.currentpage-1]
	if (targetobject.filters && targetobject.filters[0]){ //IE syntax
		if (typeof targetobject.filters[0].opacity=="number") //IE6
			targetobject.filters[0].opacity=value*100
		else //IE 5.5
			targetobject.style.filter="alpha(opacity="+value*100+")"
	}
	else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
		targetobject.style.MozOpacity=value
	else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
		targetobject.style.opacity=value
	setting.curopacity=value
},

fadeup:function(setting){
	if (setting.curopacity<1){
		this.setopacity(setting, setting.curopacity+setting.enablefade[1])
		window["fcsfade"+setting.id]=setTimeout(function(){featuredcontentslider.fadeup(setting)}, 50)
	}
	else{ //when fade is complete
		if (setting.cacheprevpage!=setting.currentpage) //if previous content isn't the same as the current shown div (happens the first time the page loads/ script is run)
			setting.contentdivs[setting.cacheprevpage-1].style.display="none" //collapse last content div shown (it was set to "block")
		setting.onChange(setting.cacheprevpage, setting.currentpage)
	}
},

cleartimer:function(setting, timervar){
	if (typeof timervar!="undefined"){
		clearTimeout(timervar)
		clearInterval(timervar)
		if (setting.cacheprevpage!=setting.currentpage){ //if previous content isn't the same as the current shown div
			setting.contentdivs[setting.cacheprevpage-1].style.display="none"
		}
	}
},

css:function(el, targetclass, action){
	var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig")
	if (action=="check")
		return needle.test(el.className)
	else if (action=="remove")
		el.className=el.className.replace(needle, "")
	else if (action=="add")
		el.className+=" "+targetclass
},

autorotate:function(setting){
 window["fcsautorun"+setting.id]=setInterval(function(){featuredcontentslider.turnpage(setting, "next")}, setting.autorotate[1])
},

getCookie:function(Name){
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return null
},

setCookie:function(name, value){
	document.cookie = name+"="+value

},


init:function(setting){
	var persistedpage=this.getCookie("fcspersist"+setting.id) || 1
	var urlselectedpage=this.urlparamselect(setting.id) //returns null or index from: mypage.htm?featuredcontentsliderid=index
	this.settingcaches[setting.id]=setting //cache "setting" object
	setting.contentdivs=[]
	setting.toclinks=[]
	setting.topzindex=0
	setting.currentpage=urlselectedpage || ((this.enablepersist)? persistedpage : 1)
	setting.prevpage=setting.currentpage
	setting.revealtype="on"+(setting.revealtype || "click")
	setting.curopacity=0
	setting.onChange=setting.onChange || function(){}
	if (setting.contentsource[0]=="inline")
		this.buildpaginate(setting)
	if (setting.contentsource[0]=="ajax")
		this.ajaxconnect(setting)
}

}
/*end slider pentru box right pagina artist la statistici*/

function toggle_translate(p)
{
	if(p=='ro')
	{
			document.getElementById('vers').style.display='none';
			document.getElementById('trans').style.display='';
			document.location.hash = '#ro';
	}
	else
	{
			document.getElementById('vers').style.display='';
			document.getElementById('trans').style.display='none';
			document.location.hash ='';
	}
}

function fetchBanners(zona)
{
	var _bmAds_ = window['_bmAds' + zona];
	var url =  baseURL.replace(/shop.?\/$/i,'')+'index.php?module=banners&action=banners&ajx=1';
	var params = "entity_id="+_bmAds_.entity_id+'&zone='+_bmAds_.zone+'&entity_type_id='+_bmAds_.entity_type_id+'&site='+_bmAds_.site;
	new Ajax.Request(url, {
		method: 'get',
		parameters:params,
		onSuccess: function(transport) {
			var show = _bmAds_.show;
			$(show).innerHTML = transport.responseText;
		}
	});
}

function clicked(bid, zid)
{
	var params = "&zid="+zid+"&bid="+bid;
	var url = baseURL.replace(/shop.?\/$/i,'')+'index.php?module=banners&action=click';
	new Ajax.Request(url,{
	method:'post',
	parameters:params,
	onSuccess:function(transport){
		if (transport.responseText.length){
			var objResponse = transport.responseText.evalJSON();
			alert(objResponse.link);
			target = objResponse.target;
			window.open(objResponse.link, 'banners_window_' + zid);
		}
	}
	});
	return false;
}


/*********************************************** msgbox.js **************************************************/
var MsgBox = function() {
	this.msg = '';						//mesaj statis
	this.contentId = '';				//id-ul div-ului in care se pune mesajul - cu clasa mCi pentru a fi ascuns
	this.url = '';						//url pentru iframe
	this.title = 'Bestmusic';			//Titlul afisat in bara mesajului
	this.width = '500';					//width-ul boxului
	this.height = '300';				//height-ul boxului
	this.close = 'inchide ';			//textul pt butonul de close
	this.fullBg = false;				//true ascunde toata pagina cu bg transparent, false nu ascunde decat zona boxului
	this.persist = false;				//true daca se doreste sa nu se stearga contentul la close


	this.cont;
	this.window;
	this.totalW = document.viewport.getWidth();
	this.totalH = document.viewport.getHeight();
	this.Win = window;
	this.curPos;
};

MsgBox.prototype = {
	init:function() {
		var bg, msgbox, title, close, close_span;

		msgbox = this.createElement('div', 'msg', '', {height:this.height-55+'px'});
		this.cont = this.createElement('div', 'msgcont', '', {display:'none'}, '');
		this.window = this.createElement('div', 'window', '', {width:this.width+'px', height:this.height+'px', top:(this.totalH-this.height)/2+'px', left:(this.totalW-this.width)/2+'px'});
		title = this.createElement('div', 'title', 'column first full', '', this.title);
		close = this.createElement('a', 'close', 'align-right', '', this.close);
		close_span = this.createElement('span', '', '', '', 'x');

		if (this.fullBg) {
			bg = this.createElement('div', 'msgbg', '', {height:this.totalH+'px'});
			this.cont.appendChild(bg);
		}
		close.appendChild(close_span);
		title.appendChild(close);
		this.window.appendChild(title);
		this.window.appendChild(msgbox);
		this.cont.appendChild(this.window);
		document.body.appendChild(this.cont);

		if (this.url != '') {
			msgbox.innerHTML = '<iframe id="frame_box" src="' + this.url + '" frameborder="0"></iframe>';
		} else if (this.contentId != '') {
			msgbox.innerHTML = $(this.contentId).innerHTML;
			$(this.contentId).remove();
		} else if (this.msg != '') {
			msgbox.innerHTML = this.msg;
		}

		var inOBJ = this;

		Event.observe(close, 'click', function(e){inOBJ.hide();return false});

		Event.observe(this.Win, 'resize', function(e){inOBJ.resize();});

		if (Prototype.Browser.IE6) {
			Event.observe(this.Win, 'scroll', function(e){inOBJ.arange();});
		}
	},

	createElement:function(tag, id, className, stiluri, text) {
		if (tag && tag != '') {
			var elem;
			elem = document.createElement(tag);

			if (text && text != '') {
				var elemText;
				elemText = document.createTextNode(text);
				elem.appendChild(elemText);
			}

			if (id && id != '') {
				elem.id = id;
			}

			if (className && className != '') {
				elem.className = className;
			}

			if (stiluri && stiluri != '') {
				for (i in stiluri) {
					prop = i.toString();
					val = stiluri[i].toString();
					eval('elem.style.'+prop+' = "'+val+'"');
				}
			}

			return elem;
		} else {
			return false;
		}
	},

	resize:function() {
		var w = document.viewport.getWidth();
		var h = document.viewport.getHeight();
		this.cont.style.width = w+'px';
		this.cont.style.height = h+'px';
		this.window.style.left = (w-this.width)/2+'px';
		this.window.style.top = (h-this.height)/2+'px';
	},

	arange:function() {
		var XY = document.viewport.getScrollOffsets();

		if (XY.left != this.cont.style.left || XY.top != this.cont.style.top) {
			this.cont.style.left = XY.left+'px';
			this.cont.style.top = XY.top+'px';
		}
	},

	show:function() {
		Effect.Appear(this.cont);

		document.observe('dom:loaded',
			function(event){
				if (Prototype.Browser.IE) {
					var sels = $$('select');
					sels.each(function(sel, iter){sel.style.display='none'});
				}

				var objs = $$('object');
				objs.each(function(obj, iter){obj.style.display='none'});

				var embs = $$('embed');
				embs.each(function(emb, iter){emb.style.display='none'});
			}
		);
	},

	hide:function() {
		Effect.Fade(this.cont);

		if (Prototype.Browser.IE) {
			var sels = $$('select');
			sels.each(function(sel, iter){sel.style.display='block'});
		}

		var objs = $$('object');
		objs.each(function(obj, iter){obj.style.display='block'});

		var embs = $$('embed');
		embs.each(function(emb, iter){emb.style.display='block'});

		if (!this.persist) {
			this.cont.remove();
		}
	}
}
/*********************************************** end msgbox.js **************************************************/

/*** functii pentru feederul de tip artist ***/

function artistFeederClickEv(event)
{
	var element = event.element();
	artistFeederClickEvFn(element);
}

function artistFeederClickEvFn(element)
{
	if(artistFeederScrollTimer )
	{
		clearTimeout(artistFeederScrollTimer);
	}
	var newsid = element.readAttribute('id');
	var id = newsid.replace(/action_/,'');
	var others_a =  element.siblings();



	var elementCnt = others_a.length+1;

	for(j = 1; j <= elementCnt; j++)
	{
		if(j!=id)
		{
			$('content_'+j).hide();
			$('image_'+j).hide();
			$('action_'+j).removeClassName('selected_feed');
		}
		else
		{
			$('content_'+id).appear();
			$('image_'+id).appear();
			$('action_'+j).addClassName('selected_feed');
		}
	}
}

function artistFeederScroll(id)
{
	if(!id)
	{
		id=1;
	}

	radioCnt=$('action_'+id).siblings().length +1;

	artistFeederClickEvFn($('action_'+id));
	artistFeederScrollTimer = setTimeout('artistFeederScroll('+(id%radioCnt+1)+')',artistFeederScrollTime);
}
/*** sfarsit functii pentru feederul de tip artist ***/

/** start functie contorizare clickuri meniu **/
function menuContor(id)
{
	
	var url = baseURL + 'index.php';
	var parameters = '?action=menu_count';
		var params = {menu_id:id, aj:1};
		new Ajax.Request(url+parameters, 
		{
			method:'post',
			parameters: params,
			onSuccess: function (transport)
			{
				return true;
			}
		
		});
	return true;			
}

/*** sfarsit functie contorizare clickuri meniu ***/


/*** start functie select casa de discuri ***/
function changePublishersSelect()
	{
		if(document.getElementById('filter_country').value != '') 
			location.href=baseURL+'index.php?module=publishers&action=listing&country_id='+document.getElementById('filter_country').value+'&pag=1'; 
		else 
			location.href=baseURL+'index.php?module=publishers';
	}

/*** end functie select casa de discuri***/


/** start functii pentru playlist functions **/

	
	function showPlaylists()
	{
		if(document.getElementById("playlist").style.display=="block")
			document.getElementById("playlist").style.display="none";
		else
			document.getElementById("playlist").style.display="block";
	}
	function saveToPlaylist(id)
	{
		var checkboxes=document.getElementsByName("playlistCheck");
		var songs= new Array();
		if(checkboxes.length>0)
		{
			for(var i=0;i<checkboxes.length;i++)
				if(checkboxes[i].checked==true)
					{
						//alert(checkboxes[i].id)
						addSongs(checkboxes[i].id,id);
						//uncheck selectii
						
					}
		}
		document.getElementById("checkAll").checked =false;
		selectAll();
	}
	function selectAll()
	{
		var checkboxes=document.getElementsByName("playlistCheck");
		if(document.getElementById("checkAll").checked == true)
			{
				for(var i=0;i<checkboxes.length;i++)
					{
						checkboxes[i].checked=true;
					}
			}
		else
			{
				for(var i=0;i<checkboxes.length;i++)
					checkboxes[i].checked=false;
			}
	}
	function addSongs(song,playlist)
	{
		var url = baseURL + 'index.php';
		var parameters = '?module=music&action=playlistHandler';
		var params = {playlist_id: playlist, id: song, ajxF:1, type:'addElem'};
		new Ajax.Request(url+parameters, 
		{
			method:'post',
			parameters: params,
			onSuccess: function (transport)
			{
				var string = transport.responseText.evalJSON()
				if(string.ok==1) 
					{
						var val=document.getElementById("count"+playlist).innerHTML;
						val++;
						document.getElementById("count"+playlist).innerHTML=val;
					};
			}
		
		});
	}
	
	function createPlaylist()
	{
		titlu = document.getElementById("playlist_name").value;
		if(titlu != 'creaza-ti playlist' && titlu != '')
		{
			var url = baseURL + 'index.php';
			var parameters = '?module=music&action=playlistHandler';
			var params = {title:titlu, ajxF:1, type:'createPlaylist'};
			new Ajax.Request(url+parameters, 
			{
				method:'post',
				parameters: params,
				onSuccess: function (transport)
				{
					var string = transport.responseText.evalJSON()
					if(string.ok==1)
						{
							//adaug playlist-ul in lista
							var list=document.getElementById("list");
							list.innerHTML+="<li onclick='saveToPlaylist("+string.raspuns.id+")' style='cursor:pointer;'>"+string.raspuns.title+"(<span id='count"+string.raspuns.id+"'>0</span>)</li>"
							saveToPlaylist(string.raspuns.id);
						}
						
				}
			
			});
			document.getElementById("playlist_name").value='creaza-ti playlist';
		}
	}
/** sfarsit functii pentru playlist functions **/

// start functii pentru salvare statistici ascultari
	
	function mediaListenSave(last_duration, artist_id, track_id, listener_id, media_type, from_radio)
	{
		var url = baseURL + 'index.php';
		var parameters = '?module=music&action=musicStats';
		var params = {'sentFromAjx':'1024', 'last_duration': last_duration, 'artist_id':artist_id, 'track_id':track_id, 'listener_id':listener_id, 'media_type':media_type, 'from_radio':from_radio};
		new Ajax.Request(url+parameters,
			{
				method:'post',
				parameters: params
			}
		)
	}




// end functii pentru salvare statistici ascultari
// start  functii pentru plus hp

			function togglePlus(id)
			{
				var plus = document.getElementById('span'+id);
			
				if(plus.className == 'plus_gen')
					plus.className = 'minus_gen';
				else
					plus.className = 'plus_gen';
				//se inchid restul genurilor deschise
				hideAllExcept(id);
				toggleVisibility('drop'+id);
				
				
				//toggleVisibility('{$key}');
			}
			function hideAllExcept(id)
			{
				for(i=0;i<8;i++)
				{
					if(id != i) 
						{
							document.getElementById('drop'+i).style.display="none";
							document.getElementById('span'+i).className = 'plus_gen';
						}
					
				}
			
			}

// end  functii pentru plus hp

// start functii pentru rotit FB

var pattern= new Image();
	

function animate(first)
	{   
		if(first)
		{
			pattern.src = baseURL+'external/new/templates/default/img/fbcon.png'; 
			var ctx = document.getElementById('mycanvas').getContext('2d');
			ctx.drawImage(pattern,4,4);
			ctx.save(); 
			ctx.translate(12,12);
			ctx.restore(); 
		}
		else
			setInterval('drawShape()',10);
	}	

	function drawShape()
	{
		// get the canvas element using the DOM
		var canvas = document.getElementById('mycanvas');

		// Make sure we don't execute when canvas isn't supported
		if (canvas.getContext){

		// use getContext to use the canvas for drawing
		var ctx = canvas.getContext('2d');
		ctx.clearRect(0, 0, 24, 24);


		ctx.save();
		ctx.translate(12,12);

		var time = new Date(); 
		ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + 
		( (2*Math.PI)/6000)*time.getMilliseconds() );   
		ctx.translate(-8,-8);
		ctx.drawImage(pattern,0,0);
		ctx.restore(); 

		}
		
	}
	
	
	
// end functii pentru rotit FB


//start functii salvare user

function save_user_image(link,id_poza)
{
	var url = baseURL + 'index.php';
	var parameters = '?module=events&action=BBimg_link';
	var params = {'sentFromAjx':'1024', 'link':link, 'img_id':id_poza};
	new Ajax.Request(url+parameters,
		{
			method:'post',
			parameters: params,
			onSuccess: function (transport)
			{
				if (transport.responseText == 'no_err')
				{
					document.getElementById('revendica').innerHTML = 'Ti-ai revendicat poza!';
					document.location = link;
				}
				else if (transport.responseText == 'err_usr')
					document.getElementById('revendica').innerHTML = 'Ai ales deja o poza!';
				else if (transport.responseText == 'err_img')
					document.getElementById('revendica').innerHTML = 'Poza a fost aleasa deja!';
			}
		}
	)
	
	//alert(link);
}

function deleteClubDay(day_id)
{
	var url = baseURL + 'index.php';
	var parameters = '?module=club_reservations&action=del_private_day&day_id='+day_id;
	new Ajax.Request(url+parameters,
		{
			method:'get',
			onSuccess: function (transport)
			{
				count_per--;
				if(count_per > 0)
					document.getElementById('row_'+day_id).innerHTML = '';
				else
					location.reload(true);
			}
		
		}
	)
}
//end functii salvare user

function goToLink( param )
{
	if(param.indexOf('http')>-1)
	{
		window.location=param;
	}
	else
	{
		window.location=baseURL+'index.php?'+param;
	}
}
