$(document).ready(function() {
	$('textarea[maxlength]').keyup(function(){  
        //get the limit from maxlength attribute  
        var limit = parseInt($(this).attr('maxlength'));  
        //get the current text inside the textarea  
        var text = $(this).val();  
        //count the number of characters in the text  
        var chars = text.length;  
		// update counter
		$("#textcount").html(limit - text.length);
  
        //check if there are more characters then allowed  
        if(chars > limit){  
            //and if there are use substr to get the text before the limit  
            var new_text = text.substr(0, limit);  
  
            //and change the current text with the new text  
            $(this).val(new_text);  
        }  
    });
	
	$("#morebutton").hover(function() {
		$("#bnot").slideDown("fast");
	});
	
	$("#bnot").hover(function() {
		return true;
	}, function() {
		$("#bnot").slideUp("fast");
	});
});

$(window).scroll(function() {
	if ($(this).scrollTop() > 300 && $('#bbar').hasClass('hidden')) {
		$('#bbar').animate({ top: '+=44px' }, 500);
		$('#bbar').removeClass("hidden").addClass("showing");
	} else if ($(this).scrollTop() <= 300 && $('#bbar').hasClass('showing')) {
		$('#bbar').animate({ top: '-=44px' }, 500);
		$('#bbar').removeClass("showing").addClass("hidden");
		$("#bnot").slideUp("fast");
	}
});

function doSlide(what) {
	var writestyle = $('#writereview').css("display");
	var readstyle = $('#readreview').css("display");
	var infostyle = $("#infobox").css("display");
	if (what == 'writereview') {
		if (readstyle == 'block') {
			$('#readreviewbutton').attr('src','/images/button_read_reviews.png');
			$('#readreview').slideUp("fast");
		}
		if (infostyle == 'block') {
			$("#infobox").slideUp("fast");
			$('#infobutton').attr('src','/images/button_info_off.png');
		}
		if (writestyle == 'none') {
			$('#writereviewbutton').attr('src','/images/button_write_a_review_active.png');
			$('#writereview').slideDown("fast");
		} else {
			$('#writereviewbutton').attr('src','/images/button_write_a_review.png');
			$('#writereview').slideUp("fast");
		}
	}
	if (what == 'readreview') {
		if (infostyle == 'block') {
			$("#infobox").slideUp("fast");
			$('#infobutton').attr('src','/images/button_info_off.png');
		}
		if (writestyle == 'block') {
			$('#writereviewbutton').attr('src','/images/button_write_a_review.png');
			$('#writereview').slideUp("fast");
		}
		if (readstyle == 'none') {
			$('#readreviewbutton').attr('src','/images/button_read_reviews_active.png');
			$('#readreview').slideDown("fast");
		} else {
			$('#readreviewbutton').attr('src','/images/button_read_reviews.png');
			$('#readreview').slideUp("fast");
		}
	}
}

function showInfo() {
	var writestyle = $('#writereview').css("display");
	var readstyle = $('#readreview').css("display");
	var votestyle = $("#infobox").css("display");
	
	if (writestyle == 'block') {
		$('#writereviewbutton').attr('src','/images/button_write_a_review.png');
		$('#writereview').slideUp("fast");
	}
	if (readstyle == 'block') {
		$('#readreviewbutton').attr('src','/images/button_read_reviews.png');
		$('#readreview').slideUp("fast");
	}
	if (votestyle == 'none') {
		$("#infobox").slideDown("fast");
		$('#infobutton').attr('src','/images/button_info_on.png');
	} else {
		$("#infobox").slideUp("fast");
		$('#infobutton').attr('src','/images/button_info_off.png');
	}
}

function castVotes(fight) {
	var not;
	var errors = 0;
	var errortext = '';
	var email = $("#vote_email").val();
	var notify = $("#vote_notify").attr('checked');
	var hw = $("#vote_hw").val();
	var lw = $("#vote_lw").val();
	if (notify == true) { not = 1; } else { not = 0; }
	
	if (hw == 0) {
		errortext = errortext + "Please choose a heavyweight film!\n";
		$("#vote_hw").css('background-color','yellow');
		errors++;
	}

	if (lw == 0) {
		errortext = errortext + "Please choose a lightweight film!\n";
		$("#vote_lw").css('background-color','yellow');
		errors++;
	}
	
	if (!check_email(email)) {
		errortext = errortext + "Please enter a valid email address!";
		$("#vote_email").css('background-color','yellow');
		errors++;
	}
	
	if (errors > 0) {
		alert(errortext);
		return false;
	} else {
		$.post("/cast_vote.php", { id: hw, lwid: lw, email: email, notify: not, fight: fight });
		Set_Cookie('voted',fight,55920,'/','.filmfights.com');
		Set_Cookie('votedemail',email,55920,'/','.filmfights.com');
		$("#votingbooth").html("<div class=\"unverified_black\">Your current vote status: <span>UNVERIFIED!</span></div><div class=\"unverified_orange\">Please check your email for a message from voting@filmfights.com<br />Sometimes it hides in the 'spam' folder. Naughty, naughty email.</div>");
	}
}

function writeReview(id,user_id) {
	var entry = $("#review_text").val();
	var el = entry.length;
	
	if (el > 1) {
		$.post("/ajax_write_review.php", { id: id, user: user_id, entry: entry },
		 function(data) {
			if (data == '0') {
				$("#writereview").html("<h3>You are not authorized to write a review.");
				setTimeout("doSlide('writereview')",3000);
			} else {
				$("#writereview").html('<div class="thanks"><img src="/images/button_thank_you_for_review.png" width="201" height="23" alt="Thank You For Your Review" /><br />Film Fights, and the filmmaker, appreciate it!</div>');
				setTimeout("doSlide('writereview')",3000);
			}
		});
	} else {
		alert("You should probably write something before hitting Submit...try again.");
	}
}

function addMail() {
	var email = $("#email").val();
	
	if (check_email(email)) {
		$.post("/ajax_add_email.php", { email: email });
		$("#email").val("Thanks!");
		$("#email").attr("disabled","disabled");
	} else {
		alert("Please enter a valid email address.");
	}
}

function writeCancel() {
	$('#reviewentrybox').val('');
	$('#writereviewbutton').attr('src','/images/button_write_a_review.png');
	$('#writereview').slideUp("fast");
}

function CountTitleChars() {
	var total_chars = 23;
	var txtbox = document.getElementById('vid_title');
	$("#vid_title").css('background-color','#ffffff');
	var txtlength = txtbox.value.length;
	if (txtlength > total_chars) {
		txtbox.value = txtbox.value.substring(0,total_chars);
	}
	var charstring = txtlength + "/23 characters";
	var charleftstring = (23-txtlength) + " char left";
	$('#titlechars').text(charstring);
	$('#titlecharleft').text(charleftstring);
}

function CountDescChars() {
	var total_chars = 100;
	var txtbox = document.getElementById('vid_desc');
	$("#vid_desc").css('background-color','#ffffff');
	var txtlength = txtbox.value.length;
	if (txtlength > total_chars) {
		txtbox.value = txtbox.value.substring(0,total_chars);
	}
	var charstring = txtlength + "/100 characters";
	var charleftstring = (100-txtlength) + " char left";
	$('#descchars').text(charstring);
	$('#desccharsleft').text(charleftstring);
}

function resetFightSelect() {
	$("#fightid").css('background-color','#ffffff');
}

function decision(message, url){
if(confirm(message)) location.href = url;
}

function showCalendar() {
	var cal = document.getElementById('calendar');
	cal.style.display = "block";
}

function hideCalendar() {
	var cal = document.getElementById('calendar');
	cal.style.display = "none";
}

function showCalendarMonth(year,month) {
	var d = new Date();
	var time = d.getTime();
	$("div#calendar").load("cal.php?year="+year+"&month="+month+"&dummy="+time+"");
}

function showReview(id,movie) {
	var d = new Date();
	var time = d.getTime();
	$("div#readreview").load("/ajax_reviews.php?id="+id+"&movie="+movie+"&gibberish="+time);
}

function doReply(id) {
	$('#reply'+id).toggle();
}

function cancelReply(id) {
	$('#review_text'+id).val('');
	$('#reply'+id).toggle();
}

function startSubmit(upid) {
	$('#submitform').toggle();
	$('#submitprogress').toggle();
	$('#submitbox').height(110);
	$('#submit_step').text('Step 2 of 3');
	
	// progress bars  location.href = 'http://filmfights.com/submit
	setInterval("updateProgressBar()",300);
}

function updateProgressBar() {
	var d = new Date();
	var time = d.getTime();
	var id = $("#UPLOAD_IDENTIFIER").val();

	$("#progresstats").load("/upload_progress.php?ret=stats&id="+id+"&gibberish="+time);
	// update bar length
	var time = d.getTime();
	$.get("/upload_progress.php?ret=wid&id="+id+"&gibberish="+time, function(data){
		document.getElementById('progress').style.width=data+'px';
	});
}

function checkSubmission(upid) {
	var errortext = '';
	var errors = 0;
	// check form values
	if ($('#vid_title').val() == '') {
		errors++;
		errortext = errortext + 'You did not enter a title!\n';
		$('#vid_title').css('background-color','#ff6969');
	}
	
	if ($('#vid_desc').val() == '') {
		errors++;
		errortext = errortext + 'You did not enter a description!\n';
		$('#vid_desc').css('background-color','#ff6969');
	}
	
	if ($('#fightid').val() == '0') {
		errors++;
		errortext = errortext + 'You did not choose a fight!\n';
		$('#fightid').css('background-color','#ff6969');
	}
	
	if ($('#terms').attr('checked') != true) {
		errors++;
		errortext = errortext + 'You must agree to the Terms of Service.\n';
	}
	
	if ($('#ff_intro').attr('checked') != true) {
		errors++;
		errortext = errortext + 'Please verify that you put in the Film Fights intro.\n';
	}	
	
	if ($('#ff_widescreen').attr('checked') != true) {
		errors++;
		errortext = errortext + 'Please verify that your film is a widescreen resolution.\n';
	}
	
	if (errors > 0) {
		alert(errortext);
		return false;
	} else {
		startSubmit(upid);
	}
}

function groupSetHideAll() {
	$("div.g_slider:visible").slideUp("fast");
}

function groupSetSlideUp(what) {
	$("#"+what).slideUp("fast");
}

function groupSetShow(what) {
	var current = $("#"+what).css("display");
	if (current != "block") {
		groupSetHideAll();
		$("#"+what).slideDown("fast");
	}
}

function groupLeave(who) {
	$.post("/ajax_group_user.php", { id: who, act: "leave" });
	setTimeout("window.location.reload()",500);
}

function groupJoin(who) {
	var group = $("#groups_list").val();
	$.post("/ajax_group_user.php", { id: who, act: "join", group: group });
	groupSetHideAll();
	groupSetShow('apply_finished');
}

function checkGroupName() {
	var group_name = $("#group_name").val();
		$.post("/ajax_group_user.php", { act: "checkname", name: group_name },
		function(data){ 
			if (data == 0) {
				$("img.check").attr("src","/images/bubble_checkbox_red.png");
				$("#validgroup").val("0");
				$("#group_name").css("color","red");
			} else {
				$("img.check").attr("src","/images/bubble_checkbox.png");
				$("#validgroup").val("1");
				$("#group_name").css("color","#ffffff");
			}
		});
}

function groupStart(who) {
	var valid = $("#validgroup").val();
	if (valid == 0) {
		alert("That group name appears to already be in use. Please choose another!");
		return false;
	}
	var groupname = $("#group_name").val();
	var homepage = $("#group_home_page").val();
	var bio = $("#group_bio").val();
	
	$.post("/ajax_group_user.php", { id: who, act: "start", groupname: groupname, homepage: homepage, bio: bio },
	function(data){
		if (data == 0) {
			$("#start_finished").html("<p>There was a problem creating your group. Please try again or contact the site administrators.</p>");
		}
		groupSetHideAll();
		groupSetShow('start_finished');
	});
}

function setNotifys(who) {
	var errortext = '';
	var errors = 0;
	var checkat = $("#email_not").attr('checked');
	if (checkat == true) { emailsetting = 1; } else { emailsetting = 0; }
	
	var checkat = $("#text_not").attr('checked');
	if (checkat == true) { textsetting = 1; } else { textsetting = 0; }
	
	var cellnumber = $("#cell_number").val();
	var carrier = $("#cell_carrier").val();
	
	if (textsetting == 1) {
		if (carrier == 0) {
			errors++;
			var errortext = errortext + "You forgot to choose a carrier.\n";
		}
		
		if (cellnumber == '') {
			errors++;
			var errortext = errortext + "You forgot to enter a cellphone number.\n";
		}
	}
	
	if (errors > 0) {
		alert(errortext);
		return false;
	} else {
		$.post("/ajax_group_user.php", { id: who, act: "notifications", emailset: emailsetting, cellset: textsetting, number: cellnumber, carrier: carrier },
		function(){
			groupSetHideAll();
			groupSetShow('notify_finished');
		});
	}
}	

function groupLoadSmack(group) {
	var movieId = $("#fight_list").val();
	$.post("/ajax_group_leader.php", { act: "loadsmack", group: group, movie: movieId },
	function(data) {
		$("#stentry").val(data);
	});
}

function groupSubmitSmack(group) {
	var movieId = $("#fight_list").val();
	var smack = $("#stentry").val();
	$.post("/ajax_group_leader.php", { act: "submitsmack", group: group, movie: movieId, smack: smack });
	setTimeout("window.location.reload()",500);
}

function groupSubmitInfo(group) {
	var url = $("#group_home_page").val();
	var bio = $("#group_bio").val();
	
	$.post("/ajax_group_leader.php", { act: "submitinfo", group: group, url: url, bio: bio });
	setTimeout("groupSetHideAll()",500);
}

function groupGiveUp(group) {
	var user = $("#user_list").val();
	if (confirm("Are you SURE you want to do this??")) {
		$.post("/ajax_group_leader.php", { act: "giveup", group: group, user: user });
		setTimeout("window.location.reload()",500);
	}
}

function groupDenyUser(user,group) {
	$.post("/ajax_group_leader.php", { act: "denymember", group: group, user: user });
	$("#memreq"+user).html("Request Processed.");
}

function groupApproveUser(user,group) {
	$.post("/ajax_group_leader.php", { act: "approvemember", group: group, user: user });
	$("#memreq"+user).html("Request Processed.");
}

function check_email(e) {
	var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";

	for(i=0; i < e.length ;i++){
		if(ok.indexOf(e.charAt(i))<0){ 
			return (false);
		}	
	} 

	if (document.images) {
		re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
		re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		if (!e.match(re) && e.match(re_two)) {
			return (-1);		
		} 
	}
}

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

if ( expires )
{
expires = expires * 1000 * 60;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

