/* clearText()
 *
 * Clears default text from input box on focus. Doesn't remove non-default text.
 * Usage: onFocus="clearText(this)"
 *
 */
function clearText(field){
	if (field.defaultValue==field.value)
	field.value = ""
}

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( ( $(window).height() - this.height() ) / 2+$(window).scrollTop() ) -75 + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}


jQuery(document).ready(function() {
	/*
	$('.innerfade').innerfade({
		animationtype: 'slide',
		speed: 1000,
		timeout: 5000,
		type: 'sequence',
		containerheight: '80px'
	});
	*/

	jQuery(document).ready(function() {
		jQuery.preloadImages = function() {
	  for(var i = 0; i<arguments.length; i++)
	  {
		$("<img />").attr("src", arguments[i]);
	  }
	}
	
	});
	$.preloadImages("/images/nav1_on.png", "/images/nav2_on.png","/images/nav3_on.png","/images/tab1_off.png","/images/tab2_on.png");
	
	// Clicking on a search option changes operation of search box
	$('.tabs > a').click(function(e) {
		$('#query').val($(this).attr('title')); // Put title value into query input
		$('#query').attr('defaultValue',$(this).attr('title')); // Update default value so clearing will work
		$('#search').attr('action',$(this).attr('href')); // Update action destination
		
		// Remove all on classes & add all off classes
		$( ".tabs > a" ).each(function() {
			$('#'+$(this).attr('id')).removeClass($(this).attr('id')+'_on');
			$('#'+$(this).attr('id')).addClass($(this).attr('id')+'_off');
		})
		$(this).removeClass($(this).attr('id')+'_off'); // Remove off on selected
		$(this).addClass($(this).attr('id')+'_on'); // Add on on selected
		return false; // prevent from navigating to url.
	});
	
	// Dropdown menu
	$("ul.drop li").hover(function(){
        $(this).addClass("hover");
		$('ul:first',this).css('width', ($(this).width()-1)+'px'); // Make width same as parent its dropping from
        $('ul:first',this).css('visibility', 'visible');
    }, function(){
        $(this).removeClass("hover");
        $('ul:first',this).css('visibility', 'hidden');
    });
    $("ul.drop li ul li:has(ul)").find("a:first").append(' &raquo; ');

	// Reviewing
	$("#reviewicon").click(function() {
		$("#reviewicon").slideUp(500);
		$("#review").slideDown(500);
	});
	$("#jumpreview").click(function() {
		$("#reviewicon").slideUp(500);
		$("#review").slideDown(500);
	});
	
	// Video Review
	$("#videoreview").click(function() {
		//$('#loopedSlider').loopedSlider({ autoStart: 0, restart: 0, slidespeed: 0, containerClick: false });
		//clearInterval(interval);
		$("#videoreview").html('<embed src="'+$(this).attr('alt')+'" type="application/x-shockwave-flash" width="480" height="300" allowscriptaccess="always" allowfullscreen="true" wmode="opaque"></embed>');
		$("#videoreview").attr('id','videoreviewclicked'); // prevent further clicks from triggering this
	});

	// Movie Trailer
	$(".videotrailer").click(function() {
		if($(this).attr('class')=='videotrailer') {
			$(this).html('<embed width="480" height="300" allowFullScreen="true" src="http://d.yimg.com/m/up/fop/embedflv/swf/fop.swf" type="application/x-shockwave-flash" flashvars="id='+$(this).attr('alt')+'&autoStart=1&prepanelEnable=0&infopanelEnable=0&carouselEnable=0&enableFullScreen=1" wmode="opaque"></embed>');
			$(this).attr('class','videotrailerclicked'); // prevent further clicks from triggering this
		}
	});
	
	// Registration and Login
	$(".showlogin").live("click",function(e) {
		//e.stopPropagation(); DOESNT WORK ON LIVE EVENTS
		//e.preventDefault();
		if ($('#registerlogin').is(':visible')) { // already showing so just hide it
			$('#registerlogin').fadeOut(500);
			$(document).unbind('click',logindocClick);
		} else {
			$("#registerlogin").center();
			$("#registerlogin").slideToggle(500);
			$('#registerlogin').bind("click",function(e){ e.stopPropagation(); });
			$(document).bind('click',logindocClick);
		}
		die(); // internet explorer hack to prevent propagation bubbling up to document click
		return false;
	});
	function logindocClick(e) { // click detected outside of login window
		if (e.button!='2') {
			$('#registerlogin').fadeOut(500);
			$(document).unbind('click',logindocClick);
		}
	}

	
	
	$(".close").click(function() {
		$(document).trigger("click");
	});
	
	$("#register").click(function() {
		$("#captcha").slideDown(500);
	});
	$("#registrationuser").blur(function() { // on offclick
		if ($("#registrationuser").val()!='') { // nonempty?
			$.post("/ajax.php", { username: $("#registrationuser").val(), action: "checkusername" }, 
				function(data) {
					if (data.substring(0,1)=="1") { // First char 1=SUCCESS!
						$("#registrationuseresponse").html('<img src="/images/silk/accept.png" title="This username is available." />');
						$("#registrationuseresponse").slideDown(500);
					} else {
						$("#registrationuseresponse").html('<img src="/images/silk/cancel.png" title="This username is already taken. Choose another." />');
						$("#registrationuseresponse").slideDown(500);
					}
				}
			);
			return false;
		}
	});
	
	/* REPLYING */
	$(".togglereply").live("click",function() { // live for reply link in comments
		if ($('#reply_'+$(this).attr('alt')).length==0) { // only make reply div if it doesnt exist here already...
			$('#reply').clone().attr('id','reply_'+$(this).attr('alt')).appendTo("#review_"+$(this).attr('alt'));
		}
		$('#reply_'+$(this).attr('alt')).slideToggle(500);
	});
	$(".submitreply").live("click",function() {
		replyid=$(this).parent().parents("div:first").attr('id'); // id of first parent div
		comment=$(this).parent().children('textarea:first').val();
		if ( (comment=='')|(comment==$(this).parent().children('textarea:first').attr('defaultValue')) ) {
			$('#alert').alert('Please enter a comment to submit.');
		} else {
			$.post("/ajax.php", { parent: replyid.substr(6), movie: $('#movie').val(), action: "comment", comment: comment }, 
				function(data) {
					json=$.evalJSON(data.substring(1));
					if (data.substring(0,1)=="1") { // First char 1=SUCCESS!
						$('#'+replyid).html('Thank you for your comment:<br />"'+json.comment+'"');
					}
					$('#alert').alert(json.msg);
				}
			);
		}
		return false;
	});
	
	/* COMMENTS */
	$(".togglecomments").click(function() {
		commentsid='comments_'+$(this).attr('alt');
		if ($('#'+commentsid).length==0) { // only make comments div if it doesnt exist here already...
			$('#comments').clone().attr('id','comments_'+$(this).attr('alt')).appendTo("#review_"+$(this).attr('alt'));
		}
		$('#'+commentsid).slideToggle(500);
		$.post("/ajax.php", { parent: $(this).attr('alt'), movie: $('#movie').val(), action: "getcomments" }, 
			function(data) {
				if (data.substring(0,1)=="1") { // First char 1=SUCCESS!
					$('#'+commentsid).html(data.substring(1));
				} else {
					json=$.evalJSON(data.substring(1));
					$('#alert').alert(json.msg);
				}
			}
		);
		//$('#comments_'+$(this).attr('alt')).slideToggle(500);
	});
	
	/* FLAG POST */
	$(".flag").live("click",function() {
		$('#loading').show();
		$.post("/ajax.php", { post: $(this).attr('alt').substring(1), type: $(this).attr('alt').substring(0,1), movie: $('#movie').val(), action: "flag" }, 
			function(data) {
				json=$.evalJSON(data.substring(1));
				if (data.substring(0,1)=="1") { // First char 1=SUCCESS! cant use (this) in ajax callback
					//$(this).html('Flagged!');
					//$(this).removeClass('flag');
				}
				$('#alert').alert(json.msg);
			}
		);
		$('#loading').hide();
	});

	/* ADD TO LIST */
	$(".list").click(function() {
		$('#loading').show();
		$.post("/ajax.php", { type: $(this).attr('alt'), movie: $('#movie').val(), action: "listit" }, 
			function(data) {
				json=$.evalJSON(data.substring(1));
				if (data.substring(0,1)=="1") { // First char 1=SUCCESS! cant use (this) in ajax callback
					//$(this).html('Flagged!');
					//$(this).removeClass('flag');
				}
				$('#alert').alert(json.msg);
			}
		);
		$('#loading').hide();
		return false;
	});


	/* RATING */
	$('.star').rating({required: true, callback:
		function(value, link){ 
			$('#loading').show();
			$.post("/ajax.php", { rating: value, movie: $(this).attr('name').substring(8), action: "rate" }, 
				function(data) {
					json=$.evalJSON(data.substring(1));
					$('#alert').alert(json.msg);
				}
			);
			$('#loading').hide();
		} 
	});
	
	
	$('#similars').click(function(e) {
		if ($('#similarscontent').is(':visible')) { // already showing so just hide it
			$('#similarscontent').slideUp(500);
			$('#similars').html('<img src="/images/silk/arrow_switch.png" class="icon" /> Show Similar Movies');
		} else { // not already showing, so show them
			$('#similars').html('Loading Similar Movies ...');
			$('#loading').show();
			$.post("/ajax.php", { action: "similars", id: $('#movie').val() }, 
				function(data) { // Success!
					if (data.substring(0,1)=="1") {
						$('#similarscontent').append(data.substring(1))
						$('#similars').html('<img src="/images/silk/arrow_switch.png" class="icon" /> Hide Similar Movies');
						$('#similarscontent').slideDown(500);
					} else { // Error saving!
						json=$.evalJSON(data.substring(1));
						$('#alert').alert(json.msg);
					}
					$('#loading').hide();
				}
			);
		}
		return false;
	});
	
	
	// POST EDITING
	$(".edit").live("click",function(e) {
		if ($('#adminedit').is(':visible')) { // already showing so just hide it
			$('#adminedit').fadeOut(500);
			$(document).unbind('click',editdocClick);
		} else {
		
			$('#loading').show();
			$.post("/ajax.php", { post: $(this).attr('alt').substring(1), type: $(this).attr('alt').substring(0,1), movie: $('#movie').val(), action: "edit" }, 
				function(data) {
					//alert(data);
					json=$.evalJSON(data.substring(1));
					if (data.substring(0,1)=="1") { // First char 1=SUCCESS! cant use (this) in ajax callback
						$('#admineditframe').html(json.data);
					} else {
						$('#alert').alert('Error: '+json.msg);
					}
				}
			);
			$('#loading').hide();
		
			$("#adminedit").center();
			$("#adminedit").slideToggle(500);
			$('#adminedit').bind("click",function(e){ e.stopPropagation(); });
			$(document).bind('click',editdocClick);
		}
		die(); // internet explorer hack to prevent propagation bubbling up to document click
		return false;
	});
	function editdocClick(e) {
		if (e.button!='2') {
			$('#adminedit').fadeOut(500);
			$(document).unbind('click',editdocClick);
		}
	}
		$(".moose").live("submit",function() {
			alert('moose');
		});
	$(".editsave").live("submit",function() {
		$('#loading').show();
		$.post("/ajax.php", $(this).serialize(), 
			function(data) {
				//alert(data);
				json=$.evalJSON(data.substring(1));
				if (data.substring(0,1)=="1") { // First char 1=SUCCESS! cant use (this) in ajax callback
					$(document).trigger("click");
				}
				$('#alert').alert(json.msg);
			}
		);
		$('#loading').hide();
		return false;
	});
	$(".editdelete").live("submit",function() {
		if (confirm('Are you sure you want to delete this post? This cannot be undone.')) {
			$('#loading').show();
			$.post("/ajax.php", $(this).serialize(), 
				function(data) {
					json=$.evalJSON(data.substring(1));
					if (data.substring(0,1)=="1") { // First char 1=SUCCESS! cant use (this) in ajax callback
						$(document).trigger("click");
					}
					$('#alert').alert(json.msg);
				}
			);
			$('#loading').hide();
		}
		return false;
	});	
	
	
	/* Window popups */
	$('.swiftwindow').click(function(e) {
		window.open($(this).attr('href'),'swiftwindow','toolbar=0,status=0,width=820,height=500,scrollbars=1');
		return false;
	});
	
	$('.catobj').hover(function(event) {
		$('#categories').css({top:($('#category').position().top+60)+'px',left:($('#category').position().left+8)+'px'}).show();
    }, function(event) {
        $('#categories').hide();
    });

	

});