jQuery.ajaxSetup({
  'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript")}
});

jQuery.fn.submitWithAjax = function() {
  this.submit(function(){
    $.post($(this).attr("action"),$(this).serialize(),null,"script");
    return false;
  });
};

$(document).ready(function() {
  
  //
	// Resize lovely popup
	// ==============================
	function centerPopup() {
		if ( $('.wrapper-point').length == 0 ) return;
		var $popup = $('.wrapper-point');
		var new_top = ($(window).height() - $popup.outerHeight()) / 2;
		$popup.css({ top: new_top });
	}
  
  // NOTICE
  
  setTimeout('$("#flash_success").fadeOut();', 5000);
  setTimeout('$("#flash_notice").fadeOut();', 5000);
  setTimeout('$("#flash_error").fadeOut();', 5000);
  
  // FORMS
  //$(".comment-add").submitWithAjax();
  
  $(".viewpoint-add").submit(function(){
    if ($('#post_body').val().length > 0) {
      $('#post_body').css('background-color','#eeeeee'); 
      $('.xbtn-add-viewpoint').addClass('xbtn-add-viewpoint-disabled'); 
      $('.xbtn-add-viewpoint').attr("disabled","disabled");
      $.post($(this).attr("action"),$(this).serialize(),null,"script");
    } else {
      alert("Can't add an empty Viewpoint");
    }
    return false;
  });
  
  $(".comment-add").submit(function(){
    $('#comment_body').css('background-color','#eeeeee'); 
    $('.xbtn-add-comment').addClass('xbtn-add-comment-disabled'); 
    $('.xbtn-add-comment').attr("disabled","disabled");
    $.post($(this).attr("action"),$(this).serialize(),null,"script");
    return false;
  });
  
  
  if($("#request_body").length){
    $("#request_body").focus();
  }
  
  if($("div.request-feed").length)
    $("div.request-feed:first li.point:first")
      .addClass("show-bubble");
    $("div.request-feed:first li.point:first a:first").before("<div class='bubble'><a href='#' class='bubble-close'>x</a><p>Press '<strong>Point</strong>' to refer this question to a friend!</p></div>")
    
	$('.bubble .bubble-close').click(function(){
		$(this).parent().parent().removeClass('show-bubble');
		return false;
	});
  
  $("a.ignore_welcome").click(function(){
    $.get("close/welcome");
    if ($("#welcome-todo").length){
      $("#welcome-todo").fadeOut();
    }
    $("#request_body").focus();
    return false;
  });
  
  $("#welcome-todo a.close").click(function(){
    if ($("#welcome-todo").length){
      $("#welcome-todo").fadeOut();
    }
    return false;
  });
  
  // HELPING
  $(".start-helping").live('click', function(){
    $.get($(this).attr("href"));
    return false;
  });
  $(".stop-helping").live('click', function(){
    $.get($(this).attr("href"));
    return false;
  });
  
  // Image cropping
  
 // $("#user_sidebar dl.intro.vcard a.url img.photo.fn").crop(0, 0, 48, 48, "/images/transparent.gif")

	//
	$('a[rel=_blank]').click(function(){
		this.target = "_blank";
	});

	//
	$("#content .box-help h2").toggle(
		function () {
			$(this).parent().addClass('active');
		},
		function () {
			$(this).parent().removeClass('active');
		}
	);

  // //
  // $('div.button-help a.button').click(function(){
  //  $(this).parent().addClass('helping');
  //  return false;
  // })
  // $('div.button-help dl.help-info dd a').click(function(){
  //  $(this).parent().parent().parent().removeClass('helping');
  //  return false;
  // })

	//
	$('div.info a.comments').each(function(){
		var text = $(this).text();
		$(this).toggle(
			function () {
				var currentComment = $(this).attr('class').replace(/\s*comments\s*/, '');
				$("div."+currentComment).show();
				$(this).text('close comments');
			},
			function () {
				var currentComment = $(this).attr('class').replace(/\s*comments\s*/, '');
				$("div."+currentComment).hide();
				$(this).text(text);
			}
		);
	})
	
  $("li.point, .point-dropdown-wrapper").live('mouseover mouseout', function(event) {
      if (event.type == 'mouseover') {
        var parents = $(this).parents('.request-feed, .request-feed2, #addViewpoint');
        parents.addClass('show-point-dropdown');
        parents.css({'z-index':99});
      } else {
        var parents = $(this).parents('.request-feed, .request-feed2, #addViewpoint');
        parents.removeClass('show-point-dropdown');
        parents.css({'z-index':0});
      }
    });
	
	
  // prepare popup container
$('.container').append($('<div class="container-point"></div>'));
  
  // handle dropdown click
  $('.point-dropdown a').live("click", function(){
   var url = $(this).attr('href');
   if(url.substr(0,1) != "#"){
     $(".container-point").load(url, function(){
       centerPopup();
       $(window).resize(centerPopup);
  
       $("a.close").live("click", function(){
         $(".wrapper-point").remove();
         $(".container-point").remove();
         $('.container').append($('<div class="container-point"></div>'));
         $(window).unbind('resize', centerPopup);
         return false;
       });
       
     }).fadeIn('normal');
   }
   if($(this).hasClass("direct")) {
     
   } else {
     return false;
   }
   
  });
  

	//toplayer
	$('.container').append($('<div class="container-point"></div>'));
	$("a.point").live("click",function(){
	  var request_id = $(this).attr("data-requestid");
		$(".container-point").load("/pointings/pointto/"+request_id, function(){
		  $(window).resize(centerPopup);
			$("a.close ").click(function(){
				$(".wrapper-point").remove();
				return false;
			});
		}).fadeIn('normal');
		return false;
	});

	//
	$('.wrapper-point .point a.close').click(function(){
		$('.wrapper-point').remove();
	})

	//
	$('.scroll-pane').jScrollPane({
		showArrows: true,
		scrollbarWidth: 13
	});
	
	//
	$('textarea').not('.no-resize').autoResize({
		// On resize:
		onResize : function() {
			$(this).css({opacity:0.8});
		},
		// After resize:
		animateCallback : function() {
			$(this).css({opacity:1});
		},
		// Quite slow animation:
		animateDuration : 300,
		// More extra space:
		extraSpace : 12
	});
	
	// default text
	var defaultWhat = 'Enter a specific question that describes what you need help with';
	var defaultWho = 'Enter specific types of people you would like to get help from';
	
	// set default
	$('.box-help #what')
		.click(function(){
			if($(this).val() == defaultWhat) 
				$(this)
					.val('')
					.removeClass('default-value');
		})
		.blur(function(){
			if($(this).val() == '') 
				$(this)
					.val(defaultWhat)
					.addClass('default-value');
		});
	$('.box-help #who')
		.click(function(){
			if($(this).val() == defaultWho) 
				$(this)
					.val('')
					.removeClass('default-value');
		})
		.blur(function(){
			if($(this).val() == '') 
				$(this)
					.val(defaultWho)
					.addClass('default-value');
		});
	$('.box-help #what, .box-help #who').trigger('blur');

	//
	$('textarea').autoResize({
		// On resize:
		onResize : function() {
			$(this).css({opacity:0.8});
		},
		// After resize:
		animateCallback : function() {
			$(this).css({opacity:1});
		},
		// Quite slow animation:
		animateDuration : 300,
		// More extra space:
		extraSpace : 17
	});

	// Add More
	var moreMax = 220; // max words count
	var moreTrail = 20; // max words count until find some space char
	var moreLink = " <a class='truncmore' href='#more'>(more)</a>";
	var lessLink = " <a class='truncless' href='#less'> (less)</a>";
	$('.more-wrapper').each(function(){
		var countdown = moreMax;
		var addMore = true;
		var p = $(this).find('p');
		
		//  take out the inline author
		var author = $(this).find('.request-inline-author');
		var authorParent = author.parent();
		author
			.insertBefore(this)
			.hide()
		
		for(var i=0;i<p.length;i++){
			
			if(countdown < 0){
				$(p[i]).addClass('trunchide');
			}
			
			var curText = $(p[i]).text();
			var curLength = curText.length;
			var curCountdown = countdown;
			countdown = countdown - curLength;
			
			if(countdown < 0 && addMore){
				// find nearest next space char
				var lastText = curText.substr(curCountdown);
				var nextSpace = lastText.split(' ')[0].length;
				if(nextSpace < moreTrail) curCountdown = curCountdown + nextSpace;
				
				newText = curText.substr(0,curCountdown) + "<span class='truncdotted'>... </span><span class='trunchide'>" + curText.substr(curCountdown) + "</span>";
				$(p[i]).html(newText);
				
				$(p[i]).append(moreLink);
				addMore = false;
			}
		}
		
		// put the author back
		author
			.prependTo(authorParent)
			.show()
		
		if(!addMore){
			$(lessLink)
				.appendTo($(p[p.length-1]))
				.hide();
		}
		
		// hide and setup click
		$(this).find('.trunchide').hide();
		$(this).find('.truncmore').click(function(){
			$(this).parents('.more-wrapper').find('.trunchide,.truncless').show();
			$(this).parents('.more-wrapper').find('.truncmore,.truncdotted').hide();
			return false;
		});
		$(this).find('.truncless').click(function(){
			$(this).parents('.more-wrapper').find('.trunchide,.truncless').hide();
			$(this).parents('.more-wrapper').find('.truncmore,.truncdotted').show();
			return false;
		});
	});
	
	if($("p.more").length){
	  $.bottomlessPagination({objName:'Items'});
	}

	//
	if (($.browser.msie) && ($.browser.version == "8.0")){

		//
		$('html').addClass('ie8');

	}

	//
	if (($.browser.msie) && ($.browser.version == "7.0")){

		//
		$('html').addClass('ie7');

		//
		$('input[type="text"]').focus(function() {
			$(this).addClass('focus');
		});
		$('input[type="text"]').blur(function() {
			$(this).removeClass('focus');
		});

	}


	if (($.browser.msie) && ($.browser.version == "6.0")){

		//
		$('html').addClass('ie6');

		//
		$('#sidebar ul.info li:first-child').css({'border-left':'none'});

		//
		$('input[type="text"]').focus(function() {
			$(this).addClass('focus');
		});
		$('input[type="text"]').blur(function() {
			$(this).removeClass('focus');
		});

		//
		$('input[type=text]').addClass("text");
		$('input[type=password]').addClass("text");
		$('input[type=button]').addClass("button");
		$('input[type=reset]').addClass("reset");
		$('input[type=submit]').addClass("submit");
		$('input[type=radio]').addClass("radio");
		$('input[type=checkbox]').addClass("checkbox");
		$('input[type=file]').addClass("file");
		$('input[type=image]').addClass("image");

		$("#content .request-feed, #content table tbody tr, #content .myprofile dl").hover(
			function () {
				$(this).addClass('hover');
			},
			function () {
				$(this).removeClass('hover');
			}
		);

		//$('.sub #content ul li dl dd span').addClass("fixPNG");
		//DD_belatedPNG.fix('.fixPNG');

	}
	
	// splash page
	
	$('.btn-connect-wrapper a').hover(
		function(){
			$(this).parents('#content').find('p.note').stop(true,true).fadeIn('fast');
		},
		function(){
			$(this).parents('#content').find('p.note').stop(true,true).fadeOut('fast');
		}
	);

	//signup validation
	
	if ($('.signup-validate').length){
	 	$('.signup-validate').validate({
				meta: "validate",
				errorElement: "p",
				errorPlacement: function(error, element) {
					error.insertAfter(element);
				},
				success: function(label) {
				},
				highlight: function(input) {
					$(input).parent()
						.removeClass('form-item-checked')
						.addClass('form-item-error');
				},
				unhighlight: function(input) {
					$(input).parent()
						.removeClass('form-item-error')
						.addClass('form-item-checked');
				},
				rules: {
        "user[email]": {
          required: true, 
          email: true,
          remote: {
            url: "/do/users/validate/check_email"
          }
         },
        "user[username]": { 
          required: true,
          remote: {
            url: "/do/users/validate/username"
          }
        },
        "user[full_name]": { 
          required: true
        },
        "user[password]": {
          required:true, 
          minlength:6
        }
      },
      messages: {
  			"user[email]": {
  				required: "Enter a valid email",
  				email: "Email must be real",
  				remote: "Sorry that email is taken"
  			},
  			"user[username]": {
  				required: "Enter a valid username",
  				remote: "Username taken or has bad symbols"
  			},
  			"user[full_name]": {
  				required: "Enter your name"
  			},
  			"user[password]": {
  				required: "Enter a password",
  				minlength: 'Password too short'
  			}
      }
				
		}); 
	}

	
	//share
	$('.share-feature').hover(
		function(){ $(this).addClass('share-feature-active'); },
		function(){ $(this).removeClass('share-feature-active'); }
	);
	// signin
	$('.nav-signin').click(function(){
		var header = $(this).parents('#header');
		if(header.hasClass('nav-signin-active')){
			header.removeClass('nav-signin-active');
		}else{
			header.addClass('nav-signin-active');
		}
		return false;
	});

});