$(function(){
    var to_user_id = $('#to_user_id_handshake').val();
    
    $('#handshake_dialog').dialog({
	autoOpen: false,
	buttons: {
	    'Send Handshake': function() {
		dohandshake();
	    },
	    'Cancel': function() {
		    $(this).dialog('close');
	    }
	},
	resizable: false,
	draggable: false,
	modal: true,
	width: 400
    });

     $('#message_dialog').dialog({
	autoOpen: false,
	buttons: {
	    'Send Handshake': function() {
		dohandshake();
	    },
	    'Cancel': function() {
		    $(this).dialog('close');
	    }
	},
	resizable: false,
	draggable: false,
	modal: true,
	width: 400
    });
     
    $('.start-follow').live('click', function(){
		$('#tooltip_dialog').dialog('option', 'title', 'Follow');
		$('#tooltip_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
		$('#tooltip_dialog').dialog('open');
		var to_user_name_handshake = $("#to_user_name_handshake").val();
		// not logged in
		if(user_name =='' || user_name == null || typeof(user_name) == 'undefined' ){
			var loginurl = 'app/login/index';
			if (typeof(login_return_url) != 'undefined')
			{
				loginurl = 'app/login/?rurl=' + login_return_url;
			}
			
			$("#tooltip_dialog").html('To follow ' + to_user_name_handshake +' you must be registered and logged in. <br /> <br /> What next?  <br />Either <a href="' + loginurl + '">LOGIN</a>, register as an <a href="app/register/company_step_1">EMPLOYER</a> or register as a <a href="app/register/person_step_1">PERSON</a>');
			$('#tooltip_dialog').dialog(
				'option',
				'buttons', {
					"Close": function(){ $(this).dialog("close"); }
				}
			);
			return false;
		}
		
		//alert(to_user_id);
		follow_initiate(to_user_id);
    });
    
	if (typeof(follow_greeting_length) == 'undefined')
	{
		follow_greeting_length = 150;
	}
	
	$('#follow_greeting').live('keyup', function() {
		if ($("#follow_greeting_char_count").length > 0) {
			$("#follow_greeting_char_count").html('You have ' + (follow_greeting_length - $(this).val().length) + ' characters left.')
		} else {
			$(this).after('<p id="follow_greeting_char_count">You have ' + (follow_greeting_length - $(this).val().length) + ' characters left.</p>');
		}
		if ($(this).val().length > follow_greeting_length) {
			$(this).val($(this).val().substring(0, follow_greeting_length));
		}
	});

    $('.button .follow').live('click', function(){
		$('#tooltip_dialog').dialog('option', 'title', 'Follow');
		$('#tooltip_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
		$('#tooltip_dialog').dialog('open');
		to_user_name_handshake = $(this).siblings(".to_user_name_handshake").val();
		// not logged in
		if(user_name == '' || user_name == null || typeof(user_name) == 'undefined' ){
			 $("#tooltip_dialog").html('To follow ' + to_user_name_handshake +' you must be registered and logged in. <br /> <br /> What next?  <br />Either <a href="app/login/index">LOGIN</a>, register as an <a href="app/register/company_step_1">EMPLOYER</a> or register as a <a href="app/register/person_step_1">PERSON</a>');
			 $('#tooltip_dialog').dialog(
				'option',
					'buttons', {
					"Close": function()
						{
							$(this).dialog("close");
						}
					}
				);
			return false;
		}
		
		//alert(to_user_id);
		follow_initiate($(this).siblings(".to_user_id_handshake").val(), $(this));
		//$(this).hide().parent().find('.unfollow').show();
		
		return false;
    });
    
    $('.button .unfollow').live('click', function(){
		$('#tooltip_dialog').dialog('option', 'title', 'Unfollow');
		$('#tooltip_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
		$('#tooltip_dialog').dialog('open');
		to_user_name_handshake = $(this).siblings(".to_user_name_handshake").val();
		// not logged in
		if(user_name == '' || user_name == null || typeof(user_name) == 'undefined' ){
			 $("#tooltip_dialog").html('To unfollow ' + to_user_name_handshake +' you must be registered and logged in. <br /> <br /> What next?  <br />Either <a href="app/login/index">LOGIN</a>, register as an <a href="app/register/company_step_1">EMPLOYER</a> or register as a <a href="app/register/person_step_1">PERSON</a>');
			 $('#tooltip_dialog').dialog(
				'option',
					'buttons', {
					"Close": function()
						{
							$(this).dialog("close");
						}
					}
				);
			return false;
		}
		
		//alert(to_user_id);
		unfollow_initiate($(this).siblings(".to_user_id_handshake").val());
		
		return false;
    });

    function start_follow(to_user_id, follow_greeting){
		//alert(handshake_greeting_id);
		
		$.ajax({
			type: "POST",
			url: 'app/inbox/start_follow',
			data: ({to_user_id : to_user_id, follow_greeting : follow_greeting}),
			success: function(data){
				//$("#handshake_dialog").html(data);
				//alert(data);
				$('#tooltip_dialog').html(data);
				$('#tooltip_dialog').dialog(
					'option',
						'buttons', {
						"Close": function()
							{ $(this).dialog("close");
							}		    
						}
						);
			},
			error: function (data, status, e)
			{
				$("#tooltip_dialog").html('Error in following, please try later');
				$('#tooltip_dialog').dialog(
					'option',
						'buttons', {
						"Close": function()
							{ $(this).dialog("close");
							}		    
						}
						);
			}
		});
    }
    
    function follow_initiate(to_user_id, current_el){
		//$('#tooltip_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
		
		if(typeof(to_user_id) == 'undefined'){
			alert('Error');
			return false;
		}
	
		$.ajax({
	    url: "app/inbox/follow_initiate",
	    global: false,
	    type: "POST",
	    data: ({to_user_id : to_user_id}),
	    dataType: "json",
	    success: function(data){
		$('#tooltip_dialog').html(data.message + data.greeting );
		var follow_greeting = $("#follow_greeting").val();
		if(data.button == 'btnConfirm' && data.message !=''){
		    $('#tooltip_dialog').dialog(
			'option',
			    'buttons', {
				"Cancel": function()
				    { $(this).dialog("close");
				
				    },
				"Yes":function()
				    {
						var follow_greeting = $("#follow_greeting").val();
						if (typeof(follow_greeting) == 'undefined') {
							follow_greeting = '';
						}
						$('#tooltip_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
						//remove all buttons before get response
						$('#tooltip_dialog').dialog('option', 'buttons', {});
						
						start_follow(to_user_id , follow_greeting);
						if (current_el) current_el.hide().parent().find('.unfollow').show();
				    }			    
				}
			    );
		}else{
		     $('#tooltip_dialog').dialog(
			'option',
			    'buttons', {
				"Close": function()
				    { $(this).dialog("close");
				    }		    
				}
			    );
		}
	    },
	    error: function (data, status, e)
	    {
			$("#tooltip_dialog").html('Error in follow that person, please try later');
			$('#tooltip_dialog').dialog(
				'option',
					'buttons', {
					"Close": function()
						{ $(this).dialog("close");
						}		    
					}
					);
	    }
		});
		return false;
    }

    function unfollow(to_user_id){
		
		$.ajax({
			type: "POST",
			url: 'app/inbox/unfollow',
			data: ({to_user_id : to_user_id}),
			success: function(data){
				$('#tooltip_dialog').html(data);
				$('#tooltip_dialog').dialog(
					'option',
						'buttons', {
						"Close": function()
							{
								// if (window.console) console.log($(".to_user_id_handshake[value='" + to_user_id + "']"));
								var tempel = $(".to_user_id_handshake[value='" + to_user_id + "']").parents(".followering");
								if (tempel.hasClass('reciprocal'))
								{
									tempel.find('.button .unfollow.core').hide(); // hide unfollow
									tempel.find('.button.pink .contact-core').hide(); // hide message
									tempel.find('.button .follow.core').show();
								}
								else
								{
									tempel.remove();
								}
								$(this).dialog("close");
							}
						}
						);
			},
			error: function (data, status, e)
			{
			$("#tooltip_dialog").html('Error in following, please try later');
			$('#tooltip_dialog').dialog(
				'option',
					'buttons', {
					"Close": function()
						{
							$(this).dialog("close");
						}
					}
					);
			}
		});
	}
		
	function unfollow_initiate(to_user_id){	
		if(typeof(to_user_id) == 'undefined'){
			alert('Error');
			return false;
		}
			
			$.ajax({
			url: "app/inbox/unfollow_initiate",
			global: false,
			type: "POST",
			data: ({to_user_id : to_user_id}),
			dataType: "json",
			success: function(data){
			$('#tooltip_dialog').html(data.message + data.greeting );
			var follow_greeting = $("#follow_greeting").val();
			if(data.button == 'btnConfirm' && data.message !=''){
				$('#tooltip_dialog').dialog(
				'option',
					'buttons', {
					"Cancel": function()
						{
							$(this).dialog("close");
						},
					"Yes":function()
						{
							$('#tooltip_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
							//remove all buttons before get response
							$('#tooltip_dialog').dialog('option', 'buttons', {});
						
							unfollow(to_user_id);
						}			    
					}
					);
			}else{
				 $('#tooltip_dialog').dialog(
				'option',
					'buttons', {
					"Close": function()
						{ $(this).dialog("close");
						}		    
					}
					);
			}
			},
			error: function (data, status, e)
			{
			$("#tooltip_dialog").html('Error in follow that person, please try later');
			$('#tooltip_dialog').dialog(
				'option',
					'buttons', {
					"Close": function()
						{ $(this).dialog("close");
						}		    
					}
					);
			}
		});
		return false;
    }
    
    $('#tooltip_dialog').dialog('open');
	
    $('#send-handshake').click(function(){
		$('#handshake_dialog').dialog('open');
		$('#handshake_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
		var to_user_name_handshake = $("#to_user_name_handshake").val();
		if(user_name =='' || user_name == null || typeof(user_name) == 'undefined' ){
			$("#handshake_dialog").html('To send a handshake to ' + to_user_name_handshake +' you must be registered and logged in. <br /> <br /> What next?  <br />Either <a href="app/login/index">LOGIN</a>, register as an <a href="app/register/company_step_1">EMPLOYER</a> or register as a <a href="app/register/person_step_1">PERSON</a>');
	     
			$('#handshake_dialog').dialog(
				'option',
			    'buttons', {
				"Close": function()
				    { $(this).dialog("close");
				
				    }
			    }
		    );
			return false;
		}
		handshake_initiate(to_user_id);
    });

    $('.sendHandshake').click(function(){
		$('#handshake_dialog').dialog('open');
		$('#handshake_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
		var to_user_name_handshake = $(this).attr('rel');
		if(user_name =='' || user_name == null || typeof(user_name) == 'undefined' )
		{
			$("#handshake_dialog").html('To send a handshake to ' + to_user_name_handshake +' you must be registered and logged in. <br /> <br /> What next?  <br />Either <a href="app/login/index">LOGIN</a>, register as an <a href="app/register/company_step_1">EMPLOYER</a> or register as a <a href="app/register/person_step_1">PERSON</a>');
	     
			$('#handshake_dialog').dialog(
				'option',
			    'buttons', {
				"Close": function()
				    { $(this).dialog("close");
				
				    }
			    }
		    );
			return false;
		}
		handshake_initiate($(this).attr('href'), to_user_name_handshake);
    });
    
    
    $('#holdSendMessage').click(function() {
	$('#message_dialog').dialog('open');
	var url = 'app/common/get_display_message/11';
	
        $.get(url, function(data){
	    $("#message_dialog").html(data);
        });
	$('#message_dialog').dialog(
	    'option',
		'buttons', {
		    "Close": function()
			{
			    $(this).dialog("close");				
			},
		    "Buy Credit": function()
			{
			    $(this).dialog("close");
			    url = base_url +'app/credit/index';
			    window.location=url;
			}
		    }
		);
    });
    
    $('#sendMessage, .sendMessage').click(function() {
	$('#message_dialog').dialog('open');
	if ($(this).attr('href') != "#") {
		to_user_id = $(this).attr('href');
	}
	var url = 'app/inbox/write_message/'+ to_user_id;
	
        $.get(url, function(data){
	    $("#message_dialog").html(data);
        });
	
	//$('#message_dialog').html("Write message here");
	//handshake_initiate(to_user_id);
	$('#message_dialog').dialog(
			'option',
			    'buttons', {
				"Cancel": function()
				    { $(this).dialog("close");
				
				    },
				"Send":function()
				    {
					var message_subject = $("#message_subject").val();
					if(message_subject == '' ) {
					    alert('Please write subject');
					   return false;
					}
					var message_body = $("#message_body").val();
					if(message_body == '' ) {
					    alert('Please write  message');
					   return false;
					}
					var to_user_id = $("#email_send_to").val();
					$('#message_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
					//remove all buttons before get response
					$('#message_dialog').dialog('option', 'buttons', {});
					
					$.ajax({
					    type: "POST",
					    url: 'app/inbox/send_message',
					    //data: $("form").serialize(),
					    data: ({message_subject : message_subject, message_body: message_body, to_user_id : to_user_id}),
					    success: function(data){
						$('#message_dialog').html(data);
						$('#message_dialog').dialog(
						    'option',
							'buttons', {
							    "Close": function()
							    {
								$(this).dialog("close");							
							    }
							}
						    );
						//alert(data);
						
					    }
					});
					
				
				    }			    
				}
			    );
			    return false;
    });
    
    function handshake_initiate(to_user_id, to_user_name_handshake)
	{
		$('#handshake_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
		
		if(typeof(to_user_id) == 'undefined'){
		    alert('Error');
		    return false;
		}
		
		if (typeof(to_user_name_handshake) == 'undefined')
		{
			to_user_name_handshake = $("#to_user_name_handshake").val();
		}
		
	 $.ajax({
	    url: "app/inbox/handshake_initiate",
	    global: false,
	    type: "POST",
	    data: {'to_user_id': to_user_id},
	    dataType: "json",
	    success: function(data){
		var credit= '';
		if(data.button != 'btnClose'){
		    if(user_type_id == 2){
			credit = '<br /><br />It costs 1 credit to send a handshake, but you\'re only charged if that handshake is accepted.  Want to know more about <a href="about/handshakes">HANDSHAKES</a>?';
		    } else if(user_type_id == 1){
			credit = '<br /><br /> ' + to_user_name_handshake +' will then need to accept your handshake; we will notify you by email when they do.';
		    }
		}
		$('#handshake_dialog').html(data.message + data.greeting + credit);
		var handshake_greeting_id = $("#handshake_greeting").val();
		
		if(data.button == 'btnConfirm' && data.message !=''){
		    $('#handshake_dialog').dialog(
			'option',
			    'buttons', {
				"Cancel": function()
				    { $(this).dialog("close");
				
				    },
				"Send":function()
				    {
					var handshake_greeting_id = $("#handshake_greeting").val();
					if(handshake_greeting_id == '' ) {
					    alert('Please Select a greeting message');
					    return false;
					}
					$('#handshake_dialog').html("<br /><br /><img src='images/ajax-loader.gif'>");
					//remove all buttons before get response
					$('#handshake_dialog').dialog('option', 'buttons', {});
					
					do_handshake(to_user_id , handshake_greeting_id);
					
					eventTrackHandshake();
					
				    }			    
				}
			    );
		}else{
		     $('#handshake_dialog').dialog(
			'option',
			    'buttons', {
				"Close": function()
				    { $(this).dialog("close");
				    }		    
				}
			    );
		}
	    },
	    error: function (data, status, e)
	    {
		$("#handshake_dialog").html('You appear to be logged out. Your session may have expired. To send a handshake simply log back in again.');
		$('#handshake_dialog').dialog(
			'option',
			    'buttons', {
				"Close": function()
				    { $(this).dialog("close");
				    }		    
				}
			    );
	    }
	});
	return false;
    }
    
    function do_handshake(to_user_id, handshake_greeting_id){
	//alert(handshake_greeting_id);
	handshake_process_id = '';
	if(user_type_id == 1)
	    handshake_process_id = 1;
	else if (user_type_id == 2)
	    handshake_process_id = 2;
	$.ajax({
	    type: "POST",
	    url: 'app/inbox/doHandshake',
	    data: ({to_user_id : to_user_id, handshake_greeting_id : handshake_greeting_id, handshake_process_id : handshake_process_id}),
	    success: function(data){
		//$("#handshake_dialog").html(data);
		//alert(data);
		$('#handshake_dialog').html(data);
		$('#handshake_dialog').dialog(
			'option',
			    'buttons', {
				"Close": function()
				    { $(this).dialog("close");
				    }		    
				}
			    );
		
	    }
	});
    }
    
    function send_message(to_user_id){
	//alert(handshake_greeting_id);
	$.ajax({
	    type: "POST",
	    url: 'app/inbox/send_message',
	    data: ({to_user_id : to_user_id}),
	    success: function(data){
		//$("#handshake_dialog").html(data);
		//alert(data);
		$('#handshake_dialog').html(data);
		$('#handshake_dialog').dialog(
			'option',
			    'buttons', {
				"Close": function()
				    { $(this).dialog("close");
				    }		    
				}
			    );
		
	    }
	});
    }
    
   
});

