function PmMessagingCl () {	  	
	  	this.pm_last_msg_id = false;
		this.pm_window_opend = false;
		this.pm_debug = false;  
	}
	PmMessagingObj = new PmMessagingCl();
var isShift = false;
var pm_patient_conversation = false;
var pm_patient_hash = false;
/* debug funcs */
function DebugCl()
{
	
	this.updLastmsgid = function ()
	{
		if ( $('#pm_debug_last_msg_id').html()!= PmMessagingObj.pm_last_msg_id ) $('#pm_debug_last_msg_id').html(PmMessagingObj.pm_last_msg_id);
		if ( $('#pm_debug_msg_input').html()!= $('#pm_message').val() ) $('#pm_debug_msg_input').html($('#pm_message').val());
		if ( isShift ) $('#pm_debug_shifton').html('on'); else $('#pm_debug_shifton').html('off'); ;
		//alert('ok');
	}
}
DebugObj = new DebugCl();



$(document).ready(function() {

 $('#pm_new_messages_info').click( function(){ messaging_window(); } ); 
 $('#pm_new_messages_info_m_num').click( function(){ messaging_window(); } );
 $('#pm_new_messages_info_m_num_pat').click( function(){ window.location.replace(site_url+'controlcenter/private_nachrichten_mit_patienten/'); } );
 

  
} );


/* datenbank nach neuen messages nachfragen */
 var updatePmConversationRefreshId = setInterval( updatePmConversation, 5000);

// clearInterval(updatePmConversationRefreshId);
function pmDebugOn()
{
	 if ( PmMessagingObj.pm_debug == true )
	 {
	 	//wenn debug
	 	$('#pm_debug').css( 'display' , 'block');
	 	//update debug_pm_last_msg_id
	 	var updatepm_last_msg_idDEBUG = setInterval( DebugObj.updLastmsgid , 1000);
	 	
	 } 
	 else 
	 {	
	 	$('#pm_debug').css( 'display' , 'none');
	 }
}
function get_pm_patient_view_fuer_zahnarzt(patienthash)
{    
    if ( !patienthash ) return;
    pm_patient_conversation = true;
    pm_patient_hash = patienthash;
    jQuery.ajax({		
		url: site_url+controller.pm+'/get_pm_patient_view_fuer_zahnarzt',
        
		data: 'pm_to_patient_hash='+encodeURIComponent(patienthash),
        //+'&pm_last_msg_id='+PmMessagingObj.pm_last_msg_id
		type: "POST",
		timeout: 4000,
		error: function(){ console.log("25:Fehler"); },
		success: function(ret){
				var responseJSON = $.evalJSON(ret);	
			    $('#pm_content_message_output').html( responseJSON.messages_html );
                $('#pm_content_header_text').html( 'Private Unterhaltung mit Patient ' + responseJSON.patientname );
                $( '#pm_content_message_output').attr({ scrollTop: $('#pm_content_message_output').attr("scrollHeight")  });
				
			}
	});	
}
function closeMessagingWindow()
{
	$('#messaging_blende').css( 'display' , 'none'); 
	$('#messaging_window').css( 'display' , 'none'); 
	PmMessagingObj.pm_window_opend = false; 
}
function updatePmConversation()
{
	// whenn window nicht geoefnet oder gibts keine unterhaltung  = kein update
	if (!PmMessagingObj.pm_window_opend  || $('#pm_to_user_id').length == 0 || pm_patient_conversation  ) return;
	
	jQuery.ajax({
		// data: 'user_id='+user_id,
		url: site_url+controller.pm+'/update_pm_conversation',
		data: 'to_user_id='+$('#pm_to_user_id').val()+'&pm_last_msg_id='+PmMessagingObj.pm_last_msg_id,
		type: "POST",
		timeout: 5000,
		error: function(){ console.log("25:Fehler"); },
		success: function(ret){
				var responseJSON = $.evalJSON(ret);	
				//$(document.body).append('<div id="messaging_window" style="margin-top:'+topx+'px">'+ret+'</div>');
				// spaeter umschreiben , dass nur neue messages geladen wird
				if (responseJSON.last_msgs!='') 
				{
					$('#pm_content_message_output').append(responseJSON.last_msgs); 
					$('#pm_content_message_output').attr({ scrollTop: $('#pm_content_message_output').attr("scrollHeight")  });					
					PmMessagingObj.pm_last_msg_id = responseJSON.pm_last_msg_id;
				}
				$('#pm_new_messages_info_m_num').html( responseJSON.msg_num_from_patient );
                $('#pm_new_messages_info_m_num_pat').html( responseJSON.msg_num_from_zahnarzt );
                $('.msg_num_from_patient').html( responseJSON.msg_num_from_patient );
                $('.msg_num_from_zahnarzt').html( responseJSON.msg_num_from_zahnarzt );
				
				//messaging_window_open = true;
			}
	});	
}
function get_view_messages_from_date( timestamp , from_user_id , to_user_id )
{
	jQuery.ajax({
		// data: 'user_id='+user_id,
		url: site_url+controller.pm+'/get_view_messages_from_date',
		data: 'timestamp='+timestamp+'&from_user_id='+from_user_id+'&to_user_id='+to_user_id,
		type: "POST",
		timeout: 4000,
		error: function(){ console.log("25:Fehler"); },
		success: function(ret){	
				var responseJSON = $.evalJSON(ret);				
				PmMessagingObj.pm_last_msg_id = responseJSON.pm_last_msg_id;
				$('#pm_content_message_output').html(responseJSON.pm_content_message_output);
				$( '#pm_content_message_output').attr({ scrollTop: $('#pm_content_message_output').attr("scrollHeight")  });
							
			}
	});	
}
function messaging_window( to_user_id , from_date /*timestamp*/ )
{
    blende.show();
	topx = parseInt(((document.all)?document.body.scrollTop:window.pageYOffset))+70;
	/*
	
	*/
	jQuery.ajax({
		// data: 'user_id='+user_id,
		url: site_url+controller.pm+'/show_pm_window',
		data: 'to_user_id='+to_user_id+'&from_date='+from_date,
		type: "POST",
		timeout: 10000,
		error: function(xhr, ajaxOptions, thrownError){ console.log("Fehler: unknown "+" Status unknown "+thrownError); setTimeout( function () {messaging_window(to_user_id , from_date)}, 3000 ); } ,
		success: function(ret){
		        blende.hide();
				//document.body.style.overflow = 'hidden';
				//$("body").css("overflow", "hidden");
				var responseJSON = $.evalJSON(ret);	
				if ($('#messaging_window').length!=0) 
				{
					$('#messaging_blende').css( 'display' , 'block'); $('#messaging_window').css( 'display' , 'block'); 
					$('#messaging_window').html(responseJSON.pm_content_message_output);
					$('#messaging_window').css( 'top' , topx+'px' );
										
				} else	
				{
					$(document.body).append('<div id="messaging_blende" style="top:'+topx+'px;" >&nbsp;</div>');
					$(document.body).append('<div id="messaging_window" style="top:'+topx+'px;" >'+responseJSON.pm_content_message_output+'</div>');	
					//$('#messaging_blende').css( 'display' , 'block'); $('#messaging_window').css( 'display' , 'block'); 
				} 
				$('#pm_message').focus();
				/* style="margin-top:'+topx+'px"*/
				pmDebugOn();
				$( '#pm_content_message_output').attr({ scrollTop: $('#pm_content_message_output').attr("scrollHeight")  });
				PmMessagingObj.pm_window_opend = true;
				PmMessagingObj.pm_last_msg_id = responseJSON.pm_last_msg_id;
				
				$('#pm_close_button').click( function(){ closeMessagingWindow(); } );
				
				isShift = false; 
				$('.pm_user_teaser_inner').mouseover( function(){ $(this).css('cursor','pointer'); $(this).css('cursor','hand'); } );
				
				$('.pm_user_teaser_inner').click( function(){ messaging_window( $('.pm_left_user_id' , this).val() ); } );
				$('#messaging_window').click( function(e){ if(e.target.id=='messaging_window')	{ closeMessagingWindow(); } } );
				$('#pm_message').keyup ( function(e){ if(e.which == 16 ) isShift=false;  } );
				
				$('#pm_message').keydown (function(e) {
					//alert(e.which);					
					if (e.which == 16) isShift=true;
					if (e.which ==13 && isShift == true)
				  	{
				  		//$('#pm_message').val($('#pm_message').val()+'\n');				  		
				  		//alert('mit shift');
				  	}
					else  
  					if (e.which ==13)
				  	{
				  		if ($('#pm_message').val()!='' && $('#pm_to_user_id').val() && !pm_patient_conversation )
						{  	
							send_message_to( $('#pm_to_user_id').val() );
	  			 
						}	
                        else
                        if ( pm_patient_conversation )
                        {
                            send_message_to( pm_patient_hash , true );
                        }
						setTimeout( function () {$('#pm_message').val('')}, 100)			  		
				  	}
				  	
  				}); 
				//alert(PmMessagingObj.pm_last_msg_id);
			}
	});	
    
	
}
function send_message_to(to_user_id , pat_conv)
{
    if (pat_conv)
    {
        datastring = 'pm_patient_hash='+to_user_id+'&pm_patient_conversation=true'+'&msg_text='+$('#pm_message').val();
    }
    else
    {
        datastring = 'to_user_id='+to_user_id+'&msg_text='+$('#pm_message').val();
    }
	jQuery.ajax({
		// data: 'user_id='+user_id,
		url: site_url+controller.pm+'/send_message_to',
		data: datastring,
		type: "POST",
		timeout: 4000,
		error: function(){ console.log("25:Fehler"); },
		success: function(ret){	
				var responseJSON = $.evalJSON(ret);				
				PmMessagingObj.pm_last_msg_id = responseJSON.pm_last_msg_id;
				$($('#pm_content_message_output')).append(responseJSON.pm_quark);
				$( '#pm_content_message_output').attr({ scrollTop: $('#pm_content_message_output').attr("scrollHeight")  });
							
			}
	});	
}
function get_popup_pm_from_patient_to_zahnarzt( loginData )
{    
    topx = parseInt(((document.all)?document.body.scrollTop:window.pageYOffset))+20;
	if ($('#fast_post_popup_window').length==0) 
	{
		var inputs = [];
		for( attr in loginData) { inputs.push( attr + '=' + encodeURIComponent(loginData[attr]));   }
        //$( loginData ).each(function(){ inputs.push(this.name + '=' + encodeURIComponent(this.value)); })
        
		jQuery.ajax({
		// data: 'user_id='+user_id,
		url: site_url+controller.pm+'/get_popup_pm_from_patient_to_zahnarzt',
		data: inputs.join('&'),
		type: "POST",
		timeout: 4000,
		error: function(){ console.log("25:Fehler"); },
		success: function(ret){	
				var responseJSON = $.evalJSON(ret);
				$(document.body).append('<div id="fast_post_popup_window" style="margin-top:'+topx+'px" >'+responseJSON.loginhtml+'</div>');						
			}
	});
		
	}
	else
	{
		$('#fast_post_popup_window').css('margin-top', topx+20+'px');
		$('#fast_post_popup_window').css('display','block');
	}
    
}
function pm_from_patient_to_zahnarzt_checkemail( email )
{
    $('#pm_from_patient_to_zahnarzt_email_busy').css( 'display' , 'inline' );
    jQuery.ajax({ 
    	url: site_url+controller.pm+'/pm_from_patient_to_zahnarzt_checkemail',
    	data: 'email='+email,
    	type: "POST",
    	timeout: 4000,
    	error: function(){ $('#pm_from_patient_to_zahnarzt_email_busy').css( 'display' , 'none' ); console.log("25:Fehler"); },
    	success: function(ret){
            $('#pm_from_patient_to_zahnarzt_email_busy').css( 'display' , 'none' );    	  
            var responseJSON = $.evalJSON(ret);
    		//$(document.body).append('<div id="fast_post_popup_window" style="margin-top:'+topx+'px" >'+responseJSON.loginhtml+'</div>');
            if ( responseJSON.patient_email_exist)
            {
                $('#pm_from_patient_to_zahnarzt_name').val(responseJSON.patientname);
                $('#pm_from_patient_to_zahnarzt_name').attr("disabled", true);
                $('#pm_from_patient_to_zahnarzt_name').blur();  
                
                $('#pm_from_patient_to_zahnarzt_message').focus();
                $('#pm_from_patient_to_zahnarzt_name').blur();    
            }
            else
            {
                $('#pm_from_patient_to_zahnarzt_name').attr("disabled", false); 
            }
            						
    	}
    });
}
function pm_from_patient_to_zahnarzt_form_send()
{    
    blende.show();     
    
    var inputs = [];
	$( ':input' , $('#pm_from_patient_to_zahnarzt_form') ).each(function(){ inputs.push(this.name + '=' + encodeURIComponent(this.value)); })
    jQuery.ajax({
    	url: site_url+controller.pm+'/pm_from_patient_to_zahnarzt_send',
    	data: inputs.join('&'),
    	type: "POST",
    	timeout: 4000,
    	error: function(){ blende.hide();  console.log("25:Fehler"); },
    	success: function(ret){
            blende.hide();   	  
            var responseJSON = $.evalJSON(ret);
            if (!responseJSON.captcha_check) 
            { 
                alert('Captcha False');
            }
            else
            {
                $('#fast_post_popup_window').remove();
                alert('Ihre Nachricht wurde erfolgreich gespeichert!\nSie bekommen eine Email wenn Zahnarzt auf Ihre anfrage antwortet.')
            }
    		//$(document.body).append('<div id="fast_post_popup_window" style="margin-top:'+topx+'px" >'+responseJSON.loginhtml+'</div>');						
    	}
    });
}