function menu_hover() {
	li = $(".top_menu li:not(li li)");
	
	//for (i = 0; i < li.length; i++) if (li.eq(i).find("ul").length) li.eq(i).find("a").eq(0).append("▼");

	li.hover(
			function(){
				$("a.on").removeClass('active');
				$(this).children("a").addClass('active');
				sub = $(this).children("ul");
				if (sub.length) {
					if (sub.css('display') == 'none') {
						pos = $(this).position();
						//sub.css({'left':pos.left+'px','top':pos.top+30+'px','display':'block'});
						sub.css({'left':pos.left+'px','top':pos.top+30+'px'});
						sub.slideDown("fast");
					}
				}				
			},
			function(){
				//$(this).children("ul").css('display', 'none');
				$(this).children("ul").slideUp("fast");
				$(this).children("a").removeClass('active');
				$("a.on").addClass('active');
			}
		);
	

}

function input_focus(what, text, cl) {
	
	if ($(what).val() == "") $(what).val(text);
	if ($(what).val() != text && $(what).val() != "") $(what).addClass(cl);
	
	$(what).focus(function()
			{
				if ($(this).val() == text) {
					$(this).val("");
					$(this).addClass(cl);
				}
			}).blur(function()
			{
				if ($(this).val() == "") {
					$(this).val(text);
					$(this).removeClass(cl);
				}
			});	
}

function search_setup() {
	
	$("#search").parent().submit(function()
			{	
				q = $(".search_q").val();
				if (q == "search movie" || q == "") return false;
				$("#search_b").attr('disabled','disabled');
				window.location = $(this).attr('action')+"/"+q.replace(/ /g, '+');
				return false;
			});	
	
	input_focus(".search_q", "search movie", "search_q2");
}

function search_fanclub_setup() {
	$("#search_fanclub").parent().submit(function()
			{	
				q = $(".fanclub_search_q").val();
				if (q == "") return false;
				$("#fanclub_search_b").attr('disabled','disabled');
				window.location = $(this).attr('action')+"/"+q.replace(/ /g, '+');
				return false;
			});	
	
	//input_focus(".search_q", "search movie", "search_q2");
}

function star(d) {
	var v = $("#movie_vote div");
	v.removeClass("vote_half vote_full");
	var a = d+"";
	if (a.indexOf(".") > -1) {
		var half = true;
		d -= 1;
	}
	for (i = 0; i < 5; i++) {
		if (i<d) {			
			v.eq(i).addClass("vote_full");
		} else if (half) {
			v.eq(i).addClass("vote_half");
			half = false;
		}
	}
	
}

function voting(voted) {
	var v = $("#movie_vote div");
	v.addClass("vote_gray");
	if (!voted) {						
		v.mouseover(function(){
				star($(this).attr("title"));
			}).mouseout(function(){
				star(rate);
			}).click(function(){
				rate = $(this).attr("title");
				
				$.post(basedir+"ajax/movie_vote", "vote="+$(this).attr("title"), function(data){
					code = $("response code", data).text();
					  switch (code) {
					  	case '0':
					  		$("#vote_info").text("You've allready rated this movie to "+$("response old_vote", data).text()+".");
					  	break;
					  	default:
					  		votes = $("#votes");
					  		votes.text(parseInt(votes.text())+1);
							
							place = $("#place");
							
							old_place = (place.text()=='-')?0:parseInt(place.text());
							place.text($("response place", data).text());
							new_place = parseInt(place.text());
							
							place_diff = new_place-old_place;
							
							pc=$("#place_change");
							if(old_place==0){
								pc.css('color', '#245900');
								pc.html('<img src="media/img/movie_up.png" />'+new_place);
							}else{
								if(place_diff<0){
									pc.css('color', '#245900');
									pc.html('<img src="media/img/movie_up.png" />'+Math.abs(place_diff));
								}else if(place_diff>0){
									pc.css('color', '#850202');
									pc.html('<img src="media/img/movie_down.png" />'+place_diff);
								}else{
									pc.html('<img src="media/img/movie_still.png" /> ');
								}
							}
							$("#places_total").text($("response places_total", data).text());
							
					  		$("#rating").text($("response rating", data).text());
					  		$("#vote_info").text('Thanks for rating!');
						break;
					  }
					}, 'xml');
	
				v.unbind().css("cursor", "default");
			});
	} else {
		v.css("cursor", "default");
	}
	star(rate);
}

function ie_bg_fix() {
	if( ! jQuery.support.cssFloat) {
		a = $("a.nick").width();
		a = a < 46 ? 46 : a;
		$("div.bg").css('width', a+45+'px');
	}
}

function set_onsubmit() {
	$("#type_comment").parent().submit(
		function() {
			ta = $("#type_comment").val();
			if (ta.replace(/ /g,'').length < 2) {
				alert('Comment too short.');
				return false;
			}
			
			$("#post_comment").attr("disabled", "disabled");
			
			$.post(basedir+"ajax/add_comment", {comment: ta, movie_id: mid},
				function(data){
					$("#type_comment").val('');
					$("#post_comment").removeAttr("disabled");
				    $("#comments").prepend('<div class="new_comment">'+data+'</div>');
				    $("#comments .new_comment").eq(0).fadeIn(2000);
				    set_comment($("div.new_comment").eq(0));				    
				});
			
			return false;
		}
	);
}

function set_comment(parent) {
	boxes = parent.children(".comment_box");
	for (i = 0; i < boxes.length; i++) {
		box = boxes.eq(i);
		$(".plus", box).css('cursor', 'pointer').click(function(){ 
			comment_id = $(this).parents(".comment_box").attr('id').substring(8); 
			rate_comment(comment_id,1);			
		});
		$(".minus", box).css('cursor', 'pointer').click(function(){ 
			comment_id = $(this).parents(".comment_box").attr('id').substring(8); 
			rate_comment(comment_id,0);
		});
	}
	
	$(".comment_edit .delete", parent).click(
		function() {
			answer = confirm('Are you sure you want to delete this comment?');
			if (answer) {
				comment_id = $(this).parents(".comment_edit").attr('id').substring(5);
				$.post("ajax/delete_comment", "comment_id="+comment_id, 
					function(data){
						$("#comment_"+comment_id+", #edit_"+comment_id).slideUp(1000);
					});
			}
		});
	
	edit_lock = 'off';
		
	$(".comment_edit img.edit", parent).click(
		function() {
			if (edit_lock == 'on') {
				alert('End comment edition first.');
				return false;
			}
			edit_lock = 'on';
			
			comment_id = $(this).parents(".comment_edit").attr('id').substring(5);
			$.post(basedir+"ajax/get_edit_comment", "comment_id="+comment_id, 
				function(data){
					//$("#type_comment").val(data);
					comment = $("#comment_"+comment_id+" .comment_body");
					height = comment.height();
					height = height < 80 ? 80 : height-10;
					comment.toggle();
					
					editbox = $("<div></div>").addClass("edit");
					tarea = $("<textarea></textarea>").css('height', height+'px').val(data);

					editbox.append(tarea);					
					comment.after(editbox);
					
					editbuttons = $("#edit_"+comment_id);
					editbuttons.toggle();
					
					eb2 = $("<div></div>").addClass('comment_edit');
					cancel = $("<img />").attr('src', 'http://'+location.host+'/media/img/button_cancel.jpg').click(
							function() {
								editbox.remove();
								comment.toggle();
								eb2.remove();
								editbuttons.toggle();
								edit_lock = 'off';
							});
					save = $("<img />").attr('src', 'http://'+location.host+'/media/img/button_save.jpg').click(
							function() {
								$.post(basedir+"ajax/save_comment", {comment_id: comment_id, comment: tarea.val()}, 
									function(data){
										comment.html(data);
										
										editbox.remove();
										comment.toggle();
										eb2.remove();
										editbuttons.toggle();
										edit_lock = 'off';
									});

								
							});
					eb2.append(cancel).append(save);
					editbuttons.after(eb2);
				});
		});
	
	$(".pagination a").click(function(){
		h = $(this).attr('href');
		page = h.substring(h.lastIndexOf('/')+1);
		get_comments(page);	
		return false;
	});
}

function rate_comment(comment_id, vote) {
	$.post(basedir+"ajax/comment_vote", "comment_id="+comment_id+"&vote="+vote, function(data){
		if (data != "1") {
			span = $("#comment_"+comment_id+" .comment_rating");
			rating = parseInt(span.text());
			if (vote == 1) {
				rating += 1;
			} else {
				rating -= 1;
			}
			
			if (rating > 0) {
				rating = "+"+rating;
			}
			span.text(rating);
		}	
		imgs = $("#comment_"+comment_id+" .plus_minus img");
		imgs.css('cursor', 'default').unbind();
		$.each(imgs, function(){
			$(this).attr('src', $(this).attr('src').replace(".png", "_gray.png"));
		});
	});	
}

function get_comments(p) {
	$("#comments").addClass('comments_transparent');
	$.post(basedir+"ajax/get_comments/"+p, {movie_id: mid},
		function(data){
			$("#comments").html(data);
		    set_comment($("#comments"));
			$.scrollTo(".header_comment", 1000, {easing:'easeOutBounce', onAfter: 
				function() {
					$("#comments").removeClass('comments_transparent');
				}
			});
			
	});
}

function get_stats(mid) {
	$("#show_stats").click(
			function () {
				if ($("#chart").length > 0) {
					$("#stats").toggle()
				} else {
				    $("#show_stats_box").toggle();
					$("#stats").toggle();
					$.post(basedir+"ajax/get_movie_stats", {movie_id: mid},
						function(data){							
							$("#stats").html(data);			
						});
				}
				return false;
			});
}

function readpm(id) {
	tr = $("#pmread_"+id);
	tr2 = $("#pm_"+id);
	td = tr.children("td");
	
	if (tr.css('display') == 'none') {
		td.css('border-top-width', '0');
		tr2.children("td").css('border-bottom-width', '0');		
	} else {
		td.css('border-top-width', '1px');
		tr2.children("td").css('border-bottom-width', '1px');	
	}
	
	if (td.html() == "") {		
		loader = $('<div></div>').addClass("pm_loader");
		td.append(loader);
		tr.toggle();
			
		$.get(basedir+"ajax/get_pm/"+id, 
			function (data) {	
				td.html(data);
				
				tr2.children(".title").removeClass("new");
			});
		
	} else {
		tr.toggle();
	}
}

function pm_del_setup() {
	$("a.delete").click(
		function () {
			answer = confirm('Are you sure?');
			if ( ! answer) {
				return false;
			}
		});
}

function button_toggle(t) {
	var url = t.src;
	var url2 = url.replace('A.', 'B.');
	t.onmouseover = function () {
		t.src = url2;
	}
	t.onmouseout = function () {
		t.src = url;
	}
	t.src = url2;
}

function toggle_connect_fanclub() {
	var b = $('#connect_fanclub');
	var bb = $('#connect_fanclub_button');
	if (b.css('display') == 'block') {
		b.css('display', 'none');
		bb.css('display', 'none');
	} else {
		$.get(basedir + 'ajax/connect_fanclub_list', function(resp) {
			b.html(resp);
			b.css('display', 'block');
		});
	}
}

function connect_fanclub_list(id) {
	if (id == 0) return;
	$.post(basedir + 'ajax/connect_fanclub_list', 'movie_id=' + mid + '&type=' + id, function (resp) {
		$('#connect_fanclub2').html(resp);
		$('#connect_fanclub_button').css('display', 'none');
	});
}

function connect_fanclub(fanclub_id) {
	if ( ! fanclub_id || fanclub_id == 0) return;
	$.get(basedir + 'ajax/connect_fanclub/' + mid + '/' + fanclub_id, function () {
		$('#connect_fanclub').html('<div class="info">Your request is waiting for acceptation</div>');
		$('#connect_fanclub_button').css('display', 'none');
	});
}

function connect_fanclub_button(v) {
	$('#connect_fanclub_button').css('display', (v == 0 ? 'none' : 'block'));
}

function toggle_forum_fanclub() {
	var b = $('#add_new_discussion');

	$.get(basedir + 'ajax/fanclubs_list', function(resp) {
		b.html(resp);
		b.css('display', 'block');
	});

}

function forum_choose_fanclub_button(v) {
	$('#forum_choose_fanclub_button').css('display', (v == 0 ? 'none' : 'block'));
}

function forum_choose_fanclub(fanclub_url) {
	if ( ! fanclub_url || fanclub_url == 0) return;
	window.location = 'fanclubs/'+fanclub_url+'/forum/new_topic';
}

function set_discussion() {
	var c = $('#discussion_posts');
	if ( ! c) return;
	var p = $('.cc', c);
	if ( ! p.length) return;
	p.mouseenter(function () {
		var d = $('.post_edit', this);
		if (d) {
			if (d.css('display') == 'none')
				d.slideDown();
		}
	}).mouseleave(function () {
		var d = $('.post_edit', this);
		if (d) {
			d.slideUp();
		}
	});
	for (i = 0; i < p.length; i++) {
		post = p.eq(i);
		$('.plus', post).css('cursor', 'pointer').click(function () {
			post_id = $(this).parents(".cc").attr('id').substring(5);
			rate_post(post_id, 1);
		});
		$('.minus', post).css('cursor', 'pointer').click(function () {
			post_id = $(this).parents(".cc").attr('id').substring(5);
			rate_post(post_id, 0);
		});
	}
}

function rate_post(post_id, vote) {
	$.post(basedir+"ajax/post_vote", "post_id="+post_id+"&vote="+vote, function(data){
		span = $("#post_"+post_id+" .comment_rating");
		rating = parseInt(span.text());
		if (vote == 1) {
			rating += 1;
		} else {
			rating -= 1;
		}

		if (rating > 0) {
			rating = "+"+rating;
		}
		span.text(rating);
		imgs = $("#post_"+post_id+" .plus_minus img");
		imgs.css('cursor', 'default').unbind();
		$.each(imgs, function(){
			$(this).attr('src', $(this).attr('src').replace(".png", "_gray.png"));
		});
	});
}

function delete_post(post_id) {
	post = $("#post_" + post_id);
	post_box = $('.comment_box', post);
	post_box.addClass('post_delete');
	answer = confirm('Are you sure you want to delete this post?');
	if ( ! answer) {
		post_box.removeClass('post_delete')
		return;
	}

	$.post(basedir + "ajax/delete_post", "post_id=" + post_id,
		function(){
			post.slideUp(1000);
		});

}

function topic_cancel_translation(t) {
	answer = confirm('Are you sure you want to cancel?');
	if (answer)
		$(t.parentNode).remove();
}

function show_full_post(id, lang) {
  $.post(basedir+"ajax/get_topic_full", "topic_id="+id+"&lang="+lang, function(data){
  code = $("response code", data).text();
    switch (code) {
      case '0':
        $("#fullpost").text("Error.");
      break;
      default:
        src = $("response fullpost", data).text();
        $("#fullpost").html(src);
    break;
    }
  }, 'xml');

}
var chat_lasttime=0;
var live_id=-1;
var chat_updating=false;
var msg_ids=new Array();
var uref_max;
var uref_cnt;
function update_chat(){
    if(chat_updating) return;
    chat_updating=true;

    $.ajax({
      url: basedir+"ajax/chat_refresh/"+live_id+"/1/"+ (live_id>0?((uref_cnt==uref_max)?"1":"0"):"0") ,
      type: "POST",
      dataType: "xml",
      async: true,
      data: "last_msg_time="+chat_lasttime,
      success: function(data) {
 
        //Usrs
		if(live_id>0){
			var users= $("response response_users users_list", data);
			if(users.length !== 0){
			  $("#chat_users_list").html(users.text());
			  $("#chat_total_users").html($("response response_users total", data).text());
			  $("#chat_users_count").html('('+$("response response_users users", data).text()+' users)');
			}
		}
      
        //Msgs
        chat_lasttime=$("response response_msgs time", data).text();
        var msgs= $("response response_msgs msg", data);
        var author, text;
        
        $.each(msgs, function(){
         author= $(this).find('author_link').text();
         text = $(this).find('text').text();
         when = $(this).find('when').text();
         id=$(this).find('id').text();
         if(msg_ids.indexOf(id)==-1){
            msg_ids.push(id);
            $('<div class="chat_post"><div class="chat_post_msg">'+author+': '+text+'</div><div class="chat_post_time"><input class="timestamp" type="hidden" value="'+when+'"/><span class="add_date"></span></div></div>').insertAfter("#chatbegin");
         }
        });
        update_chat_msg_times();
        chat_updating=false;
      },
      error: function(){
        chat_updating=false;
      }
    });
    uref_cnt++;
    if(uref_cnt>uref_max)
      uref_cnt=1;

}

function update_chat_msg_times(){
  var timestamps=$(".timestamp");
  var timediff;
  var timeunit;
  //alert(chat_lasttime);
  $.each(timestamps, function(){
    timeunit="secs ago";
    timediff=chat_lasttime-$(this).attr('value');
    
    if(timediff>3600){
      timediff=Math.floor(timediff/3600);
      timeunit="hours ago";
    }else if(timediff>60){
      timediff=Math.floor(timediff/60);
      timeunit="mins ago";
    }
      
    $(this).parent().find('.add_date').text(timediff+" "+timeunit);
  });
}

function chat_setup(id, isGuest){
  live_id=id;

  if(isGuest){
    uref_cnt=uref_max=3;
    if(id>0) setInterval(update_chat, 30000);
	else setInterval(update_chat_msg_times, 5000);
  }else{
    $("#post_msg").click(chat_send);
	uref_cnt=uref_max=6;
	setInterval(update_chat, 5000);
  }
  
  update_chat();
}

function chat_send(event){
  
  event.preventDefault()
  var msg=$("#msg");
  if(msg.attr('disabled') != '') return;
  
  var msg_data=msg.serialize();
  msg.attr('disabled', 'disabled');
  $.ajax({
    url: basedir+"ajax/live_chat_post/"+live_id,
    type: "POST",
    data: msg_data,
    success: function(data){
      var rstat=$("response status", data).text();
      if(rstat == "1") {
        $("#msg").attr('value','');
        $("#msg").attr('disabled', '');
      }else if(rstat == "2") {
        $("#msg").attr('value', 'Your account is already banned.');
      }
    },
    error: function(){
      $("#msg").attr('disabled', '');
    },
  });

  return false;
}

function formatZero(src){
  if(src<10)
    return "0"+src;
  else      
    return src;
}
function serverDate2Local(serverString){
  if(serverString=="") return "";
  x=serverString.split("/");
  var d = new Date(x[2], x[1]-1, x[0], x[3], x[4], 0, 0);
  d.setMinutes(d.getMinutes()-d.getTimezoneOffset());
  strOut = formatZero(d.getDate()) + "." + formatZero(d.getMonth()+1) + "." + d.getFullYear() + " " + formatZero(d.getHours()) + ":" + formatZero(d.getMinutes());
  return strOut;
}
function setupTransmissionDates(){
  var ltDates=$(".live_date");
  $.each(ltDates, function(){
    $(this).text(serverDate2Local($(this).text()));
    $(this).css("visibility", "visible");
  });
}
