var playList;
var error;
var movieList;
var isValidated = false;
var movieListLenght;
var debugCount = 0;

$(document).ready(function(){ 
	
	$("#clipsHolder").hide();
	$("#optionsMenu").hide();

	$('body').click(function(event)
	{	
		if ($(event.target).is("#contact, .cancel"))
		{		
			event.preventDefault();
			if($("#reelError").find("#error").text() != '')
			{
				$('#contactFormHolder').toggle();
			}else{
				$('#contactFormHolder').toggle();
				$('#clipDetails').toggle();			
			}	
			if(!isValidated)
			{
				validateContactForm();
			}
		}
		if ($(event.target).is("#options"))
		{		
			event.preventDefault();
			$("#optionsMenu").toggle();
		}
		if($(event.target).is("li a#dl, a#dl, a#dl span, a#dl img"))
		{
			event.preventDefault();
			var dlid = $("#dl").attr('rel');
			var dlurl = "http://www.theshowreel.tv/movies/"+dlid;
			window.open(dlurl,'download','menubar=no,width=250,height=150,toolbar=no,directories=no,resizable=no,scrollbars=no,location=no,status=yes');
		}
	});	
	

    	
	$('input.field, textarea.field').addClass("idleField");
	$('input.field, textarea.field').focus(function()
	{  	
			$(this).removeClass("idleField").addClass("focusField");
			if (this.value == this.defaultValue)
			{  
				this.value = '';  
			}  
			if(this.value != this.defaultValue){  
				this.select();  
			} 
	});  
	$('input.field, textarea.field').blur(function()
	{  
			if ($.trim(this.value) == ''){  
				this.value = this.defaultValue;
				$(this).removeClass("focusField").addClass("idleField"); 
			} 			
	}); 
});
function initPlayer(playList, logo, handle)
{
	if(logo != '')
	{
		if(logo == 'none')
		{
			logo = '';
		}
		
	}else{
		logo = '/img/player/logo_play.png';
	}
	flowplayer("player",
	{ 
	    src: 		"/flash/flowplayer.commercial-3.1.1.swf",
	    quality: "autohigh",  
	    version: 	[9, 115], 	 
	    onFail: 	function()
	    { 
	        document.getElementById("info").innerHTML = 
	            "You need the latest Flash version to view MP4 movies. " + 
	            "Your version is " + this.getVersion() 
	        ; 
	    },
	    wmode: 'opaque'
	    // here is our third argument which is the Flowplayer configuration 
	},
	{ 
		key: '#$c1ee2dfc6f04380d8b3',
		showErrors: false,
		onError: function() {
			this.stop();
			$('#clipError').show();
			//alert(handle);
			notifyError(handle);
		},
	    logo: { 
	        url: logo, 
	        fullscreenOnly: true, 
	        //displayTime: 10,
		    top: 70, 
		    right: 70, 
		    opacity: 0.7
	    },
		onLoad : function() {    // provide a Player event listener
        	loadThumbs();
        	$("#loader").hide();
        	if(movieID!='0')
			{
				this.play(currentMovie);				
			}
    	}, 
	    clip :
	    {            // Clip is an object, hence '{...}' 
	        onStart: function(clip)
	        { 
            	setMovieData(clip.mid);
            	// set movieinfo bitte ;)
	        }, 
	    	autoPlay: true, 
	        autoBuffering: false,
	        scaling: 'fit',
	        //accelerated: true,
	        baseUrl: 'http://showreel.navicast.net/'
   		 },
		plugins: 
		{ 
		    controls:
		    { 
		        url: 'flowplayer.controls-3.1.1.swf', 
		 
		        // display properties 
				//backgroundGradient: 'low',
			      timeColor: '#01DAFF',
			      volumeSliderColor: '#000000',
			      bufferGradient: 'none',
			      progressGradient: 'medium',
			      sliderColor: '#000000',
			      buttonOverColor: '#728B94',
			      timeBgColor: '#555555',
			      tooltipTextColor: '#ffffff',
			      progressColor: '#112233',
			      tooltipColor: '#5F747C',
			      bufferColor: '#445566',
			      buttonColor: '#5F747C',
			      backgroundColor: '#222222',
			      volumeSliderGradient: 'none',
			      borderRadius: '0px',
			      durationColor: '#ffffff',
			      backgroundGradient: [0.6,0.3,0,0,0],
			      sliderGradient: 'none',
			      height: 20,
			      opacity: 1.0,
			      //bottom: 0,		 
		        // controlbar-specific configuration 

				//autoHide: 1000,
		        // which buttons are visible and which are not? 
		        play:true, 
		        volume:true, 
		        mute:true, 
		        time:true, 
		        stop:false, 
		        playlist:true, 
		        fullscreen:true, 
		 
		        // scrubber is a well-known nickname for the timeline/playhead combination 
		        scrubber: true 
		 
		        // you can also use the "all" flag to disable/enable all controls 
		    } 
		},
		canvas:
		{ 
		    // configure background properties 
		    background: '#000000', 
		 
		    // remove default canvas gradient 
		    backgroundGradient: 'none'
		},
		screen:
		{ 
		    // configure background properties 
		    background: '#000000', 
		    backgroundGradient: 'none'
		  
		},
    	playlist: playList

   		   
	}).playlist("div.clips", {loop:looping});
	
	$("div.clipBrowser").scrollable(
	{ 
        size: 5, 
        items: '.clips',   
        hoverClass: 'hover',
        loop: true,
        easing: "swing"
    });


}

function getPlayerData(userHandle, movieID)
{
	var postData;
	postData = "handle="+userHandle+"&movieID="+movieID;

	$.ajax(
	{
	    url: "/connectors/ajax/getPlayerData.php",
		type: "POST",
	   	data: postData,
	   	dataType: "json",
	    beforeSend: function()
	    			{
						//show loader
	    			},
	    complete: 	function()
	    			{
	    				//update info
						//change movieclip
						if(!error)
						{
							//setMovieData('none');
							initPlayer(playList, logo, userHandle);
						}else{
							movieID = '0';
							//setMovieData('none');
							initPlayer(playList, logo, userHandle);
						}
	    			},
	    success: 	function(data)
	    			{ 	
	    				if(data.error == '')
	    				{
		    				playList = data.JWplaylist;
		    				movieList = data.movieList;
			    			movieListLenght = data.movieListLenght;
			    			currentMovie = data.currentMovie;
			    			handle = data.handle;
			    			logo = data.logo;
			    			looping = data.loop;
			    			//alert(playList[0].title);
		   				}else{
		    				playList = data.JWplaylist;
		    				movieList = data.movieList;
			    			movieListLenght = data.movieListLenght;
			    			logo = data.logo;
							error = data.error;
		   				}  				
		    		} 
		});	
}

function setMovieData(id)
{	
	if(id == 'none')
	{
		id = movieList[0].id;
	}
            $.each(movieList,function(i,item)
            {	
				if(item.id == id)
				{
					$("li#title").find(".playerDetail").text(item.title);
					$("li#prodco").find(".playerDetail").text(item.prodco);
					$("li#producer").find(".playerDetail").text(item.producer);
					$("li#director").find(".playerDetail").text(item.director);
					$("li#channel").find(".playerDetail").text(item.channel);
					$("li#agency").find(".playerDetail").text(item.agency);
					$("li#product").find(".playerDetail").text(item.product);
					$("li#media").find(".playerDetail").text(item.type);
					var link = "http://showreel.navicast.net/movies/"+id+".mp4";
					var dlid = id;
					
					//$("#dl").attr("href", dlid);
					$("a#dl").attr("rel", dlid);
					//$("a#dl").attr("href", link)
					//$("a#downloadLink").attr("href", link); 
		          	switch(item.type)
					{
					case "Film":
					  $("li.commercial").hide();
					  $("li.tv").hide();
					  $("li.film").show();
					  break;
					case "TV":
					  $("li.film").hide();
					  $("li.commercial").hide();
					  $("li.tv").show();
					  break;
					case "Commercial":
					  $("li.film").hide();
					  $("li.tv").hide();
					  $("li.commercial").show();
					  break;
					default:
					 $("li.type").hide();
					}
				}
            });
	$("#clipDetails").show();
	if(movieListLenght == 1)
	{
		//alert('zero');
		$(".cl").attr('href', "http://showreel.navicast.net/movies/"+movieList[0].id+".mp4");
		$(".tooltip").text(movieList[0].title);
		
	}
}
function loadThumbs()
{
	$("#clipsHolder").show();
	//$("#playerPlayer").show(); 
	var clipLinks = $('.cl');
	
	$.each(clipLinks,function(i,item)
	{	
		//var thumb = movieList[i];
		var thumb = movieList[i]['thumb_small'];
		var img = new Image();
	  // wrap our new image in jQuery, then:
		$(img).load(function ()
	    {
			$(this).hide();
	    	$(item).removeClass('loading').append(this);
	    	//$(item).find('img').attr('width', '100px');
			$(this).fadeIn();
	    })
		.error(function ()
		{
	      // notify the user that the image could not be loaded
	    })
	    .attr('src', thumb).attr('width', '100').attr('height', '80');	    
	    //.attr('src', 'http://showreel.navicast.net/getThumbnailImage.php?ch='+thumb.cid+'&aid='+thumb.id).attr('width', '100').attr('height', '80');
	    
	});

}
function validateContactForm()
{
	$.getScript("http://www.theshowreel.tv/js/jquery.validate.min.js", function()
	{
		$.validator.addMethod("defaultInvalid", function(value, element)
		{
			return value != element.defaultValue;
		}, "This field is required!");	
		var validator =
		$("#contactUserForm").validate(
		{
			errorElement: "span",
			errorContainer: $("#warning"),
			errorPlacement: function(error, element)
			{
				$(element).before(error);
			},
			submitHandler: function(form)
			{
   				sendContact();
 			},
			rules:
			{
				name:
				{
					defaultInvalid: true,
					required: true,
					minlength: 5
				},
				mail:
				{
					defaultInvalid: true,
					required: true,
					email: true
				},
				msg:
				{
					defaultInvalid: true,
					required: true,
					minlength: 5					
				}
			},
			messages:
			{
				name:
				{
					defaultInvalid: "Please enter a valid name!",
					required: "Please enter a valid name!",
					minlength: "Minimum 5 characters!"
				},
				mail:
				{
					defaultInvalid: "Mail is required!",
					required: "Mail is required!",
					email: "This must be a valid email-address!"
				},
				msg:
				{
					defaultInvalid: "Please enter a valid message!",
					required: "Please enter a valid message!",
					minlength: "Minimum 5 characters!"
				}
			}
		});
		isValidated = true;
		$('.cancel').click(function()
		{
			validator.resetForm();
		});
		var validateShare =
		$("#shareUserForm").validate(
		{
			errorElement: "span",
			errorContainer: $("#warning"),
			errorPlacement: function(error, element)
			{
				$(element).before(error);
			},
			submitHandler: function(form)
			{
   				sendShare();
 			},
			rules:
			{
				nameShare:
				{
					defaultInvalid: true,
					required: true,
					minlength: 5
				},
				from:
				{
					defaultInvalid: true,
					required: true,
					email: true
				},
				to:
				{
					defaultInvalid: true,
					required: true,
					email: true
				},
				msgShare:
				{
					defaultInvalid: true,
					required: true,
					minlength: 5					
				}
			},
			messages:
			{
				nameShare:
				{
					defaultInvalid: "Please enter a valid name!",
					required: "Please enter a valid name!",
					minlength: "Minimum 5 characters!"
				},
				from:
				{
					defaultInvalid: "Mail is required!",
					required: "Mail is required!",
					email: "This must be a valid email-address!"
				},
				to:
				{
					defaultInvalid: "Mail is required!",
					required: "Mail is required!",
					email: "This must be a valid email-address!"
				},
				msgShare:
				{
					defaultInvalid: "Please enter a valid message!",
					required: "Please enter a valid message!",
					minlength: "Minimum 5 characters!"
				}
			}
		});
	});	
}
function sendContact()
{
	var name = $("input#name").val();
	var mail = $("input#mail").val();
	var msg  = $("textarea#msg").val();
	var userMail = $("input#userMail").val();
	
	var dataString = 'name='+ name + '&mail=' + mail + '&msg=' + msg + '&userMail=' + userMail;  
  
	$.ajax(
	{  
		type: "POST",  
		url: "/connectors/ajax/sendContact.php",  
		data: dataString,
		dataType: "text",  
		success: function(data)
		{  
			if(data != 'error')
			{
				$('#contactFormHolder').html("<h2>Message Sent!</h2>")  
				.append('<br /><ul style="width: 200px;"><li><span class="playerLabel">From:</span><span class="playerDetail">'+name+'</span></li><li><span class="playerLabel">Mail:</span><span class="playerDetail">'+mail+'</span></li><li><span class="playerLabel">Message:</span><br /><span class="playerDetail">'+msg+'</span></li></ul><br /><input type="button" class="cancel" value="back" />')  
				.hide()  
				.fadeIn(750);
			}  
		}  
	});  
	return false;  
}
function sendShare()
{
	var name = $("input#nameShare").val();
	var from = $("input#from").val();
	var to = $("input#to").val();
	var msg  = $("textarea#msgShare").val();
	var notify = $("input#notify").val();
	
	var reelname = $("input#reelname").val();
	var url = $("input#url").val();
	
	var dataString = 'name='+ name + '&from=' + from + '&to=' + to + '&msg=' + msg + '&notify=' + notify + '&url=' + url + '&reelname=' + reelname;  
  
	$.ajax(
	{  
		type: "POST",  
		url: "/connectors/ajax/shareContact.php",  
		data: dataString,
		dataType: "text",  
		success: function(data)
		{  
			if(data != 'error')
			{
				$('#shareFormHolder').html("<h2>Message Sent!</h2>")  
				.append('<ul style="width: 200px;"><li><span class="playerLabel">From:</span><span class="playerDetail">'+from+'</span></li><li><span class="playerLabel">To:</span><span class="playerDetail">'+to+'</span></li><li><span class="playerLabel">Message:</span><br /><span class="playerDetail">'+msg+'</span></li></ul><br /><br />')  
				.hide()  
				.fadeIn(1000);
			}  
		}  
	});  
	return false;  
}
function notifyError(handle)
{	
	var dataString = 'handle=' + handle + '&';  
	$.ajax(
	{  
		type: "POST",  
		url: "/connectors/ajax/sendError.php",  
		data: dataString,
		dataType: "text"	 
	});  
	return false; 
}