	function disableAdvFields(v) {
	$("#advanced_form input").each(function () {
	        //if ($(this).val() == "")
			{
			  $(this).val("");
	          $(this).attr("disabled", v);
	        }
	});
	}

	
	var activeTab = 1;
	
	function onYouTubePlayerReady(playerId) {
	  ytplayer = document.getElementById("myytplayer");
	  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
	}
			
	function onytplayerStateChange(newState) {
		if(0==newState)//ended
	    setTimeout(ajaxNextTrailer, 1000);
	}
						
	function getURLParameter(name) {
		var res = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1];
		return res?unescape(res):res;
	}
	
	function ajaxNextTrailerParams(p) {

		//collect data
		var postData='yt0=Apply';
		
		//var tab = getURLParameter(escape('SearchForm[tab]'));
		//tab = tab?parseInt(tab,10):1;

		var tab = activeTab;
		
		postData+='&SearchForm[tab]='+tab;
		
		var trailerId = getURLParameter('tid')?getURLParameter('tid'):getURLParameter(escape('SearchForm[trailerId]'));
		
		if(trailerId)
		{
			postData+='&SearchForm[trailerId]='+trailerId;
		}
		else if(1==tab)
		{
			if($('#SearchForm_popular').attr('checked'))
				postData+='&SearchForm[popular]='+$('#SearchForm_popular').attr('value');
			else	
				postData+='&SearchForm[popular]=0';
			
			if($('#SearchForm_inmovietheaters').attr('checked'))
				postData+='&SearchForm[inmovietheaters]='+$('#SearchForm_inmovietheaters').attr('value');
			else	
				postData+='&SearchForm[inmovietheaters]=0';
				
			if($('#SearchForm_comingsoon').attr('checked'))
				postData+='&SearchForm[comingsoon]='+$('#SearchForm_comingsoon').attr('value');
			else	
				postData+='&SearchForm[comingsoon]=0';
				
		}
		else //SearchForm[tab]=2
		{
	
			if($('#SearchForm_search').attr('value'))
				postData+='&SearchForm[search]='+encodeURIComponent($('#SearchForm_search').attr('value'));
	
			for(i=0;i<=p.genresCount;i++)//0 for Movies checkbox
			{
				if($('#SearchForm_genre_'+i).attr('checked'))
					postData+='&SearchForm[genre]['+i+']='+$('#SearchForm_genre_'+i).attr('value');
	
			}
	
			if($('#SearchForm_genresMode_1').attr('checked'))
				postData+='&SearchForm[genresMode]='+$('#SearchForm_genresMode_1').attr('value');
			else
				postData+='&SearchForm[genresMode]='+$('#SearchForm_genresMode_0').attr('value');
	
			if($('#SearchForm_TVSeries').attr('checked'))
				postData+='&SearchForm[TVSeries]='+$('#SearchForm_TVSeries').attr('value');
	
			if($('#SearchForm_releasedFromY').attr('value'))
				postData+='&SearchForm[releasedFromY]='+$('#SearchForm_releasedFromY').attr('value');
	
			if($('#SearchForm_releasedToY').attr('value'))
				postData+='&SearchForm[releasedToY]='+$('#SearchForm_releasedToY').attr('value');
	
			if($('#SearchForm_rating').attr('value'))
				postData+='&SearchForm[rating]='+$('#SearchForm_rating').attr('value');
		}
		
		jQuery.ajax({
				'async':false,
				'timeout':5000,//can be set up in $.ajaxSetup()
			  	'type':'POST',
			  	'url':p.getTrailerUrl,
			  	'data':postData,
			  	'cache':false,
				'dataType': 'json',
				 beforeSend: function(x) { //dirty fix for 'parseerror' issue
				  if(x && x.overrideMimeType) {
				   x.overrideMimeType('application/j-son;charset=UTF-8');
				  }
				 },
				'error': function(jqXHR, textStatus, errorThrown)
				{
					//alert(textStatus);
					//if('timeout'==textStatus)
					//	alert('timeout');
				},
				'success': function(data, status)
				{
				
					if(!data.result)
					{
						$('#ytapiplayer').html('<h2>No trailers found!</h2>');
						return;
					}

					//ytplayer = $('#myytplayer');
					ytplayer = document.getElementById('myytplayer');
					
					
					if(!ytplayer)
					{	
						var params = { allowScriptAccess: 'always',allowFullScreen: true, wmode:'transparent' };
						var atts = { id: 'myytplayer' };
					
						//	http://code.google.com/p/swfobject/wiki/documentation
						swfobject.embedSWF(data.urlVideo,	//swfUrl (String, required) specifies the URL of your SWF
						                     'ytapiplayer',	//id (String, required) specifies the id of the HTML element (containing your alternative content) you would like to have replaced by your Flash content 
						                     '640',	//width (String, required) specifies the width of your SWF 
						                     '390',	//height (String, required) specifies the height of your SWF 
						                     '8',	//version (String, required) specifies the Flash player version your SWF is published for (format is: "major.minor.release" or "major") 
						                     '/vendors/swfobject/swfobject/expressInstall.swf',	//expressInstallSwfurl (String, optional) specifies the URL of your express install SWF and activates Adobe express install. Please note that express install will only fire once (the first time that it is invoked), that it is only supported by Flash Player 6.0.65 or higher on Win or Mac platforms, and that it requires a minimal SWF size of 310x137px. 
						                     {},	//flashvars (Object, optional) specifies your flashvars with name:value pairs 
						                     params,	//params (Object, optional) specifies your nested object element params with name:value pairs	 
						                     atts,	//attributes (Object, optional) specifies your object's attributes with name:value pairs	
						                     function (e) //callbackFn (JavaScript function, optional) can be used to define a callback function that is called on both success or failure of embedding a SWF file (see API documentation) 
						                     {
							                     if(!e.success)
							                     	$('#ytapiplayer').html('You need <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash player 8+</a> and JavaScript enabled to view a video.');
							                     }
						                     );
						
						ytplayer = document.getElementById('myytplayer');
						
					}
					else	                     
						ytplayer.loadVideoByUrl(data.urlVideo);
					
				
					$('#trailer_info').html('');

					if(!data.count) 
						return;

					$('#nextRandomTrailer').html(
						'<div style="font-weight:bold;padding:20px 0px 10px 0px;">'+
						'<a id="nextTrailer" href="'+p.indexUrl+'" onclick="ajaxNextTrailer();return false;" style="font-size:20px;" title=""></a>'+
						'</div>'+
						'<div style="padding-top:10px;clear:both;"></div>'
						);
						
					var reloadBtn = '<div style="padding:2px 5px 0px 0px;float:left;"><img src="'+p.baseUrl+'/images/reload20.gif'+'"/></div>';	
					$('#nextTrailer').html(reloadBtn+data.nextTrailer);
					$('#nextTrailer').attr('title',data.nextTrailerTitle);		
						
					var trailer_info ='';
						
					trailer_info += '<div style="height:30px;"></div>';
					trailer_info += '<div>'
						+'<div style="padding:0px 20px 0px 0px;float:left;"><span id="trailer_title" title="'+data.title+'">'+data.title+'</span></div>'
						+'<div style="padding:0px 20px 0px 0px;float:left;"><span id="trailer_released">&nbsp;</span></div>'
						//+'<div id="trailer_description" style="padding:0px 0px 10px 0px;">&nbsp;</div>'
						+'<div style="clear:both;"></div>'
						+'</div>';

					//genre
					trailer_info += '<div style="padding:10px 20px 0px 0px;">';

					trailer_info += '<div style="float:left;"><strong>Genre:&nbsp;</strong>';
					trailer_info += '<span id="trailer_genres"></span>';
					trailer_info += '</div>';
					trailer_info += '<div style="float:left;margin-left:10px;"><strong>Rating:</strong> <span id="trailer_rating">&nbsp;</span></div>';
					trailer_info += '</div>';

					trailer_info += '<div style="padding-top:10px;clear:both;"></div>';
					
					
					if(''!=data.urlIMDB||''!=data.urlGoogle||''!=data.urlWiki)
					{
					trailer_info += '<div style="padding:0px 0px 0px 0px;">';
					trailer_info += '<span id="trailer_imdb"> at <a href="#" target="_blank">IMDB</a></span>,';
					
					if(p.moderatorAccess)
					{
						trailer_info += '<span> <strong>Get more info with:&nbsp;</strong></span>';
						trailer_info += '<span id="trailer_google"></span>,';
						trailer_info += '<span id="trailer_wiki"></span>';
					}		

					trailer_info += '<div style="clear:both"></div>';
					trailer_info += '</div>';
					
					if(p.moderatorAccess)
					{
						trailer_info += '<div style="padding-top:10px;">';
						trailer_info += '<span id="trailer_moderate"><a target="_blank" href="#">Moderate</a></span>';
						trailer_info += '</div>';
					}

					
					trailer_info += '<div style="margin:10px 0px 0px 0px;"><span id="trailer_report"><a href="#" title="Click if you think it\'s the wrong trailer">Report</a></span></div>';

					
					$('#trailer_info').append(trailer_info);
					
					$('#trailer_info .cornered').css('background-color','#333333');
					$('#trailer_info .cornered').corner('10px')
					}

					
					
					
					
					$('#trailer_movieId').val(data.movieId2);
					$('#trailer_trailerId').val(data.id);

					$('#trailer_moderate A').attr('href',p.moderateUrl+'&movieId='+data.movieId2);

					$('#trailer_title').html(data.title);
					$('#trailer_title').attr('title','Now playing: '+data.title);

					$('#trailer_description').html(data.description);
					$('#trailer_imdb').html(data.title+' at <a href="'+data.urlIMDB+'" target="_blank">IMDB</a>');
					$('#trailer_google').html('<a href="'+data.urlGoogle+'" target="_blank">Google</a>');
					$('#trailer_wiki').html('<a href="'+data.urlWiki+'" target="_blank">Wikipedia</a>');
					$('#trailer_rating').html(data.rating2);


					if(data.released && data.released.length)
					{
						var date = data.released.split('-');
						$('#trailer_released').html(date[0]);
						$('#trailer_released').attr('title','Year: '+date[0]);
                    }

					var genres = '';
					if(data.genre)
					{
						var i=0;
						for ( k in data.genre )
							genres += ((i++)?', ':'')+data.genre[k];
					}
					else
						genres = '---';


					$('#trailer_genres').html(genres);



				
					//update social buttons
					permalinkTitleHTML = data.permalinkTitle
						.replace(/'/g, '&apos;')
						.replace(/"/g, '&quot;')
						.replace(/\</g, '&lt;')
						.replace(/\>/g, '&gt;');

					descriptionHTML = data.description
						.replace(/'/g, '&apos;')
						.replace(/"/g, '&quot;')
						.replace(/\</g, '&lt;')
						.replace(/\>/g, '&gt;');
						
						
					//http://dev.twitter.com/pages/tweet_button_faq#how-can-i-render-the-tweet-button-in-ajax-loaded-content
					$('.twitter').html(
						'<a href="http://twitter.com/share" class="twitter-share-button" data-url="'+data.permalink+'" data-text="'+permalinkTitleHTML+'" data-count="horizontal">Tweet</a>'
						);

					//@FIXME script duplicates
					//http://stackoverflow.com/questions/610995/jquery-cant-append-script-element	
					$.getScript('http://platform.twitter.com/widgets.js');
						
					$('.facebook').html('<iframe src="http://www.facebook.com/plugins/like.php?app_id=213154132051231&amp;href='+escape(data.permalink)+'&amp;send=false&amp;layout=standard&amp;width=280&amp;show_faces=false&amp;action=like&amp;colorscheme=dark&amp;font&amp;height=500" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:280px; height:50px;" allowTransparency="true"></iframe>');

					/*
					//http://www.addthis.com/help/client-api#rendering-js
					if(jQuery.trim($('.addthis').html())=='')
					{
						$('.addthis').html(
								//'<div class="addthis_toolbox addthis_default_style" >'+ 
								//'<a class="addthis_counter addthis_pill_style"></a> '+
								//'</div> '
								
								'<div class="addthis_toolbox addthis_default_style ">'+
								'<a class="addthis_button_facebook"></a>'+
								'<a class="addthis_button_twitter"></a>'+
								'<a class="addthis_button_google"></a>'+
								'<a class="addthis_button_compact"></a>'+
								'<a class="addthis_counter addthis_bubble_style"></a>'+
								'</div>'								
						);
					}
					
					//load once
					if (!window.addthis){
						$.getScript( 'http://s7.addthis.com/js/250/addthis_widget.js' );
					    //window.addthis = null;
						//addthis.init();
					}
					
					
					if(data.permalink)
					{				
						addthis.toolbox('.addthis_toolbox',
							{
								pubid: 'xa-4df1d3b1229c6b7c'
							},
							{
								url: data.permalink, 
								title: data.permalinkTitle,
								description: data.description
							}						
						);
					}
					*/

				}
		});
	}


	$(document).keydown(function (e) {
		if(e.keyCode == 32) { //e.which
			ajaxNextTrailer();
			e.preventDefault();
			}
	});
	
