Ajax.Responders.register({
 onCreate: function(request, t) {
   //display busy icon
   if( $("busyCursor") )
     $("busyCursor").show();
 },
 onComplete: function(request, t, json) {
   //hide busy icon
   if( $("busyCursor") )
     $("busyCursor").hide();

   if( json && json.message )
     alert( "Debug:\n" + unescape(json.message) );
 }
 });

function joinGroup()
{
  URL = "/scripts/try_JoinGroup.php";
  new Ajax.Request( URL, {
    method: 'get',
      onSuccess: function(t)
      {
        window.location.reload();
      },
      onFailure: function(t)
      {
        
      }
  });

}

function createCookie(name,value,days)
{
  if (days)
  {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else
    var expires = "";

  document.cookie = name+"="+value+expires+"; path=/";
}
function deleteCookie(name)
{
  createCookie(name,"", -1);
       //";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function login()
{
  var username = escape($F("username"));
  var password = escape($F("password"));

  URL = "/scripts/try_Login.php?username=" + username + "&password=" + password;
//alert( URL );
//  $("loginForm").disable();
  new Ajax.Request( URL, {
    method: 'get',
      onSuccess: function(t)
      {
        window.location.reload();
      },
      onFailure: function(t)
      {
//        $("loginForm").enable();
        $("login_error_box").update( t.responseText );
        $("password").value = "";
        if( username == "" )
          $('username').focus();
        else
          $('password').focus();
      }
  });
}

function signup()
{
  $("username_help").update("");
  $("success_box_inner").update("");
  $("email_help").update("");
  $("email2_help").update("");

  var regEx = /^[a-zA-Z]{1}[a-zA-Z0-9]{2,20}$/;

  if( !regEx.test($F("username")) )
  {
    $("username").focus();
    $("success_box_inner").update("The first character of the user name should be a letter. The user name should be at least 3 characters long and contain only letters and numbers.");
    $("success_box_inner").style.color = "#FF0000";
    return;
  }
/*  if( !regEx.test($F("blogname")) )
  {
    $("blogname").focus();
    $("success_box_inner").update("The first character of the blog name should be a letter. The blog name should be at least 3 characters long and contain only letters and numbers.");
    $("success_box_inner").style.color = "#FF0000";
    return;

  }*/
  if( $F("email") == "" )
  {
    $("email").focus();
    $("success_box_inner").update("Please enter a vlid email address.");
    $("success_box_inner").style.color = "#FF0000";
    return;

  }
  if( $F("email") != $F("email2") )
  {
    $("email").focus();
    $("success_box_inner").update("The first email does not match the second.");
    $("success_box_inner").style.color = "#FF0000";
    return;
  }

  var username = $F("username");

  URL = "/scripts/try_SignUp.php?"+$("signupForm").serialize();

  $("signupForm").disable();
  new Ajax.Request( URL, {
    method: 'get',
    onSuccess: function(t)
    {
      $("success_box_inner").innerHTML = t.responseText;
      $("success_box_inner").style.color = "#000";
      new Effect.Appear( $("success_box") );

      $("signupForm").enable();
      $("signupForm").reset();
      $("username").focus();
    },
    onFailure: function(t)
    {
      $("signupForm").enable();
      $("success_box_inner").innerHTML = t.responseText;
      $("success_box_inner").style.color = "#FF0000";
      new Effect.Appear( $("success_box") );
      $("password").value = "";
    }
  });
}

function sendCmd(cmd, opt)
{
  options = {
    callback: Prototype.emptyFunction
  }
  Object.extend(options, opt || {});

  postBody = "cmd="+cmd+"&blog="+_group_name;
  for( i=2; i<arguments.length;++i)
    postBody = postBody + "&p" + (i-1) + "=" + escape(arguments[i]);


  new Ajax.Request("/scripts/commands.php",
    {
      method: 'post',
      postBody: postBody,
      onSuccess: function(t)
      {
        options.callback(t);
      },
      onFailure: function(t)
      {
        alert( "Failure: " + t.responseText );
      }
    });
}

function hideElement(e,e2,visible,hidden)
{
  e = $(e);
  e.toggle();
  if( e.visible )
    $(e2).innerHTML = visible;
  else
    $(e2).innerHTML = hidden;
}

Effect.Generic = Class.create();
Object.extend(Object.extend(Effect.Generic.prototype, Effect.Base.prototype), {
  initialize: function(callback) {
      //this.element.setStyle({zoom: 1});
    this.callback = callback;
    var options = Object.extend({
      from: 1.0,
      to:   1.0
    }, arguments[1] || {});
    this.start(options);
  },
  update: function(position) {
    this.callback(position);
  }
});

function hideComment(img, id)
{
  new Effect.toggle(id,'blind',{duration: .25, afterFinish: 
          function()
          {
            if( $(id).visible() )
              $(img).src = '/images/minus_s.png';
            else
              $(img).src = '/images/plus_s.png';
          }} );
}

CommentHelper = Class.create();
CommentHelper.prototype =
{
  initialize: function()
  {
    this.inEdit = false;
  },
  deleteComment: function( commentId, postId )
  {
    sendCmd( "delete_comment",
           { callback: function(){
               $('commentDeleteRestoreLink_'+commentId).href = 'javascript:commentHelper.restoreComment('+commentId+','+postId+')';
               $('commentDeleteRestoreLink_'+commentId).innerHTML = 'Restore';
             }},
           commentId, postId  );

  },
  restoreComment: function( commentId, postId )
  {
    sendCmd( "restore_comment",
           { callback: function(){
               //window.location = window.location;
               $('commentDeleteRestoreLink_'+commentId).href = 'javascript:commentHelper.deleteComment('+commentId+','+postId+')';
               $('commentDeleteRestoreLink_'+commentId).innerHTML = 'Delete';
             }},
           commentId, postId  );

  },
/*  startEdit: function( elementId, commentId, postId )
  {
    if( this.inEdit )
    {
      if( $F("comment_input") != "" )
        if( !confirm("Lose your comment?") )
          return;
    }

    if( this.edit ) this.edit.remove();
    this.edit = null;
    this.inEdit = true;

    this.elem = elementId;
//    this.parentId = commentId;
    this.postId = postId;
//alert( $('comment_body_a_'+commentId) );
    comment = $('comment_body_a_'+commentId).innerHTML;


    new Insertion.Top( this.elem,
"<div id='add_comment' style='width:100%'>"+
"<form method='post' action='' id='addcomment_Form' class='mojoForm'>"+
"  <fieldset>"+
"    <ol>"+
"      <li>"+
"        <label for='comment_input'>Comment</label>"+
"        <textarea id='comment_input' style='height:60px;width:300px' ></textarea>"+
"      </li>"+
"      <div class='mojoForm_wrapper'>"+
"        <input id='add_comment_btn' value='Save' type='button' />&nbsp;"+
"        <input id='cancel_comment_btn' value='Cancel' type='button' /></form></div></div>"+
"      </div>"+
"    </ol>"+
"  </fieldset>"+
"</form>"+
"</div>" );


    Event.observe("add_comment_btn", "click", this.onSave.bindAsEventListener(this) );
    Event.observe("cancel_comment_btn", "click", this.stopEdit.bindAsEventListener(this) );

    this.edit = $("add_comment");
    $("comment_input").focus();
  },*/
  //startNewEdit: function( elementId, commentId, postId )
  showEditor: function( elementId, commentId, postId )
  {
    if( this.inEdit )
    {
      if( $F("comment_input") != "" )
        if( !confirm("Lose your comment?") )
          return;
    }

    if( this.edit ) this.edit.remove();
    this.edit = null;
    this.inEdit = true;

    this.parentId = commentId;
    this.postId = postId;
    new Insertion.Top( elementId, comment_block );

    Event.observe("add_comment_btn", "click", this.onSave.bindAsEventListener(this) );
    Event.observe("cancel_comment_btn", "click", this.stopEdit.bindAsEventListener(this) );

    this.edit = $("add_comment");
  //  $("comment_input").focus();
  },
  setDirty: function()
  {
    this.isDirty = true;
  },
  stopEdit: function()
  {
    if( this.inEdit )
    {
      if( $F("comment_input") != "" )
        if( !confirm("Lose your comment?") )
          return;
    }

    this.inEdit = false;
    this.edit.remove();
    this.edit = null;
  },
  onSave: function()
  {
    name = $F("comment_name");
    email = $F("comment_email");
    comment = $F("comment_input");
    sendCmd( "save_comment",
           { callback: this.saveCallback.bind(this) },
           this.postId, this.parentId, name, email, comment );
  },
  saveCallback: function(t)
  {
    this.inEdit = false;
    this.stopEdit();
    new Insertion.Bottom( this.elem, t.responseText );
  },
  startNewEdit: function(id, elementId, commentId, postId  )
  {
    //this.elem = $(id);
    this.elem = $(elementId);
    var t = this;
    if( !$(id).visible() )
      new Effect.toggle(id,'appear', {duration: 0.25,afterFinish:
        function() {
 	  t.showEditor( elementId, commentId, postId );
        }
      });
    else
      this.showEditor( elementId, commentId, postId );
  },
  toggle: function(id)
  {
    new Effect.toggle(id,'appear', {duration: 0.25});
  }
};


function inviteFriend( username )
{
  if( username == null || username == '' )
    return;

  url = "/scripts/invite_Friend.php?username="+username;
  new Ajax.Request( url, {
    method: 'get',
    onSuccess: function(t)
    {
      alert( "User "+username+" has been invited to your group." );
    },
    onFailure: function(t)
    {
      alert( t.responseText );
    }
  });
}

function convertHTMLEntitiesToUnicode(str)
{
  if( str.length <= 0 ) return str;

  re = /%u([\da-fA-F]{4})/;

  while( re.exec(str) != null )
    str = RegExp.leftContext + String.fromCharCode(("0x"+RegExp.$1)*1) + RegExp.rightContext;

  return str;
}


var popup_window = '';
function popitup(url, name, groupname)
{
  if( name == null )
    name = '';
  if( groupname == null )
    groupname = '';

  if (!popup_window.closed && popup_window.location)
  {
    popup_window.location.href = url;
  }
  else
  {
    try
    {
      popup_window=window.open(url,groupname+'_editWindow'+name,'resizable=1,height=500,width=600');
      if (!popup_window.opener) popup_window.opener = self;
    }
    catch( e )
    {
      popup_window = '';
      alert( "A popup blocker may be preventing the edit window from opening.\n\nDisable your popup blocker for this site." );
    }
  }
  if (window.focus)
    popup_window.focus();

  return false;
}

function doContactUs()
{
  closeInfoWindow();
  var pos =  $("container").getDimensions();
  pos.width -= 250;
  pos.height = 35;
  new Insertion.Top("container", "<div id='info_window_wrapper' style='border:solid 2px gray;border-top:none;display:none;z-index:100;'><iframe name='info_window' marginwidth='0' marginheight='0' align='left' frameborder='0' scrolling='no' src='/dialogs/contact_us.php' width='100%' height='100%'></iframe></div>" );

  Position.absolutize( $("info_window_wrapper") );
  $("info_window_wrapper").style.top = pos.height + "px";
  $("info_window_wrapper").style.left = "20px";//pos.width + "px";
  $("info_window_wrapper").style.width = "440px";
  $("info_window_wrapper").style.height = "140px";
}

function doSignup(button)
{
  closeInfoWindow();
  var pos =  $("container").getDimensions();
  pos.width -= 450;
  pos.height = 35;
  new Insertion.Top("container", "<div id='info_window_wrapper' style='border:solid 2px gray;border-top:none;display:none;z-index:100;'><iframe name='info_window' marginwidth='0' marginheight='0' align='left' frameborder='0' scrolling='no' src='/dialogs/signup.php' width='100%' height='100%'></iframe></div>" );

  Position.absolutize( $("info_window_wrapper") );
  $("info_window_wrapper").style.top = pos.height + "px";
  $("info_window_wrapper").style.left = pos.width + "px";
  $("info_window_wrapper").style.width = "440px";
  $("info_window_wrapper").style.height = "240px";
}

function doResetPassword(button)
{
  closeInfoWindow();
  var pos =  $("container").getDimensions();
  pos.width -= 450;
  pos.height = 35;
  new Insertion.Top("container", "<div id='info_window_wrapper' style='border:solid 2px gray;border-top:none;display:none;z-index:100;'><iframe name='info_window' marginwidth='0' marginheight='0' align='left' frameborder='0' scrolling='no' src='/dialogs/reset_password.php' width='100%' height='100%'></iframe></div>" );

  Position.absolutize( $("info_window_wrapper") );
  $("info_window_wrapper").style.top = pos.height + "px";
  $("info_window_wrapper").style.left = pos.width + "px";
  $("info_window_wrapper").style.width = "440px";
  $("info_window_wrapper").style.height = "170px";
}


function showSignup()
{
  new Effect.Appear( $("info_window_wrapper"), {duration:0.5} );
}

function closeSignup()
{
  new Effect.Fade( $("info_window_wrapper"), {duration:0.5,afterFinish:function(){closeInfoWindow();}}  );
}

function closeInfoWindow()
{
  if( $("info_window_wrapper") != null )
    $("info_window_wrapper").remove();
}

function nl2br(str)
{
  str = str.replace(/\r\n/g, "<br>");
  str = str.replace(/\n/g  , "<br>");
  return str;
}
function br2nl(str)
{
  str = str.replace( /\<br\>/gi       , "\n");
  str = str.replace( /\<br[\ \/]+\>/gi, "\n");
  return str;
}

