/* $Id: weblog.js 23706 2008-09-29 16:47:58Z bjorn $ */
// filmpje: <object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/OrAHBk4ZAeQ"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/OrAHBk4ZAeQ" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>
var imageUploadCallBack, number, ajaxTags, numPosts;
var editMode = null;
var oldHTML = {};
var numPostsPerPage = 10;
var singlePost = false;
var numComments = 10;    // number of comments to show

function init(){
	waitStart();
	if(document.getElementById('weblogDiv')){
  	var offset = getUrlParam('offset') || 0;
    userWeblogService.countPostsByProfilename(profileName, function(r){
        numPosts = r;
        offset = offset > numPosts ? 0 : offset;
        loadWeblogPosts(offset);
      });
  }
  else{
    number = document.location.href.match(/weblog\/([\d]+)/)[1];
    singlePost = true;
    
    AjaxTags.init(999);
    AjaxTags.setUseLink();
    AjaxTags.showTags();

    loadCommentsFor(number, 0, numComments, true);

    var numComments = AjaxNumComments;
    numComments.setNodenr(number);
    numComments.setAutoReload();
    numComments.showNumComments();

    if(document.location.href.match(/weblog\/[\d]+(#reacties)/)){
      $('img[alt=addComment]').parent().click();
    }
    
    $("ul.communitybarUl img").addClass('png');
    
    $('img[alt=reageer]').click(function(e){
      e.preventDefault();
      $('img[alt=addComment]').parent().click();
    });
		waitStop();
  }
}

function loadWeblogPosts(offset){
  offset = parseInt(offset) || 0;
  offset = offset < 0 || offset > (numPosts-1) ? 0 : offset;
//  printfire('findPostsByProfilename', profileName, offset, numPostsPerPage, onload);
  userWeblogService.findPostsByProfilename(profileName, offset, numPostsPerPage, onload);

  function onload(weblogposts){
    for(var i = 0; i < weblogposts.length && i < numPostsPerPage; i++){
      var html = createWeblogPostHtml(weblogposts[i]);
      $("#weblogDiv").append(html);
    }
    $("#weblogDiv img").addClass('png');
    if(numPosts > numPostsPerPage){
      var numPages = Math.ceil(numPosts / numPostsPerPage);
      var currentPage = Math.ceil((offset+1) / numPostsPerPage);
      var endNum = weblogposts.length < numPostsPerPage ? numPosts : offset + numPostsPerPage;
      var moreHtml = '<div style="height:40px"></div>';
      moreHtml += '<ul class="meerartikelen">';
      moreHtml += '<li class="right">';
      if(offset != 0){
        moreHtml += '<a href="/mijn3voor12/'+profileName+'/weblog?offset='+parseInt(offset - numPostsPerPage)+'">';
        moreHtml += '<img width="140" height="20" title="Klik hier voor nieuwere berichten van deze gebruiker" alt="NIEUWERE BERICHTEN" src="/pix/navigatie/nieuwereberichten.png"/></a>';
      }
      if(currentPage < numPages){
        moreHtml += '<a href="/mijn3voor12/'+profileName+'/weblog?offset='+(offset+numPostsPerPage)+'">';
        moreHtml += '<img width="130" height="20" title="Klik hier voor oudere berichten van deze gebruiker" alt="OUDERE BERICHTEN" src="/pix/navigatie/oudereberichten.png"/></a>';
      }
      moreHtml += '</li>';
      moreHtml += '<li class="numPosts">'+(offset+1)+' - '+endNum+' van '+numPosts+' berichten</li>';
      moreHtml += '</ul>';
      $("#weblogDiv").append(moreHtml);
    }
    attach("div.mouseover", highlight, document.getElementById('weblogDiv'));
     
    initLightbox();
    initCommunitybar('weblogDiv');
    AjaxTags.init(999);
    AjaxTags.setUseLink();
    AjaxTags.showTags();
    AjaxNumComments.setAutoReload();
    AjaxNumComments.showNumComments();
		
		// DRIE-2167:  Eigen User-weblog opent direct op Bericht Toevoegen
		if(false && loggedin){
			$('img[alt="newbericht"]').parent().click();
		}
		waitStop();
  }
}

function createWeblogPostHtml(post){
//printfire('createWeblogPostHtml:: ', post);
  var image = '<img src="/pix/iconen/pixel.gif" width="1" height="40" alt="" />';
  var date_posted = getDateTime(post.created);
  var title = post.title != '' ? post.title : '&nbsp;'; 

  if(post.created.getTime() != post.lastModified.getTime()){
    date_posted += ", laatst aangepast op "+getDateTime(post.lastModified);
  }

  if(post.images[0]){
    image  = '<a href="'+post.images[0].URL+'+s(650)" rel="lightbox">';
    image += '<img src="'+post.images[0].URL+'+s(470)" alt="" /></a>';
    // TODO fix layout op IE6 van description
    if(post.images[0].description){
      //image += '<div class="bijschrift">'+post.images[0].description+'</div>';
    }
  }
  
  if(post.body) {
  	post.body = post.body.replace(/<script[^>]*>((.|[\r\n])*?)<\\?\/script>/ig, "");
  }

  return $("#weblog-template").children(".msgContainerDivParent").clone()
           .find("div.header h1").html('<a href="/mijn3voor12/'+post.author.profileName+'/weblog/'+post.number+'">'+title+'</a>').end()
           .find("div.header div").html(date_posted).end()
           .find("div.msgColumnRight").html(image).end()
           .find("div.msgBody").html(post.body || '&nbsp;').end()
           .find("div.msgColumnLeft").prepend('<div class="communitybar"><div id="ajaxTags_'+post.number+'" class="ajaxTags"></div></div>').end()
           .html()
           .replace(/##NUMBER##/g, post.number)
           .replace(/##PROFILENAME##/g, post.author.profileName);
}

function delete_afterSlide(e){
  number = getNumberFromSlideDiv(slideDiv);
  if (confirm('Dit bericht wissen?')) {
    waitStart();
    userWeblogService.deletePost(number, afterDelete);
  }
  
  function afterDelete(response){
    if(singlePost){
      window.location = unescape(window.location.pathname).replace(/\/[\d]+(.*)/, '');
    }
    else{
      $('#msgContainerDiv_'+number).remove();
      waitStop();
    }
  }
}

function editweblog_beforeSlide(e){
	number = getNumberFromSlideDiv(slideDiv);
  window['after_cancel'] = function(){editweblog_afterCancel();};
  //window['after_cancel'] = editweblog_afterCancel;
  var container = $('#msgContainerDiv_'+number);
  container.find('div.header').slideUp();
  container.find('div.msgBodyContainer').slideUp();

  oldHTML.title = container.find("div.header h1 a").html() || container.find("div.header h1").html();
  oldHTML.href = container.find("div.header h1").html();
  oldHTML.date = container.find("div.header div").html();
  oldHTML.body = container.find("div.msgBody").html();
  oldHTML.images = [];
  oldHTML.images.push({ URL: container.find("div.msgColumnRight img").attr('src'),
                        description:container.find("div.msgColumnRight div.bijschrift").html() });
}

function editweblog_afterSlide(e){
  slideDiv.find('input[name=titel]').val(oldHTML.title);
  slideDiv.find('textarea[name=body]').val(oldHTML.body);
  if(oldHTML.images && oldHTML.images.length > 0 && !/pixel.gif/.test(oldHTML.images[0].URL)){
    var html = '<div class="transparent"></div>';
    html += '<img src="/pix/iconen/delete.png" alt="delete" title="Klik hier om deze afbeelding te verwijderen" width="20" height="20" />';
    slideDiv.find('div.image')
      .css({background: 'url("'+oldHTML.images[0].URL+'+s(64x64)+crop(64x64)") no-repeat'})
      .html(html)
      .click(function(){delete_image(number);});
  }
  makeRichText(slideDiv.find('textarea[name=body]')[0], 'Weblog', {width: 480, height:440});
  
  function delete_image(num){
    if(!confirm('Weet je zeker dat je deze afbeelding wilt verwijderen?')){
      return;
    }
    userWeblogService.deleteImage(num, after_delete_image);
    function after_delete_image(response){
      if(response == true){
        oldHTML.images = [];
        slideDiv.find('div.image').fadeOut('slow');
      }
    }
  }
  
}

/**
 * submit_editweblog
 * submits the edited weblog posts back to the server
 * 
 * @param {Object} e
 * @param {Object} slideDiv
 */
function submit_editweblog(e, slideDiv){
  waitStart();
  var title = slideDiv.find('input[name=titel]').val();
  var body = getText(slideDiv.find('textarea[name=body]')[0].name);

  function doUploadImage(response){
    uploadImage(response, updateWeblogPostHtml);
  }

  userWeblogService.updatePost(number, title, body, doUploadImage);
}

/**
 * submits a new message to the server
 * @param {Object} e
 */
function submit_newbericht(e){
  if(e){
    e.preventDefault(); 
  }
  waitStart();
  var title = slideDiv.find("input[name=titel]").val();
  var body = getText(slideDiv.find('textarea[name=body]')[0].name);

  function doUploadImage(response){
    uploadImage(response, addNewMessage);
  }

  userWeblogService.createPost(title, body, true, true, true, doUploadImage);

}

function addNewMessage(message){
  slideDiv.slideUp('slow', function(){
    slideDiv.empty();
    openSlide = null;
    var html = createWeblogPostHtml(message);
    $('div#weblogDiv').prepend(html);
    initCommunitybar($('div#weblogDiv div.msgContainerDiv').attr('id'));
    $("ul.communitybarUl img").addClass('png');
    waitStop();
  });
}

/**
 * uploads a related image to the server
 * @param {Object} bericht
 */
function uploadImage(bericht, afterFunc){
  function imageUploaded(url){
    if(url){
      bericht.images = [];
      bericht.images.push({URL: url});
    }
    oldHTML = bericht;
    afterFunc(oldHTML);
  }

  slideDiv.find('input[name=relateTo]').val(bericht.number);
  imageUploadCallBack = imageUploaded;
  slideDiv.find('form').submit();
}

function updateWeblogPostHtml(){
  var container = $('#msgContainerDiv_'+number); 
  if(singlePost){
	  container.find('div.header h1').html(oldHTML.title);	
	}
	else{
    container.find('div.header h1 a').html(oldHTML.title);		
	}
  container.find('div.msgBodyContainer div.msgBody').html(oldHTML.body);
  var image = '<img src="/pix/iconen/pixel.gif" width="1" height="40" alt="" />';
  if(oldHTML.images && oldHTML.images.length > 0 && !/pixel.gif/.test(oldHTML.images[0].URL)){
    image  = '<a href="'+oldHTML.images[0].URL+'+s(650)" rel="lightbox">';
    image += '<img src="'+oldHTML.images[0].URL+'+s(470)" alt="" /></a>';
    if(oldHTML.images[0].description){
      image += '<div class="bijschrift">'+oldHTML.images[0].description+'</div>';
    }
  }
  container.find("div.msgColumnRight").html(image);
  cancel_slideDiv();
  waitStop();
}

function editweblog_afterCancel(e){
  waitStart();
  var e = e || window.event;
  $('#msgContainerDiv_'+number).find('div.header').slideDown();  
  $('#msgContainerDiv_'+number).find('div.msgBodyContainer').slideDown();
  waitStop();
}

function newbericht_beforeSlide(e){
  window['after_cancel'] = function(){editweblog_afterCancel();};  
}

function newbericht_afterSlide(div){
  var area = $(div).find('textarea');
  makeRichText(area[0], 'Weblog', {width: 480, height:440});
}


function imageUploaded(url){
  if(imageUploadCallBack){
    imageUploadCallBack(url);
  }
	imageUploadCallBack = null;
}