

String.prototype.Trim = function() 
{ 
return this.replace(/(^\s*)|(\s*$)/g, ""); 
} 

String.prototype.LTrim = function() 
{ 
return this.replace(/(^\s*)/g, ""); 
} 

String.prototype.RTrim = function() 
{ 
return this.replace(/(\s*$)/g, ""); 
} 

function copyToClipboard(el) {    
     if(window.clipboardData) {  
             el.select();  
             window.clipboardData.clearData();    
             window.clipboardData.setData("Text", el.value);
             //alert('复制成功');    
     } else if(navigator.userAgent.indexOf("Opera") != -1) {    
          window.location = el.value;    
     } else if (window.netscape) {    
          try {    
               netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");    
          } catch (e) {    
               alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");    
          }    
          var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);    
          if (!clip)    
               return;    
          var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);    
          if (!trans)    
               return;    
          trans.addDataFlavor('text/unicode');    
          var str = new Object();    
          var len = new Object();    
          var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);    
          var copytext = el.value;    
          str.data = copytext;    
          trans.setTransferData("text/unicode",str,copytext.length*2);    
          var clipid = Components.interfaces.nsIClipboard;    
          if (!clip)    
               return false;    
          clip.setData(trans,null,clipid.kGlobalClipboard);    
          //alert("复制成功！")    
     }    
}   


function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function JM_cc(ob){
var obj=MM_findObj(ob); if (obj) { 
obj.select();js=obj.createTextRange();js.execCommand("Copy");}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function registerResponders() {
  Ajax.Responders.register({
    onCreate: function() {
      $('loader').show();
    },
    onComplete: function() {
      $('loader').hide();
    }
  });
}

function favour(status_id) {
  new Ajax.Request('/favourings/create/' + status_id, { 
    asynchronous: true, 
    evalScripts: true 
  });
  
  return false;
}

/*function follow(user_id, screen_name) {

	new Ajax.Request('/friendships/create/' + user_id, {
	  asynchronous: true, 
	  evalScripts: true,
	  onComplete: function(transport) {
      console.log(transport.responseText);
	    if (transport.responseText.match(/success/)) {
        refresh_follow_control(user_id, 'followed');
      } else {
        borked();
      }
    }
	});
	return;
}*/
function follow(username)
{
    var url = '/Handler/Friendship.ashx';
    var pras = 'username='+username+'&action=following';
    new Ajax.Request(url,{parameters:pras,onComplete:followcallback,onLoading:function(){$('follow-button').disabled = true}});
}
function followcallback(request)
{
    var array = request.responseText.split(":");
    $('follow-button').disabled = false;
    if(array[0] == "1")
    {
        $("follow-button").style.display = "none";
        $("follow-actions").style.display = "";
    }
    else
    {
        $("follow-button").style.display = "";
        $("follow-actions").style.display = "none";
        $("follow-details").style.display = "none";
    }
}

function follow_or_remove_multiple_from_string(user_ids, follow) {
  url = follow ? '/friendships/cmfs' : '/friendships/dmfs';
  new Ajax.Request(url, {
    method: 'post',
    parameters: { user_ids: user_ids },
    asynchronous: true,
    evalScripts: true
  });

	return;
}

/*function removeUser(user_id, screen_name) {
  new Ajax.Request('/friendships/destroy/' + user_id, {
    asynchronous: true,
    evalScripts: true,
    onComplete: function(transport) {
      if (transport.responseText.match(/success/)) {
        refresh_follow_control(user_id, 'removed');
      } else {
        borked();
      }
    }
  });
}*/
function removeUser(username)
{
    var url = '/Handler/Friendship.ashx';
    var pras = 'username='+username+"&action=delete";
    new Ajax.Request(url,{parameters:pras,onComplete:removeUsercallback});
}
function removeUsercallback(request)
{
    $('follow-button').style.display = "";
    $('follow-actions').style.display = "none";
    $('follow-details').style.display = "none";  
}

/*
function notify(on, user_id) { if (on == true || on == "true") { onoff = "on"; 
    followleave = 'follow';
	} else { 
	  onoff = "off"; 
    followleave = 'leave';
	}

	new Ajax.Request('/friends/' + followleave + '/' + user_id, {
	  asynchronous: true, 
	  evalScripts: true,
	  onComplete: function(transport) {
	    if (transport.responseText.match(/success/)) {        
        refresh_follow_control(user_id, 'notify_' + onoff);
      } else {
        borked();
      }
    }
	});
}*/
function notify(status,userId)
{
    var url = "/Handler/Notify.ashx";
    var pras="status="+status+"&userId="+userId;
    var _ajax = new Ajax.Request(url,{parameters:pras});
}

function followDetails(user_id, screen_name) {
	toggleDetails();
}

function toggleDetails() {
	var details = document.getElementById('follow-details');
	var button = document.getElementById('followed');

  var toggle_arrow = document.getElementById('follow-toggle');
	
	if (details.style.display=="block") {
		details.style.display="none";
    toggle_arrow.className = 'closed';
	} else {
		details.style.display="block";
    toggle_arrow.className = 'opened';
	}
}

function buttonType() {
	var button_type = "long";
	
	if (is_following == false) {
		button_type = "short";
	} else if (device_count == 0) { 
		button_type = "med"; 
	}
	
	return button_type;
}
/* End Profile Page Follow Control */


/* People List Actions */
function removePerson(user_id, screen_name) {
	removeUser(screen_name);
	document.getElementById('removed'+user_id).innerHTML="<button class=\"small\">follow</button> <strong>Ok.</strong> You\'re no longer following " + screen_name +".";
	document.getElementById('removed'+user_id).style.display = "inline";
	document.getElementById('control'+user_id).style.display = "none";
	//document.getElementById('block'+user_id).style.display = "none";
}
function followUser2(username)
{
    var url = '/Handler/Friendship.ashx';
    var pras = 'username='+username+'&action=following';
    new Ajax.Request(url,{parameters:pras});
}
/*
function followPerson(user_id, email) {
	follow(user_id, email); 
	document.getElementById('removed'+user_id).style.display = "none";
	document.getElementById('control'+user_id).style.display = "block";
	document.getElementById('notifications'+user_id).style.display = "inline";
	document.getElementById('block'+user_id).style.display = "none";
}
*/

/* End People List Actions */


function addEventToObject(obj,evt,func) {
	var oldhandler = obj[evt];
	obj[evt] = (typeof obj[evt] != 'function') ? func : function(ev){oldhandler(ev);func(ev);};
}

function restriper() {
  rows = $('timeline').getElementsByTagName('tr');
  counter = 0;
  
  $A(rows).each(function(row) {    
    if (counter % 2) {
      row.className = "even";
    } else {
      row.className = "odd";
    }
    
    counter += 1;
  });
}

/* Search Form Actions */
function clearUserSearch() {
  $('user_search').value = '';
  $('user_search').setStyle({
    color: '#000'
  });
}

function highlight(container, klass, term) {
  $(container).getElementsByClassName(klass).each(function(detail_span) {
    if (detail_span.innerHTML.toLowerCase().include(term)) {
     detail_span.addClassName('highlight');
    }
  });
}

/*
function followFoundUser(id, is_protected) {
  new Ajax.Request('/friendships/create/' + id, {
	  asynchronous: true, 
	  evalScripts: true,
	  onComplete: function(transport) {
	    if (transport.responseText.match(/success/)) {
        $('user_' + id).addClassName('search_following');

        if (is_protected) {
          new Insertion.Before('follow_button_' + id, "Request to follow sent.&nbsp;");
        } else if (has_devices) {
          Element.show('notification_controls_' + id);
        }

        var rb = '<span id="remove_button_' + id + '">';
        rb += '<button onclick="removeFoundUser(\'' + id + '\');">remove</button>';
        rb += '</span>';
        $('follow_button_' + id).replace(rb);
      } else {
        alert('Something went wrong!  Please refresh the page and try again.');
      }
    }
	});

	return;
}
*/

function followFoundUser(username)
{
    var url = "/Handler/Friendship.ashx";
    var pras = "username="+username+"&action=following";
    $('follow_button_'+username).disabled = true;
    var _ajax = new Ajax.Request(url,{parameters:pras,onComplete:function(request){followFoundUsercallback(request,username)}});        
}
function followFoundUsercallback(request,username)
{
    $('follow_button_'+username).disabled = false;   
    var array = request.responseText.split(":");
    if(array[0] == "1")
        $("follow_control_"+username).innerHTML = "<span id=\"notification_controls_"+username+" class=\"notification_controls\"><img src=\"/images/yes.gif\" alt=\"following\" class=\"follow-icon\" />你已关注"+username+"</span>";
    else
    {
        $("follow_control_"+username).innerHTML = "等待"+username+"验证";
    }
}

function removeFoundUser(id) {
  new Ajax.Request('/friendships/destroy/' + id, {
	  asynchronous: true, 
	  evalScripts: true,
	  onComplete: function(transport) {
	    if (transport.responseText.match(/success/)) {
        Element.hide('notification_controls_' + id);
        $('user_' + id).removeClassName('search_following');

        var ab = '<span id="follow_button_' + id + '">';
        ab += '<button onclick="followFoundUser(\'' + id + '\');">删除</button>';
        ab += '</span>';
        $('remove_button_' + id).replace(ab);
      } else {
        alert('Something went wrong!  Please refresh the page and try again.');
      }
    }
	}); 
	
	return;
}

function toggleNotifyFoundUser(on, user_id) {
	if (on == true || on == "true") { 
	  onoff = "follow"; 
	} else { 
	  onoff = "leave"; 
	}
	
	new Ajax.Request('/friends/' + onoff + '/' + user_id, {
	  asynchronous: true, 
	  evalScripts: true,
	  onComplete: function(transport) {
	    if (transport.responseText.match(/success/)) {        
        new Effect.Highlight('notification_controls_' + user_id);
      } else {
        borked();
      }
    }
	});
}

function redirect_with_host(path) {
  l = window.location;
  uri = l.protocol + '//' + l.host + path;
  window.location = uri ;
}

/* this should probably be replaced with exception reporting at some point */
function borked() {
  alert('Something went wrong!  Please refresh the page and try again.');
}

function refresh_follow_control(user_id, action_taken) {
  new Ajax.Updater('follow-control', '/account/refresh_follow_control/' + user_id + '?action_taken=' + action_taken, {asynchronous:true, evalScripts:true}); return false;
}


/*directmessage*/
function directMessage()
{
    var url = '/Handler/DirectMessage.ashx';
    var pras="content="+encodeURIComponent($("text").value)+"&action=create&username="+encodeURIComponent($('user_id').value);
    $("submit_loading").style.display="";
    $("submit").disabled = true;
    $("status-field-char-counter").style.display = "none";
    var _ajax = new Ajax.Request(url,{parameters:pras,onComplete:directMessagecallback});
}
function directMessagecallback(request)
{
    if(request.responseText != "")
    {
        $("private_message").innerHTML = request.responseText;
    }
    $("status-field-char-counter").style.display = "";
    $('submit_loading').style.display = "none";
    $("text").value = "";
    $("status-field-char-counter").innerHTML = "140";
    $("submit").disabled = false;
}


/*
FriendList
*/
function removeFriend(id,username)
{
    var url = "/Handler/Friendship.ashx";
    var pras = "username="+username+"&action=delete";
    new Ajax.Request(url,{parameters:pras});
    $('removed'+id).innerHTML = "<button onclick=\"followFriend('"+id+"','"+username+"')\">关注</button> <strong>Ok!</strong>你已取消对" + username +" 的关注";
    $('control'+id).style.display = "none";
}
function followFriend(id,username)
{
    var url = "/Handler/Friendship.ashx";
    var pras = "username="+username+"&action=following";
    new Ajax.Request(url,{parameters:pras});
    $('removed'+id).innerHTML = '';
    $('control'+id).style.display='';
}
/*followerList*/
function followPerson(username)
{
    var url = '/Handler/Friendship.ashx';
    var pras = "username="+username+"&action=following";
    new Ajax.Request(url,{parameters:pras,onComplete:function(request){followPersonCallback(request,username)}});
}
function followPersonCallback(request,username)
{
    var array = request.responseText.split(':');
    if(array[0] == "1")
    {
        $('control'+username).innerHTML = "<img src=\"/images/yes.gif\" alt=\"following\" class=\"follow-icon\" />你已关注"+username+"";
     
    }   
    else
    {
        $('control'+username).innerHTML = "<img src=\"/images/tiny_minus.gif\" alt=\"following\" class=\"follow-icon\" />等待"+username+"验证";
     
    }
}
function SelectNotifications(notifications)
{
    var url = '/Handler/SelectNotifications.ashx';
    var pras = 'notifications='+notifications;
    new Ajax.Request(url,{parameters:pras});
}

function checkinvite(code)
{
    if(code.Trim() == "")
    {
        alert('请输入邀请码');
        return false;
    }
    var url = "/Handler/CheckInviteCode.ashx";
    var pras = "invitecode="+code;
    new Ajax.Request(url,{parameters:pras,onComplete:checkinviteCallback});
    $("invitebtn").disable = true;
    return false;
}
function checkinviteCallback(request)
{
    var result = request.responseText;
    $("invitebtn").disable = false;
    if(result == "1")
    {
        $("registerDiv").style.display = "";
        $("username").focus();
        $("inviteDiv").style.display = "none";
    }
    else
    {
        $("registerDiv").style.display = "none";
        $("inviteDiv").style.display = "";
        $("invite_msg").innerHTML = "邀请码无效";
    }
}


/**
 * Copy the value of an input field's title attribute to its value attribute.
 * Clear the input field on focus if its value is the same as its title.
 * Repopulate the input field on blur if it is empty.
 * Hide the input field's associated label if it has one.
 */
var autoPopulate = {
	sInputClass:'populate', // Class name for input elements to autopopulate
	/**
	 * Main function
	 */
	init:function() {
		// Check for DOM support
		if (!document.getElementById || !document.createTextNode) {return;}
		// Find all input elements with the given className
		var arrInputs = document.getElementsByClassName('populate');
		var iInputs = arrInputs.length;
		var oInput;
		for (var i=0; i<iInputs; i++) {
			oInput = arrInputs[i];
			// Make sure it's a text input
			if( oInput.type != 'text' && oInput.type != 'password') { continue; }
			// If value is empty and title is not, assign title to value
			if ((oInput.value == '') && (oInput.title != '')) { autoPopulate.setInput(oInput) }
      else { oInput.style.color = '#000'; }
			// Add event handlers for focus and blur
			autoPopulate.addEvent(oInput, 'focus', function() {
				// If value and title are equal on focus, clear value
				if (this.value == this.title) {
					this.value = '';
          this.style.color = '#000';
					this.select(); // Make input caret visible in IE
				}
			});
			autoPopulate.addEvent(oInput, 'blur', function() {
				// If the field is empty on blur, assign title to value
				if (!this.value.length) { autoPopulate.setInput(this) }
			});
		}
	},
  
  setInput:function(obj) {
    obj.value = obj.title; obj.style.color = '#94999d'
  },

	addEvent:function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() {obj["e"+type+fn](window.event);}
			obj.attachEvent("on"+type, obj[type+fn]);
		}
	}
};

function quickSendEmail(emailList)
{
    var url = "/Handler/QuickSendEmail.ashx";
    var pras = "emailList="+emailList.Trim();
    $('emailInvite').disabled = true;
    $("sendemailBtn").disabled = true;
    var _ajax= new Ajax.Request(url,{
    asynchronous: true, 
	evalScripts: true,
    method:'post',
    parameters:pras,
    onComplete:function(request){
    var array = request.responseText.split(":");
    $('emailInvite').disabled = false;
    $("sendemailBtn").disabled = false;
    $("emailInvite").value = "";
    }})
}
