var editingField = new Array();
var contactCounter = 0;
var orgHTML = new Array();
var contactServices = new Array('Dienst', 'Hyves', 'LinkedIn', 'MSN', 'Weblog', 'Website', 'Anders');

$(document).ready(function() {
/* $('#overmij').mouseover(showTip);
 $('#overmij').mousemove(moveTip);
 $('#overmij').mouseout(hideTip);
 $('div#toolTip').mousemove(moveTip);*/

 $.post("/includes/profiles.php",{
  action: 'loadContactField'
 },function(txt){
  if (txt != '')
  {
   data = txt.split(',');
   for (i = 0; i <= data.length - 1; i = i + 4)
   {
    addContactField(data[i + 1], data[i + 2], data[i + 3], data[i]);
   }
  }
 });
 
 $('#toolTipCarrier').slideDown('slow');
 $('#editSaveBtn').toggle(function () { editAllFields() }, function () { saveAllFields() });
});

function showTip()
{
 $('div#toolTip').html('hoi');
 $('div#toolTip').css('display', 'block');
}

function hideTip()
{
 $('div#toolTip').css('display', 'none');
}

function moveTip(event)
{
 $('div#toolTip').css('left', event.pageX + 8);
 $('div#toolTip').css('top', event.pageY + 8);
}

function editField(field, type)
{
 if (editingField[field] != true)
 {
  orgHTML[field] = $('#' + field);
  switch (type)
  {
   case "small":
    editingField[field] = true;
    tempText = $('#' + field).html();
    $('#icon_' + field).hide();
    $('#' + field).replaceWith('<span id="' + field + '" class="editingSmall"><input type="text" style="width: 100px;" onkeydown="if (event.keyCode==13) { saveField(\'' + field + '\', $(\'#edit' + field + '\').val(), false); return false; } else if (event.keyCode == 27) { cancelEditField(\'' + field + '\', \'' + tempText + '\', false); return false; }" id="edit' + field + '" value="' + tempText + '" />&nbsp;<a href="#" onclick="cancelEditField(\'' + field + '\', \'' + tempText + '\', false); return false;"><img src="/images/profiles/cancel.png" class="icon" /></a><a href="#"  onclick="saveField(\'' + field + '\', $(\'#edit' + field + '\').val(), false); return false;" style="position: absolute;"><img src="/images/profiles/accept.png" class="icon" /></a></span>');
    break;
    
   case "contactservice":
    editingField[field] = true;
    service = $('#' + field + ' span.service').html();
    username = $('#' + field + ' a.username').html();
    link = $('#' + field + ' a.username').attr('href');
    if (link == undefined)
     link = '';
    commid = $('#' + field).attr('commid');
    var options = '';
    currentService = $('#' + field + ' span.service').html();
    jQuery.each(contactServices, function () {
                                              options += '<option ';
                                              if (currentService == this)
                                               options += 'selected="selected" ';
                                              options += 'value="' + this + '">' + this + '</option>';
                                             } );
    $('#' + field).replaceWith('<div class="editContactField editingContact" id="' + field + '" commid="' + commid + '"><select class="service" style="width: 100px;">' + options + '</select>: <input type="text" class="username" style="width: 130px;" value="' + username + '" /><br />Link:&nbsp;<input type="text" class="link" style="width: 150px; margin-top: 5px;" value="' + link + '" />&nbsp;<a href="#" onclick="cancelContactEditField(\'' + field + '\'); return false;"><img src="/images/profiles/cancel.png" class="icon" style="margin-top: 7px;" /></a><a href="#" onclick="saveContactField(\'' + field + '\'); return false;" style="position: absolute; margin-top: 7px;"><img src="/images/profiles/accept.png" class="icon" /></a><br /></div>');   
    break;
    
   default:
    editingField[field] = true;
    tempText = $('#' + field).html();
    $('#' + field).replaceWith('<div id="' + field + '" class="editing editContactField"><textarea id="edit' + field + '" onkeydown="if (event.keyCode == 27) { cancelEditField(\'' + field + '\', \'' + tempText + '\', true); return false; }">' + tempText + '</textarea><br /><a href="#" onclick="cancelEditField(\'' + field + '\', \'' + tempText + '\', true); return false;"><img src="/images/profiles/cancel.png" class="icon" />Annuleren</a>&nbsp;&nbsp;<a href="#" onclick="saveField(\'' + field + '\', $(\'#edit' + field + '\').val(), true); return false;"><img src="/images/profiles/accept.png" class="icon" />Opslaan</a></div>');
    $('#' + field).hide();
    $('#' + field).slideDown();
  }
 }
}

function cancelContactEditField(field)
{
 $('#' + field).replaceWith(orgHTML[field]);
 editingField[field] = false;
 if ($('#' + field).attr('commid') == '-1')
 {
  deleteContactField(field);
 }
}

function saveContactField(field)
{
 var service = $('#' + field + ' select.service').val();
 var username = $('#' + field + ' input.username').val();
 var link = $('#' + field + ' input.link').val();
 if (link.substring(0,7) != 'http://')
  link = 'http://' + link;
 var commid = $('#' + field).attr('commid');
 $('#' + field).replaceWith(orgHTML[field]);
 
 $('#' + field + ' span.service').html(service);
 $('#' + field + ' a.username').html(username);
 $('#' + field + ' a.username').attr('href', link);
 editingField[field] = false;
 
 $.post("/includes/profiles.php",{
  action: 'saveContactField', service: service, username: username, link: link, commid: commid
 },function(commid){
  //alert(commid);
  $('#' + field).attr('commid', commid);
 });
}

function cancelEditField(field, text, slideUp)
{
 if (slideUp == undefined)
  slideUp = false;
 
 if (slideUp == true)
 {
  $('#' + field).slideUp("normal", function () {
   $('#' + field).replaceWith(orgHTML[field]);
   $('#' + field).html(text);
   $('#icon_' + field).show();
  });
 } else 
 {
  $('#' + field).replaceWith(orgHTML[field]);
  $('#' + field).html(text);
  $('#icon_' + field).show();
 }
 editingField[field] = false;
}

function saveField(field, text, slideUp)
{
 $.post("/includes/profiles.php",{
  action: 'saveField', field: field, data: text
 }/*,function(txt){
  alert( txt);
 }*/);
 
 cancelEditField(field, text, slideUp);
}

function saveContactFields()
{
 $('#contactInfo > span').each(function (i) { alert($(this).children('input').val()) } )
}

function addContactField(service, username, link, commid, animate)
{
 if (animate == undefined)
  animate = false;
 if (service == undefined)
  service = 'Dienst';
 if (username == undefined)
  username = 'gebr. naam';
 if (link == undefined)
  link = '';
 if (commid == undefined)
  commid = '-1';
 contactCounter++;
 $('#contactInfo').append('<div id="contactService' + contactCounter + '" commid="' + commid + '" class="editableContact" style="width: 200px;"></div>');
 if (animate == true)
  $('#contactInfo #contactService' + contactCounter).hide();
 $('#contactInfo #contactService' + contactCounter).append('<span class="service" onclick="editField(\'contactService' + contactCounter + '\', \'contactservice\'); return false;">' + service + '</span>: <a class="username" href="' + link + '">' + username + '</a>&nbsp;<a href="#" onclick="editField(\'contactService' + contactCounter + '\', \'contactservice\'); return false;" title="Contactmogelijkheid bewerken"><img src="/images/profiles/page_white_edit.png" class="icon" /></a><a href="#" title="Contactmogelijkheid verwijderen" onclick="deleteContactField(\'contactService' + contactCounter + '\'); return false;"><img src="/images/profiles/bin.png" class="icon" /></a><br />');
 if (animate == true)
  $('#contactInfo #contactService' + contactCounter).show('normal', function () { editField('contactService' + contactCounter, 'contactservice'); } );
}

function deleteContactField(field)
{
 var commid = $('#contactInfo #' + field).attr('commid');
 if (commid != '-1')
 {
  $.post("/includes/profiles.php",{
   action: 'deleteContactField', commid: commid
  }/*,function(txt){
   alert(txt);
  }*/);
 }
 $('#contactInfo #' + field).hide('normal');
}

function editAllFields()
{
 $('.editable').each(function (i) { editField($(this).attr('id')); } );
 $('.editableSmall').each(function (i) { editField($(this).attr('id'), 'small'); } );
 $('.editableContact').each(function (i) { editField($(this).attr('id'), 'contactservice'); } );
 $('#editSaveBtn').html('<img src="/images/profiles/disk.png" class="icon">Alles opslaan');
}

function saveAllFields()
{
 $('.editing').each(function (i) { saveField($(this).attr('id'), $('#edit' + $(this).attr('id')).val(), true); } );
 $('.editingSmall').each(function (i) { saveField($(this).attr('id'), $('#edit' + $(this).attr('id')).val(), false); } );
 $('.editingContact').each(function (i) { saveContactField($(this).attr('id')); } );
 $('#editSaveBtn').html('<img src="/images/profiles/pencil.png" class="icon">Profiel bewerken');
}


function ajaxFileUpload(loading, type)
{
 //starting setting some animation when the ajax starts and completes
 $(loading)
 .ajaxStart(function(){
     $(this).show();
 })
 .ajaxComplete(function(){
     $(this).hide();
 });

 /*
     prepareing ajax file upload
     url: the url of script file handling the uploaded files
                 fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
     dataType: it support json, xml
     secureuri:use secure protocol
     success: call back function when the ajax complete
     error: callback function when the ajax failed
    
         */
 if (type == "cv")
 {
  $.ajaxFileUpload
  ({
   url:'http://www.makkeweb.nl/includes/profiles.php?action=uploadcv',
   secureuri:false,
   fileElementId:'cvfile',
   dataType: 'json',
   success: function (data, status)
   {
    if(typeof(data.error) != 'undefined')
    {
     if(data.error != '')
     {
      alert(data.error);
     }else
     {
      $('#uploadCV').html('<a href="/profiles_upload/cvs/' + data.filename + '">CV bekijken</a>&nbsp;<a href="#" onclick="$(\'#uploadCVForm\').slideDown(); return false;" title="CV uploaden/bewerken"><img src="/images/profiles/page_white_edit.png" class="icon" /></a><a href="#" title="CV verwijderen" onclick="deleteCV(); return false;"><img src="/images/profiles/bin.png" class="icon" /></a>');
      $('#uploadCVForm').slideUp();
     }
    }
   },
   error: function (data, status, e)
   {
    alert(e);
   }
  })
 } else if (type == "photo")
 {
  $.ajaxFileUpload
  ({
   url:'http://www.makkeweb.nl/includes/profiles.php?action=uploadphoto',
   secureuri:false,
   fileElementId:'photofile',
   dataType: 'json',
   success: function (data, status)
   {
    if(typeof(data.error) != 'undefined')
    {
     if(data.error != '')
     {
      alert(data.error);
     }else
     {
      var rnd = Math.round(100000 * Math.random());
      $('#uploadPhoto').empty();
      $('#uploadPhoto').html('<img src="/profiles_upload/userphotos/' + data.filename + '?' + rnd + '" style="margin: 10px;" />');
      $('#photoIcons').html('<a href="#" onclick="$(\'#uploadPhotoForm\').slideDown(); return false;" title="Foto uploaden"><img src="/images/profiles/picture_edit.png" class="icon" /></a><a href="#" title="Foto verwijderen" onclick="deletePhoto(); return false;"><img src="/images/profiles/bin.png" class="icon" /></a>');
      $('#uploadPhotoForm').slideUp();
     }
    }
   },
   error: function (data, status, e)
   {
    alert(e);
   }
  })
 }
 

 return false;

}

function deleteCV()
{
 $.post("/includes/profiles.php",{
  action: 'deleteCV'
 },function(errno)
 {
  if (errno == 0)
  {
   $('#uploadCV').html('<a href="#" onclick="$(\'#uploadCVForm\').slideDown(); return false;" title="CV uploaden">CV uploaden</a>');
  }
 });
}

function deletePhoto()
{
 $.post("/includes/profiles.php",{
  action: 'deletePhoto'
 },function(errno)
 {
  if (errno == 0)
  {
   $('#uploadPhoto').html('<div onclick="$(\'#uploadPhotoForm\').slideDown(); return false;" style="background: url(\'/images/profiles/userphoto_default.jpg\'); cursor: pointer; width: 150px; height: 150px; margin: 10px; font-weight: bold; color: #999999;" onmouseover="$(this).html(\'<br /><br /><br />klik hier om een<br />foto te uploaden\');" onmouseout="$(this).empty();"></div>');
   $('#photoIcons').html('<a href="#" onclick="$(\'#uploadPhotoForm\').slideDown(); return false;" title="Foto uploaden"><img src="/images/profiles/picture_edit.png" style="border: none; margin: 3px;" /></a>');
  }
 });
}

function saveNewMessage(username, body)
{
 $('#messageButtonHolder').html('<img id="uploadPhotoLoadingImg" src="/images/profiles/ajax-loader.gif" />');
 $.post("/includes/profiles.php",{
  action: 'saveNewMessage', messageUsername: username, messageBody: body
 },function(messageId)
 {
  addNewMessage(username, body, messageId);
 });
}

function addNewMessage(username, body, messageId)
{
 $('#profileMessages').append('<div id="message' + messageId + '" class="message"><div style="float: right"><a href="#" onclick="deleteMessage(' + messageId + '); return false;"><img src="/images/profiles/bin.png" class="icon" /></a></div><span style="padding-left: 4px; font-weight: bold;">' + username + '</span><hr class="profilesMessage" /><span style="padding-left: 4px;">' + body + '</span></div>');
 $('#newMessage').slideDown();
 $('#newMessage').attr('id', '');
 $('#messageButtonHolder').html('<a href="#" onclick="$(\'#addMessage\').slideUp(); return false;" title="Bericht verwijderen"><img src="/images/profiles/cancel.png" class="icon" />Annuleren</a>&nbsp;&nbsp;<a href="#" onclick="saveNewMessage($(\'#messageUsername\').val(), $(\'#messageBody\').val()); return false;"><img src="/images/profiles/accept.png" class="icon" />Opslaan</a>');
}

function deleteMessage(messageId)
{
 $.post("/includes/profiles.php",{
  action: 'deleteMessage', messageId: messageId
 },function(errno)
 {
  if (errno == 0)
  {
   $('#message' + messageId).slideUp("normal", function () { $('#message' + messageId).remove(); });
  }
 });
}