/****************** common.js *****************/
/* SUBOR JS pre cely LAST aj subdomeny */

// POZOR!!! TOTO ZARUCI ZE MOZEME VOLAT Z SUBSTRANKY AJAX PRIAMO NA HLAVNEJ STRANKE
document.domain = "last-memories.com";
//window.onbeforeunload = ajax_userLeavePage;

function GetXmlHttpObject(handler) {
	var objXMLHttp=null;
	if (window.XMLHttpRequest) {
		objXMLHttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return objXMLHttp;
}

$(document).ready(function(){
    ///* jQuery pre button taky maly pekny*/
    jQuery('a.minibutton').bind({
        mousedown: function() {
            jQuery(this).addClass('mousedown');
        },
        blur: function() {
            jQuery(this).removeClass('mousedown');
        },
        mouseup: function() {
            jQuery(this).removeClass('mousedown');
        }

    });
    
});

function ajax_userLeavePage(){
    if($("#ax_ismainpage").length == 0)
        return;
    var ax_ismainpage = $("#ax_ismainpage").val();
    var addr = ax_ismainpage == 1 ? "/ajax/ajax_unloaduser.php" : "/unifile.php?fti=ajax_unloaduser";
    $.getJSON(addr, {}, function() { });
    confirm("naozaj");
}

//zrusi cache aby netrebalo pridavat parameter i=3,4,5 do kazdeho volania
$.ajaxSetup ({
    cache: false
});

var reg_email = /^[a-zA-Z0-9_]+([\.\-][a-zA-Z0-9_]+)*@[a-zA-Z0-9_]+([\.\-][a-zA-Z0-9_]+)*\.[a-zA-Z]{2,5}$/;

(function($){
    $.fn.validationEngineLanguage = function(){
    };
    $.validationEngineLanguage = {
        newLang: function(){
            $.validationEngineLanguage.allRules = {
                "required": { // Add your regex rules here, you can take telephone as an example
                    "regex": "none",
                    "alertText":Ajax.JS_tooltip_required,
                    "alertTextCheckboxMultiple":Ajax.JS_tooltip_required_select,
                    "alertTextCheckboxe":Ajax.JS_tooltip_required_checkbox
                },
                "minSize": {
                    "regex": "none",
                    "alertText": "Minimum ",
                    "alertText2": " characters"
                },
                "maxSize": {
                    "regex": "none",
                    "alertText": "Maximum ",
                    "alertText2": " characters"
                },
                "min": {
                    "regex": "none",
                    "alertText": "Minimum value is "
                },
                "max": {
                    "regex": "none",
                    "alertText": "Maximum value is "
                },
                "past": {
                    "regex": "none",
                    "alertText": "* Date prior to "
                },
                "future": {
                    "regex": "none",
                    "alertText": "* Date past "
                },
                "maxCheckbox": {
                    "regex": "none",
                    "alertText": "* Checks allowed Exceeded"
                },
                "minCheckbox": {
                    "regex": "none",
                    "alertText": "Please select ",
                    "alertText2": " options"
                },
                "equals": {
                    "regex": "none",
                    "alertText": "Fields do not match"
                },
                "phone": {
                    // credit: jquery.h5validate.js / orefalo
                    "regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,
                    "alertText": "* Invalid phone number"
                },
                "email": {
                    // Simplified, was not working in the Iphone browser
                    "regex": /^([A-Za-z0-9_\-\.\'])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/,
                    "alertText": "* Invalid email address"
                },
                "integer": {
                    "regex": /^[\-\+]?\d+$/,
                    "alertText": "* Not a valid integer"
                },
                "number": {
                    // Number, including positive, negative, and floating decimal. credit: orefalo
                    "regex": /^[\-\+]?(([0-9]+)([\.,]([0-9]+))?|([\.,]([0-9]+))?)$/,
                    "alertText": "* Invalid floating decimal number"
                },
                "date": {
                    // Date in ISO format. Credit: bassistance
                    "regex": /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/,
                    "alertText":Ajax.JS_tooltip_date
                },
                "ipv4": {
                    "regex": /^([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+$/,
                    "alertText": "* Invalid IP address"
                },
                "url": {
                    "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/,
                    "alertText": "* Invalid URL"
                },
                "onlyNumberSp": {
                    "regex": /^[0-9\ ]+$/,
                    "alertText": "Numbers only"
                },
                "onlyLetterSp": {
                    "regex": /^[a-zA-Z\ \']+$/,
                    "alertText": "Letters only"
                },
                "onlyLetterNumber": {
                    "regex": /^[0-9a-zA-Z]+$/,
                    "alertText": "* No special characters allowed"
                },
                // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
                "ajaxUserCall": {
                    "url": "ajaxValidateFieldUser",
                    // you may want to pass extra data on the ajax call
                    "extraData": "name=eric",
                    "alertText": "* This user is already taken",
                    "alertTextLoad": "* Validating, please wait"
                },
                "ajaxNameCall": {
                    // remote json service location
                    "url": "ajaxValidateFieldName",
                    // error
                    "alertText": "* This name is already taken",
                    // if you provide an "alertTextOk", it will show as a green prompt when the field validates
                    "alertTextOk": "* This name is available",
                    // speaks by itself
                    "alertTextLoad": "* Validating, please wait"
                },
                "validate2fields": {
                    "alertText": "* Please input HELLO"
                },
                "email_check":{
                    "regex": /^[a-zA-Z0-9_]+([\.\-][a-zA-Z0-9_]+)*@[a-zA-Z0-9_]+([\.\-][a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/,
                    "alertText":Ajax.JS_tooltip_invalidemail
                },
                "onlyLetter":{
                    "regex":"/^[a-zA-Z\ \']+$/",
                    "alertText":Ajax.JS_tooltip_onlyLetter
                },
                "odkaz_check":{
                    "regex":"/^[a-zA-Z0-9]+((-)[a-zA-Z0-9]+)*$/",
                    "alertText":Ajax.JS_tooltip_odkazCheck
                }
            };

        }
    };
})(jQuery);


$(document).ready(function() {
    $.validationEngineLanguage.newLang()
});

// funkcie pre validation form v registracii na zobraenie tooltip aby vedel kolko ma pisat znakov
function display_password_tip(id, idform){
    var idemail = "#" + id;
    var idformular = "#" + idform;

    if(($(idemail).val().length > 1)){
        $(idformular). validationEngine("validateField", idemail);
    }
}

// zameni vsetky vyskyty html znakov ako \n, <, >, &, ' ', ", ' za html entity, toto je zbytocne relativne, pretoze to musi aj tak byt osetrene na strane servera, pouziva sa to pri vypise generovanej adresy na stranku v registracii aj v userovi niekde
function removeHTML(text) {
    var re = new RegExp("&","g");
    text = text.replace(re,"&amp;");
    re = new RegExp("<","g");
    text = text.replace(re,"&lt;");
    re = new RegExp("  ","g");
    text = text.replace(re,"&nbsp; ");
    re = new RegExp(">","g");
    text = text.replace(re,"&gt;");
    re = new RegExp('"',"g");
    text = text.replace(re,"&quot;");
    re = new RegExp("'","g");
    text = text.replace(re,"&#039;");
    re = new RegExp("\r\n","g");
    text = text.replace(re,"<br />");
    re = new RegExp("\n","g");
    text = text.replace(re,"<br />");
    return text;
}

function modalRegistration(){
    $("#register_modal").validationEngine({
        scroll:false,
        inlineValidation: false
    });

    $('#register_modal').keyup(function(e) {
        if (e.keyCode == 13) {
            $("#register_modal").submit()
        }
    });

    var dialog_buttons = {};
    dialog_buttons[Ajax.JS_common_modal_create] = function(){
        /*remove_email_validation_modal();*/
        $("#register_modal").submit()
    }
    dialog_buttons[Ajax.JS_common_modal_cancel] = function(){
        $(this).dialog('close');
    }

    $("#modalRegistration").dialog({
        modal:true,
        width:'auto',
        height:'auto',
        title: Ajax.JS_title_modalRegistration,
        draggable: false,
        resizable: false,
        buttons: dialog_buttons
    /* beforeclose: function(event, ui) { $.validationEngine.closePrompt("#email_modal");$.validationEngine.closePrompt("#password2_modal");$.validationEngine.closePrompt("#password1_modal"); } */
    });
    //$("#email_modal").focus();
}

function modalLogin(){
    var dialog_buttons = {};
    
    $('#loginform_modal').keyup(function(e) {
        if (e.keyCode == 13) {
            $("#loginform_modal").submit()
        }
    });

    dialog_buttons[Ajax.JS_common_modal_login] = function(){
        $("#loginform_modal").submit()
    }
    dialog_buttons[Ajax.JS_common_modal_cancel] = function(){
        $(this).dialog('close');
    }

    $("#modalLogin").dialog({
        modal:true,
        width:503,
        height:'auto',
        title: Ajax.JS_title_modalLogin,
        draggable: false,
        resizable: false,
        buttons: dialog_buttons
    });
    $("#login_modal").focus();
}

function modalMainErrorLogin(){
    $("#mainErrorLogin").dialog({
        modal: true,
        buttons: {
            "Ok": function() {
                $(this).dialog("close");
            }
        },
        title: 'Error',
        draggable: false,
        resizable: false,
        width: 'auto',
        minHeight: 0,
        height:'auto'
    });
}

function modalWarrning(titleText, Text, ac, buttonOKText, buttonCancelText)
{
    $("#modalWarningText").html("<div class='notice_question_noborder_min'>" + Text + "</div>");

    var dialog_buttons = {};
    dialog_buttons[buttonOKText] = function(){
        ac();
        $(this).dialog("close");
    }
    dialog_buttons[buttonCancelText] = function(){
        $(this).dialog('close');
    }

    $("#modalWarrning").dialog({
        modal:true,
        draggable: false,
        resizable: false,
        minHeight: 0,
        width: 'auto',
        height: 'auto',
        title: titleText,
        buttons: dialog_buttons
    });
}


function modalNotification(titleText, textmsg, typemsg, func)
{
    //typemsg = 1  warning, typemsg = 2 OK, typemsg = 3 question ale toto je pouzite v modalWarrning funkcii kvoli dvom button a jednoduchosti
    if(typemsg == 1)
        $("#modalNotificationText").html("<div class='notice_warning_noborder_min'>" + textmsg + "</div>");
    else
        $("#modalNotificationText").html("<div class='notice_ok_noborder_min'>" + textmsg + "</div>");

    var dialog_buttons = {};

    if((func != "undefined") && (func != null)){
        dialog_buttons["Ok"] = function(){
            func();
            $(this).dialog('close');
        }
    }
    else{
        dialog_buttons["Ok"] = function(){
            func = function() {};
            $(this).dialog('close');
            
        }
    }

    $("#modalNotification").dialog({
        modal:true,
        draggable: false,
        resizable: false,
        minHeight: 0,
        width: 'auto',
        height: 'auto',
        title: titleText,
        buttons: dialog_buttons,
        close: function(){func()}
    });
}

function modalSendMessages(refMessageId,toUserId)
{
    $("#msg_refid").val(refMessageId);
    $("#msg_touser").val(toUserId);

    ajax_fillUserName(toUserId);//naplni meno uzivatela

    var dialog_buttons = {};
    dialog_buttons[Ajax.JS_subwebsite_modal_send] = function(){
        ajax_sendMessage();
    }
    dialog_buttons[Ajax.JS_subwebsite_modal_cancel] = function(){
        $(this).dialog('close');
    }

    $("#modalSendMessages").dialog({
        modal:true,
        draggable: false,
        resizable: false,
        minHeight: 0,
        width: 'auto',
        height: 'auto',
        title: Ajax.JS_common_modal_send_messages,
        buttons: dialog_buttons
    });
    $("#msg_title").focus();

    var ax_addr = $("#ax_addr").val();
    $("#a_message").attr("href", ax_addr + "/userinfo/uid/" + toUserId);
}


function modalDisplayMessages()
{
    var dialog_buttons = {};
    dialog_buttons[Ajax.JS_last_modal_reply] = function(){
        $(this).dialog('close');
        modalSendMessages($("#msg_iddisplaymsg").val(),$("#msg_fromuserID").val());
         
    }
    dialog_buttons[Ajax.JS_last_modal_ok] = function(){
        $(this).dialog('close');
    }
    
    $("#modalDisplayMessages").dialog({
        modal:true,
        draggable: false,
        resizable: false,
        minHeight: 0,   
        width: 'auto',
        height: 'auto',
        title: Ajax.JS_common_modal_message,
        buttons: dialog_buttons
    });
}

// kedze shitny JS neobsahuje metodu replaceAll, musime ju doprototypovat, znamena, ze mozes zavolat retazec.replaceAll(co, cim) a nahradi vsetky vyskyty
String.prototype.replaceAll = function replaceAll(search, replace) {
    var temp = this;
    while(temp.indexOf(search) != -1)
        temp = temp.replace(search, replace);
    return temp;
}

//AJAX
var countmsgunread = 0;//premena pre zobrazovanie tooltipov v message toolbare
/** Ajax na kontrolu zadaneho emailu pri registracii **/
function ajax_sendMessage() {
    $('.ui-dialog-buttonpane button').attr('disabled', 'disabled');
    //$('.ui-dialog-buttonpane button:contains(Send)').val("Sending");
   
    var msg_touser = $("#msg_touser").val();
    var msg_title = $("#msg_title").val();
    var msg_text = $("#msg_text").val();
    var msg_refid = $("#msg_refid").val();
    var msg_link = 1;
    
    var ax_send_message_addr = $("#ax_send_message_addr").val();
    $.getJSON(ax_send_message_addr, {
        ac:"s",
        title:msg_title,
        message:msg_text,
        touser:msg_touser,
        refid:msg_refid,
        link:msg_link
    }, function(json) {
        callback_sendMessage(json);
    });
}

function callback_sendMessage(json) {
    if(json == null || json == "undefined") {
        alert("Error sending message");
        return;
    }

    if(json.okMessage != null && json.okMessage != "undefined") {
        $("<div class='notice_ok_noborder_min'>"+json.okMessage+"</div>").appendTo("#displaySendMessage");
        $("#displaySendMessage > div").delay(2000).fadeOut(500, function() {
            $(this).remove();
        });
        if(typeof ajax_messagePaggingShowPage == "function") {
            ajax_messagePaggingShowPage(1, "tblMessageFrom");
            ajax_messagePaggingShowPage(messagesForPage, "tblMessageFor");  // aby ma z aktualnej stranky kde klikam na reply nehodilo na prvu, tak nebudem kontrolovat maily
        }
        $("#msg_text").val("");
        $("#msg_title").val("");
    //setTimeout(function() {$("#modalSendMessages").dialog('close');}, 3000);
    }

    if(json.errorMessage != null && json.errorMessage != "undefined") {
        $("<div class='notice_warning_noborder_min'>"+json.errorMessage+"</div>").appendTo("#displaySendMessage")
        $("#displaySendMessage > div").delay(5000).fadeOut(500, function() {
            $(this).remove();
        });
    }

    if(json.syntaxErrorMessage != null && json.syntaxErrorMessage != "undefined") {
        /* $("<div class='notice_warning_noborder_min'></div>").appendTo("#displaySendMessage"); */
        for (var i=0; i<json.syntaxErrorMessage.length;i++)
        {
            $("<div class='notice_warning_noborder_min'>"+json.syntaxErrorMessage[i]+"</div>").appendTo("#displaySendMessage")
        //$("#displaySendMessage > div").append(json.syntaxErrorMessage[i]).append("<br />");
        }
        $("#displaySendMessage > div").delay(5000).fadeOut(500, function() {
            $(this).remove();
        });
    }

    $('.ui-dialog-buttonpane button').removeAttr('disabled');
    $("#displaySendMessage").fadeIn(600);
    //$("#modalSendMessages").dialog('close').delay(5000);
}

function ajax_displayMessage(messageId) {
    var ax_send_message_addr = $("#ax_send_message_addr").val();
    $.getJSON(ax_send_message_addr, {
        id:messageId,
        ac:"dmsg"
    }, function(json) {
        callback_displayMessage(json, messageId);
    });
}

function callback_displayMessage(json, messageId) {
     if($("#atoolbarMsg"+messageId).hasClass("bold_text")){// ak sa jedna o spravu ktora nie je precitana
        countmsgunread = $("#msgredtooltip").text() - 1; //zmenim o jedna menej

        if(countmsgunread == 0){ //ak je nula musim odstranit aj redtooltip
            $("#msgredtooltip").removeClass('redtooltip');
            $("#msgredtooltip").text('');
        }
        else if (countmsgunread > 0){
            $("#msgredtooltip").text(countmsgunread);//nastavim o jedno menej
        }

        $("#atoolbarMsg"+messageId).removeClass('bold_text');//vymazem bold
        $("#atoolbarMsg"+messageId).removeAttr('title');//zmazem title ze new message
    }


    if(json == null || json == "undefined") {
        alert("Error displaying message");
        return;
    }
    if(json.report == true){
        if(json.mymsg == true){
            //naplnim pred zobrazenim vsetky elementy
            $("#msg_TitleFromUser").text(json.title);
            $("#msg_FromUserName").text(json.fromUserName);
            $("#msg_TextFromUser").text('');
             
            var msgText = json.link == 0 ? json.text : makeLinksClickable(json.text);
                
            $("#msg_TextFromUser").append(msgText);


            //zobrazim modalne okno
            modalDisplayMessages();
             var ax_addr = $("#ax_addr").val();
            $("#a_message1").attr("href", ax_addr + "/userinfo/uid/" + json.fromUserId);
        
            $("#msg_refid_msg").val(json.refIdMsg);
            $("#msg_fromuserID").val(json.fromUserId);
            $("#msg_iddisplaymsg").val(json.idMsg);
        }
        else{
            modalNotification(Ajax.JS_last_modal_error, Ajax.JS_common_modal_notyourmessage, 1);
        }
         if(json.deletedmsg == false){
             modalNotification(Ajax.JS_last_modal_error,"Message not exists", 1);
         }
    }
    else
        modalNotification(Ajax.JS_last_modal_error, "Error with displaying message", 1);
}

function ajax_fillUserName(userId){
    var ax_send_message_addr = $("#ax_send_message_addr").val();
    $.getJSON(ax_send_message_addr, {
        id:userId,
        ac:"gusrId"
    }, function(json) {
        callback_fillUserName(json);
    });
}

function callback_fillUserName(json) {
    if(json == null || json == "undefined") {
        alert("Error fill user name message");
        return;
    }
    if(json.report == true)
        $("#msg_touserName").text(json.msgUserName);
    else
        modalNotification(Ajax.JS_last_modal_error, "Error with displaying name of user", 1);
}

/* Ajax na odobratie message z toolbaru */
function ajax_removeMsgFromToolbar(messageId) {
    var ax_send_message_addr = $("#ax_send_message_addr").val();
    $.getJSON(ax_send_message_addr, {
        id:messageId,
        ac:"rtb"
    }, function(json) {
        callback_removeMsgFromToolbar(json, messageId);
    } );
}

function callback_removeMsgFromToolbar(json, messageId) {
    if(json != null && json != "undefined" && json.report == true) {

        if($("#atoolbarMsg"+messageId).hasClass("bold_text")){// ak sa jedna o spravu ktora nie je precitana teda je bold
            countmsgunread = $("#msgredtooltip").text() - 1; //zmenim o jedna menej
    
            if(countmsgunread == 0){ //ak je nula musim odstranit aj redtooltip
                $("#msgredtooltip").removeClass('redtooltip');
                $("#msgredtooltip").text('');
            }
            else if (countmsgunread > 0){
                $("#msgredtooltip").text(countmsgunread);//nastavim o jedno menej
            }
        }
        $("#toolbarMsg"+messageId).remove();//vymazem z toolbaru cely riadok
    }
}

function ajax_toolbarPanel() {
    var ax_panel_addr = $("#ax_panel_addr").val();//cesta k ajaxu
    $.getJSON(ax_panel_addr, {}, function(json) {
        callback_toolbarPanel(json);
    });
}

function callback_toolbarPanel(json) {
    if(json == null || json == "undefined") {
        alert("Error toolbarPanel message");
        return;
    }
    if(json.report == true){
       
        countmsgunread = $("#msgredtooltip").text();//zistim ake cislo je posledne v tooltipe aby som mohol porovnat s cislom ktore mi pride
        if(countmsgunread == "")
            countmsgunread = 0;
        
        if($("#msgredtooltip").length != 0){
            if(json.countmsgtip != 0){
                if($("#msgredtooltip").text().length != 0){
                //if($("#msgredtooltip").hasClass("redtooltip")){//ak ma redtooltip class znamena to ze ma aspon jednu neprecitanu
//                    if(countmsgunread < json.countmsgtip){
//                        $("#soundmessage").get(0).Play();
//
//                    }
                        $("#msgredtooltip").text(json.countmsgtip)
                }
                else{
//                    if(countmsgunread < json.countmsgtip){//ani jedna sprava zatial neprecitana nie je
//                        $("#soundmessage").get(0).Play();
//                    }
                        $("#msgredtooltip").addClass('redtooltip')
                        $("#msgredtooltip").text(json.countmsgtip)
                }
            }
            else{//ak je nula novych tak pripadne odstranit tooltip
                 //if($("#msgredtooltip").hasClass("redtooltip")){//ak ma redtooltip class znamena to ze ma aspon jednu neprecitanu
                if($("#msgredtooltip").text().length != 0){
                    $("#msgredtooltip").removeClass('redtooltip');
                    $("#msgredtooltip").text('');
                }
            }
        }

        $("#toolbarmsgcount").text(json.msgcount);//celkovy pocet message

        //Toto sa vykona iba vtedy ked je potrebne prekreslit aj message v toolbare
        if(json.updateall == true){
            if(countmsgunread < json.countmsgtip){
                $(".toolbarMsg").remove(); //najprv ich dam vsetko prec
            
                var countrows = json.tableRows.length;
                for (var i=countrows; i>=0;i--)//vykreslujem od zadu
                {
                    var msg = json.tableRows[i];
                    $("#alertpanel .subpanel .view").after(msg);//after je dobra finta aby som ich dal pod <li> view
                }

                //toto je tu kvoli tomu ze aby bolo Xko akoze delete message aj po refreshy
                $("#alertpanel li").hover(function() {
                    $(this).find("a.delete").css({
                        'visibility': 'visible'
                    }); //Show delete icon on hover
                },function() {
                    $(this).find("a.delete").css({
                        'visibility': 'hidden'
                    }); //Hide delete icon on hover out
                });
            }
        }
    }
}


function ajax_addFriendRequest(userid) {
    var ax_add_friend = $("#ax_add_friend").val();
    $.getJSON(ax_add_friend, {
          friendid:userid, ac:"fr"
    }, function(json) {
        callback_addFriendRequest(json);
    });
}

function callback_addFriendRequest(json) {
    if(json == null || json == "undefined") {
        alert("Error adding friend request");
        return;
    }

    if(json.ok) {
        modalNotification(Ajax.JS_global_notification, Ajax.JS_subwebsite_added_friendRequest, 2);
    } else if(json.failed){
        modalNotification(Ajax.JS_global_notification,json.failed, 1);
    } else if(json.error) {
        modalNotification(Ajax.JS_global_notification, json.error, 1);
    } else
        modalNotification(Ajax.JS_global_notification, Ajax.JS_subwebsite_notadded_friendRequest, 1);
}


function ajax_addFriendPage(zosnulyid) {
    var ax_add_friendpage = $("#ax_add_friendpage").val();
    var ac = "add";
    $.getJSON(ax_add_friendpage, {
        zid:zosnulyid,ac:ac
    }, function(json) {
        callback_addFriendPage(json);
    });
}

function callback_addFriendPage(json) {
    if(json == null || json == "undefined") {
        alert("Error adding friend website");
        return;
    }

    if(json.ok) {
        modalNotification(Ajax.JS_global_notification, Ajax.JS_subwebsite_added_memorial, 2);
        $(".jqFriendPage:last").after(json.newFriendPage);
    } else if(json.failed){
        modalNotification(Ajax.JS_global_notification,json.failed, 1);
    }
    else
        modalNotification(Ajax.JS_global_notification, Ajax.JS_subwebsite_notadded_memorial, 1);
}

/** Meni nahlad obrazku podla zvoleneho stylu v selecte **/
function changePreview(imgName) {
    if(imgName.indexOf("customstyle", 0) == 0)
      $("#stylepreviewimg").hide();
    else {
      $("#stylepreviewimg").show();
      $("#stylepreviewimg").attr("src", "http://www.last-memories.com/images/styles/" + imgName.replace(".jpg", "_s.jpg"));
    }
}

function makeLinksClickable(text) {
    text = text.toString().replace(/((^|\s)www\.)/gi, " http://www.");
    text = text.toString().replace(/((http:\/\/)((www\.)?[^\<\s]*))/gi, "<a href='http://$3' target='_blank'>$1</a>");
    return text;
}
