function initProfilePage( playerId, url, width, height, userId, jsont ){

  if( playerId == 1 ){
    var playercolor = "333333";
    var playerautoplay = "false";
    if( jsont.indexOf("{") == 0 ){
      var json = eval( '(' + jsont + ')' );
      if( json.background_color ) playercolor = json.background_color; 
      if( json.autoplay ) playerautoplay = json.autoplay;
     }
     url += "?autoplay="+playerautoplay+"&userid="+userId+"&color1="+playercolor;
  }
  url += "&gen=" + generateLine();
  var flashvars = {};
  var params = { wmode: "transparent", allowScriptAccess:"always" };
  var attributes = { id: "profileplayer", name: "profileplayer" };
  swfobject.embedSWF( url, "profileplayercode", width, height, "8.0.0", statichost + "/swf/expressInstall.swf", flashvars, params, attributes);
}
///////////////////////////////////////////////////////////////

var IFRAME_UPDATED = false;

function destroyframe(){
  if( IFRAME_UPDATED == true ) window.location.reload();
  IFRAME_UPDATED = false;
  document.getElementsByTagName("body")[0].removeChild( $('iframe_window') );
  if( $('iframe_window') != null ) $('iframe_window').innerHMTL = "";
}

function iframeUpdated(){
  IFRAME_UPDATED = true;
}

function buildiframe( src, width, height ){
  IFRAME_UPDATED = false;
  var container = document.createElement('div');
  $(container).setAttribute("id", "iframe_window");
  $(container).set("class", "iframewindow");
  $(container).setStyle("width", width+"px");
  $(container).setStyle("height", height+"px");
  var coor = browser.getAdjustedCenter();
  $(container).setStyle("top", coor.y - (height/2) );
  $(container).setStyle("left", coor.x - (width/2) );
  $(container).setStyle("position", "absolute");
  $(container).setStyle("z-index", "4000" );
  var html = '<iframe id="'+new Date().getTime()+ '" scrolling="no" frameborder="0" style="background-color:#transparent" '+
             'width="'+(width-0)+'" height="'+(height-5)+'" src="'+ src + '"></iframe>' +
             '<div style="border:0px solid #FFF;position:relative;top:-5px" class="iframeshader"></div>';
  $(container).innerHTML = html;
  return container;
}


function editBlog(){
  var iframe = buildiframe( "/iframe/profile/editblog.jsp", 600, 190 );
  document.getElementsByTagName("body")[0].appendChild( iframe );
  showMask();
}


function editPlayer(){
  var iframe = buildiframe( "/iframe/profile/editplayer.jsp", 600, 450 );
  document.getElementsByTagName("body")[0].appendChild( iframe );
  showMask();
}

function editPersonality(){
  var iframe = buildiframe( "/iframe/profile/editpersonality.jsp", 600, 450 );
  document.getElementsByTagName("body")[0].appendChild( iframe );
  showMask();
}

function editProfile(){
  var iframe = buildiframe( "/iframe/profile/editprofileprivacy.jsp", 600, 190 );
  document.getElementsByTagName("body")[0].appendChild( iframe );
  showMask();
}

function editProfileImage(){
  var iframe = buildiframe( "/iframe/profile/editprofileimage.jsp", 600, 320 );
  document.getElementsByTagName("body")[0].appendChild( iframe );
  showMask();
}
function editInfo(){
  var iframe = buildiframe( "/iframe/profile/editinfo.jsp", 600, 450 );
  document.getElementsByTagName("body")[0].appendChild( iframe );
  showMask();
}

function editWall(){
  var iframe = buildiframe( "/iframe/profile/editwall.jsp", 600, 190 );
  document.getElementsByTagName("body")[0].appendChild( iframe );
  showMask();
}

function closeIframeOpenEditInfo(){
  hideMask();
  destroyframe();
  editInfo();
}

function closeIframe(){
  hideMask();
  destroyframe();
}

///////////////////////////////////////////////////////////////

var numofdeletes = 0;
var numofcomments = 0;
var DO_COMMENT_RELOAD = false;

function postcomment(form){
    $('commentpostsending').setStyle('display', 'block');
    $('commentpostbutton').setStyle('display', 'none');
    var targetUserId = form.userId.value;
    var comment = form.comment.value;
    var ajax = new Ajax( postcommenthandler, postcommentAjaxError, form );
    var uri = "/community/postcomment!ajax.action?"+generateLine()+
        "=0&userId="+encodeURIComponent( targetUserId ) + "&comment=" + encodeURIComponent( comment );
    ajax.get( uri, null, false );
}

function postcommentAjaxError(){
  ajaxError();
}

function postcommenthandler( obj, jsont ){
    $('commentpostsending').setStyle('display', 'none');
    $('commentpostbutton').setStyle('display', 'block');

    var json = eval( '(' + jsont + ')' );
    if(json.status == 'failure'){
        $('postcommenterror').innerHTML = json.errorMessage;
    }else{
        $('postcommenterror').innerHTML = "";
        
        if( DO_COMMENT_RELOAD ){
          window.location.href = "/comments/" + obj.getParams().userId.value;
          return;
        }

        obj.getParams().comment.value = "";

        $('ajaxcomment').setStyle('display','block');
        var comment = json.comment;

        if(typeof comment == 'undefined') {
            window.location = '/profile.jsp';
        }

        var commenttable = document.createElement( 'table' );
        $('ajaxcomment').insertBefore(commenttable, $('ajaxcomment').firstChild);
        var tbody = document.createElement( 'tbody' );
        var tr = document.createElement( 'tr' );
        var td_image = document.createElement( 'td' );
        var td_sec = document.createElement( 'td' );
        tr.appendChild( td_image );
        tr.appendChild( td_sec );
        tbody.appendChild( tr );
        commenttable.appendChild( tbody );
        commenttable.setAttribute( 'id', 'comment_'+comment.id );
        commenttable.setAttribute( 'cellSpacing', '0px' );
        commenttable.setAttribute( 'cellPadding', '0px' );
        commenttable.cellSpacing = 0;
        commenttable.cellPadding = 0;
        commenttable.setAttribute( 'className', 'commenttable' );
        commenttable.setAttribute( 'class', 'commenttable' );
        $(commenttable).setStyle('opacity', '0');
        td_image.setAttribute( 'class', 'image' );
        td_image.setAttribute( 'className', 'image' );

        var img_thumbnail = statichost + "/images/common/man_face_thumbnail.gif";
        if( comment.thumbnail != null && comment.thumbnail.length > 0 ){
            img_thumbnail = comment.thumbnail;
        }else if( comment.gender == 'F' ){
            img_thumbnail = statichost + "/images/common/woman_face_thumbnail.gif";
        }
        var image_src = '<a href="/profile.jsp?userId='+ comment.posterExternalId + '">'+
            '<img src="'+ img_thumbnail  + '"></a>';
        td_image.innerHTML = image_src;
        var posterinfo = document.createElement('div');
        posterinfo.setAttribute( 'class', 'posterinfo' );
        posterinfo.setAttribute( 'className', 'posterinfo' );
        td_sec.appendChild( posterinfo );
        var table = document.createElement('table');
        table.setAttribute( 'cellSpacing', '0px' );
        table.setAttribute( 'cellPadding', '0px' );
        table.cellSpacing = 0;
        table.cellPadding = 0;
        table.setAttribute( 'width', '100%' );
        posterinfo.appendChild( table );
        var tbody = document.createElement('tbody');
        table.appendChild( tbody );
        var tr = document.createElement('tr');
        tbody.appendChild( tr );
        var td = document.createElement('td');
        td.setAttribute( 'align', 'left' );
        tr.appendChild( td );
        td.innerHTML = '<a class="pagelink" href="/profile.jsp?userId='+ comment.posterExternalId + '">'+
            '<span class="name">'+ comment.name + '</a></span>';
        var td = document.createElement('td');
        td.setAttribute( 'align', 'right' );
        tr.appendChild( td );
        td.innerHTML = '<span class="date">'+ comment.date + '</span>';
        var tr = document.createElement('tr');
        tbody.appendChild( tr );
        var td = document.createElement('td');
        td.setAttribute( 'align', 'left' );
        tr.appendChild( td );
        td.innerHTML = '<a class="pagelink" href="/profile.jsp?userId='+ comment.posterExternalId + '">'+
            '<span class="username">'+ comment.username + '</span></a>';
        var td = document.createElement('td');
        td.setAttribute( 'align', 'right' );
        tr.appendChild( td );
        td.innerHTML = '';
        var actions = document.createElement('div');
        actions.setAttribute( 'class', 'actions' );
        actions.setAttribute( 'className', 'actions' );
        td_sec.appendChild( actions );
        var click = 'return deletecomment(\''+comment.ownerExternalId+ '\', '+comment.id+');';
        var str = '<a href="#" onclick="'+ click +'" class="pagelink">'+getText('comment_delete')+ '</a>';
        actions.innerHTML = str;
        var commentbody = document.createElement('div');
        commentbody.setAttribute( 'class', 'commentbody');
        commentbody.setAttribute( 'className', 'commentbody');
        td_sec.appendChild( commentbody );

        commentbody.innerHTML = fixComment( comment.comment );

        numofcomments++;
        $('numofcomments').innerHTML = numofcomments;

        var fx_in = new Fx.Morph( $(commenttable), {duration: 1000, transition: Fx.Transitions.linear} );
        fx_in.start({ opacity:1 });
        fixImages();
    }
}

function fixComment( comment ){
  comment = comment.replace(/\n/g, "");
  var strArray = comment.split(/(<.*?>)/);
  var newcomment = "";
  for( var a = 0; a < strArray.length; a++ ){
    if( strArray[a].match(/<.*?>/) ){
      newcomment += fixTag( strArray[a] );
    }else{
      newcomment += fixNonTag( strArray[a] );
    }
  }
  return newcomment;
}

function fixNonTag( text ){
  var strArray = text.split(" ");
  var newcomment = "";
  for( var a = 0; a < strArray.length; a++ ){
    if( strArray[a].length > 30 ){
      var every = parseInt(30/3.0);
      var times = Math.ceil( strArray[a].length / parseFloat(every) * 1.0 );
      for( var b = 0; b < times; b++ ){
        var distance = Math.min( (b+1)*every, strArray[a].length );
        newcomment += "<span class=\"wordbreak\">";
        newcomment += strArray[a].substring( b*every, distance );
        newcomment +=  "</span><wbr></wbr>";
      }
    }else{
      newcomment += strArray[a];
    }
    if( a != strArray.length - 1 ) {
      newcomment += " ";
    }
  }
  return newcomment;
}

function fixTag( tag ){
  return tag + "<wbr></wbr>";
}


function deletecomment(userId, commentId){
    var args = new Object();
    args.userId = userId;
    args.commentId = commentId;
    confirmSubmit(null, deletecommentConfirmHandler, args );
    return false;
}

function deletecommentConfirmHandler( value , args ){
    if( value == true ){
       var obj = new Object();
       obj.id = args.commentId;
       obj.userId = args.userId;
       var ajax = new Ajax( deletecommenthandler, ajaxError, obj );
       var uri = "/community/deletecomment!ajax.action?"+generateLine()+"=0&confirm=true"+
           "&userId="+encodeURIComponent( args.userId ) + "&commentId=" + encodeURIComponent( args.commentId );
       ajax.get( uri, null, false );
    }
}

function deletecommenthandler( obj, jsont ){
    var json = eval( '(' + jsont + ')' );
    var id = obj.getParams().id;
    var userId = obj.getParams().userId;
    if(json.status == 'failure'){
        dialogAlert( json.errorMessage );
    }else{
        if(numofcomments > 0){
            numofcomments--;
        }
        if( $('numofcomments') != null ){
          $('numofcomments').innerHTML = numofcomments;
        }
        numofdeletes++;
        var fx_out = new Fx.Morph( $('comment_'+id), {duration: 1000, transition: Fx.Transitions.linear} );
        fx_out.start({ opacity:0 }).chain( function(){  $('comment_'+id).setStyle('display', 'none');  } );
        if( numofdeletes > 5 ){
          window.location.reload();
          //window.location = '/profile.jsp?userId='+ userId;
        }
    }
}

function requestfriend( targetUserId, targetThumbnail, targetName ){
    if( ! loggedIn ){ 
      dialogAlert('You must be logged in to make a friend request');
    }
    var obj = new Object();
    obj.targetUserId = targetUserId;
    obj.targetThumbnail = targetThumbnail;
    obj.targetName = targetName;
    dialogRequestFriend( obj );
}

function requestfriendhandler( obj, jsont ){
    if( REQUEST_FRIEND_DIALOG != null ) REQUEST_FRIEND_DIALOG.hidenewdialogcontainer();
    REQUEST_FRIEND_DIALOG = null;

    var json = eval( '(' + jsont + ')' );   
    if(json.status == 'failure'){
        dialogAlert( json.errorMessage );
    }else{
        dialogAlertTimeout( getText("profile_friendrequestsucessful"), 2000 );
    }
}


function makefriendrequest( name, params ){
    var targetUserId = params.targetUserId;
    var comment = '';
    if( $('_request_comment_').style.display == 'inline' ){
        comment = $('_request_comment_').value;
    }
    var ajax = new Ajax( requestfriendhandler, ajaxError );
    var uri = "/community/requestfriend!ajax.action?"+generateLine()+
        "=0&userId="+encodeURIComponent( targetUserId ) + "&comment=" + encodeURIComponent( comment );
    ajax.get( uri, null, false );
}



function createRequestButtons( params ){

    var table = document.createElement('table');
    var tbody = document.createElement('tbody');
    var tr = document.createElement('tr');
    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    tr.appendChild(td1);
    tr.appendChild(td2);
    tbody.appendChild(tr);
    table.appendChild(tbody);
    table.setAttribute("align", "center");
    $(table).setStyle("width", "200");
    $(td1).setStyle("text-align", "center");
    $(td2).setStyle("text-align", "center");
    td1.appendChild(new Dialog().createButton(getText("profile_addfriend"), makefriendrequest, params ));
    td2.appendChild(new Dialog().createButton(getText("button_Cancel"), cancelRequestFriend, params ));
    return table;
}

function toggleRequestCommentBox(){
    if( $('_request_comment_').style.display == 'none' ){
        $('_request_comment_').style.display = 'inline';
        $('_request_text_').innerHTML = getText("button_Cancel");
    }else{
        $('_request_comment_').style.display = 'none';
        $('_request_text_').innerHTML = getText("profile_addadditionalcomment");
    }
}

var REQUEST_FRIEND_DIALOG = null;

function cancelRequestFriend(){
  if( REQUEST_FRIEND_DIALOG != null ) REQUEST_FRIEND_DIALOG.hidenewdialogcontainer();
  REQUEST_FRIEND_DIALOG = null;
}

function dialogRequestFriend( params ){
    var handler = null;
    var width = 450;
    var height = 80;

    if( REQUEST_FRIEND_DIALOG != null ) return;
    showMask();


    REQUEST_FRIEND_DIALOG = new Dialog();
    REQUEST_FRIEND_DIALOG.seal();
    var container = REQUEST_FRIEND_DIALOG.createdialogcontainer( width, height );
    document.getElementsByTagName("body")[0].appendChild( container );
    var maindiv = document.createElement('div');
    var div = document.createElement('div');
    $(div).setStyle("width", "95%");
    $(div).setStyle("height", 20);
    $(div).setStyle("background-color", "#5292d1");
    $(div).setStyle("border-bottom", "1px solid #123456");
    $(div).setStyle("padding", "5px");
    $(div).setStyle("font-size", "12pt");
    $(div).setStyle("font-weight", "bold");
    $(div).setStyle("color", "#FFF");
    div.innerHTML = getText("profile_makefriendrequest");
    maindiv.appendChild( div );
    var table = document.createElement('table');
    var tbody = document.createElement('tbody');
    var tr = document.createElement('tr');
    var td_image = document.createElement('td');
    var td_text = document.createElement('td');
    table.appendChild(tbody);
    tbody.appendChild(tr);
    tr.appendChild( td_image );
    tr.appendChild( td_text );
    if( typeof params.targetThumbnail != 'undefined' && params.targetThumbnail.length > 0 ){
        td_image.innerHTML = '<img style="border:2px solid #000" src="'+params.targetThumbnail+'">';
    }
    var str = "<div align='left'>"+getText("profile_requestdialog1")+"<br><br>"+
              "<a class='pagelink' href='#' onclick='toggleRequestCommentBox();return false;' id='_request_text_' " +
              "style='font-size:8pt;text-decoration:none;'>"+
              getText("profile_addadditionalcomment") + "</a></div>";
    var text = REQUEST_FRIEND_DIALOG._createTextBox(str, 350, 'auto');

    td_text.appendChild( text );
    maindiv.appendChild( table );

    var textarea = document.createElement('textarea');
    textarea.setAttribute( 'id', '_request_comment_' );
    $(textarea).setStyle('display', 'none');
    $(textarea).setStyle('position', 'relative');
    $(textarea).setStyle('left', '35px');
    $(textarea).setStyle('width', '350px');
    $(textarea).setStyle('height', '40px');
    $(textarea).setStyle('font-size', '8pt');

    maindiv.appendChild( textarea );
    maindiv.appendChild( createRequestButtons(params) );
    $('_messagefield_'+ REQUEST_FRIEND_DIALOG.id ).appendChild( maindiv );
    $(container).setStyle("opacity", "0");
    var fx = new Fx.Morph( $(container), {duration: 300, transition: Fx.Transitions.linear} );
    fx.start({ opacity:1 });
    document.getElementsByTagName("body")[0].appendChild(container);
}

function removefriend(userId){
    var args = new Object();
    args.userId = userId;
    confirmSubmit(null, removefriendConfirmHandler, args );
    return false;
}

function removefriendConfirmHandler( value , args ){
  if( value == true ){
    var userId = args.userId;
    var ajax = new Ajax( removefriendhandler, ajaxError, userId );
    var uri = "/community/deletefriend!ajax.action?"+generateLine()+"=0&userId="+encodeURIComponent( userId )+"&confirm=true";
    ajax.get( uri, null, false );
  }
}

function removefriendhandler( obj, jsont ){
  var json = eval( '(' + jsont + ')' );
  if(json.status == 'failure'){
    dialogAlert( json.errorMessage );
  }else{
    window.location = "/profile.jsp";
  }
}

function fixImages(){
  var MAX_HEIGHT = 350;
  var MAX_WIDTH  = 350;

  $$("#comments .commentbody img").each(function(el){
    el = $(el);
    var height = el.getCoordinates().height;
    var width  = el.getCoordinates().width;
    if( height <= MAX_HEIGHT && width <= MAX_WIDTH ) return;
    var percheight = MAX_HEIGHT / height;
    var percwidth  = MAX_WIDTH / width;
    var perc = (percheight < percwidth) ? percheight : percwidth;
    el.setStyle('width', (width*perc) + 'px');
    el.setStyle('height', (height*perc) + 'px');
  });

  $$("#ajaxcomment .commentbody img").each(function(el){
    el = $(el);
    var height = el.getCoordinates().height;
    var width  = el.getCoordinates().width;
    if( height <= MAX_HEIGHT && width <= MAX_WIDTH ) return;
    var percheight = MAX_HEIGHT / height;
    var percwidth  = MAX_WIDTH / width;
    var perc = (percheight < percwidth) ? percheight : percwidth;
    el.setStyle('width', (width*perc) + 'px');
    el.setStyle('height', (height*perc) + 'px');
  });

}
