$(function(){
   var ph_r='写回复...';
   var ph_g='写下你的想法';
   var ph_p='写下你实现这个想法的动态';
   var url='/goal/create';
   var loader='<img src="/images/site/spinner.gif" width="16" height="16" border="0" class="img loader">';
   var updir='/images/upload';
   var avatardir='/images/upload/profile';
  function  hint(t){
  jQuery.noticeAdd({text:t,stay: false});
  }

   $("button,input:submit,a.btn").button();
   //$( 'a.btn' ).click(function() { return false; });
	$( "#sortable" ).sortable();
	$( "#sortable" ).disableSelection();
	$( "#tabs" ).tabs();

	$('.seek').button({icons: {primary: "ui-icon-plusthick"}});
	$('.is-seeking').button({disabled: true,icons:{primary: "ui-icon-check"}});
    $('.unseek').button({icons: {primary: "ui-icon-closethick"}});
    $('.reply').button({icons: {primary: "ui-icon-arrowreturnthick-1-w"}});
    $('.delete').button({icons: {primary: "ui-icon-trash"}});
	$('.imgthumb').live('click',function() {
			$(this).next().dialog({
            width:600,
			show: 'blind',
			modal: true,
			resizable: false
			});
			return false;
		});
    function openDialog(baseButton,hiddenInput,thumbSize){
	$("#file-form" ).dialog ({
			height: 200,
			width: 300,
			modal: true,
			resizable: false,
			buttons: {
				"上传": function() {
                 if($('input[name=file]',$(this))) {
					 $('#upform').submit();
					 $('#file-form .tips').html(loader);
					 $('#upframe').one('load', function(){
							up_output = $(this).contents().find('#output').text();
							originfilename = $(this).contents().find('#originfilename').text();
							thumb = $(this).contents().find('#thumb').text();
							if(baseButton=='.addAvatar'){
							dir=avatardir;
							}else{
							dir=updir;				
							}
							if (up_output == "success"){
							$(baseButton).siblings('.img').remove().end().before('<input type="hidden" id="img" name='+hiddenInput+' class="img" value="'+originfilename+'"><img src="'+dir+'/'+thumb+'" width='+thumbSize+' class="img"><span class=delimg>x</span>');
							$('#file').val('');
							$('#file-form .tips').html('');
							if(baseButton=='#go'){
							if($('#goalcontent').val()==''){$('#goalcontent').val('分享图片');}
							}
							$("#file-form" ).dialog( "close" );
							}
						});
				 }
				},
				"取消": function() {
					$( this ).dialog( "close" );
				}
			}
			});
	}


    $('.addimg').button({icons: {primary: "ui-icon-image"},text: false}).click(function() {
				openDialog('#go','img','100');
				return false;
			});
	$('.addAvatar').button().click(function() {
					openDialog('.addAvatar','Profile[avatar]','72');
				return false;
			});


    $('.delimg').live('click',function(){
	var x=$(this);dr='';
	if(x.prev('img').attr('width')<100){dr='profile';}
	x.after(loader);
	$.post('/post/delimg/',{data:x.prev('img').attr('src'),d:dr},function(r){
		if(r=='deleted'){
	    x.siblings('.img').andSelf().remove();
		}
	});
	});

	$('.setStatus').button({icons: {primary: "ui-icon-gear"},text: false}).each(function() {
			$(this).next().menu({
				select: function(event, ui) {
					$(this).hide();
					$.post(ui.item.children('a').attr('href'),function(r){
					
					});
				},
				input: $(this)
			}).hide();
		}).click(function(event) {
			var menu = $(this).next();
			if (menu.is(":visible")) {
				menu.hide();
				return false;
			}
			menu.menu("deactivate").show().css({top:0, left:0}).position({
				my: "left top",
				at: "right top",
				of: this
			});
			$(document).one("click", function() {
				menu.hide();
			});
			return false;
		})



   TAE='blur focus change '+($.browser.mozilla?'paste input':'keyup');
   
   $('textarea').live(TAE,function(){
	   var T=$(this);
	   if($(this).attr("name") === "content"){
	   T.attr('rel',ph_p);
	   }
	   if(T.val()!=''){
       T.siblings('button[type="submit"]').removeAttr("disabled").attr('aria-disabled','false').removeClass('ui-button-disabled ui-state-disabled disabled');
	   }else{
	   T.siblings('button[type="submit"]').attr('disabled','disabled').addClass('ui-button-disabled ui-state-disabled');
	   }
   });

$('.ph').each(function() {   
var fm=$('form',$(this));
var ta=$('textarea',$(this));
if (ta.val() === '')
        {
            ta.val(ta.attr('rel'));
            ta.addClass('pholder');
        }
$(this).focusin(function() {
            if (ta.val() === ta.attr('rel'))
                ta.val('');
            ta.removeClass('pholder');
			if(ta.attr('name')!='goalcontent') {
				ta.addClass('higher');
				ta.siblings('a').show();
			}
			ta.siblings('button').show();
			
});

$(this).focusout(function() {
            if (ta.val() === '')
            {
                ta.val(ta.attr('rel'));
            ta.addClass('pholder');
			ta.siblings('button').hide();
			ta.siblings('a').hide();
			if(ta.attr('name')!='goalcontent') ta.removeClass('higher');
            }
});
fm.bind('submit', function(event) {
          if (ta.val() === ta.attr('rel'))
            ta.val("");
        });    

});




	$('.#placeholder').each(function(i) {
       
        var item = $(this);
        var form = item.parents('form:first');
        if (item.val() === '')
        {
            item.val(item.attr('rel'));
            item.addClass('pholder');
			item.siblings('button').hide();
        }
       
        item.bind('focus.placeholder', function(event) {
            if (item.val() === item.attr('rel'))
                item.val('');
            item.removeClass('pholder');
			if(item.attr('name')!='goalcontent') item.addClass('higher');
			item.siblings('button').show();

        });
       
        item.bind('blur.placeholder', function(event) {
            if (item.val() === '')
            {
                item.val(item.attr('rel'));
            item.addClass('pholder');
			item.siblings('button').hide();
			if(item.attr('name')!='goalcontent') item.removeClass('higher');
            }
        });
       
        form.bind("submit.placeholder", function(event) {
          if (item.val() === item.attr('rel'))
            item.val("");
        });    
       
    });
 $('li.progress').hover(
	  function () {
        $('.ops-hover:first',this).css('visibility','visible');
      }, 
      function () {
        $('.ops-hover:first',this).css('visibility','hidden');
      }
);


  

   $('#go').live('click',function(){
	        var tval=$('textarea').val();var tw=$('textarea').width();$(this).after(loader);
			$.post(url,{'data':$(this).parents('form').serialize()},function(r){
				if(r) {
					if(r=='posted'){//贴子已发出
					hint('刚刚发表了这个想法的最新动态！');
					$('#goalcontent').val(ph_p).addClass('pholder').removeClass('higher').blur();
					$('#showbox').load('/goal/progress');
					}else{//发表了新想法
					hint('刚刚发表了一个新想法，开始发表实现这个想法的动态吧！');
					  $('.hiddengid').remove();
					  $('#eyebrow span:first-child').html(tval).addClass('topgoal').append('<span class=switchNew>x</span>');
					  $('#goalcontent').attr('name','content').attr('rel',ph_p).val(ph_p).addClass('pholder').blur();//转换成贴子模式
					  url='/post/create';
  					  $('#goal-form').append('<input type=hidden class=hiddengid name=goal_id value='+r+'>');
					}
					  //$('textarea').val('');
						  $('#go').attr('disabled','disabled').addClass('disabled').siblings('.img,.delimg').remove().end().siblings('button,a').andSelf().hide();
			}
			});
			return false;
		});

        $('#eyebrow span.switchNew').live('click',function(){
 	    $('#eyebrow span:first-child').html('').removeClass('topgoal');
        $('#goalcontent').attr('name','goalcontent').attr('rel',ph_g).val(ph_g);
		url='/goal/create';
		$('.hiddengid').remove();
		$('textarea').removeClass('higher');
        return false;
		});

		$('.mygoal').live('click',function(){
   		$('.hiddengid').remove();
		var goal_id=$(this).attr('href');
		var goal=$(this).html();
	    $('#eyebrow span:first-child').html(goal).addClass('topgoal').append('<span class=switchNew>x</span>');
        $('#goalcontent').attr('name','content').attr('rel',ph_p).val(ph_p);
		url='/post/create';
		$('#goal-form').append('<input type=hidden  class=hiddengid name=goal_id value='+goal_id+'>');
		return false;
		});




		$('#go2').live('click',function(){
			$.post('/post/create',{'data':$(this).parents('form').serialize()},function(r){
					if(r=='duplicate'){//重复发表了贴子
					hint('不用重复发表啦！');
					exit();
					}else if(r=='posted'){//贴子已发出
					hint('刚刚发表了这个想法的最新动态！');
					$('#showbox').load('/goal/progress');
					}
					  $('textarea').val('');
					  $('#go2').attr('disabled','disabled').addClass('disabled');
			});
			return false;
		});




       $('.reply,.re').live('click',function() {
		  if($(this).parents('.progress-body').children('.replybox').is(':visible')){
            $(this).parents('.progress-body').children('.replybox').hide();
			return false;
        }else{
			var post_id=$(this).attr('data');
			$(this).parents('.progress-body').children('.replybox').show().children('.listreply').load('/post/comments/'+post_id);
			return false;
		  }
	   });


		$('.delete').live('click',function(){
			var line=$(this);
			var post_id=line.attr('data');
			var imgname=line.parents('.progress-content').find("img").attr('src');
			$.post('/post/delete/'+post_id,{data:imgname},function(d){
			line.parents('.fpgentry').slideUp('slow');
				   });
			return false;
		});

		$('.delre').live('click',function(){
			var line=$(this);
			var comment_id=line.attr('data');
			$.post('/comment/delete/'+comment_id,function(data){
			line.parents('.comment').slideUp('slow');
				   });
			return false;
		});

		$('.replybtn').live('click',function(){
			var curr=$(this);var post_id=curr.prevAll('#post_id').val();
			$.post('/post/reply',{'data':curr.parents('form').serialize()},function(r){
				if( r == 'posted' ) {
			       curr.prev().attr('rel',ph_r).val(ph_r).removeClass('higher').addClass('pholder').blur();
				   curr.attr('disabled','disabled').addClass('disabled').hide();
				   curr.parent().prev().load('/post/comments/'+post_id);
				}
			});
			return false;
		});


		$('#search').live('click',function(){
			$.post($(this).parents('form').attr('action'),{'data':$('input[name=q]').val()},function(data){
				 $('.progresses').html(data);
			});
			return false;
		});

        

		$('.ustats').live('click',function(){
			var $url=$(this).attr('href');
			var $title=$(this).attr('title');
			$.get($url,function(data){
			$('#showUser').html(data).dialog({
            width:700,
			title:$title,
			show: 'blind',
			resizable: false
			});
			});
			return false;
		});

		//$('.opmenu .btn').click(function(){
		//		$(this).next().toggle();
		//});



	/* for keeping track of what's "open" */
	var activeClass = 'dropdown-active', showingDropdown, showingMenu, showingParent;
	/* hides the current menu */
	var hideMenu = function() {
		if(showingDropdown) {
			showingDropdown.removeClass(activeClass);
			showingMenu.hide();
		}
	};
	
	/* recurse through dropdown menus */
	$('.dropdown').each(function() {
		/* track elements: menu, parent */
		var dropdown = $(this);
		var menu = dropdown.next('ul.dropdown-menu'), parent = dropdown.parent();
		/* function that shows THIS menu */
		var showMenu = function() {
			hideMenu();
			showingDropdown = dropdown.addClass('dropdown-active');
			showingMenu = menu.show();
			showingParent = parent;
		};
		/* function to show menu when clicked */
		dropdown.bind('click',function(e) {
			if(e) e.stopPropagation();
			if(e) e.preventDefault();
			showMenu();
		});
		/* function to show menu when someone tabs to the box */
		dropdown.bind('focus',function() {
			showMenu();
		});
	});
	
	/* hide when clicked outside */
	$(document.body).bind('click',function(e) {
		if(showingParent) {
			var parentElement = showingParent[0];
			if(!$.contains(parentElement,e.target) || !parentElement == e.target) {
				hideMenu();
			}
		}
	});



         $('.unseek').live('click',function(){
			var $thisobj=$(this);
			var $url=$thisobj.attr('href');
			$.get($url,function(data){
			$thisobj.addClass('hide').prev('.seek').removeClass('hide');
			});
			return false;
			});

         $('.seek').live('click',function(){
			 var $thisobj=$(this);
			var $url=$thisobj.attr('href');
			$.get($url,function(){
			$thisobj.addClass('hide').next('.unseek').removeClass('hide');
			});
			return false;
			});

			//$('#seek').live('click',function(){
			// $.get($('a',this).attr('href'),function(){
		     //   $('#seek').replaceWith('<span class="is-following"><i></i><strong>我正在做</strong></span>');
		     //});
			 //return false;});

//$('#pagination').hover(function(){$('#more').css('visibility','visible');},function(){$('#more').css('visibility','hidden');});

function more(){
	var url=$('#more').attr('href');
	if(url){
		$('#more').html(loader);
	$.get(url,function(data){
	var li=$('ul',data).html();
		$('#more').parents('li').replaceWith(li);
		});
    }
}
$(window).scroll(function () { 
if ($(window).scrollTop() == $(document).height()-$(window).height()){
   more();
}    
});


$('.showemail').live('click',function(){
     $('.emailcontent').toggle();
});

	$('#toggle_all').toggle(
      function () {
        $(':checkbox').attr('checked','true');
      },
      function () {
        $(':checkbox').removeAttr('checked');
      });

	$('a.service').live('click',function(){
        var service=$(this).attr('href');
	    $(this).parent().addClass('current').siblings().removeClass('current');
	    $('#inputbox').hide().animate({'margin-left':'500px'},10).show().animate({'margin-left':'220px'},150);
		$('.blobhint').hide();
	    $('input[name="provider_box"]').val(service).hide();
	   return false;
	});
	    $('#import').live('click',function(){
			$(this).after(loader);
			$.post('/invite/getContacts/',{'data':$(this).parents('form').serialize()},function(r){
				$('form[name="openinviter"]').html(r);
			});
			return false;
	})
var tog = true; 
$('#toggle_all').live('click',function(){
  $("input[type=checkbox]").attr('checked',!tog);
  tog = !tog;
 }); 

    $('#send').live('click',function(){
			$.post('/invite/ivEmail/',{'data':$(this).prev().val()},function(r){
				  hint(r);
			});
			return false;
	})
	$('#send2').live('click',function(){
			$(this).after(loader);
	$.post('/invite/sendInvites/',{'data':$(this).parents('form').serialize()},function(r){
			ok=$('#ok',r).text();
		    if(ok){
			$('#list-content').parent().load('/invite/inviter/');
			}
			hint(r);
			});
			return false;
	})

});
