//** * jQuery.ScrollTo - Easy element scrolling using jQuery. * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Dual licensed under MIT and GPL. * Date: 5/25/2009 * @author Ariel Flesler * @version 1.4.2 * * http://flesler.blogspot.com/2007/10/jqueryscrollto.html*/
(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
$.fn.hintlabel = function(hintClass){if(!hintClass){hintClass = 'hint';}return this.each(function(){var label = $(this);var input = null;if ( $(this).next('input[type="text"]') || $(this).next('input[type="password"]') ){input = $(this).next('input');}if( input ){var styles = ['font-size', 'line-height', 'padding-top', 'padding-bottom', 'padding-left'];var apply = {};$.each(styles, function(i, style){apply[style] = input.css(style);});$.extend(apply, {'text-align': 'left', 'position': 'absolute', 'border-width': '1px', 'border-style': 'solid', 'border-color': 'transparent', 'cursor': 'text'});$(this).parent().css({'position': 'relative'});$(this).css(apply).addClass(hintClass);$(this).bind('click', function(event){$(this).hide();input.trigger('focus');});input.bind('focus', function(event){if( label.is(':visible') ){label.hide();}});input.bind('blur', function(event){if( $(this).val() == '' ) {if( label.is(':hidden') ){label.show();}}});} else {return this;}});};

$(function(){
	
	//hints
	$('input[placeholder], textarea[placeholder]').each(function(){if ($(this).val().length==0) { $(this).val($(this).attr('placeholder'));$(this).addClass('hinted') }; });
	$('input[placeholder], textarea[placeholder]').live("focus", function(){if ($(this).val() == $(this).attr('placeholder')) $(this).val('').removeClass('hinted'); });
	$('input[placeholder], textarea[placeholder]').live("blur", function(){if ($(this).val().length==0) { $(this).val($(this).attr('placeholder')).addClass('hinted') }; });
	$('label.tohint').hintlabel();

	//textareal limits
	$('textarea[maxlength]').live('keyup', function() {
		if($(this).val().length > $(this).attr('maxlength')) $(this).val($(this).val().substr(0, $(this).attr('maxlength')));
		if($(this).attr('maxcounter').length > 0) $('#maxcounter_'+$(this).attr('maxcounter')).text( $(this).attr('maxlength') - $(this).val().length );
	});		

	$('textarea[maxlength]').each(function() {
		$('#maxcounter_'+$(this).attr('maxcounter')).text( $(this).attr('maxlength') - $(this).val().length );
	});		

	//tip
	$('span.tip').tipsy({fade:true, gravity: 's'});
	$('.tooltip').tooltip();
	
	//autosubmit
	$('.autosubmit').keypress(function(e){
	      if(e.which == 13){$(this).closest('form').submit(); return false;}
	 });
	
	autosize_apply();
	
	//people live search
	var peopleLiveSearchTimer = null;
	$('#people_live_search').keyup(function(){
		clearTimeout(peopleLiveSearchTimer);
		peopleLiveSearchTimer = setTimeout(function(){ peopleLiveSearch(true); }, 400);		
	});
	
	$('#people_live_industry, #people_live_location').change(function(){ peopleLiveSearch(false); });
	

	var notificationTimer = null;
	if ($('#notification_anchor').length > 0) notificationTimer = setInterval(function(){ 
		
		$.ajax({
			type: "POST", url: $("#ajaxLink").val(), data: 'action=msg_count_get',
			success: function(msg){
				json = jsonQuery(msg);
				if (json != null && !isNaN(json.rv)) {
					if (json.rv == -101) {
						if ($('#login_modal').length==0) return newmodal('login_modal');
					} else if (json.rv == 1) {
						if ($('#login_modal').length>0) newmodal_remove();
						$('#notification_count').text(json.count);
						if (json.count*1==0) {$('#notification_count').parent().hide();} else {$('#notification_count').parent().show();}								
					}
				}
			}
		});
		
	}, 60000);		
	
	
	//wall stuff
	$('.cm_collapsed').live("focus", function(){
		$(this).removeClass('cm_collapsed').focus();
		$(this).closest('li').removeClass('collapsed').find('.avatar, .buttons').show();
	})		
	
	if ($('#wall_upload').length > 0) {
		var wall_upload = new AjaxUpload($('#wall_upload'),{
			action: $("#ajaxLink").val()+'?action=wall_upload&entry_id='+$('#entry_id').val()+'&entry_type='+$('#entry_type').val(), name: 'uploadfile', autoSubmit: true,
			onSubmit : function(file, ext){showLoading($('#share'));},
			onComplete: function(file, response){
				removeLoading($('#share'));
				json = jsonQuery(response);
				
				if (json == null || isNaN(json.rv)) {_alert('error', $('#unhandledErr').val());
				} else if (json.rv != 1){_alert('error', json.rt);
				} else {
					var attach = $('#share_attach');
					$(attach).attr('alt', json.uid);
					$(attach).find('.name').text(json.name);
					$(attach).find('.size').text(json.size);
					$('#share_attach_btn').hide();	
					$(attach).show();	
				}
			}
		});			
	}		
	
	
	//startup edit
	if ($('#draft_upload').length > 0) {
		var darft_upload_block = $('#draft_files');
		var draft_upload = new AjaxUpload($('#draft_upload'),{
			action: $("#ajaxLink").val()+'?action=plan_draft_file_upload&project='+$('#draft_upload').attr('alt'), name: 'uploadfile', autoSubmit: true,
			onSubmit : function(file, ext){showLoading(darft_upload_block);},
			onComplete: function(file, response){
				removeLoading(darft_upload_block);
				json = jsonQuery(response);

				if (json == null || isNaN(json.rv)) {_alert('error', $('#unhandledErr').val());
				} else if (json.rv != 1){_alert('error', json.rt);
				} else {$('#draft_upload').closest('li').before('<li><div class="view"><div class="right"><div class="buttons small"><div class="remove"><a class="xremove" href="#" onclick="$(this).closest(\'li\').remove(); return false;">&nbsp;</a></div></div></div><input type="hidden" class="post" name="file[]" value="'+json.id+'"/><p class="position">'+json.name+' ('+json.size+')</p></div></li>');	}
			}
		});			
	}	
	
	
	
//	//upload/crop
//	if ($('#avatarUpload').length > 0) {
//		var inner_section = $('.inner-section:first');
//		new AjaxUpload($('#avatarUpload'),{
//			action: $("#ajaxLink").val()+'?action='+$('#avatarUpload').attr('alt'), name: 'uploadfile',
//			onSubmit : function(file, ext){showLoading(inner_section);},
//			onComplete: function(file, response){
//				removeLoading(inner_section);
//				json = jsonQuery(response);
//				if (json == null || isNaN(json.rv)) { _alert('notify error', $('#unhandledErr').val());
//				} else if (json.rv != 1){ _alert('notify error', json.rt);
//				} else {
//					if (json.rt_crop == 0) {$('#profileAvatar').attr('src', json.rt_path); return;}
//					$('#crop_box').attr('src', ''); $('#crop_preview').attr('src', '');
//					var link = json.rt_path; var width = json.rt_width; var height = json.rt_height; 
//					$('#crop_height').val(height); $('#crop_width').val(width);
//					$('#crop_box').css({width: width + 'px', height: height + 'px'});					
//					$('#crop_box').attr('src', link); $('#crop_preview').attr('src', link); $('#crop_holder').find('input[name=link]').val(link);
//					$('#crop_box').imgAreaSelect({aspectRatio: '1:1', onSelectChange: showPreview, parent: '#crop_holder', x1: 0, y1: 0, x2: 160, y2: 160});	
//					$('#crop_holder').parent().children('.wrapper').toggle();
//				}
//			}
//		});
//		
//		
//		
//	}
	
	
	
	
})


function crop_picture(){
	h = $('body:first');
	showLoading(h);
	ajaxCall(getPostFields($('#crop_holder')), function(){ removeLoading(h); },  function(){ go(json.url); })
	return false;
}

function formaction(element) {
	var form = $(element).closest('.formaction');
	showLoading(form);
	ajaxCall(
			getPostFields(form),
			function(){ removeLoading(form); },
			function(){ 
				if (form.hasClass('formaction_toggle')) {
					form.hide();
					form.parent().children('.formaction_toggle_note').show();
				} else if (isValue(form.attr('alt'))) {
					eval(form.attr('alt'));
				}
			}
	)	
	return false;
}

function quickaction(action, obj_load) {
	showLoading($(obj_load));
	ajaxCall(
			'action='+action,
			function(){ removeLoading($(obj_load)); },
			function(){ 
				if (isValue(json.rt)) {_alert('success', json.rt);}
				if (isValue(json.js)) {eval(json.js);} 					
			}
	)
	return false;
}


function newmodal_submit(btn) {
	var modal = $(btn).closest('.newmodal');
	
	$(modal).find('.modal_error').hide();
	var wrapper = $(modal).find('.wrapper:first');
	showLoading(wrapper);

	var data = getPostFields($(modal).find('.modal_inner'));
	
	$.ajax({
		type: "POST", url: $("#ajaxLink").val(), data: data,
		success: function(msg){
		removeLoading(wrapper);
		json = jsonQuery(msg);
		if (json == null || isNaN(json.rv)) {
			$(modal).find('.modal_error').html($('#unhandledErr').val()).show(); $(modal).find('.modal_inner').show();
		} else if (json.rv != 1){
			$(modal).find('.modal_error').html( isValue(json.rt)?json.rt:$('#unhandledErr').val() ).show(); $(modal).find('.modal_inner').show();
		} else {
			newmodal_remove();
			$(modal).find('.modal_inner').hide();
			$(modal).find('.buttons').hide();
//			if (isValue(json.rt)) {$(modal).find('.modal_notify').html(isValue(json.rt)?json.rt:'Action completed successfully').show();}
			if (isValue(json.rt)) { _alert("success", json.rt);}
			if (isValue(json.js)) {eval(json.js);}
		}
	}
	});	
	
	return false;
}


function newmodal(action) {
	newmodal_remove();
	var html = '';
	html += '<div class="modal newmodal">';
		html += '<div class="overlay"></div>';
		html += '<div class="modal-content"><div class="modal-inside"><div class="wrapper">';
		
			html += '<div class="titlebox">';
				html += '<div class="right"><a href="#" id="modal_login_close" onclick="return newmodal_remove();" class="xremove">&nbsp;</a></div>';
				html += '<h3 class="modal_title">Loading..</h3>';
			html += '</div>';
			
			html += '<div class="modal-main">';
				html += '<div class="notify error modal_error" style="display:none"></div>';
				html += '<div class="notify modal_notify" style="display:none"></div>';
				html += '<div class="modal_inner"></div>';
			html += '</div>';
			
			html += '<div class="modal-confirm" style="display:none;"><div class="buttons">';
				html += '<div class="button"><a class="btn-primary" href="#" onclick="return newmodal_submit(this);">Send</a></div>';
				html += '<div class="alt"><a href="#" class="cancel" onclick="return newmodal_remove();">Cancel</a></div>';
			html += '</div></div>';
			
		html += '</div></div></div>';
	html += '</div>';
	
	$('body').append(html);
	
	var modal = $('body').find('.newmodal:last');
	var modal_content = modal.find('.modal-content');
	modal_content.bind('click', function(e){e.stopPropagation();});
	var overlay = modal.find('.overlay');
	// positioning;	
	newmodal_position(modal_content, overlay);
	
	var wrapper = $(modal).find('.modal-main:first');
	showLoading(wrapper);
	
	ajaxCall('action='+action, 
			function(){modal.find('.modal_title').html('&nbsp;'); removeLoading(wrapper);}, 
			function(){
				modal.find('.modal_title').text(json.modal_title); modal.find('.modal_inner').html(json.modal_inner); 
				if (json.modal_btn != undefined){
					modal.find('.modal-confirm').show().find('.btn-primary').text(json.modal_btn);  
					if (json.modal_btn_cancel != undefined) modal.find('.modal-confirm').find('.cancel').text(json.modal_btn_cancel);  
				} 
				newmodal_position(modal_content, overlay);
			},  
			modal.find('.modal_error')
			)
	return false;
}

function newmodal_position(modal_content, overlay) {
	var _clientWidth = (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth);
	var _clientHeight = (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight);
	var _scrollHeight = (document.documentElement.scrollHeight ? document.documentElement.scrollHeight : document.body.scrollHeight);
	var _scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	var _top = (_clientHeight - modal_content.height())/2 + _scrollTop;
	if( _top < 0 ){ _top = 12 }
	modal_content.css({'top': _top+'px'});
	overlay.css({'height': _scrollHeight+'px'});	
}

function newmodal_remove() {$('.newmodal').remove(); return false;}

function quickp_hide() {$('.quickprofile').hide(); return false;}

function quickp(obj, id){
	quickp_hide();
	
	var qid = 'quickprofile_'+id;
	var qprofile = $('.'+qid);
	
	if (qprofile.length == 0) {
		var html = '';
		html += '';
		html += '<div class="quickprofile '+qid+'"><div class="tip-wrapper"><div class="tip-content-wrapper">';
		html += '<div class="tip-content">';
			html += '<div class="right"><a href="#" onclick="return quickp_hide();" class="xremove">&nbsp;</a></div>';
			html += '<div class="q-notify notify" style="display:none"></div>';
			html += '<div class="profile q-content"></div>';
		html += '</div>';
		html += '<div class="tip-arr"></div>';
		html += '</div></div></div>';
		
		$('body').append(html);
		var qprofile = $('.'+qid);
		qprofile.css({'position': 'absolute', 'width': '600px'});
			
		var content = $(qprofile).find('.tip-content:first');
		showLoading(content);
		
		ajaxCall('action=user_quick_profile&id='+id, 
				function(){removeLoading(content);}, 
				function(){qprofile.find('.q-content').html(json.html); quickp_position(obj, qprofile); },  
				qprofile.find('.q-notify')
		);
	} else {
		qprofile.show();
	}
	
	
	//$('body').bind('click', function(e){ quickp_hide(); });
	qprofile.bind('click', function(e){ e.stopPropagation(); });
	quickp_position(obj, qprofile);
	
	
	return false;
}

function quickp_position(obj, qprofile) {
	var _x;
	var _y;
	var shift = 0;
	if(obj.outerHeight() < 40){
		var shift = (40 - obj.outerHeight())/2;
		qprofile.css({'height': 40+'px' });
	} else {
		qprofile.css({'height': obj.outerHeight()+'px'});
	}
	var foldback = -(qprofile.find('.tip-wrapper').height()-qprofile.height())/2;
	qprofile.find('.tip-wrapper').css({'position': 'relative','top': foldback+'px','left': obj.outerWidth()+5+'px'});
	_x = obj.offset().left;
	_y = obj.offset().top - shift;
	qprofile.css({'top': _y+'px', 'left': _x+'px'});	
}


//loading
function showLoading(into) {
	var loaders = into.find('.hu-loading');
	if( loaders.length == 0 ) {
		into.css({'position': 'relative'}).append(getLoading());
	}
}
function removeLoading(from) {
	from.removeAttr('style');
	from.find('.hu-loading').remove();
}

function getLoading() {
	var img = $('<img src="http://www.humanipo.com/img/ajax-loader.gif">').addClass('hu-loader-img').css({'border': 'none', 'position': 'relative', 'top': '50%'});
	var loader = $('<div>').addClass('hu-loading').css(
		{'position': 'absolute',
		 'top': 0,
		 'bottom': 0,
		 'left': 0,
		 'right': 0,
		 'background-image': 'url(http://www.humanipo.com/img/white88.png)',
		 'background-repeat': 'repeat',
		 'background-color': 'transparent',
		 'text-align': 'center'
		}).append(img);
	return loader;
}


function jsonQuery(str){try{return eval("(" + str + ")");}catch(exception){return null;}}


function ajaxCall(data, callback, success, error_element) {
	$.ajax({
		type: "POST",url: $("#ajaxLink").val(),data: data,	
		success: function(msg){
			json = jsonQuery(msg);
			callback();
			if (json == null || isNaN(json.rv) || json.rv != 1) {
				var err = $('#unhandledErr').val();
				if (json != null && isValue(json.rt)) err = json.rt;
				if (error_element != undefined) {					
					if(error_element=='alert') { _alert('error', err);
					} else if(error_element=='none') { //do nothing
					} else { if ($(error_element).length>0) {$(error_element).html(err).show();} }
					
				} else {
					_alert('error', err);
				}
			} else {
				success();
			}
		}
	
	});	
}

function getPostFields(form, class_name) {
	var data = '';
	if (class_name == undefined) class_name = 'post';
	$(form).find('.'+class_name).each(function(index) {
		var val = $(this).val();
		if ($(this).attr('type') == 'checkbox') {
			if ($(this).is(':checked')) {if(val.length == 0) { val = 1;}} else {return;}
		} else if ($(this).attr('type') == 'radio') {
			if ($(this).is(':checked')) {val = val;} else {return;}
		} else {
			var ph = $(this).attr('placeholder');
			if (ph != undefined && ph == val) return;
		}
		if (data != '') data = data + '&';
		data = data + $(this).attr('name')+"="+encodeURIComponent(val);
	}); 
	return data;
}

function go(url, time) {
	if (isValue(url)) {
		if (isValue(time)) {setTimeout(function() {window.location.href = url}, time);} else {window.location.href = url;}
	} else {
		if (isValue(time)) {setTimeout(function() {location.reload()}, time);} else {location.reload();}
	}
}

function isValue(value) {
	if (value != undefined && value != null && value.length != 0) return true;
	return false;
}

function toggleEdit(obj, onOff){
	if( onOff == true ){obj.closest('.view').hide().next('.modify').show();
	} else {obj.closest('.modify').hide().prev('.view').show();}
	return false;
}

function saveEdit(obj, switchDraft) {
	var form = $(obj).parents('.modify:first');
	var view = $(form).parent().children('.view:first');
	showLoading(form);
	ajaxCall(getPostFields(form), 
			function(){removeLoading(form);}, 
			function(){
				toggleEdit(obj, false);
				$('.unversioned_draft').show();
				if (switchDraft == true) {$(view).find('.version_switch').click(); $(view).find('.plan_draft').show(); $(view).find('.nocontent').hide();}
				$(form).find('.clean').each(function(){$(this).val('').blur()})
				if (json.js != undefined) eval(json.js);
				if (json.cdata != undefined) {
					$.each(json.cdata, function(k, v) {
						$(view).find('.'+k).html(v+' '); 
						if (k=='cd_name' || k=='cd_headline'){$('body').find('.'+k).text(v);} 
						if (k=='cd_general_meta' || k=='cd_teaser_meta' || k=='cd_summary_meta'){$(view).find('.'+k).parent().show();} 
					});
				} else if (json.html != undefined) {
					$(form).parent().before(json.html);
				}
			});
	return false;
}


function _alert(type, msg){
	var alrt = $('#alert_global').show();
	var alrt_content = alrt.find('.outer-wrapper');
	var alrt_msg = $('#alert_msg');
	alrt_msg.attr('class','');
	alrt_msg.html(msg);
	if(!alrt_msg.hasClass(type)) alrt_msg.addClass('notify').addClass(type);

	var _clientWidth = (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth);
	var _clientHeight = (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight);
	var _scrollHeight = (document.documentElement.scrollHeight ? document.documentElement.scrollHeight : document.body.scrollHeight);
	var _scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	var _top = (_clientHeight - alrt_content.height())/2 + _scrollTop;
	alrt_content.css({'top': _top+'px'});
	alrt.find('.over').css({'height': _scrollHeight+'px'});
}

//my profile stuff
function deleteEdit(obj, act, entry) {
	var h = $(obj).closest('.view');
	showLoading(h);
	ajaxCall('action='+act+'&id='+entry, 
			function(){removeLoading(h);}, 
			function(){$(h).parent().remove();} 
	)
	return false;
}

function privacyChange(obj, module) {
	var p = $(obj).parent();
	var h = $(obj).closest('.fn_privacy');
	$(h).children().hide();
	var data = "action=user_profile_access_change&module=" + module;
	ajaxCall(data, function(){}, function(){ $(h).children().show(); $(p).hide(); });
	return false;
}
//


////////wall stuff

function wallGroupPicker(obj, sevent){
	sevent.stopPropagation(); 
	var obj = $(obj);
	var picker = $('#wall_group_picker');
	
	$("body").bind("click", function( event ) { picker.hide(); $(this).unbind( event );});	
	picker.bind('click', function(e){ e.stopPropagation(); });
	
	// positioning
	var _x = (obj.position().left+(obj.outerWidth()/2))-(picker.outerWidth()/2);
	var _y = obj.position().top + obj.outerHeight()+5;
	picker.css({'position': 'absolute', 'top': _y+'px', 'left': _x+'px'}).show();
	return false;
}


function dropnav(obj, id){
	$('#'+id+'fn').remove();
	$('.more-options').hide();
	$('.dropnav').removeClass('pressed');
	var options = $('#'+id).clone();
	$(options).attr('id', $(options).attr('id')+'fn');
	var opt_wrap = options.find('.wrapper');
	options.bind('mouseleave', function(event){
		$(this).remove();
		obj.removeClass('pressed');
	}).show();
	$('body').append(options);
	options.css({'height': opt_wrap.outerHeight()+100+'px', 'width': opt_wrap.outerWidth()+100+'px'});
	obj.addClass('pressed');
	var _x = obj.position().left;
	var _y = obj.position().top + obj.outerHeight();
	options.css({'position': 'absolute', 'top': _y, 'left': _x, 'z-index': 666});
	return false;
}

function wallPost(obj, group) {
	var tarea = $('#share_input');
	var text = $(tarea).val();
	$('#wall_group_picker').hide();
	if (text == '' || text == $(tarea).attr('placeholder')) {$(tarea).parent().addClass('error'); return false;}
	$(tarea).parent().removeClass('error');
	showLoading($('#share'));
	
	ajaxCall('action=wall_post&entry_id='+$('#entry_id').val()+'&entry_type='+$('#entry_type').val()+'&text='+encodeURIComponent(text)+'&share_attach='+$('#share_attach').attr('alt')+'&group='+group,
			function(){removeLoading($('#share'));},
			function(){
						$(tarea).css({'height':'1.2em', 'line-height':'1.1em'}).val('').trigger('blur');
						$('#feed').prepend(json.html);
						$('#feed .feed_empty').remove();
						wallPostAttachClean();})
	return false;	
}

function wallPostAttachClean() {
	$('#share_attach').attr('alt', '');
	$('#share_attach').hide();
	$('#share_attach_btn').show();
	return false;
}

function wallPostReply(obj, parent) {
	var loader = $(obj).parents('li.modify:first');
	var tarea = $(loader).find('.tarea:first');
	var text = $(tarea).val();
	if (text == '' || text == $(tarea).attr('placeholder')) return false;
	showLoading(loader);
	
	ajaxCall('action=wall_post&parent='+parent+'&text='+encodeURIComponent(text),
		function(){removeLoading(loader);},
		function(){wallHideAddComment(tarea); $(loader).before(json.html); $(obj).parent().find('a').click(); $(tarea).attr('style','');
		})
	return false;	
}

function postShowReplies(obj) {
	var msg = $(obj).parents('.msg:first');
	$(msg).find('ul.replies li.feedpost').show();
	$(obj).parent().remove();
	return false;
}

function postDelete(obj) {
	return newmodal("wall_post_delete_modal&post_id="+$(obj).closest('li').attr('alt'));
}

function postLike(obj, like) {
	$(obj).hide();
	var msg = $(obj).parents('.feedpost:first');
	ajaxCall('action=wall_post_like&post_id='+$(msg).attr('alt')+'&like='+like, 
			function(){$(obj).show();}, 
			function(){
				if (like == 1) {
					$(msg).find('.x_unlike').hide(); $(msg).find('.x_like').show();					
				} else {
					$(msg).find('.x_like').hide(); $(msg).find('.x_unlike').show();
				}
			});
	return false;	
}

function activityGet(before) {
	var type = 1;
	var data = 'action=activity_get&type='+$('#feed_filter li.selected').attr('alt')+'&before='+before;
	var feed = $('#feed');	
	if (feed.length == 0) return false;
	$('#show_next').attr('alt','').parent().hide();
	showLoading(feed);
	ajaxCall(data,
			function(){removeLoading(feed);},
			function(){
				if (json.before != undefined) $('#show_next').attr('alt',json.before).parent().show(); 
				$(feed).append(json.html);
				autosize_apply();
				$('span.tip').tipsy({fade:true, gravity: 's'});				
			}
	)
	return false;
}

function wallGet(before_post_id, after_post_id, post_id, clean) {
	var data = 'action=wall_get&entry_type='+$('#entry_type').val()+'&entry_id='+$('#entry_id').val()+'&before_post_id='+before_post_id+'&after_post_id='+after_post_id+'&post_id='+post_id;
	var feed = $('#feed');
	if (feed.length == 0) return false;
	if (clean == true) $(feed).html('');
	
	if (!isNaN(post_id) || !isNaN(before_post_id))$('#show_prev').attr('alt','').parent().hide();
	if (!isNaN(post_id) || !isNaN(after_post_id))$('#show_next').attr('alt','').parent().hide();

	showLoading(feed);
	ajaxCall(data, 
			function(){removeLoading(feed)}, 
			function(){
				$(feed).find('.feed_empty').remove();
				if (json.direction != undefined && json.direction == '0') {$(feed).prepend(json.html);} else {$(feed).append(json.html);}
				
				if (json.first_post_id != undefined) {
					$('#show_prev').attr('alt','').parent().hide();
					if (json.first_post_id.length > 0) $('#show_prev').attr('alt', json.first_post_id).parent().show();					
				}
				if (json.last_post_id != undefined) {
					$('#show_next').attr('alt','').parent().hide();
					if (json.last_post_id.length > 0) $('#show_next').attr('alt', json.last_post_id).parent().show();					
				}
				
				if (!isNaN(post_id)) $('#feed').children('li[alt='+post_id+']').addClass('focus').prepend($('#focus').html());
				autosize_apply();
				$('span.tip').tipsy({fade:true, gravity: 's'});
	});
}

function wallShowAddComment(obj) {
	$(obj).closest('.msg').find('ul.replies li.modify').find('textarea').focus();
	return false;
}
function wallHideAddComment(obj) {
	$(obj).closest('li').addClass('collapsed').find('.avatar, .buttons').hide();
	$(obj).closest('li').find('textarea').val('').blur().addClass('cm_collapsed');
	return false;
}
////////wal stuff end


//project draft
function versionCopy(obj) {
	$(obj).closest('.block').find('textarea.post').val($(obj).closest('.block').find('.x_version').val());
	return false;
}

function draftSave() {
	var h = $('#draft_data');
	showLoading(h);
	ajaxCall(getPostFields(h), function(){removeLoading(h);}, function(){$('#draft_buttons').remove(); _alert('success', json.rt); go(json.url, 1500);})
	return false;
}
//end project draft

function newsActionConfirm(id) {
	$('#msg_accept_btn_'+id).attr('alt', 1);
	newmodal_remove();
	$('#msg_accept_btn_'+id).click();
	return false;
}

function newsAction(obj, news_id, accept, right_side) {
	var news = $(obj).closest('li');
	var buttons = $(obj).closest('.buttons');
	showLoading(news);	
	ajaxCall('action=news_action&id='+news_id+'&accept='+accept+'&confirm='+$(obj).attr('alt')+'&token='+$(news).attr('alt'), 
			function(){removeLoading(news); $(news).removeClass('new');}, 
			function(){  
				if (json.modal_param!=undefined) {
					newmodal(json.modal_param);		
				} else {
					var note = json.rt;
					if (json.redirect!=undefined) {go($(obj).attr('href')); note='Redirecting...'} 
					
					if (right_side) {
						var ul = news.closest('ul');
						news.remove();
						if (ul.children().length>0) { ul.find('li:first').show(); } else { ul.closest('.block').hide(); }
						
					} else {
						if (isValue(note)) $(buttons).before('<div class="status"><em>'+note+'</em></div>');
						$(buttons).remove(); 																	
					}
				}
				
				var count = $('#notification_count').text();
				if (!isNaN(count)) {var newcount = count*1-1; $('#notification_count').text(newcount);  if (newcount*1==0) {$('#notification_count').parent().hide();} }			
			}
	)
	return false;
}

function switchTab(obj, tab_class, tab_index) {
	$(obj).closest('ul').children().removeClass('selected');
	$(obj).closest('li').addClass('selected');
	$('.'+tab_class).hide();
	$('.'+tab_class+'_'+tab_index).show();
	if ($('.'+tab_class+'_'+tab_index+'_right').find('ul:first').children().length>0) $('.'+tab_class+'_'+tab_index+'_right').show();
	return false;
}


function planInterest(obj, id, type) {
	var h = $(obj).closest('.block');
	showLoading(h);
	var active = 0;
	if ($(obj).is(':checked')) active = 1;
	ajaxCall('action=plan_interest&active='+active+'&project='+id+'&type='+type, function(){removeLoading(h);}, function(){});
}

function planShareRegister(id, type) {
	ajaxCall('action=plan_share_register&type='+type+'&id='+id, function(){}, function(){}, 'none');
}

function notificationsSaveAll(obj, type) {
	var h = $(obj).closest('.settings');
	showLoading(h);
	ajaxCall('action=notifications_save_all&type='+type+'&'+getPostFields(h), function(){removeLoading(h);}, function(){_alert('success', json.rt); go(null, 1000); });
	return false;
}

//function linkedinImportInitial(profile_url) {
//	$.ajax({
//		type: "POST",url: $("#ajaxLink").val(),data: 'action=linkedin_import_initial',	
//		success: function(msg){
//			json = jsonQuery(msg);
//			if (json == null || isNaN(json.rv) || json.rv != 1) { go(profile_url); } else { go(json.url); }
//		}
//	});	
//}

function moreText(obj) {$(obj).hide().parent().children('.mrtx').show(); return false;}


function showPreview(img, selection){
	if (parseInt(selection.width) > 0)
	{
		var rx = 160 / selection.width;
		var ry = 160 / selection.height;
		
		width = $('#crop_width').val();
		height = $('#crop_height').val();
		
		mLeft = Math.round(rx * selection.x1);
		mTop = Math.round(ry * selection.y1);

		$('#crop_preview').css({
			width: Math.round(rx * width) + 'px',
			height: Math.round(ry * height) + 'px',
			marginLeft: '-' + mLeft + 'px',
			marginTop: '-' + mTop + 'px'
		});
		
		$('#crop_x').val(selection.x1);
		$('#crop_y').val(selection.y1);
		$('#crop_x2').val(selection.width);
	}
}

function showPreviewBlog(img, selection){
	if (parseInt(selection.width) > 0)
	{
		var rx = 300 / selection.width;
		var ry = 200 / selection.height;
		
		width = $('#crop_width').val();
		height = $('#crop_height').val();
		
		mLeft = Math.round(rx * selection.x1);
		mTop = Math.round(ry * selection.y1);
		
		$('#crop_preview').css({
			width: Math.round(rx * width) + 'px',
			height: Math.round(ry * height) + 'px',
			marginLeft: '-' + mLeft + 'px',
			marginTop: '-' + mTop + 'px'
		});
		
		$('#crop_x').val(selection.x1);
		$('#crop_y').val(selection.y1);
		$('#crop_x2').val(selection.width);
		$('#crop_y2').val(selection.height);
	}
}


function peopleLiveSearch(nchange, nmore) {
	var n = $('#people_live_search').val().toLowerCase();
	var l = $('#people_live_location').val();
	var i = $('#people_live_industry').val();
	var more = $('#more');
	var max = more.attr('alt');
	var max_default = more.attr('default');
	var count = 1;

	if (nchange) {
		if ($('#people_live_search').attr('alt')==n) return;
		$('#people_live_search').attr('alt', n);		
	}
	
	if (nmore) max = max*1 + max_default*1;
	more.attr('alt', max);

	$('li.u_li').each(function(k, item){
		var hide = false;
		if (count>max) hide = true;
		if (!hide && l.length>0 && !$(item).hasClass('u_l_'+l)) hide = true;
		if (!hide && i.length>0 && !$(item).hasClass('u_i_'+i)) hide = true;
		if (!hide && n.length>0 && ($(item).attr('alt').indexOf(n)<=-1) ) hide = true;
		
		if (hide) {
			$(item).hide();
		} else {
			if ($(item).hasClass('u_img')) {
				var avatar = $(item).find('.avatar img'); 
				$(avatar).attr('src', avatar.parent().attr('alt')).show();
//				$(avatar).html('<img width="50" height="50" src="'+avatar.attr('alt')+'"/>');
				$(item).removeClass('u_img');
			}
			$(item).show();
			count++;
		}
	});	
	
	if (count>max) {more.show();} else {more.hide();}
}	


function user_follow(obj, id) {
	$(obj).hide();
	ajaxCall(
			'action=user_follow&id='+id+'&follow='+$(obj).attr('alt'),
			function(){ $(obj).show(); },
			function(){ $(obj).text(json.text).attr('class', json.classname+'').attr('alt', json.alt+''); }
	);
	return false;
}

function acc_follow(obj, id) {
	$(obj).hide();
	ajaxCall(
			'action=acc_follow&id='+id+'&follow='+$(obj).attr('alt'),
			function(){ $(obj).show(); },
			function(){ $(obj).text(json.text).attr('class', json.classname+'').attr('alt', json.alt+''); }
	);
	return false;
}

function plan_favourite(obj, id) {
	$(obj).parent().hide();
	var favourite = 1;
	if ($(obj).parent().hasClass('active')) favourite = 0;
	ajaxCall(
			'action=plan_favourite&id='+id+'&favourite='+favourite,
			function(){ $(obj).parent().show(); },
			function(){ if (json.favourite==1) {$(obj).parent().addClass('active')} else {$(obj).parent().removeClass('active')}; }
	);
	return false;
}

function autosize_apply() {
	$('.autoresize').autosize({
	 	//onResize : function() {$(this).css({opacity:0.8});},
	    animateCallback : function() {$(this).css({opacity:1});},
	    animateDuration : 300,
    	extraSpace : 40
	}).removeClass('autoresize');	
}

function linkedinWindow(base, action, ref) {
	var newwindow=window.open(base+"/"+action+"?ref="+ref+"&remember="+($("#remember_me").is(":checked")?1:0),"Connect","height=500,width=600");
	if (window.focus) {
		newwindow.focus();
	}
	return false;	
}

function facebookWindow(base, action, ref) {
	var newwindow=window.open(base+"?action="+action+"&ref="+ref+"&remember="+($("#remember_me").is(":checked")?1:0),"Connect","height=500,width=600");
	if (window.focus) {
		newwindow.focus();
	}
	return false;	
}

function slide(objUp, objDown) {
	objUp.slideUp(250, function(e){
		objUp.hide();
		objDown.slideDown(250);
	});	
}

function quickToggle(selected, entry_data, group_uid) {
	$(selected).closest('ul').children().removeClass('selected').addClass('disabled');
	$(selected).parent().removeClass('disabled').addClass('selected');
	
	$('.qp_group_post').hide();
	if (isValue(group_uid)) {
		$('#qp_button_post').hide();
		$('#qp_button_post_to').attr('alt', group_uid).show();
	} else {
		$('#qp_button_post').attr('alt', entry_data).show();		
		$('#qp_button_post_to').hide();
	}
	
	$('#qp_links').children().hide();
	$('#qp_link_'+entry_data).show();
	
	
	return false;
}

function quickGroupPicker(obj, sevent){
	sevent.stopPropagation(); 
	var obj = $(obj);
	var picker = $('#qp_group_post_'+obj.attr('alt'));
	
	$("body").bind("click", function( event ) { picker.hide(); $(this).unbind( event );});	
	picker.bind('click', function(e){ e.stopPropagation(); });
	
	// positioning
	var _x = (obj.position().left+(obj.outerWidth()/2))-(picker.outerWidth()/2);
	var _y = obj.position().top + obj.outerHeight()+5;
	picker.css({'position': 'absolute', 'top': _y+'px', 'left': _x+'px'}).show();
	return false;
}

function quickPost(obj, group) {
	var tarea = $('#quick_input');
	var text = $(tarea).val();
	$('.qp_group_post').hide();
	if (text == '' || text == $(tarea).attr('placeholder')) {$(tarea).parent().addClass('error'); return false;}
	$(tarea).parent().removeClass('error');
	showLoading($('#qp_holder'));
	var entry_data = $(obj).attr('alt').split('_');
	
	ajaxCall('action=wall_post&quick=1&entry_id='+entry_data[1]+'&entry_type='+entry_data[0]+'&text='+encodeURIComponent(text)+'&share_attach='+$('#share_attach').attr('alt')+'&group='+group,
			function(){removeLoading($('#qp_holder'));},
			function(){
						$(tarea).val('').trigger('blur');
						$('#qp_feed').html(json.html);
						slide($('#qp_post'), $('#qp_posted'));
//						wallPostAttachClean();
			})
	return false;	
}
