$(document).ready(function(){ 

	var current_vid = 0;
	var ratedAlready = 0;
	var words = new Array('', 'Ghastly', 'Watchable', 'Pretty Good', 'Really Good', 'Awesome');
	var comments_visible = 0;
	var embed_visible = 0;
	var requested = jQuery.url.segment(2);

	check_member();
	get_comments();

	$('#mailinglist_form').submit(function() {
		mailing_list_submit();
		return false;
	});

	$('.stars').hover(function() {
		stars((this).id);
	});

	$('.stars').click(function() {
		rate($('#trailer_id').val(),(this).id);
	});

	$('#home_splash').click(function() {
		$('#home_splash').fadeOut(1000,function() {
			$('#home_splash').remove();
		});
		$('#home_lower').fadeOut(1000,function() {
			$('#home_lower').remove();
		});

	});

	$('.delete').click(function() {
		delete_comment((this).id);
	});

	$('#trailer_commerce .posterlink').click(function() {
		poster_link((this).id);
	});
	$('#trailer_commerce .amazon_link').click(function() {
		amazon_link((this).id);
	});

	$('.embed').click(function() {
		if (embed_visible == 0) {
			$('#big_window #trailer_box #trailer_window').append('<div id="grayout"></div><div id="embed"><div class="close"><a>Close</a></div><H2>Embed</H2><P>To embed this movie in your blog or website, simply copy the code below.  </P><TEXTAREA><script type="text/javascript" src="http://trailersfromhell.com/t/'+current_vid+'"></script></TEXTAREA></div>');
			$('#big_window #trailer_box #trailer_window #embed textarea').select();
			$('#big_window #trailer_box #trailer_window #embed .close a').click(function() {
				close_embed();
			});
			embed_visible = 1;
		} else {
			close_embed();
			embed_visible = 0;
		}
	});

	$('.show_comments').click(function() {
		if (comments_visible == 0) {
			$('#comments').slideDown('fast',function(){
//				scrollTo( '#comments #top', 1200 );
			});
			comments_visible = 1;
		} else {
			$('#comments').slideUp('fast');
			comments_visible = 0;
		}
	});

	$('#register').click(function() {
		register_form();
	});

	$('#login').click(function() {
		login_form();
	});

	var video1 = $('.video1').attr('id');
	var video2 = $('.video2').attr('id');
	var trailer_id = $('.trailer_id').attr('id');
	show_video(video1,trailer_id,false);

	$('#trailer_top_right a').click(function() {
		var inactive = 0;
		if ((this).id == video1) { inactive = video2; } else { inactive = video1; }
		$('#trailer_top_right ul li #'+inactive).parent().removeClass('active');
		$('#trailer_top_right ul li #'+inactive).parent().addClass('inactive');
		$(this).parent().removeClass('inactive');
		$(this).parent().addClass('active');
		show_video((this).id,trailer_id,true);
	});


	function show_video(video_id,trailer_id,auto) {
		suffix = $('#suffix1').val(),
		duration = $('#duration1').val(),
		current_vid = video_id;
		var browser = navigator.userAgent;
		if (browser.match('iPhone') || browser.match('iPad')) {
			$('#trailer_window_content').html('<video src="/images/trailers/'+video_id+'.mp4" height="480" width="640" controls poster="/images/stills/'+trailer_id+'.jpg" type="video/mp4"></video>');
		} else {
			var flashvars = {width: 640,height: 500,file: '/images/trailers/'+video_id+'.'+suffix,image: '/images/stills/'+trailer_id+'.jpg','duration': duration,autostart: auto};
			var params = {allowfullscreen:'true',wmode:'transparent',allowscriptaccess:'always' };
			var attributes = {'name': 'player'};
//			swfobject.embedSWF("/lib/flvplayer.swf", "trailer_window_content", "640", "480", "8.0.0", '', flashvars, params, attributes);
			swfobject.embedSWF("/lib/player.swf", "trailer_window_content", "640", "504", "9.0.0", '', flashvars, params, attributes);
		}
		trailer_tracker(video_id);
	}

	function stars(num) {
		$("#ratingWord").html(words[num]);
		for (a = 1; a < 6; a++) {
			if (a <= num) {
				var src = '/images/ostar.png';
				$('#star'+a).attr("src", src);
			} else {
				var src = '/images/bstar.png';
				$('#star'+a).attr("src", src);
			}
		}
	}

	function rate(tid,rating) {
		if (ratedAlready == 1) {
			alert('You have already rated this trailer');
			return false;
		}
	    $.ajax({
	        type: "GET",
	        url: '/functions/rate.php?tid='+tid+'&rating='+rating,
	        success: function(a) {
				ratedAlready = 1;
				var SplitResult = a.split(";");
				rated(SplitResult[0],SplitResult[1]);
	        }
	    });
	}

	function rated(num,ratings) {
		var out = '';
		for (a = 1; a < 6; a++) {
			if (a <= num) {
				out += '<img src="/images/ostar.png" width="13" height="13" border="0">';
			} else {
				out += '<img src="/images/rstar.png" width="13" height="13" border="0">';
			}
		}
		out += '<div id="ratingWord">'+ratings+' Ratings</div>';
		$(".rating").html(out);
	}

	function close_embed() {
		$('#big_window #trailer_box #trailer_window #embed').remove();
		$('#big_window #trailer_box #trailer_window #grayout').remove();
	}

	function trailer_tracker(vid) {
	    $.ajax({
	        type: "GET",
	        url: '/functions/trailer_tracker.php?vid='+vid,
	        success: function(a) {
	        }
	    });
		return false;
	}

	function register_form() {
	    $.ajax({
	        type: "GET",
	        url: '/functions/register.php?trailer_id='+$('#trailer_id').val(),
	        success: function(a) {
				$('#new_comment .comment').html(a);
				$('#login').click(function() {
					login_form();
				});
				$('#register_form').submit(function() {
					register();
					return false;
				});
	        }
	    });
	}

	function register() {
		var user_name = $('input[id=user_name]');
		if (user_name.val().length == 0) {
			alert('You must enter a username.');
	        return false;
		}
		var password = $('input[id=password]');
		if (password.val().length == 0) {
			alert('You must enter a password.');
	        return false;
		}
		var password_r = $('input[id=password_r]');
		if (password_r.val().length == 0) {
			alert('You must enter your email address twice.');
	        return false;
		}
		if (password_r.val() != password.val()) {
			alert('Your passwords do not match.');
	        return false;
		}
		var email_address = $('input[id=email_address]');
		if (email_address.val().length == 0) {
			alert('You must enter your password twice.');
	        return false;
		}
		var email_address_r = $('input[id=email_address_r]');
		if (email_address_r.val().length == 0) {
			alert('You must enter your email address twice.');
	        return false;
		}
		if (email_address.val() != email_address_r.val()) {
			alert('Your email addresses do not match.');
	        return false;
		}
		var answer = $('input[id=answer]');
		if (answer.val().length == 0) {
			alert('You must enter the answer to the security question.');
	        return false;
		}

		var data = $("#register_form").serialize();
		$.ajax({
			type: "POST",
			url: '/functions/register_submit.php',
	        dataType: "text",
	        data: data,
			error: function(){ alert('Sorry, an error occurred.  Please try again.'); },
			success: function(a) {
				if (a.match('Error')) {
					alert(a);
				} else {
					$('#new_comment .comment').html(a);
				}
			}
		});
	    return false;
	}



	function login_form() {
	    $.ajax({
	        type: "GET",
	        url: '/functions/login.php?trailer_id='+$('#trailer_id').val(),
		    error: function(){ alert('Error loading document'); },
	        success: function(a) {
				$('#new_comment .comment').html(a);
				if (jQuery.url.segment(3) == 'confirm') {
					$('#new_comment .comment').prepend('<H3>Confirmed!</H3><P>Your email address has been confirmed, and you may now log in and post comments.  Thanks!</P><P>&nbsp;</P>');
				}

				$('#register').click(function() {
					register_form();
				});
				$('#login_form').submit(function() {
					login();
					return false;
				});
				$('#forgot').click(function() {
					forgot();
					return false;
				});
	        }
	    });
	}
	
	function login() {
		var password = $('input[id=password]');
		if (password.val().length == 0) {
			alert('You must enter a password.');
	        return false;
		}
		var email_address = $('input[id=email_address]');
		if (email_address.val().length == 0) {
			alert('You must enter your email address.');
	        return false;
		}

		var data = $("#login_form").serialize();
		$.ajax({
			type: "POST",
			url: '/functions/login_submit.php',
	        dataType: "text",
	        data: data,
			error: function(){ alert('Sorry, an error occurred.  Please try again.'); },
			success: function(a) {
				if (a.match('Error')) {
					$('#new_comment .comment').prepend('<div class="error">'+a+'</div>');
					return false;
				}
				var pieces = a.split(':');
				if (pieces[3] == 0) {
					alert('You have not yet confirmed your account.');
				} else if (pieces[2]=='') {
					alert('The password you entered was incorrect.  Please try again.');
				} else if (pieces[0]&&pieces[1]&&pieces[2]&&pieces[3]) {
					$.cookie('tfh_cli', pieces[0], {path: '/',domain:'.trailersfromhell.com'});
					$.cookie('tfh_cid', pieces[1], {path: '/',domain:'.trailersfromhell.com',expires: 7});
					$.cookie('tfh_cok', pieces[2], {path: '/',domain:'.trailersfromhell.com'});
					$.cookie('tfh_sta', pieces[3], {path: '/',domain:'.trailersfromhell.com'});
					show_comment_post_form();
					check_member();
					$('#comments #mid #comments_list #comment0').remove();
					get_comments();
				}
				return false;
			}
		});
	    return false;
	}

	
	
	function forgot() {
	    $.ajax({
	        type: "GET",
	        url: '/functions/forgot.php',
		    error: function(){ alert('Error loading document'); },
	        success: function(a) {
				$('#new_comment .comment').html(a);
				$('#forgot_form').submit(function() {
					forgot_send();
					return false;
				});
	        }
	    });
	}

	function forgot_send() {
		var data = $("#forgot_form").serialize();
	    $.ajax({
	        type: "POST",
	        url: '/functions/forgot.php',
		    error: function(){ alert('Error loading document'); },
	        dataType: "text",
	        data: data,
	        success: function(a) {
				$('#new_comment .comment').html(a);
				$('#forgot').click(function() {
					forgot();
				});
	        }
	    });
	}
	
	
	function show_comment_post_form() {
	    $.ajax({
	        type: "GET",
	        url: '/functions/comment_post_form.php?trailer_id='+$('#trailer_id').val(),
		    error: function(){ alert('Error loading document'); },
	        success: function(a) {
				$('#new_comment .comment').html(a);
				$('#comment_post_form').submit(function() {
					comment_submit();
					return false;
				});
	        }
	    });
	}	

	function comment_submit() {
		var comment = $('textarea[id=comment]');
		if (comment.val().length == 0) {
			alert('You must enter a comment.');
	        return false;
		}

		var data = $("#comment_post_form").serialize();
		$.ajax({
			type: "POST",
			url: '/functions/comment_post_submit.php',
	        dataType: "text",
	        data: data,
			error: function(){ alert('Sorry, an error occurred.  Please try again.'); },
			success: function(a) {
				show_comment_post_form();
				get_comments();
		        return false;
			}
		});
	}

	function get_comments() {

		var offset = 0;
		if ($('#comments #mid #comments_list .one_comment').length == 0) {
			$('#comment_count').html(0);
		} else if ($('#comments #mid #comments_list #comment0').length == 1) {
		} else {
			offset = $('#comments #mid #comments_list .one_comment').length;
		}

	    $.ajax({
	        type: "GET",
	        url: "/functions/get_comments.php?trailer_id="+$('#trailer_id').val()+'&offset='+offset,
	        dataType: "xml",
	        success: function(xml) {
				$(xml).find('posts').each(function(){
					$(this).find('post').each(function(){
						var comment_id = $(this).find("comment_id").text();
						var exists = $('#comments_list #comment'+comment_id).length;
						if (exists == 0) {
							var this_user_id = $('#uid').val();
							var user_id = $(this).find("user_id").text();
							var user_name = $(this).find("user_name").text();
							var admin = $(this).find("admin").text();
							if (admin == 1) {
								user_name += '&nbsp;<span class="staff">Staff</span>';
							}
							var fmodified = $(this).find("fmodified").text();
							var comment = $(this).find("comment").text();
							var exists = $('#comments #mid #comments_list #comment0').length;
							if (exists > 0)	{
								$('#comments #mid #comments_list #comment0').fadeOut(1000,function() {
									$('#comments #mid #comments_list #comment0').slideUp(100,function() {
										$('#comments #mid #comments_list #comment0').remove();
										$('#comments #mid #comments_list').append('<div class="one_comment" ID="comment'+comment_id+'"><div class="comment_info"><H3>'+user_name+'</H3><P class=date>'+fmodified+'</P></div><div class="comment"><P>'+comment+'</P></div></div>');
										if (user_id == this_user_id && $.cookie('tfh_cli') == 1) {
											$('#comments #mid #comments_list #comment'+comment_id+' .comment').append('<div class=delete><A CLASS="delete" ID="'+comment_id+'">Delete Comment</A></div>');
											$('.comment .delete .delete').click(function() {
												delete_comment((this).id);
											});
										}
										$('#comments #mid #comments_list #comment'+comment_id).append('<div class="new_overlay"></div>');
										$('#comments #mid #comments_list #comment'+comment_id+' .new_overlay').fadeOut(1500,function() {
											$('#comments #mid #comments_list #comment'+comment_id+' .new_overlay').remove();
										});
									});
								});
							} else {
								$('#comments #mid #comments_list').append('<div class="one_comment" ID="comment'+comment_id+'"><div class="comment_info"><H3>'+user_name+'</H3><P class=date>'+fmodified+'</P></div><div class="comment"><P>'+comment+'</P></div></div>');
								if (user_id == this_user_id && $.cookie('tfh_cli') == 1) {
									$('#comments #mid #comments_list #comment'+comment_id+' .comment').append('<div class=delete><A CLASS="delete" ID="'+comment_id+'">Delete Comment</A></div>');
									$('.comment .delete .delete').click(function() {
										delete_comment((this).id);
									});
								}
								$('#comments #mid #comments_list #comment'+comment_id).append('<div class="new_overlay"></div>');
								$('#comments #mid #comments_list #comment'+comment_id+' .new_overlay').fadeOut(1500,function() {
									$('#comments #mid #comments_list #comment'+comment_id+' .new_overlay').remove();
								});
							}
							$('#comment_count').html($('#comments #mid #comments_list .one_comment').length);
						}
				    });
			    });
				if (requested == 'comments') {
					$('#comments').slideDown('fast',function(){
						scrollTo( '#comments', 1200 );
					});
					comments_visible = 1;
				}

	        }
	    });

		if ($('#comments #mid #comments_list .one_comment').length == 0) {
			var out = '<div class="one_comment" ID="comment0"><div class="comment_info"></div><div class="comment"><H3>no comments have yet been entered for this trailer</H3><P>Feel free to post the first comment below.</P></div></div>'
			$('#comments #mid #comments_list').prepend(out);
		}


//		setTimeout(get_comments, 3000);
	}


	function check_member() {
	    $.ajax({
	        type: "GET",
	        url: '/functions/check_member.php',
	        dataType: "xml",
	        success: function(xml) {
				$(xml).find('users').each(function(){
					$(this).find('user').each(function(){
						var user_id = $(this).find("user_id").text();
						var user_name = $(this).find("user_name").text();
						var cli = $(this).find("cli").text();
						var status = $(this).find("status").text();
						if (user_id) {
							if (status == 0) {
								$('#member_info').html('You have registered, but have not yet confirmed your registration by clicking on the link in the email we sent you.  Please complete your registration in order to post messages here.');
								$('#new_comment .comment').html('You have registered, but have not yet confirmed your registration by clicking on the link in the email we sent you.  Please complete your registration in order to post messages here.');
							} else {
								$('#member_info').html('You are logged in as '+user_name+'.  <A class="logout">Logout</A>');
								$('#uok').val(1);
								show_comment_post_form();
								$('#member_info .logout').click(function() {
									$('#member_info').html('');
									logout();
								});
							}
						}
					});
				});
	        }
	    });
	}

	function logout() {
		$('#comments #mid #comments_list .comment .delete').remove();
		$.cookie('tfh_cok', '', {expires: 7, path: '/'});
		login_form();
		$('#comments #mid #comments_list .one_comment').remove(function(){
			get_comments();
		});
	}

	function delete_comment(id) {
		input_box=confirm("Are you certain you want to delete this comment?");
		if (input_box==true) { 
			$('#comments #mid #comments_list #comment'+id).fadeOut('fast',function() {
				$('#comments #mid #comments_list #comment'+id).remove();
			});
		    $.ajax({
		        type: "GET",
		        url: '/functions/remove_comment.php?comment_id='+id,
		        success: function(a) {}
		    });
			var current_count = $('#comment_count').html();
			$('#comment_count').html(Number(current_count)-1);
		    return false;
		}
	}

	function poster_link(id) {
		window.open('http://www.moviegoods.com/affiliate2/adclick.asp?affiliateid=2506&master_movie_id='+id,'Moviegoods','left=200,top=200,width=900,height=600,menubar=yes,location=yes,scrollbars=yes');
		return false;
	}

	function amazon_link(id) {
		window.open('http://www.amazon.com/exec/obidos/ASIN/'+id+'/trafrohel-20','Amazon','left=200,top=200,width=900,height=600,menubar=yes,location=yes,scrollbars=yes');
		return false;
	}



	function mailing_list_submit() {
		var email_address = $('input[id=email_address]');
		if (email_address.val().length == 0) {
			alert('You must enter your email address.');
	        return false;
		}

		var data = $("#mailinglist_form").serialize();
		$.ajax({
			type: "POST",
			url: '/functions/mailing_list_submit.php',
	        dataType: "text",
	        data: data,
			error: function(){ alert('Sorry, an error occurred.  Please try again.'); },
			success: function(a) {
				if (a.match('Error')) {
					$('#email_response').html(a);
				} else {
					$('#mailinglist_form').html(a);
				}
			}
		});
	    return false;
	}



});

