// messages.js

var cIdTextArea = '';
var iInsertPos  = 0;
var cTellaFriendTypeMember = 'friendsbysearchname';
var lTelAfriendDialogLoaded = false;

function showMessTab( cIdMessArea, elpos, iTab ) {
  
	cIdTextArea  = cIdMessArea;
  eltab = elpos + iTab;
  el = document.getElementById( eltab );
  
  if (el.style.display == 'block')
  {
  
  	// document.getElementById(elpos).style.height = '1px';
  	el.style.display = 'none';
    Set_Cookie( 'SmiliesDisp', 'none', 60 , '/', '', '' ) ;
    
    
    $('#dialogtellafriend').dialog('option', 'buttons', { "Ok": function() { $(this).dialog("close"); } });
    return;
  }
  else
  { 
  

   
   $('#dialogtellafriend').dialog('option', 'buttons', { "Ok": function() { $(this).dialog("close"); } });
   

   hideEachMessTab(); // alle boxen dicht, dus ook telafriend ed
   for (var i_tem = 1; i_tem < 3; i_tem++)
   {
     eltab = $( '#' + elpos + i_tem );
     
    ( i_tem == iTab ) ? $(eltab).show() : $(eltab).hide(); 
    
    
   }
   }

  Set_Cookie( 'SmiliesDisp', 'block', 60 , '/', '', '' ) ;
  if  ( iTab == 1) showSmilies( elpos + 'containersmilies' , 'standaardsmileys' )
  if  ( iTab == 2 ) getPhotos( elpos + 'containerphotos' ) ;
  
   
  return false;
}

function hideMessTab( el ) {
	
  $( '#' + el ).hide();
  
  Set_Cookie( 'SmiliesDisp', 'none', 60 , '/', '', '' ) ;
}


function hideEachMessTab()
{
	 $( '.messtabs' ).hide();
}	

function showSmilies( cContainer, cAct ) {
	
	$("#" + cContainer ).load('/ajax/ajaxsmilies.p', { act: cAct , language : cLanguage } );
	
}	

function getPhotos( cContainer )
{

	$("#" + cContainer ).load('/ajax/ajaxsmilies.p', { act: 'fotoboek' , language : cLanguage } );
}





function doGetCaretPosition (control) {
var CaretPos = 0;
// IE Support
if (document.selection) 
{
control.focus();
var Sel = document.selection.createRange ();
var Sel2 = Sel.duplicate();
Sel2.moveToElementText(control);
var CaretPos = -1;
while(Sel2.inRange(Sel))
{
Sel2.moveStart('character');
CaretPos++;
}
}

// Firefox support

else if (control.selectionStart || control.selectionStart == '0')
CaretPos = control.selectionStart;

return (CaretPos);

}

/**** dit origineel werkt niet lekker in IE 
function doGetCaretPosition (ctrl) {

    var CaretPos = 0;
    // IE Support
    if (document.selection) {

        ctrl.focus ();

        var Sel = document.selection.createRange ();
        
        Sel.moveStart ('character', -ctrl.value.length);
        
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
        CaretPos = ctrl.selectionStart;

    
    return (CaretPos);
}

***/

function setCaretPosition(ctrl, pos)
{

    if(ctrl.setSelectionRange)
    {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}
	
function insertAtCursor( myValue) {
	
	  myField = document.getElementById( cIdTextArea );
	  
    iInsertPos = doGetCaretPosition( myField );
    
    //IE support
    if (document.selection) {
        myField.focus();

        sel = document.selection.createRange();
        sel.text = myValue;

    //Mozilla/Firefox/Netscape 7+ support
    } else if (myField.selectionStart || myField.selectionStart == '0') {

        myField.focus();
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
        myField.setSelectionRange(endPos+myValue.length, endPos+myValue.length);
    } else {
        myField.value += myValue;
    }
    
    
}



function JatSmiley( domobj , IdUserProfile, IdSmiley )
{
  var agree=confirm( 'Deze smiley toevoegen bij je eigen smileys?' );
  if (agree)
  {

      new Ajax.Request( '/profielsmileyrip.p' ,  { 
  	    method:'get', 
   	   	    parameters: { iduserprofile: IdUserProfile, idsmiley: IdSmiley, language: cLanguage }  ,
        onSuccess: function(transport){messagebox( '' ,  transport.responseText ); } ,
        onFailure: function() { messagebox( 'Error' ,   (cLanguage == 'en') ? 'Something went wrong...' : 'Er ging iets mis...' ); }

     } );
    
 }
}


function deleteMessage( cScope, cScopeValue, cMessageRowid, cIdDom )
{



  var cError    = "";
  var cMessage  = "";
  
	$.get( cDomain + "/ajax/ajaxcommentdelete.p", { scope: cScope, scopevalue: cScopeValue, MessageRowid: cMessageRowid , Language : cLanguage},
         function(data){
         $(data).find('result').each(function(){ 
         	cError    = $("error", this).text();
         	cMessage  = $("message", this).text();
         	if (cError != "") messagebox( 'Error' ,  cError );
         	else
         	 {
         	 	el = document.getElementById( cIdDom );  
         	  $( el ).hide( "slow" );
         	 	if (cMessage != "") showmessage( el , 'succes', cMessage , true );
         	 }

         	})
  },  "xml");
}

function insertBold( cIdMessArea )
{
	cIdTextArea  = cIdMessArea;
	
	insertAtCursor( '[b][/b]');
  setCaretPosition( document.getElementById( cIdMessArea) , iInsertPos + 3);
  
	
}	

function insertItalic( cIdMessArea )
{
	cIdTextArea  = cIdMessArea;
	insertAtCursor( '[i][/i]');
  setCaretPosition( document.getElementById( cIdMessArea) , iInsertPos + 3);
}	

function insertUrl( cIdMessArea )
{
	cIdTextArea  = cIdMessArea;
	insertAtCursor( '[url=http://www.]website[/url]');
  setCaretPosition( document.getElementById( cIdMessArea) , iInsertPos + 16);
}	

function insertImg( cIdMessArea )
{
	cIdTextArea  = cIdMessArea;
	insertAtCursor( '[img]http://...[/img]');
  setCaretPosition( document.getElementById( cIdMessArea) , iInsertPos + 12)	;
}	

function insertDJ( cIdMessArea )
{
	cIdTextArea  = cIdMessArea;
	insertAtCursor( '[dj][/dj]');
  setCaretPosition( document.getElementById( cIdMessArea) , iInsertPos + 4)	;
}	

function getPreview( cIdMessArea ) 
{		
  var cPreview = document.getElementById( cIdMessArea ).value;
  if ( cIdMessArea == 'commenttelafriend')  cPreview = AttentFriendsourceString() + cPreview;
  
  $.post( cDomain + "/ajax/ajaxpreview.p", { preview: cPreview, width: 300  },
         function(data){
          
          $("#preview").html(data);
			    $("#preview").dialog( "open" );
     });
}



function reply( cScope, cScopeValue, cMessageRowid, cIdMessArea )
{
  
  var cError    = "";
  var cMessage  = "";
  
 	el = document.getElementById(cIdMessArea);

  if ( cMessageRowid == '' ) 	
  { ScrollToElement( el );
  	setCaretPosition(el, 0);
  	return;
  }	

  
  
	$.get( cDomain + "/ajax/ajaxgetmessage.p", { scope: cScope, scopevalue: cScopeValue, MessageRowid: cMessageRowid , Language : cLanguage},
         function(data){
         $(data).find('result').each(function(){ 
         	cError    = $("error", this).text();
         	cMessage  = $("message", this).text();
         	if (cError != "") messagebox( 'Error' , cError );
         	else
         	 {
            /* cursor aan begin */
         	 	el.value+= "\n" + cMessage ;
        	 	setCaretPosition(el, 0);
         	 	
         	 	/* cursor aan eind
         	 	el.focus();
         	 	el.value+= cMessage ;
         	 	*/
         	 }

         	})
  },  "xml");
}



function appendfriends()
{

    var cRestartRowid = '';
    
    if (cTellaFriendTypeMember == 'friendsbysearchname') cRestartRowid = $( '#restartrowidfriends' ).val();
    else cRestartRowid = $( '#restartrowidfavorites' ).val();
    	
    $( '#morefriendsloading' ).show();
    
    jQuery.get(
        '/ajax/ajaxgetmembersbasicxml.p',
        {
            'typememberdata' : cTellaFriendTypeMember ,
            'restartrowid' : cRestartRowid ,
            'batchsize' : 75
        },
        function(data) {
        	  
        	cRestartRowid = $('result', data).attr('restartrowid');
        	
        	( cRestartRowid == "" ) ?  $( "#morefriends" ).hide() :  $( "#morefriends" ).show();

          if (cTellaFriendTypeMember == 'friendsbysearchname') $( '#restartrowidfriends' ).val( cRestartRowid );
          else $( '#restartrowidfavorites' ).val( cRestartRowid );
          
        	  
          $(data).find('result member').each(function() {   
          	if (cTellaFriendTypeMember == 'friendsbysearchname') 
          	   $( '#containerappendfriends' ).append( checkbox_member( this ));
          	else 
          		 $( '#containerappendfavorites' ).append( checkbox_member( this ));
          		
          });   
          $( '#morefriendsloading' ).hide();
          $("#screenshot").remove();
          screenshotPreview(); // for screenshots

            
        },
        'xml'
    );
    
};



function checkbox_member(member)
{
	
   cHtml = '<input type="checkbox" name="member' + $(member).attr('iduserprofile') + '" />'
           + '<a href="/profielinfo.p?idUserprofile=' 
           + $(member).attr('iduserprofile') + ((cLanguage=='en') ? '&amp;language=en' : '' )
           + '" rel="' + $(member).attr('pic') + '"'
           + ' class="screenshot" title="' + $(member).attr('searchname') + '" >' 
           + $(member).attr('searchname')
           + '</a><br/>';
           
   
           
   return cHtml;      
  
};

function AttentFriendsourceString()
{  var cSourceString = '';
	
   if ( window.location.href.indexOf( 'fotoboek' ) > 0 ) cSource = ((cLanguage=='en') ? 'photoboek' : 'fotoboek' );
   else if ( window.location.href.indexOf( 'party' ) > 0 ) cSource = 'partyagenda';
   else if ( window.location.href.indexOf( 'profielinfo' ) > 0 ) cSource = cSource = ((cLanguage=='en') ? 'memberpage' : 'memberpagina' );
  	
   cSourceString = '[url=' 
  	        + window.location.href + ']' 
            + ((cLanguage=='en') ? 'This message is sent from: ' : 'Dit bericht is verstuurd vanuit: ' ) 
            + cSource
  	        + '[/url]' + '\r\r' ;
  	          
   return cSourceString;          
}


function submittelafriend(sender)
{
  var cSelectedFriends = '';
	$("#containerappendfriends :checked").each(  function(index) 
	{ 
		if (index > 0) cSelectedFriends = cSelectedFriends + '+';
		cSelectedFriends = cSelectedFriends + this.name.substr( 6 ) ; 
   });
   
	$("#containerappendfavorites :checked").each(  function(index) 
	{ 
		if ( cSelectedFriends.length  > 0 ) cSelectedFriends = cSelectedFriends + '+';
		cSelectedFriends = cSelectedFriends + this.name.substr( 6 ) ; 
   });

	$("#containeryourself :checked").each(  function(index) 
	{ 
		if ( cSelectedFriends.length  > 0 ) cSelectedFriends = cSelectedFriends + '+';
		cSelectedFriends = cSelectedFriends + this.name.substr( 6 ) ; 
		
   });
   
   
   
 	if (cSelectedFriends == ''	)
	{ showmessage(sender, 'error', ((cLanguage=='en') ? 'No recipients selected' : 'Er zijn geen ontvangers geselecteerd' ), true );
		return; }
	calltellafriend( sender, cSelectedFriends );
}

function calltellafriend( sender, cSelectedFriends )
{
	var cComment = AttentFriendsourceString() + $( "#commenttelafriend" ).val();
	var lPrivate = ( $("#commentprivate" ).attr( "checked" )  == true );
	
	
  $.ajax({ type: "POST" ,
        url: cDomain + "/ajax/ajaxtellafriend.p", 
        data: { selectedfriends: cSelectedFriends, comment: cComment, private: lPrivate },
        dataType: "xml" ,
         success: function(data){
  
        $(data).find('result').each(function()
         {          
           var $mess = $(this).find('message');
           if ( $( $mess ).length  > 0 )
           { var cMessage = $($mess).text();
           	var cType    = $($mess).attr('type' );
           	var cTitle   = $($mess).attr('title' );
           	
           	if (cType == 'Alert') 
           	{
          
           		  $("#dialogcontainer").dialog( 'option', 'position', 'center' );
           		  $('#dialogcontainer').dialog( 'option', 'width', 700);	
               	
               	if ( cTitle == '' )  cTitle = (cLanguage=='en') ? 'Alert' : 'Waarschuwing';
               	$('#dialogcontainer').dialog('option', 'title', cTitle  );		
                 $("#dialogcontainer").html( cMessage );
                 $('#dialogcontainer').dialog('option', 'buttons', { "Ok": function() { $(this).dialog("close"); } });
         			  $("#dialogcontainer").dialog( "open" );
         	
           	}	
           	else if ( cMessage != '' ) showmessage( sender , cType, cMessage, true ); 
           }
           
        	}); // each(function)
  
        } , // succes
        error: function(request,error){ messagebox( 'Error' ,  'Oeps ' + request.statusText  ) ; }
        });
}

function showtellafrienddialog( sender )
{
	
    if ( lTelAfriendDialogLoaded == true)
    {
    	$("#dialogtellafriend").dialog( "open" );
    	return;
    }
    
    
    $.ajax({ type: "GET" ,
        url: cDomain + "/ajax/ajaxtellafriend.p", 
        data: { action: 'showform', ref: window.location.href },
        dataType: "xml" ,
         success: function(data){
          if ( data == undefined) 
          { messagebox( 'Error' , 'no data' );
          	return;
          }	
  
        $(data).find('result').each(function()
         {          
           var $mess = $(this).find('formtellafriend');
           if ( $( $mess ).length  > 0 )
           { var cMessage = $($mess).text();
           	 var cTitle   = $($mess).attr('title' );
         
           	
           	
             $('body').append('<div id="dialogtellafriend" ></div>');								 
             $("#dialogtellafriend").dialog({ width: 580 , height: 'auto', position : 'center' });
	    	
             if ( cTitle == '' )  cTitle = 'Tell a friend';
             $('#dialogtellafriend').dialog('option', 'title', cTitle  );		
             $("#dialogtellafriend").html( cMessage );
             
             
             $("#dialogtellafriend").click(function(e)
                { var $this = $(e.target);   
                	
                	
                	 if ($this.attr( 'id'  ) == 'telafriendsubmit' ) submittelafriend(this);
			             else 
			             {
                	    if ($this.attr( 'onclick' ) == null ) $this = $this.closest("div"); 
                      if ($this.attr( 'onclick' ) != null )
   	                  { eval($this.attr( 'onclick' ));
   	                  	return false;
       	               }	 
                   }  
                 } );       
             	
             $('#dialogtellafriend').dialog('option', 'buttons', { "Ok": function() { 
             	  $('#dialogtellafriend').unbind('click'); // dat je geen dubbele clicks krijgt bij sluiten
             	  $(this).dialog("close"); } });
             
         		 $("#dialogtellafriend").dialog( "open" );
         		 $("#screenshot").remove();
             screenshotPreview(); // for screenshots

             $("input:radio[name=typeSelectMemberData]").unbind('click'); // dat je geen dubbele clicks krijgt bij sluiten
	           $("input:radio[name=typeSelectMemberData]").click(function()
             { if ($(this).val() != cTellaFriendTypeMember )
             	   { cTellaFriendTypeMember = $(this).val();
                 
                  if (cTellaFriendTypeMember == 'friendsbysearchname') 
                   {$( '#containerappendfavorites' ).hide();  
                   	$( '#containeryourself' ).hide();  
                   	$( '#containerappendfriends' ).show(); 
                   	if ( $('#containerappendfriends').is(':empty') || ( $( '#restartrowidfriends' ).val() != '' ) )
                   	  appendfriends();
                   }
                   else if (cTellaFriendTypeMember == 'favoritesbysearchname') 
                   { $( '#containerappendfriends' ).hide(); 
                   	 $( '#containeryourself' ).hide();  
                   	 $( '#containerappendfavorites' ).show();
                   	 if ( $('#containerappendfavorites').is(':empty') || ( $( '#restartrowidfavorites' ).val() != '' ))
                   	   appendfriends();
                   }	 
                   else if (cTellaFriendTypeMember == 'yourself') 
                   { $( '#containerappendfriends' ).hide(); 
                   	 $( '#containeryourself' ).show();  
                   	 $( '#containerappendfavorites' ).hide();
                   }	 
                   
             	   } 
             });
         	
           }	
           
        	}); // each(function)
  
          lTelAfriendDialogLoaded = true;
  
        } , // succes
        error: function(request,error){ messagebox( 'Oeps ' + request.statusText , 'Status: ' + request.statusText  ); }
        });

     
  return false;   

}

$(document).ready(function() {
			$("#preview").dialog({
				autoOpen: false,
				modal: false,
				height:250,
				width: 400,
				resizable: true,
				draggable: true,
				overlay: { 
					opacity: 0.5, 
					background: "black" 
				}
			});
   			
});