$(document).ready(function() {
  $(".activity div.clist-item").hover(function(){$(this).find(".act-hider").show();}, function(){$(this).find(".act-hider").hide();})
  $("textarea.resizable:not(.processed), div.resizable:not(.processed)").TextAreaResizer();
  $('textarea.expanding').autogrow({maxHeight:192,minHeight:40,lineHeight:16});
  $("textarea.selrte").keydown(selupdate).keyup(selupdate).mousedown(selupdate).mouseup(selupdate).focus(selupdate);
  //$("textarea.selrte").mousemove(selupdate);
  $("input[type='submit']").dblclick(function(){return false;});
  $(".tooltip-link").mousedown(function(){var o=$(this).offset();var b=$("#root").offset();leftVal=o.left-b.left;topVal=o.top-b.top;});
  $("a[href^='#q']").click(faqlink);faqlink();syminfo();
  $("span.button input").focus(function(){$(this).parents(".button").addClass("button-focus");}).blur(function(){$(this).parents(".button").removeClass("button-focus");});
  try{$("a.mp_zoom, a.p_zoom").fancybox({'hideOnOverlayClick':true,'padding':21,'zoomSpeedChange':0,'easingChange':0});}catch(e){}
  if(!jQuery.supported() && $("#supported_brw").length)$("#supported_brw").show();
  $.ajaxSetup({cache: false});
});

var leftVal=0;var topVal=0;
function show_tt(e){tt.show(e);}
function hide_tt(e){tt.hide(e);}

var tt={
  str:null,
  obj:null,
  show:function(e){
    obj=$(this);
    str=obj.attr("title");
    obj.attr("title","");
    $("#tooltip div.bodytext").text(str);
    $("#tooltip").show(400);
  },
  hide:function(e){
    obj.attr("title",str);
    $("#tooltip").hide();
  }
}

function update(d) {
  var r = false;
  if((d!='')&&(d!='error')) {
    for(var i=0;i<$(d).length;i++){
      var o=$(d).eq(i);
      var id=o.attr("id");
      if (id){
        switch(id){
          case'res':r=o.html();break;
          case'url':r=o.text();location.assign(r);return true;break;
          case'reload':location.reload(true);return true;break;
          case'chg_title':document.title = o.text();break;
          case'sharp':
            document.location = '#'+o.text();
            break;
          default :
            if(!$("#"+id).length){
              if(o.hasClass("tooltip")){
                aat=true;$('body').click(function(){p_destroy(id);aat=false;});                
                o.click(function(e){e.stopPropagation();});                
                $("#page-body").append(o);o.hide();
                if(o.hasClass("tooltip-b")) o.css("left",(leftVal-o.width()/2+16)+"px").css("top",(topVal-o.height()-8)+"px");
                else o.css("left",leftVal+"px").css("top",(topVal+20)+"px");
                o.show();
              }
              if(o.hasClass("popup")){$("body").append(o);$("div.page select").addClass("hidden");o.show();}
              $(".fcs").focus();
            } else if((o.html()=='')&&($("#"+id))){$("#"+id).remove();
            } else {
              $("#"+id).replaceWith(o);o.hide();
              if(o.hasClass("tooltip")){
                $('body').click(function(){p_destroy(id);aat=false;});                
                o.click(function(e){e.stopPropagation();});
                if(o.hasClass("tooltip-b")) o.css("left",(leftVal-o.width()/2+16)+"px").css("top",(topVal-o.height()-8)+"px");
                else o.css("left",leftVal+"px").css("top",(topVal+20)+"px");
              }
              o.show();
            }
        }
      }
    }
    try{init_div();}catch(e){}
  }
//  if(r) return r;
  return r;
}
function p_destroy(id){$("#"+id).remove();$("div.page select").removeClass("hidden");}
function process(o){o.hide().next().show();}
function demand(u){$.get(u, "html", update);}
function preview(id){var f=$("#"+id).parents().find("form");$.post("/image/popup/rte_preview?rte_area="+id,f.serialize(),"html",update)};
function postform(id,url){var f=$("#"+id);$.post((url||f.attr("action")),f.serialize(),function(r){update(r);});}
function chk_log(){$('#login_submit').hide().next().show();$.getJSON("/login/check?"+$("#login_form").serialize(),function(r){if(r.status=="done"){location.reload(true);}else{$("#errmsg p").html(r.error);$("#errmsg").show();$('#login_submit').show().next().hide();}});}
function cls_log() {$("#login").remove();}
function faqlink(){$(".anchor").removeClass("anchoract");$("#"+(($(this).attr("href")||location.href).split("#")[1])).addClass("anchoract");}
function syminfo(){if($("#symchg").length && $("#symval").length){var o=$("#symval").offset();var b=$("#user-bar").offset();$("#symchg").css("left",(o.left-b.left+32)+"px").css("top",(o.top-b.top-58)+"px").fadeIn("slow",function(){$(this).animate({opacity:1},2000,function(){$(this).fadeOut("slow");});});}}

function ajaxFileUpload(i){
    if($("#file_to_upload").val()!=""){
      $.ajaxFileUpload({
        url:'/profile/action/upload_photo?uid='+i+'&r='+Math.random(),
        secureuri:false,
        fileElementId:'file_to_upload',
        dataType: 'json',
        success: function (data, status) {
          $("#file_to_upload").val("");
          if(typeof(data.error) != 'undefined'){
            if(data.error != ''){alert(data.error);} 
            else {
              if (data.msg!=""){imgPath=data.msg;$("#mp").attr("src",imgPath);} 
              else {alert("File uploading error.");}
            }
          }
        },
        error: function (data, status, e){alert(e);}
        }
      );
    }
    return false;
  };
var aai=false;
var aat=false;
function ajaxAddImage(){
  if(aai)return false;aai=true;var v=$("#image_alt").val();
  if($('#image_file').val()!="") {
    // $('#target_f').val("1");
    $.ajaxFileUpload({
      url:"/image/action/add_image?"+$('#add_image').serialize(),
      secureuri:false,
      fileElementId:'image_file',
      dataType: 'text',
      success: function(r){var t=update(r);if(t)doIns('[img]'+t+'[/img]');aai=false;},
      error: function(r){update(r);aai=false}
      }
    );
  } else {
    //$('#target_f').val("0");
    $.post("/image/action/add_image?"+$('#add_image').serialize(),function(r){var t=update(r);if(t)doIns("[img]"+t+"[/img]");aai=false});
  }
}
function ajaxAddPhoto(){
  if(aai)return false;aai=true;var v=$("#photo_title").val();
  if($('#photo_file').val()!="") {
    $.ajaxFileUpload({
      url:"/photos/action/photo_create?"+$('#photo_create_form').serialize(),
      secureuri:false,
      fileElementId:'photo_file',
      dataType: 'text',
      success: function(r){aai=false;var t=update(r);if(t!=false){location.assign("/photos?album="+t);}},
      error: function(r){aai=false;update(r);}
      }
    );
  } else {
   aai=false;$('#pht_error').hide();$('#file_error').show();$('#photo_create_btn').show().next().hide();
  }
}
function ajaxAddNotePhoto(){
  if(aai)return false;aai=true;var v=$("#photo_title").val();
  if($('#photo_file').val()!="") {
    $.ajaxFileUpload({
      url:"/note/action/insert_photo?"+$('#photo_create_form').serialize(),
      secureuri:false,
      fileElementId:'photo_file',
      dataType: 'text',
      success: function(r){aai=false;update(r);},
      error: function(r){aai=false;update(r);}
      }
    );
  } else {
    aai=false;$('#pht_error').hide();$('#file_error').show();$('#photo_create_btn').show().next().hide();
  }
}

/* Text area resizer */
(function($) {
	var textarea, staticOffset;
	var iLastMousePos = 0;
	var iMin = 50;
	var grip;
	$.fn.TextAreaResizer = function() {
		return this.each(function() {
		    textarea = $(this).addClass('processed'), staticOffset = null;
		    $(this).wrap('<div class="resizable-textarea"><span></span></div>').parent().append($('<div class="grippie"></div>').bind("mousedown",{el: this} , startDrag));
		    var grippie = $('div.grippie', $(this).parent())[0];
		});
	};
	function startDrag(e) {
		textarea = $(e.data.el);
		textarea.blur();
		iLastMousePos = mousePosition(e).y;
		staticOffset = textarea.height() - iLastMousePos;
		textarea.css('opacity', 0.95);
		$(document).mousemove(performDrag).mouseup(endDrag);
		return false;
	}

	function performDrag(e) {
		var iThisMousePos = mousePosition(e).y;
		var iMousePos = staticOffset + iThisMousePos;
		if (iLastMousePos >= (iThisMousePos)) {iMousePos -= 5;}
		iLastMousePos = iThisMousePos;
		iMousePos = Math.max(iMin, iMousePos);
		textarea.height(iMousePos + 'px');
		if (iMousePos < iMin) {endDrag(e);}
		return false;
	}

	function endDrag(e) {
		$(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
		textarea.css('opacity', 1);
		textarea.focus();
		textarea = null;
		staticOffset = null;
		iLastMousePos = 0;
	}

	function mousePosition(e) {
		return { x: e.clientX + document.documentElement.scrollLeft, y: e.clientY + document.documentElement.scrollTop };
	};
	
})(jQuery);

var sel_obj=null,sel_range=null,sel_id=null,sel_beg=0,sel_end=0,sel_str='',sel_scrl=null;
function selupdate(){sel_range=$(this).getSelection();sel_obj=$(this);sel_beg=sel_range.start;sel_end=sel_range.end;sel_str=sel_range.text;}
function doInsTag(t){doIns("["+t+"]"+sel_str+"[/"+t+"]",((sel_str.length>0)?false:t.length+2));}
function doIns(t,p){if(sel_obj==null)sel_obj=$("textarea.selrte");sel_scrl=sel_obj.scrollTop();sel_obj.val(sel_obj.val().substring(0,sel_beg)+t+sel_obj.val().substring(sel_end,sel_obj.val().length));sel_end=sel_beg+(p||t.length);sel_str='';sel_obj.setCursorPosition(sel_end);sel_obj.scrollTop(sel_scrl);}
function doInsSmiley(t,id){p_destroy(id);doIns(" "+t+" ");}
function doInsVideo(){if(aai)return false;aai=true;$.getJSON("/image/action/rte_video?"+$("#rte_video").serialize(),function(r){aai=false;if(r.status=="done"){p_destroy('rte_video_d');doIns('[video]'+r.dt+'[/video]');}else{$("#errmsg div.bodytext").html(r.error);$("#errmsg").show();}});}
function doInsLink(){if(aai)return false;aai=true;$.getJSON("/image/action/rte_url?"+$("#rte_url").serialize(),function(r){aai=false;if(r.status=="done"){p_destroy('rte_url_d');doIns('[url'+(r.dt?'='+r.du:'')+']'+(r.dt?r.dt:r.du)+'[/url]');}else{$("#errmsg div.bodytext").html(r.error);$("#errmsg").show();}});}
(function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
    $(this).focus();
  }
})(jQuery);

(function() {
	var fieldSelection = {
		getSelection: function() {
			var e = this.jquery ? this[0] : this;
			return (
				('selectionStart' in e && function() {
					var l = e.selectionEnd - e.selectionStart;
					return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
				}) ||
				(document.selection && function() {
					e.focus();
					var r = document.selection.createRange();
					if (r == null) {
						return { start: 0, end: e.value.length, length: 0 }
					}
					var re = e.createTextRange();
					var rc = re.duplicate();
					re.moveToBookmark(r.getBookmark());
					rc.setEndPoint('EndToStart', re);
					return { start: rc.text.length, end: rc.text.length + r.text.length, length: r.text.length, text: r.text };
				}) ||
				function() {
					return { start: 0, end: e.value.length, length: 0 };
				}
			)();
		},

		replaceSelection: function() {
			var e = this.jquery ? this[0] : this;
			var text = arguments[0] || '';
			return (
				('selectionStart' in e && function() {
					e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
					return this;
				}) ||
				(document.selection && function() {
					e.focus();
					document.selection.createRange().text = text;
					return this;
				}) ||
				function() {
					e.value += text;
					return this;
				}
			)();
		}
	};

	jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });

})();

(function(jQuery){var self=null;jQuery.fn.autogrow=function(o){return this.each(function(){new jQuery.autogrow(this,o);});};jQuery.autogrow=function(e,o){this.options=o||{};this.dummy=null;this.interval=null;this.line_height=this.options.lineHeight||parseInt(jQuery(e).css('line-height'));this.min_height	=this.options.minHeight||parseInt(jQuery(e).css('min-height'));this.max_height=this.options.maxHeight||parseInt(jQuery(e).css('max-height'));this.textarea=jQuery(e);if(this.line_height==NaN)this.line_height=0;this.init();};jQuery.autogrow.fn=jQuery.autogrow.prototype={autogrow:'1.2.2'};jQuery.autogrow.fn.extend=jQuery.autogrow.extend=jQuery.extend;jQuery.autogrow.fn.extend({init:function(){var self=this;this.textarea.css({overflow:'hidden',display:'block'});this.textarea.bind('focus',function(){self.startExpand()}).bind('blur',function(){self.stopExpand()});this.checkExpand();},startExpand:function(){var self=this;this.interval=window.setInterval(function(){self.checkExpand()},400);},stopExpand:function(){clearInterval(this.interval);},checkExpand:function(){if(this.dummy==null){this.dummy=jQuery('<div></div>');this.dummy.css({'font-size':this.textarea.css('font-size'),'font-family':this.textarea.css('font-family'),'width':this.textarea.css('width'),'padding':this.textarea.css('padding'),'line-height':this.line_height+'px','overflow-x':'hidden','position':'absolute','top':0,'left':-9999}).appendTo('body');}var html=this.textarea.val().replace(/(<|>)/g,'');if($.browser.msie){html=html.replace(/\n/g,'<BR>new');}else{html=html.replace(/\n/g,'<br>new');}if(this.dummy.html()!=html){this.dummy.html(html);if(this.max_height>0 &&(this.dummy.height()+this.line_height>this.max_height)){this.textarea.css('overflow-y','auto');}else{this.textarea.css('overflow-y','hidden');if(this.textarea.height()<this.dummy.height()+this.line_height||(this.dummy.height()<this.textarea.height())){this.textarea.animate({height:(this.dummy.height()+this.line_height)+'px'},100);}}}}});})(jQuery);
jQuery.supported=function(){if(typeof jQuery.supported.result!="undefined")return jQuery.supported.result;jQuery.supported.browsers=[["safari","412"],["opera","9.0"],["msie","6.0"],["mozilla","1.9"]];jQuery.supported.result=false;var b=jQuery.supported.browsers;for(var i=0;i<b.length;i++){if(typeof jQuery.browser[b[i][0]]!="undefinded" && jQuery.browser[b[i][0]]){var a1=b[i][1].split(".");var a2=jQuery.browser.version.split(".");var d1=a1.shift();var d2=a2.shift();if(parseFloat(d2+"."+a2.join(""))>=parseFloat(d1+"."+a1.join("")))jQuery.supported.result=true;}}return jQuery.supported.result;}; 
jQuery.popup=function(url,args){args=jQuery.extend({win:window,w:600,h:400,wintype:'_blank'},args);if(!args.t)args.t=screen.height/2-args.h/2;if(!args.l)args.l=screen.width/2-args.w/2;if(args['wintype']=='_top')args.win.location.href=url;else open(url,args['wintype'],'width='+args.w+',height='+args.h+',top='+args.t+',left='+args.l+',scrollbars,toolbar=0,resizable=0,status=0,location=0');return;};
jQuery.fn.extend({everyTime:function(interval,label,fn,times,belay){return this.each(function(){jQuery.timer.add(this,interval,label,fn,times,belay);});},oneTime:function(interval,label,fn){return this.each(function(){jQuery.timer.add(this,interval,label,fn,1);});},stopTime:function(label, fn){return this.each(function(){jQuery.timer.remove(this,label,fn);});}});
jQuery.extend({timer:{guid:1,global:{},regex:/^([0-9]+)\s*(.*s)?$/,powers:{'ms':1,'cs':10,'ds':100,'s':1000,'das':10000,'hs':100000,'ks':1000000},timeParse:function(value){if(value==undefined||value==null)return null;var result=this.regex.exec(jQuery.trim(value.toString()));if(result[2]){var num=parseInt(result[1],10);var mult=this.powers[result[2]]||1;return num*mult;}else{return value;}},add:function(element,interval,label,fn,times,belay){var counter=0;if(jQuery.isFunction(label)){if(!times)times=fn;fn=label;label=interval;}interval=jQuery.timer.timeParse(interval);if(typeof interval!='number'||isNaN(interval)||interval<=0)return;if(times&&times.constructor!=Number){belay=!!times;times=0;}times=times||0;belay=belay||false;if(!element.$timers)element.$timers={};if(!element.$timers[label])element.$timers[label]={};fn.$timerID=fn.$timerID||this.guid++;var handler=function(){if(belay&&this.inProgress)return;this.inProgress=true;if((++counter>times&&times!==0)||fn.call(element,counter)===false)jQuery.timer.remove(element,label,fn);this.inProgress=false;};handler.$timerID=fn.$timerID;if(!element.$timers[label][fn.$timerID])element.$timers[label][fn.$timerID]=window.setInterval(handler,interval);if(!this.global[label])this.global[label]=[];this.global[label].push(element);},remove:function(element,label,fn){var timers=element.$timers,ret;if(timers){if(!label){for(label in timers)this.remove(element,label,fn);}else if(timers[label]){if(fn){if(fn.$timerID){window.clearInterval(timers[label][fn.$timerID]);delete timers[label][fn.$timerID];}}else{for(var fn in timers[label]){window.clearInterval(timers[label][fn]);delete timers[label][fn];}}for(ret in timers[label])break;if(!ret){ret=null;delete timers[label];}}for(ret in timers)break;if(!ret)element.$timers=null;}}}});
if (jQuery.browser.msie)jQuery(window).one("unload",function(){var global=jQuery.timer.global;for(var label in global){var els=global[label],i=els.length;while(--i)jQuery.timer.remove(els[i],label);}});
