

function updateSticky() {
    var lastSticky = $('li[data-separator]').first();

    $('li[data-separator]').each(function () {

        if ($(this).position().top <= 0) {
            lastSticky = $(this);
        }
    });
    var id = lastSticky.attr('data-separator');
    $('#sticky-heading').html(id);
}


function recipientFoundView(searchForTxt, searchType, listIds) {
    $.ajax({
    	url: '/Messenger/RecipientListSearchView',
    	data : {
    		searchFor: searchForTxt,
    		searchType: searchType,
    		lids: listIds,
    		origPat: $('#tab-patient').attr("data-original-patient")
    	},
        dataType: 'html',
        cache: false,
        success: function (data) {
            if (searchType == 'u') {
                $('#result_area_list_usr').empty();
                $(data).appendTo('#result_area_list_usr');
            }
            if (searchType == 'p') {
                $('#result_area_list_pat').empty();
                $(data).appendTo('#result_area_list_pat');
            }
            if (searchType == 'g') {
                $('#result_area_list_grp').empty();
                $(data).appendTo('#result_area_list_grp');
            }
        }
    });
}

// Can this user send messages to patients. Set value in attribute 
function userCanAddPatient() {
    var canSend = false;
    $.ajax({
        url: '/Messenger/UserCanSendMsgToPatient',
        type: 'POST',
        dataType: 'json',
        async: false,
        success: function (data) {
            canSend = data;
        }
    });
    $('#tab-patient').attr("data-can-send-patient", canSend);
}

function verifyMessage(formContainer) {
    var result;
    $.ajax({
        url: '/Messenger/VerifyMessage',
        type: 'POST',
        data: formContainer.serialize(),
        dataType: 'json',
        async: false,
        success: function (data) {
            //alert("exito");
            result = data;
        }
    });

    return result;
}






function doOnOrientationChange() {
    setTimeout(function() {
        //$(window).trigger("throttledresize"); 
        $('body').css({'display':'none'}).css({'display':'block'});
    }, 400);    
    //window.scrollTo(0, 0);      // To hide iphone virtual keyword; set inside of setTimeout and call window.scrollTo()
}

window.addEventListener('orientationchange', doOnOrientationChange);

// Calculate new height using lineheight to increment or decrement height. ScrollHeight is used as reference. Recursive
function calculateHeight(origHeight, newScrollHeight, lineHeight) {
    var newHeight;
    if (origHeight > newScrollHeight) {
        newHeight = origHeight - lineHeight;
        newHeight = calculateHeight(newHeight, newScrollHeight, lineHeight);
    } else {
        if ((origHeight + lineHeight) > newScrollHeight)
            return origHeight;
        else
            newHeight = calculateHeight(origHeight + lineHeight, newScrollHeight, lineHeight);
    }
    return newHeight;
}

// Set Height for input element (used for Subject)
function setHeightInput(inputElem) {

	var lineHeight = parseFloat($(inputElem).css("line-height").replace(/[^-\d\.]/g, '')); // Get line-height value, remove px or other non digit characters and convert to string.
    var origHeight = $(inputElem).height();

    $(inputElem).height(0);                          // Reset cero also calculate new scrollheight depending what text is included in the field

    var newScrollHeight = $(inputElem).prop('scrollHeight');    // scrollHeight with 
    var newHeight = calculateHeight(origHeight, newScrollHeight, lineHeight);       // Calculate height depending lineheight. (not just assigning scrollHeight to this.height which is the common practice)

    $(inputElem).height(newHeight);
}

// Display results for Search window
function getRecipientInfo(searchCtl, searchType) {
    // After press Enter search for results
    searchCtl.trigger('blur');					// AX-24898.24919.2 .blur(); // blur (or focus in other field) remove virtual keyword)
    if (searchCtl.val().length > 0) {
        setTimeout(function() {
            // Get Ids for the corresponding Option (0-To, 1-Cc, 2-Bcc)
            var argsResult = new Array(); 
            argsResult['ids'] = argsResult['names'] = '';
            argsResult = setTokenIds($('#RecipientTo').tokenInput("get"), argsResult);
            argsResult = setTokenIds($('#RecipientCc').tokenInput("get"), argsResult);
            argsResult = setTokenIds($('#RecipientBcc').tokenInput("get"), argsResult);
            
            recipientFoundView(searchCtl.val(), searchType, argsResult['ids']);
        }, 200);  // SetTimeout .2 sec. to avoid android virtual keyword hide part of the list after closed
    } else {
        if (searchType == "u")
            $('#result_area_list_usr').empty();
        if (searchType == "p")
            $('#result_area_list_pat').empty();
        if (searchType == "g")
            $('#result_area_list_grp').empty();
    }
      }

      // Autosize TextboxArea on window resize to prevent unnecessary scroll bars
      function sizeTextboxArea() {
          // AX-1385 Check if inforForm is valid
          if ($("#infoForm").length > 0) {
              var heightTextAre = $(window).height() - $("#infoForm").offset().top - 245;       // Calculate min-height for textarea. 320
              $("#MessageText").css("minHeight", heightTextAre);
              $("#MessageText").css("height", heightTextAre);
              // remove and re-add the plugin on this field to re-calculate the minimum height
              $("#MessageText").trigger('autosize.destroy');
              $("#MessageText").autosize({ append: false });
              $("#MessageText").trigger('autosize.resize');
          }          
      }

$(document).ready(function () {
	

	sizeTextboxArea();
	$("#MessageText").autosize();
	// Set autosize jquery plug in
	//$('input[type=text], textarea').focus(function () { // Text area and input set position at top
    $("#MessageText").on('focus', function () { // Text area and input set position at top // AX-24898.24919.2 .focus(function () {
		var vScrollPos = $(this).offset().top;
		$("html, body").animate({ scrollTop: vScrollPos }, "slow");
		keepAlive();        // Reset autoLogout
    }).on('blur', function () {			// AX-24898.24919.2 .blur(function() {
		keepAlive();        // Reset autoLogout
	}).on('keyup', function () {
	    keepAlive();        // Reset autoLogout
	});


	setHeightInput('#Subject');

	// disallow enter in subject
	$('#message-compose').on('keypress', 'textarea.autoresize', function (event) {
		if (this.id == "Subject" && event.keyCode == 13) {
			event.preventDefault();
			return false;
		}
		return true;
	});

	// auto adjust the height of subject area. 
	$('#message-compose').on('keyup', 'textarea.autoresize', function (event) {
		var maxLenght = parseInt($(this).attr('maxlength'));

		if (this.id == "Subject" && $(this).val().length > maxLenght) {
			var cutText = $(this).val().substr(0, maxLenght);
			$(this).val(cutText);
			event.preventDefault();
			return false;
		}
		if (this.id == "Subject" && event.keyCode == 13) {
			var repl = $(this).val().replace(/(\r\n|\n|\r)/gm, "");         // Remove CR LF 
			$(this).val(repl);
			event.preventDefault();
			return false;
		}
		setHeightInput(this);
		keepAlive();        // Reset autoLogout
		return true;
    }).on('focus', function () {        // AX-24898.24919.2 .focus(function () {
		keepAlive();        // Reset autoLogout
    }).on('blur', function () {			// AX-24898.24919.2 .blur(function() {
		keepAlive();        // Reset autoLogout
	});

    $('#message-compose').find('textarea.autoresize').trigger('keyup');          // AX-24898.24919.2 .keyup(); AX-25122

	$('#a-send').addClass('disable');       // By default disable Send button

	$('.uselessCcBcc').on('click', function () {
		$(".uselessCcBccArea").hide();      // hide Cc/Bcc area
		$(".ccBccArea").show();             // show CC and Bcc areas
        $("#token-input-RecipientCc").trigger('focus');      // AX-24898.24919.2 .focus();
		keepAlive();        // Reset autoLogout

	});

	$("#a_cancelSearch").on('click', function () {
		keepAlive();        // Reset autoLogout
		setTimeout(function() {
			setValuesBeforeReturnCompose();
		}, 200);            // Set timeout because in android after clicking Cancel and open again it show Cancel anchor as :active
	});

	// Set Delete button for input fields with class deletable. from http://stackoverflow.com/questions/2803532 (don't use type="search" because doesn't work in iphone)
	$('input.deletable').wrap('<span class="deleteicon" />').after($('<span/>').on('click', function () {
        $(this).prev('input').val('').trigger('focus');      // AX-24898.24919.2 .focus();
	}));

	// Search list display for Users
	//$("#searchItemU").keypress(function () {  // Keypress doesn't trigger in android chrome browser, instead use "input keyup"
    $("#searchItemU").on('input keyup', function (e) {        // AX-24898.24919.2 $("#searchItemU").bind('input keyup', function (e) {
		keepAlive();        // Reset autoLogout
		if (e.which == 13) {    // After press Enter search for results
			getRecipientInfo($(this), "u");
		}
	});

	// Search list display for Patients
    $("#searchItemP").on('input keyup', function (e) {      // AX-24898.24919.2 $("#searchItemP").bind('input keyup', function (e) {
		keepAlive();        // Reset autoLogout
		if (e.which == 13) {    // After press Enter search for results
			getRecipientInfo($(this), "p");
		}
	});

	// Search list display for Groups
    $("#searchItemG").on('input keyup', function (e) {        // AX-24898.24919.2 $("#searchItemG").bind('input keyup', function (e) { 
		keepAlive();        // Reset autoLogout
		if (e.which == 13) {    // After press Enter search for results
			getRecipientInfo($(this), "g");
		}
	});

	$('#IsPriority').val(false);
	// Set Urgent flip switch 
	//setflipSlider();

	// For tabs need to in jquery register hover, because in iphone css selector :hover present when is suppouse not to be.
	$('.tabs a').hover(
         function () {
         	if (!$(this).hasClass('disable'))
         		$(this).addClass('tabs_hover');        //$(this).css({ "background-color": "red" });
         },
         function () {
         	$(this).removeClass('tabs_hover');         //$(this).css({ "background-color": "blue" });
         }
     );


});

function SetRecipientReplyForward(idEncoded, fullName, recipientType, option) {
    //fullName = htmlDecode(fullName);
    fullName = decodeEntities(fullName);
    var recipientTypeVal = recipientType == "User" ? 0 : recipientType == "Group" ? 1 : 2;
    if (option == "To") {
        $("#RecipientTo").tokenInput('add', { IdEncrypted: idEncoded, NameDescription: fullName, SearchRecipientType: recipientTypeVal });
    }
    if (option == "Cc") {
        $("#RecipientCc").tokenInput('add', { IdEncrypted: idEncoded, NameDescription: fullName, SearchRecipientType: recipientTypeVal });
    }
    if (option == "Bcc") {
        $("#RecipientBcc").tokenInput('add', { IdEncrypted: idEncoded, NameDescription: fullName, SearchRecipientType: recipientTypeVal });
    }
    $('#a-send').removeClass("disable");
}



function SetSelectedRecipient(id, idEncoded, fullName, recipientType) {
    //fullName = htmlDecode(fullName);
    fullName = decodeEntities(fullName);
    var recipientTypeVal = recipientType == "User" ? 0 : recipientType == "Group" ? 1 : 2;
    if ($("#searchForOption").val() == "t") {
    	$("#RecipientTo").tokenInput('add', { IdEncrypted: idEncoded, NameDescription: fullName, SearchRecipientType: recipientTypeVal });
        $("#token-input-RecipientTo").trigger('focus');      // AX-1385 // AX-24898.24919.2 .focus();
    }
    if ($("#searchForOption").val() == "c") {
    	$("#RecipientCc").tokenInput('add', { IdEncrypted: idEncoded, NameDescription: fullName, SearchRecipientType: recipientTypeVal });
        $("#token-input-RecipientCc").trigger('focus');      // AX-1385 // AX-24898.24919.2 .focus();
    }
    if ($("#searchForOption").val() == "b") {
    	$("#RecipientBcc").tokenInput('add', { IdEncrypted: idEncoded, NameDescription: fullName, SearchRecipientType: recipientTypeVal });
        $("#token-input-RecipientBcc").trigger('focus');      // AX-24898.24919.2 .focus();
    }
    setValuesBeforeReturnCompose();

    $('#a-send').removeClass("disable");

}


function setValuesBeforeReturnCompose() {
    $("#searchItemU").val("");
    $("#searchItemP").val("");
    $("#searchItemG").val("");

    $('#result_area_list_usr').empty();
    $('#result_area_list_pat').empty();
    $('#result_area_list_grp').empty();

    /*
    $('#search-glass-to').hide();
    $('#search-glass-cc').hide();
    $('#search-glass-bcc').hide();*/
	
    $("#message-compose-search").hide();
    $("#message-search-overlay").hide();

}

// Set ids and name from input autocomplete data (jquery.tokenInput plugin)        
function setTokenIds(recipientTokens, argsResult) {
    if (recipientTokens != null && recipientTokens.length > 0) {
        $.each(recipientTokens, function () {
            var recipientType = this.SearchRecipientType == 0 ? "User" : this.SearchRecipientType == 1 ? "Group" : "Patient";
            argsResult.ids += this.IdEncrypted + "\006" + recipientType + "\007";       // Char(007) as separator between one recipient to other; Char(006) as separator between Id y RecipientType        
            argsResult.names += this.NameDescription + "; ";
        });
    }
    return argsResult;
}

// Get the patient Id recipient from tokens. Return 0 if there is no patient
function getPatientIdInTokens(recipientTokens) {
    var patientId = "";
    if (recipientTokens != null && recipientTokens.length > 0) {
        $.each(recipientTokens, function () {
            if (this.SearchRecipientType == 2) 
                patientId = this.IdEncrypted;
        });
    }
    return patientId;
}

// Check if user can send to patient and patient is not already selected as recipient
function includePatients() {
    
    var canSendToPat = $('#tab-patient').attr("data-can-send-patient");
    if (canSendToPat == "false")
        return false;
    
    if ($('#token-input-RecipientTo').length > 0 && getPatientIdInTokens($('#RecipientTo').tokenInput("get")) != "")    
        return false;
    if ($('#token-input-RecipientCc').length > 0 && getPatientIdInTokens($('#RecipientCc').tokenInput("get")) != "")
        return false;
    if ($('#token-input-RecipientBcc').length > 0 && getPatientIdInTokens($('#RecipientBcc').tokenInput("get")) != "")
        return false;
    return true;
}

function includePatientsInSearch(ctl) {
    var canSendToPat = $('#tab-patient').attr("data-can-send-patient");
    var id = $(ctl).attr("id");
    return canSendToPat && id != "RecipientBcc";
}

function getAllSelectedRecipients() {
    var argsResult = new Array();
    argsResult['ids'] = argsResult['names'] = '';
    argsResult = setTokenIds($('#RecipientTo').tokenInput("get"), argsResult);
    argsResult = setTokenIds($('#RecipientCc').tokenInput("get"), argsResult);
    argsResult = setTokenIds($('#RecipientBcc').tokenInput("get"), argsResult);
    
    return argsResult;
}

function alreadySelected(recipientArray, idEncrypted) {
    var exist = false;
    var idsArray = recipientArray.ids.split('\007');    // Char(007) as separator between one recipient to other; Char(006) as separator between Id y RecipientType        
    $.each(idsArray, function () {
        var itemArray = this.split('\006');
        if (itemArray[0] == idEncrypted)
            exist = true;
    });
    return exist;
}

function checkDisplayCc() {
    var recipientCcTokens = $('#RecipientCc').tokenInput("get");
    if (recipientCcTokens != null && recipientCcTokens.length > 0) {
        $(".uselessCcBccArea").hide();  // Reply all of forward
        $(".ccBccArea").show();         // 
    } else {
        $(".uselessCcBccArea").show(); // By default show Cc/Bcc area
        $(".ccBccArea").hide(); // By default hide CC and Bcc areas 
    }
}

// open Search window
function openSearchWin(searchOptionTxt, searchOptionVal) {
	//$("#message-compose").hide();
    $("input").trigger('blur');					// AX-24898.24919.2 .blur();
	$("#message-compose").scrollTop(0);
	setTimeout(function() {
		$("#message-compose-search").show();
		$("#message-search-overlay").show();
	}, 400);
	
    $('#message-compose-search').attr("data-search-option-val", searchOptionVal);
    $("#search-title").text(searchOptionTxt);
    
    // Disable patient tab because there is a patient already selected or SearchBy Bcc doesn't allow Patient or User doesn't have MsgAccess true (allow send to Patient)
    if (!includePatients() || searchOptionVal == "2") {
        $('#tab-patient').prop('disabled', true);
        $('#tab-patient').addClass('disable');
    } else {
        $('#tab-patient').prop('disabled', false);
        $('#tab-patient').removeClass('disable');
    }

    if ($('#tab-group').hasClass('active')) {
        $('#tab-group').removeClass('active');
        var contentG = $('#tab-group').attr('href');
        $(contentG).hide();
    }
    if ($('#tab-patient').hasClass('active')) {
        $('#tab-patient').removeClass('active');
        var contentP = $('#tab-patient').attr('href');
        $(contentP).hide();
    }
    // User is active always
    $('#tab-user').addClass('active');
    var contentU = $('#tab-user').attr('href');
    $(contentU).show();
}

// bind events to the dialog buttons
function dialogConfirmLostMsg(backUrl, messageAction) { // AX-1385 message Action parameter
	// unbind other events before binding new clicks
	$("#alert-ok-btn").off();
	$("#alert-no-btn").off();
	$("#alert-yes-btn").off();

    $("#alert-no-btn").on("click", function () {
        hideAlertDialog();
    });

    $("#alert-ok-btn").on("click", function () {
        hideAlertDialog();
    });

    $("#alert-yes-btn").on("click", function () {
        hideAlertDialog();
        $(".desktop-nav-items a").off();    // AX-1385 Remove function set in _MessageCompose.cshtml
        $("ul.menu li ul a.prompt").off();  // AX-1385 Remove function set in _MessageCompose.cshtml
        if (backUrl == "") // AX-1385
            closeComposeShowPrevious(messageAction, "");   // AX-1385 Second parameter is for "success" after send message
        else {
            window.location = backUrl;
        }
    });
}

function onCancelCompose(backUrl, msgConfirmLostTxt, messageAction) { // AX-1385
    keepAlive();        // Reset autoLogout
    dialogConfirmLostMsg(backUrl, messageAction);   // AX-1385 New parameter messageAction
    var recipientToTokens = $('#RecipientTo').tokenInput("get");
    var recipientCcTokens = $('#RecipientCc').tokenInput("get");
    var recipientBccTokens = $('#RecipientBcc').tokenInput("get");

    if ((recipientToTokens != null && recipientToTokens.length > 0) ||
                    (recipientCcTokens != null && recipientCcTokens.length > 0) ||
                    (recipientBccTokens != null && recipientBccTokens.length > 0) ||
                    $('#Subject').val() != '' ||
                    $('#MessageText').val() != '') {
        showAlertDialogYesNo(msgConfirmLostTxt);
    } else {
        $(".desktop-nav-items a, ul.menu li ul a.prompt, ul.menu li ul a#userHelp").off();    // AX-1385 Remove function set in _MessageCompose.cshtml
        if (backUrl == "") // AX-1385
            closeComposeShowPrevious(messageAction, "");   // AX-1385 Second parameter is success
        else {
            window.location = backUrl;
        }
    }
}

// bind events to the dialog buttons
function dialogConfirmSubjectEmpty()
{
    $("#alert-no-btn").on("click", function () {
        hideAlertDialog();
    });

    $("#alert-ok-btn").on("click", function () {
        hideAlertDialog();
    });

    $("#alert-yes-btn").on("click", function () {
        hideAlertDialog();
    });
}


function chunk_split(body, chunklen, end) {
  // original by: Paulo Freitas
  //    input by: Brett Zamir (http://brett-zamir.me)
  // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Theriault
  //   example 1: chunk_split('Hello world!', 1, '*');
  //   returns 1: 'H*e*l*l*o* *w*o*r*l*d*!*'
  //   example 2: chunk_split('Hello world!', 10, '*');
  //   returns 2: 'Hello worl*d!*'
  chunklen = parseInt(chunklen, 10) || 76;
  end = end || '\r\n';

  if (chunklen < 1) {
    return false;
  }
  return body.match(new RegExp('.{0,' + chunklen + '}', 'g'))
    .join(end);
}

// Word Wrap because with names without spaces it render widther than must be.
function wordwrap(text) {
    var split = text.split(" ");
    var key = 0;
    split.forEach(function(item) {
        if (item.length > 15) {
            split[key] = chunk_split(item, 15, "&#8203;");
        }
        key++;
    });
    return split.join(" ");
}

function wordwrapEncode(text) {
    var split = text.split("&#8203;");
    var key = 0;
    split.forEach(function (item) {
        split[key] = htmlEncode(item);
        key++;
    });
    return split.join("&#8203;");
}


function htmlEncode(value){
  //create a in-memory div, set it's inner text(which jQuery automatically encodes)
  //then grab the encoded contents back out.  The div never exists on the page.
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

function decodeEntities(input) {
    var y = document.createElement('textarea');
    y.innerHTML = input;
    return y.value;
}
