
/* $Id: class_base.js 62 2009-02-18 02:59:27Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js
var SocialEngineAPI = {

  version : '0.1.0alpha'

};



SocialEngineAPI.Base = new Class({

  // Methods
  initialize: function()
  {
    this.version = SocialEngineAPI.version;
  },
  
  
  
  RegisterModule: function(moduleObject)
  {
    moduleObject.Base = this;
  }

});
/* $Id: class_comments.js 62 2009-02-18 02:59:27Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js

// Required language variables: 39,155,175,182,183,184,185,187,784,787,829,830,831,832,833,834,835,854,856,891,1025,1026,1032,1034,1071

SocialEngineAPI.Comments = new Class({
  
  // Class
	Implements: [Options],
  
  
  
  
  // Properties
  Base: {},
  
  page: 1,
  
  total: 0,
  
  changed: false,
  
  isEditing: false,
  
  
  options: {
    // Controls ajax request options
    'ajaxURL' : 'misc_js.php',
    'ajaxMethod' : 'post',
    'ajaxSecure' : false,
    
    // Can the viewer comment
    'canComment' : false,
    'commentHTML' : false,
    'commentCode' : false,
    
    // Controls the height of the comment box
    'originalHeight' : 70,
    
    // The type of comment ex. 'media'
    'type' : false,
    
    // The column that identifies the type ex. 'media_id'
    'typeIdentifier' : false,
    
    // The actual ID of the object commented on
    'typeID' : false,

    // Pagination Info
    'paginate' : false,
    'cpp' : false,

    // Comment links
    'commentLinks' : {'reply' : false, 'walltowall' : false},
    
    // Some other stuff to identify the object
    'object_owner' : false,
    'object_owner_id' : false,
    'typeTab' : false,
    'typeCol' : false,
    'typeTabParent' : false,
    'typeColParent' : false,
    'typeChild' : false
  },
  
  
  
  
  // Methods
  initialize: function(options)
  {
    this.setOptions(options);
    
    if( this.options.initialTotal ) this.total = this.options.initialTotal;

    var bind = this;
    window.addEvent('domready', function()
    {
      bind.showPostComment();
      
      //bind.options.originalHeight = textarea_autogrow('comment_body');
      bind.getComments(1);
    });
  },
  
  
  
  
  showPostComment: function()
  {
  	comments_headline = 9999018;
  	var headline = "";
  	if (typeof comments_source != 'undefined') {
  		switch (comments_source) {
  			case "blog":
  			case "gallery":
  				comments_headline = 9999019;
  				var innerHTML = "<div>";
			    // POST COMMENT
			    innerHTML += 
			      "<div class='comment_headline'>" +
			        this.Base.Language.Translate(9999019) +
			        " (<span class='tc' id='" + this.options.type + '_' + this.options.typeID + '_totalcomments' + "'>" + this.total + "</span>)" +
			      "</div>";
  			break;
  			default:
  				var innerHTML = "<div style='padding:0px 50px;'>";
			    // POST COMMENT
			    innerHTML += 
			      "<div class='comment_headline'>" + se_username + " " +
			        this.Base.Language.Translate(854) +
			        " (<span class='tc' id='" + this.options.type + '_' + this.options.typeID + '_totalcomments' + "'>" + this.total + "</span>)" +
			      "</div>";
			    headline = this.Base.Language.TranslateFormatted(comments_headline, [se_username]);
  			break;
  		}
  	}
  	else {  	
    	var innerHTML = "<div style='padding:0px 50px;'>";
	    // POST COMMENT
	    innerHTML += 
	      "<div class='comment_headline'>" + se_username + " " +
	        this.Base.Language.Translate(854) +
	        " (<span class='tc' id='" + this.options.type + '_' + this.options.typeID + '_totalcomments' + "'>" + this.total + "</span>)" +
	      "</div>";
	      headline = this.Base.Language.TranslateFormatted(comments_headline, [se_username]);
  	}
    
      
    if( this.options.canComment )
    {
      innerHTML += 
        "<form action='misc_js.php' method='post' target='ajaxframe'>" +
          "<div class='profile_postcomment'>" +
          	headline +
            "<textarea name='comment_body' id='comment_body' cols='25' class='comment_area'>" + this.Base.Language.Translate(829) + "</textarea>";
      
      if( this.options.commentHTML ) innerHTML += 
            "<div style='margin-top: 5px; float:left;'>" +
              this.Base.Language.TranslateFormatted(1034, [this.options.commentHTML]) +
            "</div>";
      
      if( this.options.commentCode ) innerHTML += 
            "<div style='float: left; margin-top: 5px;'>" +
              "<a href='javascript:void(0);' onClick=\"this.blur();$('secure_image').src=$('secure_image').src+'?'+(new Date()).getTime();\">" +
                "<img src='./images/secure.php' id='secure_image' border='0' height='20' width='67' class='signup_code'>" + 
              "</a>" +
              " <input type='text' name='comment_secure' id='comment_secure' class='text' size='6' maxlength='10'> " +
              "<img src='./images/icons/tip.gif' border='0' class='Tips1' style='vertical-align: middle;' title='" + this.Base.Language.Translate(856) + "'>" +
            "</div>";
      
      innerHTML += 
            "<div style='text-align: right; margin-top: 5px;'>" +
            "<input type='submit' id='comment_submit' class='button' style='float:right;' value='" + this.Base.Language.Translate(833) + "'><div style='clear:both;'></div>" +
            "<input type='hidden' name='task' value='comment_post'>" +
            "<input type='hidden' name='type' value='" + this.options.type + "'>" +
            "<input type='hidden' name='iden' value='" + this.options.typeIdentifier + "'>" +
            "<input type='hidden' name='value' value='" + this.options.typeID + "'>";
      
      if( this.options.object_owner && this.options.object_owner_id )
      {
        innerHTML += '<input type="hidden" name="object_owner" value="' + this.options.object_owner + '">' +
		     '<input type="hidden" name="object_owner_id" value="' + this.options.object_owner_id + '">';
      } else {
        innerHTML += '<input type="hidden" name="user" value="' + this.Base.Owner.user_info.user_username + '">';
      }

      if( this.options.typeTab ) innerHTML += 
            "<input type='hidden' name='tab' value='" + this.options.typeTab + "'>";
      
      if( this.options.typeCol ) innerHTML += 
            "<input type='hidden' name='col' value='" + this.options.typeCol + "'>";
      
      if( this.options.typeTabParent ) innerHTML += 
          '<input type="hidden" name="tab_parent" value="' + this.options.typeTabParent + '">';
      
      if( this.options.typeColParent ) innerHTML += 
          '<input type="hidden" name="col_parent" value="' + this.options.typeColParent + '">';
      
      if( this.options.typeChild ) innerHTML += 
          '<input type="hidden" name="child" value="1">';
      
      innerHTML += 
            "</div>" +
            "<div id='comment_error' style='color: #FF0000; display: none;'></div>" +
          "</div>" +
        "</form>";
    }
    
    // DELETE COMMENT
    innerHTML += 
      '<div style="display: none;" id="confirmcommentdelete">' +
        '<div style="margin-top: 10px;">' +
          this.Base.Language.Translate(1026) +
        '</div>' +
        '<br />' +
        '<form action="misc_js.php" method="post" target="ajaxframe">' +
        '<input type="submit" class="button" value="' + this.Base.Language.Translate(175) + '" onClick="parent.TB_remove();"> ' +
        '<input type="button" class="button" value="' + this.Base.Language.Translate(39) + '" onClick="parent.TB_remove();">' +
        '<input type="hidden" name="task" value="comment_delete">' +
        '<input type="hidden" name="comment_id" id="del_comment_id" value="0">' +
        '<input type="hidden" name="type" value="' + this.options.type + '">' +
        '<input type="hidden" name="iden" value="' + this.options.typeIdentifier + '">' +
        '<input type="hidden" name="value" value="' + this.options.typeID + '">';

    if( this.options.object_owner && this.options.object_owner_id )
    {
      innerHTML += '<input type="hidden" name="object_owner" value="' + this.options.object_owner + '">' +
		   '<input type="hidden" name="object_owner_id" value="' + this.options.object_owner_id + '">';
    } else {
      innerHTML += '<input type="hidden" name="user" value="' + this.Base.Owner.user_info.user_username + '">';
    }

    if( this.options.typeTab ) innerHTML += 
        '<input type="hidden" name="tab" value="' + this.options.typeTab + '">';
    
    if( this.options.typeCol ) innerHTML += 
        '<input type="hidden" name="col" value="' + this.options.typeCol + '">';
    
    if( this.options.typeTabParent ) innerHTML += 
        '<input type="hidden" name="tab_parent" value="' + this.options.typeTabParent + '">';
    
    if( this.options.typeColParent ) innerHTML += 
        '<input type="hidden" name="col_parent" value="' + this.options.typeColParent + '">';
    
    if( this.options.typeChild ) innerHTML += 
        '<input type="hidden" name="child" value="1">';

  
    
    innerHTML += 
        '</form>' +
      '</div></div>';
    
    
    
    var postCommentContainerElement = $(this.options.type + '_' + this.options.typeID + '_postcomment');
    postCommentContainerElement.innerHTML = innerHTML;
    
    
    // Add events
    var bind = this;
    if( this.options.canComment )
    {
      postCommentContainerElement.getElement('form').addEvent('submit', function()    { bind.checkText(); });
      postCommentContainerElement.getElement('textarea').addEvent('focus', function() { bind.removeText(this);  });
      postCommentContainerElement.getElement('textarea').addEvent('blur', function()  { bind.addText(this);     });
      $('ajaxframe').addEvent('load', function()  { getComments();     });
    }
    
  },
  
  
  
  
  getComments: function(direction)
  {
    if( direction=='next' )
      this.page++;
    else if( direction=='previous' )
      this.page--;
    else if( $type(direction) )
      this.page = direction;
    
    if( this.options.paginate ) {
      window.scroll(0,0);
    } else {
      this.options.cpp = this.total;
    }

    if( this.options.object_owner && this.options.object_owner_id )
    {
      var object_owner = this.options.object_owner;
      var object_owner_id = this.options.object_owner_id;
      var user = '';
    } else {
      var object_owner = '';
      var object_owner_id = '';
      var user = this.Base.Owner.user_info.user_username;      
    }

    // AJAX
    var bind = this;
    var request = new Request.JSON({
      'url' : this.options.ajaxURL,
      'method' : this.options.ajaxMethod,
      'secure' : this.options.ajaxSecure,
      'data' : {
        'task'  : 'comment_get',
        'user'  : user,
	'object_owner' : object_owner,
	'object_owner_id' : object_owner_id,
        'type'  : this.options.type,
        'iden'  : this.options.typeIdentifier,
        'value' : this.options.typeID,
        'cpp'   : this.options.cpp,
        'p'     : this.page
      },
      'onComplete' : function(responseObject, responseText)
      {
        bind.updateComments(responseObject);
      }
    });
    request.send();
  },
  
  
  
  
  // THIS FUNCTION UPDATES THE COMMENTS
  updateComments: function(responseObject)
  {
    if( $type(responseObject)!="object" )
    {
      alert('There was an error processing the request.');
      return false;
    }
    
    
    // Prepare
    this.total  = parseInt(responseObject.total_comments) || 0;
    this.page   = responseObject.p;
    
    var maxpage = responseObject.maxpage;
    var p_start = responseObject.p_start;
    var p_end   = responseObject.p_end;
    
    var totalCommentElement     = $(this.options.type + '_' + this.options.typeID + '_totalcomments');
    var commentContainerElement = $(this.options.type + '_' + this.options.typeID + '_comments');
    var comments = $H(responseObject.comments);
    
    // UPDATE TOTAL COMMENTS AND PAGE VARS
    totalCommentElement.innerHTML = this.total;

    // CREATE DIV TO HOLD COMMENT BODY FOR CLEANING
    var commentBodyDiv = document.createElement('div');
    
    // EMPTY CONTAINER 
    commentContainerElement.empty();
    
    // LOOP OVER COMMENTS
    var bind = this;
    if(bind.Base.Core.settings.setting_url) { var querySeparator = '?'; } else { var querySeparator = '&'; }
    comments.each(function(commentObject, commentID)
    {
      var newComment = new Element('div', {
        'id' : 'comment_' + commentID
      });
      
      // BUILD COMMENT
      var newCommentInnerHTML = "<div style='background-image:url(images/trennlinie.gif); background-position:30px 0px; padding:6px 50px; background-repeat:no-repeat; margin-top: 10px; margin-bottom: 20px;'>";
      
      // AUTHOR PHOTO
      if( commentObject.comment_authoruser_id && commentObject.comment_authoruser_exists )
        newCommentInnerHTML += "<div style='float: left; text-align: center; width: 90px;'><a href='" + commentObject.comment_authoruser_url + "'><img src='" + commentObject.comment_authoruser_photo + "' class='photo' width='" + commentObject.comment_authoruser_photo_width + "' border='0'></a></div>";
      else
        newCommentInnerHTML += "<div style='float: left; text-align: center; width: 90px;'><img src='./images/nophoto.gif' class='photo' width='75' border='0'></div>";
      
      newCommentInnerHTML += "<div style='overflow: hidden;'>";
      
      // AUTHOR NAME/LINK
      if( !commentObject.comment_authoruser_id )
        newCommentInnerHTML += "<div class='profile_comment_author'><b>" + bind.Base.Language.Translate(835) + "</b></div>";
      else if( !commentObject.comment_authoruser_exists )
        newCommentInnerHTML += "<div class='profile_comment_author'><b>" + bind.Base.Language.Translate(1071) + "</b></div>";
      else
        newCommentInnerHTML += "<div class='profile_comment_author'><a href='" + commentObject.comment_authoruser_url + "'><b>" + commentObject.comment_authoruser_displayname + "</b></a>" + " " + bind.Base.Language.Translate(9999020) + "</div>";
      
      // COMMENT DATE
      newCommentInnerHTML += "<div class='profile_comment_date'>" + bind.Base.Language.Translate(commentObject.comment_date_since).replace(/%1\$d/, commentObject.comment_date_ago) + "</div>";
      
      // COMMENT BODY
      newComment.setProperty('html', commentObject.comment_body);
      
      newCommentInnerHTML += "<div class='profile_comment_body' id='profile_comment_body_" + commentID + "'>" + commentObject.comment_body + "&nbsp;</div>";
      newCommentInnerHTML += "<div class='profile_comment_links'>";
      
      // COMMENT LINKS
      var links = new Array();
      if( bind.Base.Viewer.user_exists && commentObject.comment_authoruser_id && commentObject.comment_authoruser_exists )
      {

        // REPLY LINK (VISIBLE ONLY TO OWNER)
	if(bind.options.commentLinks.reply && bind.Base.Viewer.user_info.user_id == bind.Base.Owner.user_info.user_id && bind.Base.Viewer.user_info.user_id != commentObject.comment_authoruser_id) 
        { 
          links.push("<a href='"+commentObject.comment_authoruser_url+querySeparator+"v=comments'>" + bind.Base.Language.Translate(787) + "</a>"); 
        }

	// WALL-TO-WALL (VISIBLE ONLY IF USER CAN SEE AUTHOR'S PROFILE)
	if(bind.options.commentLinks.walltowall && commentObject.comment_authoruser_id != bind.Base.Owner.user_info.user_id && commentObject.comment_authoruser_private == false) 
	{ 
	  links.push("<a href=\"javascript:TB_show('" + bind.Base.Language.Translate(1032) + "', 'profile_comments.php?user=" + bind.Base.Owner.user_info.user_username +"&user2=" + commentObject.comment_authoruser_username + "&TB_iframe=true&height=450&width=550', '', './images/trans.gif');\">" + bind.Base.Language.Translate(891) + "</a>");
        }

        // MESSAGE (VISIBLE IF USER IS NOT AUTHOR)
        if( commentObject.comment_authoruser_id!=bind.Base.Viewer.user_info.user_id )
        {
          links.push("<a href=\"javascript:TB_show('" + bind.Base.Language.Translate(784) + "', 'user_messages_new.php?to_user=" + commentObject.comment_authoruser_displayname + "&to_id=" + commentObject.comment_authoruser_username + "&TB_iframe=true&height=400&width=450', '', './images/trans.gif');\">" + bind.Base.Language.Translate(834) + "</a>");
        }
        
        // EDIT (VISIBLE IF USER IS AUTHOR)
        if( commentObject.comment_authoruser_id==bind.Base.Viewer.user_info.user_id )
        {
          links.push("<a class=\"commentEditLink\" href=\"javascript:void(0);\" id='comment_edit_link_" + commentID + "'>" + bind.Base.Language.Translate(187) + "</a>");
        }
        
      }

      // DELETE (VISIBLE IF USER IS AUTHOR OR USER IS OWNER)
      if((commentObject.comment_authoruser_exists && commentObject.comment_authoruser_id == bind.Base.Viewer.user_info.user_id) || (bind.Base.Viewer.user_exists && bind.Base.Viewer.user_info.user_id == bind.Base.Owner.user_info.user_id))
      {
        links.push("<a class=\"commentDeleteLink\" href=\"javascript:void(0);\" id='comment_delete_link_" + commentID + "'>" + bind.Base.Language.Translate(155) + "</a>");
      }
      
      newCommentInnerHTML += links.join('&nbsp;-&nbsp;');
      newCommentInnerHTML += "&nbsp;</div></div></div>";
      
      // ADD NEW INNERHTML
      newComment.setProperty('html', newCommentInnerHTML);
      newComment.inject(commentContainerElement);
      
      // ADD EVENTS
      if( newComment.getElement('.commentEditLink') ) newComment.getElement('.commentEditLink').addEvent('click', function()
      {
        bind.editComment(commentID);
      });
      
      if( newComment.getElement('.commentDeleteLink') ) newComment.getElement('.commentDeleteLink').addEvent('click', function()
      {
        bind.confirmDelete(commentID);
      });
    });
    
    // CREATE PAGINATION DIV
    if(this.options.paginate && this.total > this.options.cpp) { 
      var commentPaginationTop = new Element('div', {'styles': {'text-align' : 'right', 'margin-right' : '50px', 'color' : '#737373'}});
      var commentPaginationBottom = new Element('div', {'styles': {'text-align' : 'right', 'margin-right' : '50px', 'color' : '#737373'}});
      if(this.page > 1) {
        var paginationHTMLTop = "<a href='javascript:void(0);' id='comment_last_page_top'>&#171; " + bind.Base.Language.Translate(182) + "</a>";
        var paginationHTMLBottom = "<a href='javascript:void(0);' id='comment_last_page_bottom'>&#171; " + bind.Base.Language.Translate(182) + "</a>";
      } else {
        var paginationHTMLTop = "<font class='disabled'>&#171; " + bind.Base.Language.Translate(182) + "</font>";
        var paginationHTMLBottom = "<font class='disabled'>&#171; " + bind.Base.Language.Translate(182) + "</font>";
      }
      if(p_start == p_end) {
        paginationHTMLTop += "&nbsp;|&nbsp; " + this.Base.Language.TranslateFormatted(184, [p_start, this.total]) + "&nbsp;|&nbsp;";
        paginationHTMLBottom += "&nbsp;|&nbsp; " + this.Base.Language.TranslateFormatted(184, [p_start, this.total]) + "&nbsp;|&nbsp;";
      } else {
        paginationHTMLTop += "&nbsp;|&nbsp; " + this.Base.Language.TranslateFormatted(185, [p_start, p_end, this.total]) + "&nbsp;|&nbsp;";
        paginationHTMLBottom += "&nbsp;|&nbsp; " + this.Base.Language.TranslateFormatted(185, [p_start, p_end, this.total]) + "&nbsp;|&nbsp;";
      }
      if(this.page != maxpage) {
        paginationHTMLTop += "<a href='javascript:void(0);' id='comment_next_page_top'>" + bind.Base.Language.Translate(183) + " &#187;</a>";
        paginationHTMLBottom += "<a href='javascript:void(0);' id='comment_next_page_bottom'>" + bind.Base.Language.Translate(183) + " &#187;</a>";
      } else {
        paginationHTMLTop += "<font class='disabled'>" + bind.Base.Language.Translate(183) + " &#187;</font>";
        paginationHTMLBottom += "<font class='disabled'>" + bind.Base.Language.Translate(183) + " &#187;</font>";
      }
      commentPaginationTop.setProperty('html', paginationHTMLTop);
      commentPaginationBottom.setProperty('html', paginationHTMLBottom);
      //commentPaginationTop.inject(commentContainerElement, 'top');
      commentPaginationBottom.inject(commentContainerElement);

      // ADD EVENTS
      if( commentPaginationTop.getElement('a[id=comment_last_page_top]') ) commentPaginationTop.getElement('a[id=comment_last_page_top]').addEvent('click', function()
      {
        bind.getComments('previous');
      });

      if( commentPaginationBottom.getElement('a[id=comment_last_page_bottom]') ) commentPaginationBottom.getElement('a[id=comment_last_page_bottom]').addEvent('click', function()
      {
        bind.getComments('previous');
      });
      
      if( commentPaginationTop.getElement('a[id=comment_next_page_top]') ) commentPaginationTop.getElement('a[id=comment_next_page_top]').addEvent('click', function()
      {
        bind.getComments('next');
      });

      if( commentPaginationBottom.getElement('a[id=comment_next_page_bottom]') ) commentPaginationBottom.getElement('a[id=comment_next_page_bottom]').addEvent('click', function()
      {
        bind.getComments('next');
      });
    }

  },
  
  
  // Adds a comment
  addComment: function(is_error, comment_body, comment_date)
  {
    if( !this.options.canComment )
      return false;
    
    if( is_error )
    {
      $('comment_error').style.display = 'block';
      if( !comment_body.trim() )
      {
        this.addText($('comment_body'));
        $('comment_error').innerHTML = this.Base.Language.Translate(831);
      }
      else
      {
        $('comment_error').innerHTML = this.Base.Language.Translate(832);
      }
      $('comment_submit').value = this.Base.Language.Translate(833);
      $('comment_submit').disabled = false;
    }
    else
    {
      $('comment_error').style.display = 'none';
      $('comment_error').innerHTML = '';
      
      $('comment_body').value = '';
      $('comment_body').style.height = this.options.originalHeight + 'px';
      this.addText($('comment_body'));
      
      $('comment_submit').value = this.Base.Language.Translate(833);
      $('comment_submit').disabled = false;
      
      if( $('comment_secure') )
      {
        $('comment_secure').value = '';
        $('secure_image').src = $('secure_image').src + '?' + (new Date()).getTime();
      }
      
      // INPUT COMMENTS
      this.page = 1;
      this.total++;
      this.getComments();
    }
  },
  
  
  
  editComment: function(commentID)
  {
    var bind = this;
    if( this.isEditing ) return false;
    this.isEditing = true;
    
    
    //var commentContainerElement = $(this.options.type + '_' + this.options.typeID + '_comments');
    //var commentElement = commentContainerElement.getElement('profile_comment_body_' + commentID);
    var commentElement = $('profile_comment_body_' + commentID);
    
    var height = commentElement.offsetHeight + 10;
    var commentText = commentElement.innerHTML.replace(/<br>/gi, '\r\n').replace(/>/gi, '&gt;');
    
    var innerHTML = '';
    innerHTML += "<form action='misc_js.php' method='post' target='ajaxframe' name='editCommentForm'>";
    innerHTML += "<textarea name='comment_edit' id='comment_edit_" + commentID + "' style='height: " + height +" px; width: 100%;'>" + commentText + "</textarea>";
    innerHTML += "<input type='hidden' name='task' value='comment_edit'>";
    innerHTML += "<input type='hidden' name='comment_id' value='" + commentID + "'>";
    innerHTML += "<input type='hidden' name='type' value='" + this.options.type + "'>";
    innerHTML += "<input type='hidden' name='iden' value='" + this.options.typeIdentifier + "'>";
    innerHTML += "<input type='hidden' name='value' value='" + this.options.typeID + "'>";
    
    if( this.options.typeTab ) innerHTML += 
        '<input type="hidden" name="tab" value="' + this.options.typeTab + '">';
    
    if( this.options.typeCol ) innerHTML += 
        '<input type="hidden" name="col" value="' + this.options.typeCol + '">';
    
    if( this.options.typeTabParent ) innerHTML += 
        '<input type="hidden" name="tab_parent" value="' + this.options.typeTabParent + '">';
    
    if( this.options.typeColParent ) innerHTML += 
        '<input type="hidden" name="col_parent" value="' + this.options.typeColParent + '">';
    
    if( this.options.typeChild ) innerHTML += 
        '<input type="hidden" name="child" value="1">';
    
    
    innerHTML += "</form>";
    
    
    // Inject
    commentElement.innerHTML = innerHTML;
    //textarea_autogrow('comment_edit_' + commentID);
    $('comment_edit_' + commentID).focus();
    
    
    // Add events
    $('comment_edit_' + commentID).addEvent('blur', function()
    {
      document.editCommentForm.submit();
      bind.isEditing = false;
    });
  },
  
  
  
  confirmDelete: function(commentID)
  {
    $('del_comment_id').value = commentID;
    TB_show(this.Base.Language.Translate(1025), '#TB_inline?height=100&width=300&inlineId=confirmcommentdelete', '', '../images/trans.gif');
  },
  
  
  
  
  
  
  
  // UI Methods
  removeText: function(commentBody)
  {
    if( !this.changed )
    {
      commentBody.value = '';
      commentBody.style.color = '#000000';
      this.changed = true;
    }
  },
  
  
  
  addText: function(commentBody)
  {
    if( !commentBody.value.trim() )
    {
      commentBody.value = this.Base.Language.Translate(829);
      commentBody.style.color = '#888888';
      this.changed = false;
    }
  },
  
  
  
  checkText: function(commentBody)
  {
    if( !this.changed ) {
      $('comment_body').value='';
    }
    
    $('comment_submit').value = this.Base.Language.Translate(830);
    $('comment_submit').disabled = true;
  }
  
});

/* $Id: class_core.js 62 2009-02-18 02:59:27Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js

SocialEngineAPI.Core = new Class({
  
  // Properties
  Base: {},
  
  settings: {},
  
  plugins: {},
  
  options : {
    ajaxURL : 'js_api.php'
  },

  
  
  
  // Methods
  initialize: function()
  {
    
  },

  
  
  
  // Import Methods
  ImportSettings: function(settings)
  {
    this.settings = settings;
  },

  
  
  
  // Import Methods
  ImportPlugins: function(plugins)
  {
    this.plugins = plugins;
  }
  
});
/* $Id: class_language.js 62 2009-02-18 02:59:27Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js

if( typeof(SocialEngineAPI)=="undefined" )
  var SocialEngineAPI = {};

SocialEngineAPI.Language = new Class({
  
  // Properties
  Base: {},

  
  
  
  // Methods
  initialize: function()
  {
    this.languageVariables = new Hash();
  },
  
  
  Translate: function(id)
  {
    var rawValue = this.languageVariables.get(id) || 'Missing Language Variable #' + id;
    return rawValue;
  },
  
  
  TranslateFormatted: function(id, params)
  {
    var rawValue = this.languageVariables.get(id) || 'Missing Language Variable #' + id;
    params.unshift(rawValue);
    var formattedValue = sprintf.run(params);
    return formattedValue;
  },
  
  
  
  
  // Import Methods
  Import: function(languageVariableObject)
  {
    if( $type(languageVariableObject)=="object" )
      this.languageVariables.extend(languageVariableObject);
  }
  
});



// Backwards compatibilty
var SocialEngineLanguage = SocialEngineAPI.Language;
/* $Id: class_tags.js 130 2009-03-21 23:36:57Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js

// Required language variables: 39,1212,1213,1214,1215,1228

SocialEngineAPI.Tags = new Class({
  
  // Class
	Implements: [Options],
  
  
  
  
  // Properties
  Base: {},
  
  isTagging: false,

  newtag : false,

  tags : [],
  
  
  options: {
    // Controls ajax request options
    'ajaxURL' : 'misc_js.php',
    'ajaxMethod' : 'post',
    'ajaxSecure' : false,
    
    // Can the viewer media
    'canTag' : false,
    
    // The type of media ex. 'group'
    'type' : false,
    
    // The actual ID of the object being tagged
    'media_id' : false,

    // Path to the image
    'media_dir' : false,
    
    // Some other stuff to identify the object
    'object_owner' : false,
    'object_owner_id' : false
  },
  
  
  
  
  // Methods
  initialize: function(options)
  {
    this.setOptions(options);

    if( this.options.initialTotal ) this.total = this.options.initialTotal;

    var bind = this;
    window.addEvent('load', function() 	// instead of 'domready'
    {
      bind.showTagForm();
    });
  },
  
  
  
  showTagForm : function()
  {
    var innerHTML = "";
    var bind = this;

    if( this.options.canTag ) 
    {
      innerHTML +=
        "<div class='media_photo_tagform_titlebar'><img src='images/icons/photos16.gif' class='icon' />" + this.Base.Language.Translate(1212) + "</div>" +
        "<div style='padding: 7px;'>" +
        "<div style='text-align: left;'>" +
        "<div style='font-size: 7pt; margin-bottom: 5px;'>" + this.Base.Language.Translate(1213) + "</div>" +
        "<div style='text-align: center;'><input type='text' style='width: 130px; padding-left: 4px; font-size: 8pt;' name='media_photo_tag' id='media_photo_tag' class='text' maxlength='40'/></div>" +
        "</div>" +
        "<div id='media_photo_friendlist' class='media_photo_friendlist'>";
      
      if( bind.Base.Viewer.user_exists ) 
      {
        innerHTML += "<div><a href='javascript:void(0)' id='tag_me'>" + bind.Base.Viewer.user_displayname + bind.Base.Language.Translate(1214) + "</a></div>";
      }
      
      innerHTML += "</div>" +
        "<div>" +
        "<input type='button' class='button' name='save' id='tag_save' value='" + bind.Base.Language.Translate(1215) + "' />&nbsp;&nbsp;" +
        "<input type='button' class='button' id='tag_cancel' name='cancel' value='" + bind.Base.Language.Translate(39) + "' />" +
        "</div>" +
        "</div>";
      
      var newTagForm = new Element('div', {
        'id' : 'media_photo_tagform',
        'class' : 'media_photo_tagform',
        'html' : innerHTML
      });
      
      var mediaContainer = $('media_photo_div');
      newTagForm.inject(mediaContainer);
      
      // ADD EVENTS
      if( newTagForm.getElement('input[id=tag_cancel]') ) newTagForm.getElement('input[id=tag_cancel]').addEvent('click', function()
      {
        bind.cancelTag();
      });
      if( newTagForm.getElement('input[id=tag_save]') ) newTagForm.getElement('input[id=tag_save]').addEvent('click', function()
      {
        bind.saveTag(0);
      });
      if( newTagForm.getElement('a[id=tag_me]') ) newTagForm.getElement('a[id=tag_me]').addEvent('click', function()
      {
        bind.saveTag(bind.Base.Viewer.user_info.user_id);
      });
      
      var request = new Request.JSON({
        url: 'misc_js.php?task=friends_all',
        secure: this.options.ajaxSecure,
        onComplete: function(jsonObj)
        { 
          bind.addFriendToList(jsonObj.friends);
        }
      }).send();
    }
  },
  
  
  
  addFriendToList : function(friends)
  {
    var bind = this;
    
    friends.each(function(friend)
    {
      for(var x in friend)
      {
        var newDiv = new Element("div", {'id' : 'friend_div_'+x});
        var newAnchor = new Element("a", {'href' : 'javascript:void(0)', 
          'id' : 'friend_link_'+x,
          'html' : friend[x]
        }).inject(newDiv);
        
        newDiv.inject($('media_photo_friendlist'));
        
        $('friend_link_'+x).addEvent('click', function() { bind.saveTag(x); });
      }
    });
  },
  
  
  
  insertTag : function(tag_id, tag_link, tag_text, tag_x, tag_y, tag_width, tag_height, tagged_user)
  {
    var newHTML = '';
    var bind = this;
    
    if($('media_tags').style.display == 'none') 
    {
      $('media_tags').style.display = 'block';
    } else if(bind.tags.length != 0) 
    {
      newHTML = '<span id="tag_comma_'+tag_id+'">, </span>';
    }
    
    var newSpan = new Element("span", {'id' : 'full_tag_'+tag_id, 'html' : newHTML});
    if(tag_link != '') 
    {
      var newAnchor = new Element("a", {'href' : tag_link, 
        'id' : 'tag_link_'+tag_id,
        'html' : tag_text
      }).inject(newSpan);
    } 
    else
    {
      var newAnchor = new Element("span", {
        'id' : 'tag_link_'+tag_id,
				'html' : tag_text,
				'styles' : {'cursor' : 'pointer'}
			}).inject(newSpan);
    } 
    
    if( bind.Base.Viewer.user_exists && (bind.Base.Viewer.user_info.user_username == tagged_user || bind.Base.Viewer.user_info.user_username == bind.Base.Owner.user_info.user_username)) 
    {
      var media_tags_text = $(newSpan).get('html');
      $(newSpan).set('html', media_tags_text, ' (<a href=\'javascript:void(0);\' id=\'new_removetag_link\'>' + bind.Base.Language.Translate(1228) + '</a>)');
    }
    
    newSpan.inject($('media_tags'));
    
    bind.createTag(tag_id, tag_text, tag_x, tag_y, tag_width, tag_height);
    
    $('tag_link_'+tag_id).addEvent('mouseover', function() { bind.showTag(tag_id); });
    $('tag_link_'+tag_id).addEvent('mouseout', function() { bind.hideTag(tag_id); });
    
    if($('new_removetag_link'))
    {
      $('new_removetag_link').addEvent('click', function() { bind.removeTag(tag_id); });
      $('new_removetag_link').set('id', 'removetag_link_'+tag_id);
    }
    
    bind.tags.push(tag_id);
  },
  
  
  
  createTag : function(tag_id, label_text, tag_x, tag_y, tag_width, tag_height)
  {
    var bind = this;
      
    // CREATE TAG AND LABEL
    new Element("div", {'id' : 'tag_'+tag_id, 'html' : '<img src="./images/trans.gif" width="100%" height="100%" />', 'class' : 'tag_div_hidden', 'styles' : {'width' : (parseInt(tag_width)-4)+'px', 'height' : (parseInt(tag_height)-4)+'px', 'top' : tag_x+'px', 'left' : tag_y+'px'}}).inject($('media_photo_div'));
    new Element("div", {'id' : 'tag_label_'+tag_id, 'html' : label_text, 'class' : 'tag_label', 'styles' : {'display' : 'none', 'top' : (parseInt(tag_x)+parseInt(tag_height)+10)+'px', 'left' : tag_y+'px'}}).inject($('media_photo_div'));
    
    // ADD MOUSEOVER/MOUSEOUT EVENTS
    $('tag_'+tag_id).addEvent('mouseover', function() { bind.showTag(tag_id); });
    $('tag_'+tag_id).addEvent('mouseout', function() { bind.hideTag(tag_id); });
  },
  
  
  
  showTag : function(tag_id)
  {
    $('tag_'+tag_id).className = 'tag_div';
    $('tag_label_'+tag_id).style.display = 'block';
  },
  
  
  
  hideTag : function(tag_id)
  {
    $('tag_'+tag_id).className = 'tag_div_hidden';
    $('tag_label_'+tag_id).style.display = 'none';
  },
  
  
  
  addTag : function()
  {
    if( !this.isTagging )
    {
      this.isTagging = true;
      this.newtag = new MooCrop('media_photo');
      
      var bind = this;

      var indicator = $('media_photo_tagform').inject(bind.newtag.wrapper);
      indicator.setStyles({'top' : this.newtag.crop.bottom+10, 'left' : this.newtag.crop.right+10, 'display' : 'block'});
      
      this.newtag.addEvent('onBegin', function(imgsrc, crop, bound, hanlde) { indicator.setStyle('display', 'none'); });
      this.newtag.addEvent('onCrop', function(imgsrc, crop, bound, hanlde) { indicator.setStyles({'top' : crop.bottom+10, 'left' : crop.right+10, 'display' : 'none'}); });
      this.newtag.addEvent('onComplete', function(imgsrc, crop, bound, hanlde) { indicator.setStyle('display', 'block'); });
    }
  },
  
  
  
  cancelTag : function()
  {
    if( this.isTagging )
    {
      $('media_photo_tag').value = '';
      $('media_photo_tagform').inject('media_photo_div').setStyle('display', 'none');
      var stopTagging = this.newtag.removeOverlay.bind(this.newtag);
      stopTagging();
      this.isTagging = false;
    }
  },
  
  
  
  saveTag : function(mediatag_user_id)
  {
    if( this.isTagging )
    {
      if( this.options.object_owner && this.options.object_owner_id )
      {
        var object_owner = this.options.object_owner;
        var object_owner_id = this.options.object_owner_id;
        var user = '';
      }
      else
      {
        var object_owner = '';
        var object_owner_id = '';
        var user = this.Base.Owner.user_info.user_username;      
      }
      
      // Use ajax only
      var bind = this;
      var request = new Request.JSON({
        url: this.options.ajaxURL,
        method: this.options.ajaxMethod,
        secure: this.options.ajaxSecure,
        data: {
          'task' : 'tag_do',
          'ajax' : true,
          'mediatag_user_id' : mediatag_user_id,
          'mediatag_text' : $('media_photo_tag').value,
          'mediatag_x' : this.newtag.crop.top,
          'mediatag_y' : this.newtag.crop.left,
          'mediatag_height' : this.newtag.crop.height,
          'mediatag_width' : this.newtag.crop.width,
          'user' : user,
          'object_owner' : object_owner,
          'object_owner_id' : object_owner_id,
          'type' : this.options.type,
          'media_id' : this.options.media_id,
          'media_dir' : this.options.media_dir
        },
        onComplete: function(jsonObj)
        {
          if( $type(jsonObj.mediatag_id) )
          {
            bind.insertTag(
              jsonObj.mediatag_id,
              jsonObj.mediatag_link,
              jsonObj.mediatag_text,
              jsonObj.mediatag_x,
              jsonObj.mediatag_y,
              jsonObj.mediatag_width,
              jsonObj.mediatag_height,
              jsonObj.mediatag_user_username
            );
          }
        }
      }).send();
      
      // Stuff
      $('media_photo_tag').value = '';
      $('media_photo_tagform').inject('media_photo_div').setStyle('display', 'none');
      var stopTagging = this.newtag.removeOverlay.bind(this.newtag);
      stopTagging();
      this.isTagging = false;
    }
  },
  
  
  
  removeTag : function(tag_id)
  {
    if( this.options.object_owner && this.options.object_owner_id )
    {
      var object_owner = this.options.object_owner;
      var object_owner_id = this.options.object_owner_id;
      var user = '';
    }
    else
    {
      var object_owner = '';
      var object_owner_id = '';
      var user = this.Base.Owner.user_info.user_username;      
    }
    
    // Use ajax only
    var bind = this;
    var request = new Request.JSON({
      url: this.options.ajaxURL,
      method: this.options.ajaxMethod,
      secure: this.options.ajaxSecure,
      data: {
        'task' : 'tag_remove',
        'ajax' : true,
        'mediatag_id' : tag_id,
        'user' : user,
        'object_owner' : object_owner,
        'object_owner_id' : object_owner_id,
        'type' : this.options.type,
        'media_id' : this.options.media_id
      }
    }).send();
    
    // Destroy stuff
    $('tag_'+tag_id).destroy();
    $('tag_label_'+tag_id).destroy();
    
    $('full_tag_'+tag_id).destroy();
    
    if(this.tags.indexOf(tag_id) == 0 && $('tag_comma_'+this.tags[1]))
    {
      $('tag_comma_'+this.tags[1]).destroy();
    }
    
    this.tags.splice(this.tags.indexOf(tag_id), 1);
    
    if(this.tags.length == 0)
    {
      $('media_tags').style.display = 'none';
    }
  }
});








/***
 * MooCrop (v. rc-1 - 2007-10-24 )
 *
 * @version			rc-1
 * @license			BSD-style license
 * @author			nwhite - < nw [at] nwhite.net >
 * @infos			http://www.nwhite.net/MooCrop/
 * @copyright		Author
 * 

 */
var MooCrop = new Class({

	calculateHandles : true,
	current : {},

	options : {
		maskColor : 'black',
		maskOpacity : '.3',
		handleColor : '#FFFFFF',
		handleWidth : '5px',
		handleHeight : '5px',
		cropBorder : '1px dashed #FFFFFF',
		min : { 'width' : 50, 'height' : 50 },
		showMask : true, // false to remove, helps on slow machines
		showHandles : false // hide handles on drag
	},

	initialize: function(el, options){
		this.setOptions(options);
		this.img = $(el);
		if ( this.img.get('tag') != 'img') return false;

		this.resizeFunc = this.refresh.bindWithEvent(this);
		this.removeFunc = this.removeListener.bind(this);

		this.buildOverlay();
		this.setup();
	},

	setup: function(){
		$(this.cropArea).setStyles({
			'width': this.options.min.width, 
			'height': this.options.min.height,
			'top' : (this.img.height - this.options.min.height)/2,
			'left': (this.img.width - this.options.min.width) / 2 
		});

		this.current.crop = this.crop = this.getCropArea();
		this.handleWidthOffset = this.options.handleWidth.toInt() / 2;
		this.handleHeightOffset = this.options.handleHeight.toInt() /2;

		this.fixBoxModel();
		this.drawMasks();
		this.positionHandles();
	},

	getCropArea : function(){
		var crop = this.cropArea.getCoordinates();
		crop.left -= this.offsets.x; crop.right -= this.offsets.x; // calculate relative (horizontal)
		crop.top -= this.offsets.y; crop.bottom  -= this.offsets.y; // calculate relative (vertical)
		return crop;
	},

	fixBoxModel : function(){
		var diff = this.boxDiff = (this.crop.width - this.options.min.width)/2;

		var b = this.bounds = { 'top' : diff, 'left' : diff, 
			'right' : this.img.width+(diff*2), 'bottom' : this.img.height+(diff*2),
			'width' : this.options.min.width+(diff*2), 'height' : this.options.min.height+(diff*2) };

		this.wrapper.setStyles({
			'width' : b.right, 'height' : b.bottom,
			'background' : 'url('+this.img.src+') no-repeat '+diff+'px '+diff+'px'
		});

		this.north.setStyle('width',b.right);
		this.south.setStyle('width',b.right);
	},

	activate : function(event,handle){
		event.stop();
		this.current = { 'x' : event.page.x, 'y' : event.page.y, 'handle' : handle, 'crop' : this.current.crop };
		if(this.current.handle == 'NESW' && !this.options.showHandles) this.hideHandles();
		this.fireEvent('onBegin',[this.img.src,this.getCropInfo(),this.bounds,handle]);
		document.addEvent('mousemove', this.resizeFunc);
		document.addEvent('mouseup', this.removeFunc);
	},

	removeListener : function(){
		if( this.current.handle == 'NESW' && !this.options.showHandles) this.showHandles();
		document.removeEvent('mousemove', this.resizeFunc);
		document.removeEvent('mouseup', this.removeFunc);
		this.crop = this.current.crop;
		this.fireEvent('onComplete',[this.img.src,this.getCropInfo(),this.bounds,this.current.handle]);
	},

	refresh : function(event){
		var xdiff = this.current.x - event.page.x;
		var ydiff = this.current.y - event.page.y;

		var b = this.bounds;  var c = this.crop;  var handle = this.current.handle; var styles = {}; //saving bytes
		var dragging = (handle.length > 2) ? true : false;
		
		if( handle.contains("S") ){//SOUTH
			if(c.bottom - ydiff > b.bottom ) ydiff = c.bottom - b.bottom; // box south
			if(!dragging){
				if( (c.height - ydiff) < b.height ) ydiff = c.height - b.height; // size south
				styles['height'] = c.height - ydiff; // South handles only
			}
		}
		if( handle.contains("N") ){//NORTH
			if(c.top - ydiff < b.top ) ydiff = c.top; //box north
			if(!dragging){
				if( (c.height + ydiff ) < b.height ) ydiff = b.height - c.height; // size north
				styles['height'] = c.height + ydiff; // North handles only
			}
			styles['top'] = c.top - ydiff; // both Drag and N handles
		}
		if( handle.contains("E") ){//EAST
			if(c.right - xdiff > b.right) xdiff = c.right - b.right; //box east
			if(!dragging){
				if( (c.width - xdiff) < b.width ) xdiff = c.width - b.width; // size east
				styles['width'] = c.width - xdiff;
			}
		}
		if( handle.contains("W") ){//WEST
			if(c.left - xdiff < b.left) xdiff = c.left; //box west
			if(!dragging){
				if( (c.width + xdiff) < b.width ) xdiff = b.width - c.width; //size west
				styles['width'] = c.width + xdiff;
			}
			styles['left'] = c.left - xdiff; // both Drag and W handles
		}
		var preCssStyles = $merge(styles);
		if( $defined(styles.width)) styles.width -= this.boxDiff*2;
		if( $defined(styles.height)) styles.height -= this.boxDiff*2;

		this.cropArea.setStyles(styles);
		this.getCurrentCoords(preCssStyles);
		this.drawMasks();
		this.positionHandles();
		this.fireEvent('onCrop',[this.img.src,this.getCropInfo(),b,handle]);
	},

	getCurrentCoords : function(changed){
		var current = $merge(this.crop);
		
		if($defined(changed.left)){
			current.left = changed.left;
			if($defined(changed.width)) current.width = changed.width;
			else current.right = current.left + current.width;
		}
		if($defined(changed.top)){
			current.top = changed.top;
			if($defined(changed.height)) current.height = changed.height;
			else current.bottom = current.top + current.height;
		}
		if($defined(changed.width) && !$defined(changed.left)){
			current.width = changed.width; current.right = current.left + current.width;
		}
		if($defined(changed.height) && !$defined(changed.top)){
			current.height = changed.height; current.bottom = current.top + current.height;
		}
		this.current.crop = current;
	},

	drawMasks : function(){
		if(!this.options.showMask) return;
		var b = this.bounds;  var c = this.current.crop; var handle = this.current.handle;

		this.north.setStyle('height', c.top + 'px' );
		this.south.setStyle('height', b.bottom  - c.bottom  + 'px');
		this.east.setStyles({ height: c.height + 'px', width: b.right  - c.right + 'px',  top: c.top  + 'px', left: c.right + 'px'});
		this.west.setStyles({ height: c.height + 'px', width: c.left + 'px', top: c.top + 'px'});
	},

	positionHandles: function(){
		if(!this.calculateHandles) return;
		var c = this.current.crop; var wOffset = this.handleWidthOffset; var hOffset = this.handleHeightOffset;

		this.handles.get('N').setStyles({'left' : c.width / 2 - wOffset + 'px', 'top' : - hOffset + 'px'});
		this.handles.get('NE').setStyles({'left' : c.width - wOffset + 'px', 'top' : - hOffset + 'px'});
		this.handles.get('E').setStyles({ 'left' : c.width - wOffset + 'px', 'top' : c.height / 2 - hOffset + 'px'});
		this.handles.get('SE').setStyles({'left' : c.width - wOffset + 'px', 'top' : c.height - hOffset + 'px'});
		this.handles.get('S').setStyles({'left' : c.width / 2 - wOffset + 'px', 'top' : c.height - hOffset + 'px'});
		this.handles.get('SW').setStyles({'left' : - wOffset + 'px', 'top' : c.height - hOffset + 'px'});
		this.handles.get('W').setStyles({'left' : - wOffset + 'px', 'top' : c.height / 2 - hOffset + 'px'});
		this.handles.get('NW').setStyles({'left' : - wOffset + 'px', 'top' : - hOffset + 'px'});
	},

	hideHandles: function(){
		this.calculateHandles = false;
		this.handles.each(function(handle){
			handle.setStyle('display','none');
		});
	},

	showHandles: function(){
		this.calculateHandles = true;
		this.positionHandles();
		this.handles.each(function(handle){
			handle.setStyle('display','block');
		});
	},

	buildOverlay: function(){
		var o = this.options;

		this.wrapper = new Element("div", {
			'styles' : {'z-index' : 100, 'position' : 'relative', 'width' : this.img.width, 'height' : this.img.height, 'background' : 'url('+this.img.src+') no-repeat' , 'float' : this.img.getStyle('float') , 'margin-left' : 'auto' , 'margin-right' : 'auto'  }
		}).injectBefore(this.img);

		this.img.setStyle('display','none');

		this.offsets = { x : this.wrapper.getLeft(), y : this.wrapper.getTop() };

		// SET WRAPPER MOUSEOVER TO STOP PROPAGATION OF MOUSEOVER EVENT
		this.wrapper.addEvent('mouseover', function(event) { return false; });

		if(this.options.showMask){		// optional masks
			var maskStyles = { 'position' : 'absolute', 'overflow' : 'hidden', 'background-color' : o.maskColor, 'opacity' : o.maskOpacity};
			this.north = new Element("div", {'styles' : $merge(maskStyles,{'left':'0px'})}).injectInside(this.wrapper);
			this.south = new Element("div", {'styles' : $merge(maskStyles,{'bottom':'0px', 'left':'0px'})}).injectInside(this.wrapper);
			this.east =  new Element("div", {'styles' : maskStyles}).injectInside(this.wrapper);
			this.west =  new Element("div", {'styles' : $merge(maskStyles,{'left':'0px'})}).injectInside(this.wrapper);
		}

		this.cropArea = new Element("div", { 'styles' : { 'position' : 'absolute', 'top' : '0px', 'left' : '0px', 'border' : o.cropBorder, 'cursor' : 'move' },
		'events' : {
			'dblclick' : function(){ this.fireEvent('onDblClk',[this.img.src,this.getCropInfo(),this.bounds])}.bind(this),
			'mousedown' : this.activate.bindWithEvent(this,'NESW')}
		}).injectInside(this.wrapper);

		this.handles = new Hash();
		['N','NE','E','SE','S','SW','W','NW'].each(function(handle){
			this.handles.set(handle, new Element("div", {
			'styles' : { 'position' : 'absolute', 'background-color' : o.handleColor, 
						 'width' : o.handleWidth, 'height' : o.handleHeight, 'overflow' : 'hidden', 'cursor' : (handle.toLowerCase()+'-resize')},
			'events' : {'mousedown' : this.activate.bindWithEvent(this,handle)}
			}).injectInside(this.cropArea));
		},this);
	},

	getCropInfo : function(){
		var c = $merge(this.current.crop);
		c.width -= this.boxDiff*2; c.height -= this.boxDiff*2;
		return c;
	},

	removeOverlay: function(){
		this.wrapper.destroy();
		this.img.setStyle('display','');
	}

});
MooCrop.implement(new Events, new Options);
/* $Id: class_url.js 62 2009-02-18 02:59:27Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js

SocialEngineAPI.URL = new Class({
  
  // Properties
  Base: {},
  
  url_base : null,
  
  url_info : {},
  
  
  
  // Methods
  initialize: function()
  {
    
  },
  
  
  url_create: function(name, user, id1, id2, id3)
  {
    var url_template = ( SocialEngine.Core.settings.setting_url ? this.url_info[name].url_subdirectory : this.url_info[name].url_regular );
    if( !url_template ) return false;
    
    url_template = url_template.replace('$user', user);
    url_template = url_template.replace('$id1', id1);
    url_template = url_template.replace('$id2', id2);
    url_template = url_template.replace('$id3', id3);
    
    return this.url_base + url_template;
  },
  
  
  url_userdir: function(user_id)
  {
    //alert(user_id + ' ' + ((user_id - 1) % 1000).toString());
    return 'uploads_user/' + (user_id + 999 - ((user_id - 1) % 1000)).toString() + '/' + user_id + '/';
  },
  
  
  
  
  
  // Import methods
  ImportURLBase: function(url_base)
  {
    this.url_base = url_base;
  },
  
  ImportURLInfo: function(url_info)
  {
    this.url_info = url_info;
  }
  
  
});
/* $Id: class_user.js 151 2009-04-01 06:14:22Z john $ */

// Required language vars: 743-747,773,1113 (status) 759 (delete), 1199 (notifys)

// This file will no longer be included by default. A minified version is included as part of core-min.js

SocialEngineAPI.User = new Class({
  
  // Properties
  Base: {},
  
  user_exists : false,
  
  user_displayname : false,
  
  user_displayname_short : false,
  
  user_info : {},
  
  profile_info : {},
  
  level_info : {},
  
  usersetting_info : {},
  
  options : {
    // Controls ajax request options
    'ajaxURL' : 'misc_js.php',
    'ajaxMethod' : 'post',
    'ajaxSecure' : false,
    
    // Display name order method
    'displayname_order' : 'standard'
  },
  
  user_status: '',
  
  user_notify_cookie: {},
  
  user_notify_count: 0,
  
  
  
  // Methods
  initialize: function()
  {
    
  },
  
  
  userPhotoFullPath: function()
  {
    // No URL class
    if( !this.Base.URL )
      return false;
    
    // No user photo
    if( !this.user_info.user_photo )
      return this.Base.URL.url_base + 'images/nophoto.gif';
      
    return this.Base.URL.url_base + this.Base.URL.url_userdir(this.user_info.user_id) + this.user_info.user_photo;
  },
  
  
  
  // Methods - user status
  userStatusChange: function()
  {
    if( !$('ajax_status') ) return false;
    
    var userStatus = this.user_status.replace(/<wbr>/g, '').replace(/&shy;/g, '');
    
    var statusHTML = this.user_displayname_short + 
      " <input type='text' class='text_small' name='status_new' id='status_new' maxlength='100' value='";
    
    statusHTML += ( userStatus=='' ? this.Base.Language.Translate(744) : userStatus );
    statusHTML += "' size='10' style='width: 140px; margin: 2px 0px 2px 0px;' onkeypress='return ( (new Event(event)).key==\"enter\" ? SocialEngine.Viewer.userStatusChangeSubmit() : true );'>" +
      "<br />" +
      "<a href='javascript:void(0);' onclick='SocialEngine.Viewer.userStatusChangeSubmit(); return false;'>" +
        this.Base.Language.Translate(746) +
      "</a> | <a href='javascript:void(0);' onclick='SocialEngine.Viewer.userStatusChangeReturn(); return false;'>" +
        this.Base.Language.Translate(747) +
      "</a>";
    
    $('ajax_status').innerHTML = statusHTML;
    $('status_new').focus();
    $('status_new').select();
  },
  
  
  userStatusChangeReturn: function()
  {
    if( !$('ajax_status') ) return false;
    
    if( this.user_status=='' )
    {
      $('ajax_status').innerHTML = "<a href='javascript:void(0);' onclick='SocialEngine.Viewer.userStatusChange(); return false;'>" + this.Base.Language.Translate(743) + "</a>";
    }
    else
    {
      $('ajax_status').innerHTML = 
        "<div id='ajax_status'>" + this.user_displayname_short +
          " <span id='ajax_currentstatus_value'>" + this.user_status + "</span><br />" +
          "<div style='padding-top: 5px;'>" +
            "<div style='float: left; padding-right: 5px;'>" +
              "[ <a href='javascript:void(0);' onClick='SocialEngine.Viewer.userStatusChange(); return false;'>" + this.Base.Language.Translate(745) + "</a> ]" +
            "</div>" +
            "<div class='home_updated'>" +
              "<span id='ajax_currentstatus_date'>" + this.Base.Language.Translate(1113) + " " + this.Base.Language.TranslateFormatted(773, [1]) + "</span>" +
            "</div>" +
            "<div style='clear: both; height: 0px;'></div>" +
          "</div>" +
        "</div>";
    }
  },
  
  
  userStatusChangeSubmit: function()
  {
    if( !$('ajax_status') ) return false;
    
    var bind = this;
    var request = new Request.JSON({
      'url' : this.options.ajaxURL,
      'method' : this.options.ajaxMethod,
      'secure' : this.options.ajaxSecure,
      'data' : {
        'task'  : 'status_change',
        'status'  : $('status_new').value
      },
      'onComplete' : function(responseObject, responseText)
      {
        bind.user_status = responseObject.status;
        bind.userStatusChangeReturn();
      }
    }).send();
  },
  
  
  
  // Methods - user status
  userDelete: function()
  {
    TB_show(this.Base.Language.Translate(759), '#TB_inline?height=100&width=300&inlineId=confirmdelete', '', '../images/trans.gif');
  },
  
  
  userDeleteConfirm: function(delete_token)
  {
    var bind = this;
    var request = new Request.JSON({
      'url' : 'user_account_delete.php',
      'method' : this.options.ajaxMethod,
      'secure' : this.options.ajaxSecure,
      'data' : {
        'task'  : 'dodelete',
        'token'  : delete_token
      },
      'onComplete' : function(responseObject, responseText)
      {
        window.location = 'home.php';
      }
    }).send();
  },
  
  
  
  // Methods - actions
  userActionDelete: function(action_id)
  {
    var bind = this;
    var request = new Request.JSON({
      'url' : this.options.ajaxURL,
      'method' : this.options.ajaxMethod,
      'secure' : this.options.ajaxSecure,
      'data' : {
        'task'  : 'action_delete',
        'action_id'  : action_id
      },
      'onComplete' : function(responseObject, responseText)
      {
        if( $('action_' + action_id) )
        {
          $('action_' + action_id).style.display = 'none';
          total_actions--;
          if( total_actions == 0 )
            $('actions').style.display = "none";
        }
      }
    }).send();
  },
  
  
  
  // Methods - notifications
  userNotifyShow: function()
  {
    this.user_notify_cookie = new Hash.Cookie('se_show_newupdates', {duration: 3600});
    var minimizedCount = parseInt(this.user_notify_cookie.get('total'));
    if( !$type(minimizedCount) ) minimizedCount = 0;

    if( minimizedCount < this.user_notify_count )
    {
      this.user_notify_cookie.set('total', 0);
      $('newupdates').style.display = 'block';
      $('newupdates').fade('in');
    }
  },
  
  
  userNotifyPopup: function()
  {
    TB_show(this.Base.Language.Translate(1198), '#TB_inline?height=150&width=300&inlineId=newupdates_popup', '', './images/trans.gif');
  },
  
  
  userNotifyUpdate: function()
  {
    var bind = this;
    var request = new Request.JSON({
      'url' : this.options.ajaxURL,
      'method' : this.options.ajaxMethod,
      'secure' : this.options.ajaxSecure,
      'data' : {
        'task'  : 'notify_get'
      },
      'onComplete' : function(responseObject, responseText)
      {
        bind.userNotifyGenerate(responseObject);
        bind.userNotifyShow();
      }
    }).send();
  },
  
  
  userNotifyGenerate: function(notifyData)
  {
    if( !$type(notifyData.notifys) || notifyData.notifys.length==0 || !$('newupdates_popup') )
    {
      $('notify_total').innerHTML = this.user_notify_count = 0;
      return;
    }
    
    // Update count in red box
    //$('notify_total').innerHTML = this.user_notify_count = notifyData.total;
    $('notify_total').innerHTML = this.user_notify_count = notifyData.total_grouped;
    
    // Update popup contents
    var HTML =
      "<div style='margin-top: 10px;'>" +
        this.Base.Language.TranslateFormatted(1199, ["<span id='notifyscount'>" + notifyData.total_grouped + "</span>"]) + 
      "</div>";
    
    notifyData.notifys.each(function(notify_info)
    {
      HTML +=
        "<div style='font-weight: bold; padding-top: 5px;' id='notify_" + notify_info.notifytype_id + "_" + notify_info.notify_grouped + "'>" +
          "<a href='javascript:void(0);' onClick=\"SocialEngine.Viewer.userNotifyDelete('" + notify_info.notifytype_id + "', '" + notify_info.notify_grouped + "');\">X</a>" +
          "<img src='./images/icons/" + notify_info.notify_icon + "' border='0' style='border: none; margin: 0px 5px 0px 5px; display: inline; vertical-align: middle;' class='icon' />" +
          "<a href='" + notify_info.notify_url + "'>" + notify_info.notify_text_output + "</a>" +
        "</div>";
    });
    
    $('newupdates_popup').innerHTML = HTML;
  },
  
  
  userNotifyDelete: function(notifytype_id, notify_grouped)
  {
    var bind = this;
    var request = new Request.JSON({
      'url' : this.options.ajaxURL,
      'method' : this.options.ajaxMethod,
      'secure' : this.options.ajaxSecure,
      'data' : {
        'task'  : 'notify_delete',
        'notifytype_id'  : notifytype_id,
        'notify_grouped'  : notify_grouped
      },
      'onComplete' : function(responseObject, responseText)
      {
        $("TB_window").getElements('div[id=notify_'+notifytype_id+'_'+notify_grouped+']').each(function(el)
        {
          if(el.id == 'notify_'+notifytype_id+'_'+notify_grouped)
          {
            el.style.display = 'none';
            bind.user_notify_count--;
          }
        });
        
        $('newupdates_popup').getElements('div[id=notify_'+notifytype_id+'_'+notify_grouped+']').each(function(el)
        {
          if(el.id == 'notify_'+notifytype_id+'_'+notify_grouped)
          el.style.display = 'none';
        });
        
        $('notify_total').innerHTML = bind.user_notify_count;
        
        $("TB_window").getElements('span[id=notifyscount]').each(function(el)
        {
          if(el.id == 'notifyscount') el.innerHTML = bind.user_notify_count;
        });
        
        if( bind.user_notify_count == 0 )
        {
          TB_remove();
          $('newupdates').style.display = 'none';
        }
      }
    }).send();
  },
  
  
  userNotifyHide: function()
  {
    $('newupdates').fade('out');
    this.user_notify_cookie.set('total', this.user_notify_count)
  },
  
  
  userPhotoRemove: function()
  {
    var bind = this;
    var request = new Request.JSON({
      'url' : 'user_editprofile_photo.php',
      'method' : this.options.ajaxMethod,
      'secure' : this.options.ajaxSecure,
      'data' : {
        'task'  : 'remove'
      }
    }).send();
    
    if( $('userEditRemovePhotoLink' ) && $('userEditPhotoImg') )
    {
      $('userEditRemovePhotoLink' ).destroy();
      $('userEditPhotoImg' ).src = 'images/nophoto.gif';
    }
    
    else
    {
      window.location.reload( false );
    }
  },
  
  
  
  
  
  // Import methods
  ImportUserInfo: function(user_info)
  {
    // Handle anonymous users
    if( !user_info || $type(user_info)!="object" || !user_info.user_exists )
    {
      this.user_exists = false;
      return;
    }
    
    this.user_exists = true;
    
    // Prepare data
    user_info.user_id = parseInt(user_info.user_id);
    delete user_info.user_exists;
    
    // Save user info
    this.user_info = user_info;
    
    // Generate display name
    this.user_info.user_fname = this.user_info.user_fname.trim();
    this.user_info.user_lname = this.user_info.user_lname.trim();
    
    if( this.user_info.user_fname && this.user_info.user_lname )
    {
      // Asian
      if( this.options.displayname_order=="asian" )
      {
        this.user_displayname_short = this.user_info.user_lname;
        this.user_displayname = this.user_info.user_lname + ' ' + this.user_info.user_fname;
      }
      
      // Standard
      else
      {
        this.user_displayname_short = this.user_info.user_fname;
        this.user_displayname = this.user_info.user_fname + ' ' + this.user_info.user_lname;
      }
    }
    
    else if( this.user_info.user_fname )
    {
      this.user_displayname = this.user_displayname_short = this.user_info.user_fname;
    }
    
    else if( this.user_info.user_lname )
    {
      this.user_displayname = this.user_displayname_short = this.user_info.user_lname;
    }
    
    else if( this.user_info.user_username )
    {
      this.user_displayname = this.user_displayname_short = this.user_info.user_username;
    }
  }
  
});
/* $Id: autogrow.js 62 2009-02-18 02:59:27Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js



/*
 * SocialEngineMods Javascript Library Lite v0.1
 * http://www.SocialEngineMods.Net
 *
 * Copyright SocialEngineMods.Net
 * This code is licensed GPL for use exclusively on SocialEngine sites
 *
 */





/* Extensions */


Function.prototype.bind = function(obj) {
  var method = this, temp = function() {
    return method.apply(obj, arguments)
  };
  return(temp);
}; 


/* SEMods */


SEMods = function () {};

/* SEMods TextAreaControl */


SEMods.TextAreaControl = function(object) {
    this.obj = object;
    this.obj.style['overflow'] = 'hidden';
    this.originalHeight = this.obj.getStyle('height').toInt();
    var updater = this.update.bind(this);
    object.addEvent("focus", this.onFocus.bind(this));
    object.addEvent("blur", this.onBlur.bind(this));
    this.update();
};

SEMods.TextAreaControl.prototype = {
    obj : null,
    updating : false,
    autoGrow : false,
    originalHeight : null,
    shadowElement : null,
    increment : 0,
    timer : null,
    lastLength : 0,
    
    setAutoGrow : function(autoGrow) {
        this.autoGrow = autoGrow;
        this.createShadowElement();
        this.update();
    },
    
    onUpdate : function() {
        if(this.autoGrow && this.lastLength != this.obj.value.length) {
            this.lastLength = this.obj.value.length;
            this.updateShadowElement();
            this.obj.style.height = Math.max(this.originalHeight, this.shadowElement.offsetHeight + this.increment) + 'px';
        }
    },
    
    beginUpdate : function() {
        if(this.updating)
            return false;
        this.updating = true;
        return true;
    },
    
    endUpdate : function() {
        this.updating = false;
    },
    
    update : function() {
        if(!this.beginUpdate())
            return;
        
        this.onUpdate();
        this.endUpdate();
    },
    
    createShadowElement : function() {
        if(this.shadowElement)
            return;
        
        this.shadowElement = document.createElement("DIV");
        this.shadowElement.style.position = "absolute";
        this.shadowElement.style.top = "-99999px";
        this.shadowElement.style.left = "-99999px";
        
        document.body.appendChild(this.shadowElement);
    },
    
    updateShadowElement : function () {
        if(this.shadowElement) {
	    text = this.obj.value+'<br>';
            this.shadowElement.innerHTML = text.toString().replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#039;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br />');
            var fontSize = this.getPXMetrics( this.obj.getStyle('font-size'), 10);
            var lineHeight = this.obj.getStyle('line-height');
            // Opera misses on line-height
            if((/Opera/i.test(navigator.userAgent))) 
              lineHeight = this.getPXMetrics( lineHeight, 0) + 3 + 'px';
              
            this.increment = fontSize + 10;
        
            this.shadowElement.style['width'] = this.obj.offsetWidth + 'px';
            this.shadowElement.style['lineHeight'] = lineHeight;
            this.shadowElement.style['fontSize'] = this.obj.getStyle('font-size');

            this.shadowElement.style['fontFamily'] = this.obj.getStyle('font-family');
            this.shadowElement.style['paddingLeft'] = this.obj.getStyle('padding-left');
            this.shadowElement.style['paddingRight'] = this.obj.getStyle('padding-right');
            
        } 
    },
    
    onFocus : function() {
      this.timer = setInterval(this.update.bind(this), 500);
    },
    
    onBlur : function() {
      if(this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    // em's not supported for now
    getPXMetrics : function(metric, defvalue) {
      var metricBase = parseFloat(metric);
      if(isNaN(metricBase)) return defvalue!=null ? defvalue : metricBase;
      return /px/i.test(metric) ? metricBase : /pt/i.test(metric) ? 1.3333*metricBase  : metricBase;
    }
    
};


/* Global namespace helper functions */


function textarea_autogrow(elementid) {
    var el = $(elementid);
//    if(!el) alert("textarea_autogrow(): element not found");
    if(el && !el._controlled) {
        el._controlled = true;
        new SEMods.TextAreaControl(el).setAutoGrow(true);
	return el.getStyle('height').toInt();
    }
};

/* $Id: activate_flash.js 62 2009-02-18 02:59:27Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js

theObjects = document.getElementsByTagName("object");
for (var i = 0; i < theObjects.length; i++) {
theObjects[i].outerHTML = theObjects[i].outerHTML;
}

/* $Id: autosuggest.js 62 2009-02-18 02:59:27Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js



// author: Timothy Groves - http://www.brandspankingnew.net
// version:	2.1.3 - 2007-07-19



if (typeof(bsn) == "undefined")
	_b = bsn = {};


if (typeof(_b.Autosuggest) == "undefined")
	_b.Autosuggest = {};
// unneccessary alert
//else
//	alert("Autosuggest is already set!");












_b.AutoSuggest = function (id, param)
{
	// no DOM - give up!
	//
	if (!document.getElementById)
		return 0;
	
	
	
	
	// get field via DOM
	//
	this.fld = _b.DOM.gE(id);

	if (!this.fld)
		return 0;
	
	
	
	
	// init variables
	//
	this.sInp 	= "";
	this.nInpC 	= 0;
	this.aSug 	= [];
	this.iHigh 	= 0;
	
	
	
	
	// parameters object
	//
	this.oP = param ? param : {};
	
	// defaults	
	//
	var k, def = {minchars:1, meth:"get", varname:"input", className:"autosuggest", timeout:2500, delay:0, offsety:-5, shownoresults: true, noresults: "No results!", maxheight: 250, cache: true, maxentries: 25, blurtrigger: false, multisuggest: true};
	for (k in def)
	{
		if (typeof(this.oP[k]) != typeof(def[k]))
			this.oP[k] = def[k];
	}
	
	
	// set keyup handler for field
	// and prevent autocomplete from client
	//
	var p = this;
	
	// NOTE: not using addEventListener because UpArrow fired twice in Safari
	//_b.DOM.addEvent( this.fld, 'keyup', function(ev){ return pointer.onKeyPress(ev); } );
	
	this.fld.onkeypress 	= function(ev){ return p.onKeyPress(ev); };
	this.fld.onkeyup 	= function(ev){ return p.onKeyUp(ev); };
	if (typeof(this.oP.callback) == "function" && this.oP.blurtrigger) {
	  this.fld.onblur = function(event) { 
		if(document.activeElement && typeof(event) === "undefined") { 
			var targetFocus = document.activeElement;
		} else {
			var targetFocus = event.explicitOriginalTarget;
			while(targetFocus.parentNode) {
			  if(targetFocus.tagName == 'A' && typeof(targetFocus.id) == 'string') { if(targetFocus.id.substring(0, 10) == 'bsnsuggest') { break; } }
			  targetFocus = targetFocus.parentNode;
			}
			if(typeof(targetFocus.id) != 'string') { targetFocus.id = ''; }
		}
		if(targetFocus.id.substring(0, 10) != 'bsnsuggest') {
		  p.oP.callback( {id:p.fld.value, value: p.fld.value} ); 
		  p.clearSuggestions();
		}
	  }
	}
	
	this.fld.setAttribute("autocomplete","off");
};
















_b.AutoSuggest.prototype.onKeyPress = function(ev)
{
	var key = (window.event) ? window.event.keyCode : ev.keyCode;



	// set responses to keydown events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// TAB sets the current highlighted value
	//
	var RETURN = 13;
	var TAB = 9;
	var ESC = 27;
	var SEMICOLON = 186;
	
	var bubble = 1;

	switch(key)
	{
		case RETURN:
			if(this.aSug.length != 0 && this.iHigh) {
				this.setHighlightedValue();
				bubble = false;
			} else {
				if(this.fld.value.length > 0) {
					if (typeof(this.oP.callback) == "function") {
						this.clearSuggestions();
						this.oP.callback( {id:this.fld.value, value: this.fld.value} );
					}
					bubble = false;
				} else  {
					bubble = false;
				}
				
			}
			break;

		case ESC:
			this.clearSuggestions();
			break;
				
	}

	return bubble;
};



_b.AutoSuggest.prototype.onKeyUp = function(ev)
{
	var key = (window.event) ? window.event.keyCode : ev.keyCode;
	


	// set responses to keydown events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// TAB sets the current highlighted value
	//

	var ARRUP = 38;
	var ARRDN = 40;
	
	var bubble = 1;

	switch(key)
	{


		case ARRUP:
			this.changeHighlight(key);
			bubble = 0;
			break;


		case ARRDN:
			this.changeHighlight(key);
			bubble = 0;
			break;
		
		
		default:
			//this.getSuggestions(this.fld.value);
			// ADDED BY WEBLIGO
			var new_value = this.fld.value.split(/[;]+/ig);
			this.getSuggestions(new_value[new_value.length-1]);
	}

	return bubble;
	

};








_b.AutoSuggest.prototype.getSuggestions = function (val)
{
	
	// if input stays the same, do nothing
	//
	if (val == this.sInp)
		return 0;
	
	
	// kill list
	//
	_b.DOM.remE(this.idAs);
	
	
	this.sInp = val;
	
	
	// input length is less than the min required to trigger a request
	// do nothing
	//
	if (val.length < this.oP.minchars)
	{
		this.aSug = [];
		this.nInpC = val.length;
		return 0;
	}
	
	
	
	
	var ol = this.nInpC; // old length
	this.nInpC = val.length ? val.length : 0;
	
	
	
	// if caching enabled, and user is typing (ie. length of input is increasing)
	// filter results out of aSuggestions from last request
	//
	var l = this.aSug.length;
		if (this.nInpC > ol && l && l<this.oP.maxentries && this.oP.cache)
	{
		var arr = [];
		for (var i=0;i<l;i++)
		{
			if (this.aSug[i].value.substr(0,val.length).toLowerCase() == val.toLowerCase() || this.aSug[i].info.substr(0,val.length).toLowerCase() == val.toLowerCase()) {
				arr.push( this.aSug[i] );
			}
		}
		this.aSug = arr;
		
		// ADDED BY WEBLIGO
		if(this.aSug.length < l) {
			var pointer = this;
			var input = this.sInp;
			clearTimeout(this.ajID);
			this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
		} else {
			this.createList(this.aSug);
		}
		
		return false;
	}
	else
	// do new request
	//
	{
		var pointer = this;
		var input = this.sInp;
		clearTimeout(this.ajID);
		this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
	}

	return false;
};





_b.AutoSuggest.prototype.doAjaxRequest = function (input)
{
	// check that saved input is still the value of the field
	// CHANGED BY WEBLIGO
	var new_value = this.fld.value.split(/[;]+/ig);
	if (input != new_value[new_value.length-1])
		return false;
	
	
	
	var pointer = this;
	
	
	// create ajax request
	//
	if (typeof(this.oP.script) == "function")
		var url = this.oP.script(encodeURIComponent(this.sInp));
	else
		var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp);
	
	if (!url)
		return false;
	
	var meth = this.oP.meth;
	var input = this.sInp;
	
	var onSuccessFunc = function (req) { pointer.setSuggestions(req, input) };
	var onErrorFunc = function (status) {  };

	var myAjax = new _b.Ajax();
	myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
};





_b.AutoSuggest.prototype.setSuggestions = function (req, input)
{
	// if field input no longer matches what was passed to the request
	// don't show the suggestions
	// CHANGED BY WEBLIGO
	var new_value = this.fld.value.split(/[;]+/ig);
	if (input != new_value[new_value.length-1])
		return false;
	
	this.aSug = [];
	
	
	if (this.oP.json)
	{
		var jsondata = eval('(' + req.responseText + ')');
		
		for (var i=0;i<jsondata.results.length;i++)
		{
			// CHANGED BY WEBLIGO
			this.aSug.push(  { 'id':jsondata.results[i].id, 'value':jsondata.results[i].value, 'info':jsondata.results[i].info, 'photo':jsondata.results[i].photo, 'photo_width':jsondata.results[i].photo_width }  );
		}
	}
	else
	{

		var xml = req.responseXML;
	
		// traverse xml
		//
		var results = xml.getElementsByTagName('results')[0].childNodes;

		for (var i=0;i<results.length;i++)
		{
			if (results[i].hasChildNodes())
				this.aSug.push(  { 'id':results[i].getAttribute('id'), 'value':results[i].childNodes[0].nodeValue, 'info':results[i].getAttribute('info') }  );
		}
	
	}
	
	this.idAs = "as_"+this.fld.id;
	

	this.createList(this.aSug);

};














_b.AutoSuggest.prototype.createList = function(arr)
{
	var pointer = this;
	
	
	
	
	// get rid of old list
	// and clear the list removal timeout
	//
	_b.DOM.remE(this.idAs);
	this.killTimeout();
	
	
	// if no results, and shownoresults is false, do nothing
	//
	if (arr.length == 0 && !this.oP.shownoresults) 
		return false;
	
	
	// create holding div
	//
	var div = _b.DOM.cE("div", {id:this.idAs, className:this.oP.className});	
	
	var hcorner = _b.DOM.cE("div", {className:"as_corner"});
	var hbar = _b.DOM.cE("div", {className:"as_bar"});
	var header = _b.DOM.cE("div", {className:"as_header"});
	header.appendChild(hcorner);
	header.appendChild(hbar);
	div.appendChild(header);
	
	
	
	
	// create and populate ul
	//
	var ul = _b.DOM.cE("ul", {id:"as_ul"});
	
	
	
	
	// loop throught arr of suggestions
	// creating an LI element for each suggestion
	//
	for (var i=0;i<arr.length;i++)
	{
		// format output with the input enclosed in a EM element
		// (as HTML, not DOM)
		//
		var val = arr[i].value;
		var val2 = arr[i].info;
		var st = val.toLowerCase().indexOf( this.sInp.toLowerCase() );
		var st2 = val2.toLowerCase().indexOf( this.sInp.toLowerCase() );
		
		if(st != -1) {
			var output = val.substring(0,st) + "<em>" + val.substring(st, st+this.sInp.length) + "</em>" + val.substring(st+this.sInp.length);
			var output2 = val2;
		} else {
			var output = val;
			var output2 = val2.substring(0,st2) + "<em>" + val2.substring(st, st2+this.sInp.length) + "</em>" + val2.substring(st2+this.sInp.length);
		}
		
		if (val != val2) {
			output = output2+" ("+output+")";
		}
		
		var span 		= _b.DOM.cE("span", {}, output, true);
		
		// CHANGED BY WEBLIGO
		var image		= _b.DOM.cE("img", {src:arr[i].photo, width: arr[i].photo_width, border:"0"});
		image.removeAttribute("height");
		span.insertBefore(image, span.childNodes[0]);

		var a 			= _b.DOM.cE("a", { href:"javascript:void(0);" });
		
		var tl 		= _b.DOM.cE("span", {className:"tl"}, " ");
		var tr 		= _b.DOM.cE("span", {className:"tr"}, " ");
		a.appendChild(tl);
		a.appendChild(tr);
		
		a.appendChild(span);
		
		a.name = i+1;
		a.id = 'bsnsuggest_'+(i+1);
		a.onclick = function () { pointer.setHighlightedValue(); return false; };
		a.onmouseover = function () { pointer.setHighlight(this.name); };
		
		var li = _b.DOM.cE(  "li", {}, a  );
		
		ul.appendChild( li );
	}
	
	
	// no results
	//
	if (arr.length == 0 && this.oP.shownoresults)
	{
		var li = _b.DOM.cE(  "li", {className:"as_warning"}, this.oP.noresults  );
		ul.appendChild( li );
	}
	
	
	div.appendChild( ul );
	
	var fcorner = _b.DOM.cE("div", {className:"as_corner"});
	var fbar = _b.DOM.cE("div", {className:"as_bar"});
	var footer = _b.DOM.cE("div", {className:"as_footer"});
	footer.appendChild(fcorner);
	footer.appendChild(fbar);
	div.appendChild(footer);
	
	
	
	// get position of target textfield
	// position holding div below it
	// set width of holding div to width of field
	//
	var pos = _b.DOM.getPos(this.fld);
	
	div.style.left 		= pos.x + "px";
	div.style.top 		= ( pos.y + this.fld.offsetHeight + this.oP.offsety ) + "px";
	div.style.width 	= this.fld.offsetWidth + "px";
	
	
	
	// set mouseover functions for div
	// when mouse pointer leaves div, set a timeout to remove the list after an interval
	// when mouse enters div, kill the timeout so the list won't be removed
	//
	div.onmouseover 	= function(){ pointer.killTimeout() };
	div.onmouseout 		= function(){ pointer.resetTimeout() };


	// add DIV to document
	//
	document.getElementsByTagName("body")[0].appendChild(div);
	
	
	
	// currently no item is highlighted
	//
	this.iHigh = 0;
	
	
	
	
	
	
	// remove list after an interval
	//
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, this.oP.timeout);
};















_b.AutoSuggest.prototype.changeHighlight = function(key)
{	
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	var n;

	if (key == 40)
		n = this.iHigh + 1;
	else if (key == 38)
		n = this.iHigh - 1;
	
	
	if (n > list.childNodes.length)
		n = list.childNodes.length;
	if (n < 1)
		n = 1;
	
	
	this.setHighlight(n);
};



_b.AutoSuggest.prototype.setHighlight = function(n)
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
		this.clearHighlight();
	
	this.iHigh = Number(n);
	
	list.childNodes[this.iHigh-1].className = "as_highlight";


	this.killTimeout();
};


_b.AutoSuggest.prototype.clearHighlight = function()
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
	{
		list.childNodes[this.iHigh-1].className = "";
		this.iHigh = 0;
	}
};


_b.AutoSuggest.prototype.setHighlightedValue = function ()
{
	if (this.iHigh)
	{
		// CHANGED BY WEBLIGO
		var all_values = this.fld.value.split(/[;]+/ig);
		all_values.pop();
		all_values.push(this.aSug[ this.iHigh-1 ].value);
		if(this.oP['multisuggest']) { var semicolon = ';'; } else { var semicolon = ''; }
		this.sInp = this.fld.value = all_values.join(';')+semicolon;
		
		// move cursor to end of input (safari)
		//
		this.fld.focus();
		if (this.fld.selectionStart)
			this.fld.setSelectionRange(this.sInp.length, this.sInp.length);
		

		// pass selected object to callback function, if exists
		//
		if (typeof(this.oP.callback) == "function")
			this.oP.callback( this.aSug[this.iHigh-1] );
			
			
		this.clearSuggestions();
	}
};













_b.AutoSuggest.prototype.killTimeout = function()
{
	clearTimeout(this.toID);
};

_b.AutoSuggest.prototype.resetTimeout = function()
{
	clearTimeout(this.toID);
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, 1000);
};







_b.AutoSuggest.prototype.clearSuggestions = function ()
{
	
	this.killTimeout();
	this.aSug 	= [];
	var ele = _b.DOM.gE(this.idAs);
	var pointer = this;
	if (ele)
	{
		var fade = new _b.Fader(ele,1,0,250,function () { _b.DOM.remE(pointer.idAs) });
	}
};










// AJAX PROTOTYPE _____________________________________________


if (typeof(_b.Ajax) == "undefined")
	_b.Ajax = {};



_b.Ajax = function ()
{
	this.req = {};
	this.isIE = false;
};



_b.Ajax.prototype.makeRequest = function (url, meth, onComp, onErr)
{
	
	if (meth != "POST")
		meth = "GET";
	
	this.onComplete = onComp;
	this.onError = onErr;
	
	var pointer = this;
	
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest)
	{
		this.req = new XMLHttpRequest();
		this.req.onreadystatechange = function () { pointer.processReqChange() };
		this.req.open("GET", url, true); //
		this.req.send(null);
	// branch for IE/Windows ActiveX version
	}
	else if (window.ActiveXObject)
	{
		this.req = new ActiveXObject("Microsoft.XMLHTTP");
		if (this.req)
		{
			this.req.onreadystatechange = function () { pointer.processReqChange() };
			this.req.open(meth, url, true);
			this.req.send();
		}
	}
};


_b.Ajax.prototype.processReqChange = function()
{
	
	// only if req shows "loaded"
	if (this.req.readyState == 4) {
		// only if "OK"
		if (this.req.status == 200)
		{
			this.onComplete( this.req );
		} else {
			this.onError( this.req.status );
		}
	}
};










// DOM PROTOTYPE _____________________________________________


if (typeof(_b.DOM) == "undefined")
	_b.DOM = {};



/* create element */
_b.DOM.cE = function ( type, attr, cont, html )
{
	var ne = document.createElement( type );
	if (!ne)
		return 0;
		
	
	for (var a in attr) 
		ne[a] = attr[a];

	var t = typeof(cont);
	
	if (t == "string" && !html)
		ne.appendChild( document.createTextNode(cont) );
	else if (t == "string" && html)
		ne.innerHTML = cont;
	else if (t == "object")
		ne.appendChild( cont );

	return ne;
};



/* get element */
_b.DOM.gE = function ( e )
{
	var t=typeof(e);
	if (t == "undefined")
		return 0;
	else if (t == "string")
	{
		var re = document.getElementById( e );
		if (!re)
			return 0;
		else if (typeof(re.appendChild) != "undefined" )
			return re;
		else
			return 0;
	}
	else if (typeof(e.appendChild) != "undefined")
		return e;
	else
		return 0;
};



/* remove element */
_b.DOM.remE = function ( ele )
{
	var e = this.gE(ele);
	
	if (!e)
		return 0;
	else if (e.parentNode.removeChild(e))
		return true;
	else
		return 0;
};



/* get position */
_b.DOM.getPos = function ( e )
{
	var e = this.gE(e);

	var obj = e;

	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	
	var obj = e;
	
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

	return {x:curleft, y:curtop};
};










// FADER PROTOTYPE _____________________________________________



if (typeof(_b.Fader) == "undefined")
	_b.Fader = {};





_b.Fader = function (ele, from, to, fadetime, callback)
{	
	if (!ele)
		return 0;
	
	this.e = ele;
	
	this.from = from;
	this.to = to;
	
	this.cb = callback;
	
	this.nDur = fadetime;
		
	this.nInt = 50;
	this.nTime = 0;
	
	var p = this;
	this.nID = setInterval(function() { p._fade() }, this.nInt);
};




_b.Fader.prototype._fade = function()
{
	this.nTime += this.nInt;
	
	var ieop = Math.round( this._tween(this.nTime, this.from, this.to, this.nDur) * 100 );
	var op = ieop / 100;
	
	if (this.e.filters) // internet explorer
	{
		try
		{
			this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity = ieop;
		} catch (e) { 
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			this.e.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+ieop+')';
		}
	}
	else // other browsers
	{
		this.e.style.opacity = op;
	}
	
	
	if (this.nTime == this.nDur)
	{
		clearInterval( this.nID );
		if (this.cb != undefined)
			this.cb();
	}
};



_b.Fader.prototype._tween = function(t,b,c,d)
{
	return b + ( (c-b) * (t/d) );
};
/* $Id: smoothbox.js 62 2009-02-18 02:59:27Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js


/*
 * Smoothbox v20080623 by Boris Popoff (http://gueschla.com)
 * To be used with mootools 1.2
 *
 * Based on Cody Lindley's Thickbox, MIT License
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

TB_WIDTH = 0;
TB_HEIGHT = 0;

var TB_doneOnce = 0;
var TB_ready = false;
var TB_useReady = true;


// add smoothbox to href elements that have a class of .smoothbox
function TB_init()
{
  TB_ready = true;
	$$("a.smoothbox").each(function(el){el.onclick=TB_bind});
}

window.addEvent('domready', TB_init);
//window.addEvent('load', TB_init);



function TB_bind(event)
{
  if( TB_useReady && !TB_ready ) return;
  
	var event = new Event(event);
	// stop default behaviour
	event.preventDefault();
	// remove click border
	this.blur();
	// get caption: either title or name attribute
	var caption = this.title || this.name || "";
	// get rel attribute for image groups
	var group = this.rel || false;
	// display the box for the elements href
	TB_show(caption, this.href, group);
    this.onclick = TB_bind;
    return false;
}

// called when the user clicks on a smoothbox link
function TB_show(caption, url, rel, loading, disable_close)
{
  if( TB_useReady && !TB_ready ) return;
  
  // set default closing mechanism
  if(!disable_close) { disable_close = 0; }

  // create iframe, overlay and box if non-existent
  if (!$("TB_overlay"))
  {
    (new Element('div').setProperty('id', 'TB_overlay')).inject($('smoothbox_container') || document.body);
    $('TB_overlay').setOpacity(0.6);
    TB_overlaySize();
  }

  if (!$("TB_window"))
  {
    (new Element('div').setProperty('id', 'TB_window')).inject($('smoothbox_container') || document.body);
    $('TB_window').setOpacity(0);
  }
  else 
  {
    $('TB_window').destroy(); //$('TB_window').dispose();
    (new Element('div').setProperty('id', 'TB_window')).inject($('smoothbox_container') || document.body);
    $('TB_window').setOpacity(0);
  }

  if(disable_close == 0) { $("TB_overlay").onclick=TB_remove; } else { $("TB_overlay").onclick = ''; }
  window.onscroll = TB_position;
    
  // check if a query string is involved
  var baseURL = url.match(/(.+)?/)[1] || url;
    
  // CODE TO SHOW IFRAME
  var queryString = url.match(/\?(.+)/)[1];
  var params = TB_parseQuery(queryString);
  
  TB_WIDTH = (params['width'] * 1) + 30;
  TB_HEIGHT = (params['height'] * 1) + 40;
  
  var ajaxContentW = TB_WIDTH - 30, ajaxContentH = TB_HEIGHT - 45;
  
  if (url.indexOf('TB_iframe') != -1)
  {
    urlNoQuery = url.split('TB_');
    $("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>X</a></div></div><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "&in_smoothbox=true' id='TB_iframeContent' name='TB_iframeContent' scrolling='auto' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;' onload='TB_showWindow()'> </iframe>";
  }
  else
  {
    $("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>X</a></div></div><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>";
  }

  $("TB_closeWindowButton").onclick = TB_remove;

  if (url.indexOf('TB_inline') != -1)
  {
    $("TB_ajaxContent").innerHTML = ($(params['inlineId']).innerHTML);
    TB_position();
    TB_showWindow();
  }
  else if (url.indexOf('TB_iframe') != -1)
  {
    //alert("UHOH1");
    TB_position();
    if (frames['TB_iframeContent'] == undefined) {//be nice to safari
      $(document).keyup(function(e){
                    var key = e.keyCode;
                    if (key == 27) {
                        TB_remove()
                    }
      });
      TB_showWindow();
    }
  }
  else
  {
    //alert("UHOH2");
    var handlerFunc = function(){
          TB_position();
          TB_showWindow();
    };
    new Request.HTML({
      method: 'get',
      update: $("TB_ajaxContent"),
      onComplete: handlerFunc
    }).get(url);
  }

  window.onresize = function()
  {
    TB_position();
    TB_overlaySize();
  }

  document.onkeyup = function(event)
  {
    var event = new Event(event);
    if (event.code == 27) { // close
        TB_remove();
    }
  }


}

//helper functions below

function TB_showWindow()
{
  if( TB_useReady && !TB_ready ) return;
  
  if (TB_doneOnce == 0) {
      TB_doneOnce = 1;
      
      $('TB_window').set('tween', {
          duration: 250
      });
      $('TB_window').tween('opacity', 0, 1);
      
  }
  else {
      $('TB_window').setStyle('opacity', 1);
  }

//  $('TB_window').setStyle('opacity', 1);
}

function TB_remove()
{
  if( TB_useReady && !TB_ready ) return;
  
  $("TB_overlay").onclick = null;
  document.onkeyup = null;
  document.onkeydown = null;
  
  if ($('TB_closeWindowButton')) 
      $("TB_closeWindowButton").onclick = null;
  
  $('TB_window').set('tween', {
      duration: 250,
      onComplete: function(){
          $('TB_window').destroy(); //$('TB_window').dispose();
      }
  });
  $('TB_window').tween('opacity', 1, 0);
  
  
  
  $('TB_overlay').set('tween', {
      duration: 400,
      onComplete: function(){
          $('TB_overlay').destroy(); //$('TB_overlay').dispose();
      }
  });
  $('TB_overlay').tween('opacity', 0.6, 0);
  
  window.onscroll = null;
  window.onresize = null;
  
  TB_init();
  TB_doneOnce = 0;
  return false;
}

function TB_position()
{
  if( TB_useReady && !TB_ready ) return;
  
  $('TB_window').set('morph', {
    duration: 75
  });
  $('TB_window').morph({
    width: TB_WIDTH + 'px',
    left: (window.getScrollLeft() + (window.getWidth() - TB_WIDTH) / 2) + 'px',
    top: (window.getScrollTop() + (window.getHeight() - TB_HEIGHT) / 2) + 'px'
	});	
}

function TB_overlaySize()
{
  if( TB_useReady && !TB_ready ) return;
  
  // we have to set this to 0px before so we can reduce the size / width of the overflow onresize 
  $("TB_overlay").setStyles({
    "height": '0px',
    "width": '0px'
  });
  $("TB_overlay").setStyles({
    "height": window.getScrollHeight() + 'px',
    "width": window.getScrollWidth() + 'px'
  });
}


function TB_parseQuery(query)
{
  if( TB_useReady && !TB_ready ) return;
  
  // return empty object
  if (!query)  return {};
  var params = {};
  
  // parse query
  var pairs = query.split(/[;&]/);
  for (var i = 0; i < pairs.length; i++)
  {
    var pair = pairs[i].split('=');
    if (!pair || pair.length != 2) continue;
    // unescape both key and value, replace "+" with spaces in value
    params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
  }
  return params;
}

/* $Id: sprintf.js 62 2009-02-18 02:59:27Z john $ */

// This file will no longer be included by default. A minified version is included as part of core-min.js


/*
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf()
{
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}

