var dirty = 0;
var edit = false;
var noteid = 0;
var noteid1 = 0;
var dirty1 = 0;
var timeoutid;
var tab = 0;
var allowautosave = false;
var curr_notebook = 'My Notes';
var friendsresponse;
var arrOptions = new Array();
var arrOptions1 = new Array();
var arrOptions2 = new Array();
var shared_edit = false;
var ua = navigator.userAgent;

function clearForm(form) {
    $(':input',form).each(function(){
        var type = this.type;
        var tag = this.tagName.toLowerCase();
        if(type == 'text' || type == 'password' || tag == 'textarea') {
            this.value = "";
        } else if(type == 'checkbox' || type == 'radio') {
            this.checked = false;
        } else if(tag == 'select') {
            this.selectedIndex = 0;
        }
    }); 
}

function handleAutoSave(id,inline) {
    if(dirty) {
        return;
    } else if(allowautosave) {
        dirty = 1;        
        timeoutid = window.setTimeout("autoSave('"+id+"',"+inline+");",20000);  
    } 
}

function autoSaveResp(data) {
    if(handleSessionTimeout(data)) {
        if($(data).find('autosave').attr('status') == 'OK') {
            edit=true;
            dirty = 0;
            noteid = $(data).find('noteid').text();
            inline = $(data).find('autosave').attr('inline');

            if(inline == 'true') {
                elem = "notetxt_"+noteid;
            } else {
                elem = "notetext";            
            }        
            handleAutoSave(elem,inline);
        }
    }
}

function autoSave(id,inline) {
    tinyMCE.triggerSave(true,true);           

    var content = $("#"+id).val();
    if(content == "") {
        dirty = 0;
        return;
    }
    var page = $("#mypage").val();
    if(inline) {
        var data = {'noteid': noteid, 'inline': true, browser: ua, title: $("#notetitle_"+noteid).val(), content: content, tag: $("#notetag_"+noteid).val(), categoryid: $("#categoryselect_"+noteid).val(), categoryname: $("#categoryselect_"+noteid+" option:selected").text(),page: page};
    } else {
        var data = {'inline': false, browser: ua, title: $("#notetitle").val(), content: content, tag: $("#notetag").val(), categoryid: $("#categoryselect").val(),categoryname: $("#categoryselect option:selected").text(),page: page};
    }
    if(page == '3') {
        data['cid'] = $("#communityid").val();
    }
    if(edit) {
        ajaxPost("/notes/autoSave/"+noteid,data,autoSaveResp);
    } else {
        ajaxPost("/notes/autoSave",data, autoSaveResp);        
    }
}

function createEditor(id,inline) {
    tinyMCE.init({
        mode : 'exact',
        elements: id,        
        setup : function(ed) {                
                ed.onKeyUp.add(function(ed, e) {                                      
                        if((id == "notetext") && ($("#editblk").length > 0)) {
                            editAlert();
                            ed.setContent("");
                            $("#notetitle").val('');
                            $("#notetag").val('');
                        } else if(!shared_edit) {
                            allowautosave = true;
                            handleAutoSave(id,inline);
                        }
                    });                
                }, 
        width: "660",
        height: "270",  
        theme : 'advanced',
        theme_advanced_buttons1 : 'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect',
        theme_advanced_buttons2 : 'bullist,numlist,|,outdent,blockquote,|,undo,redo,|,link,unlink,anchor,image,code,|,hr,removeformat,visualaid,|,sub,sup,,charmap',
        theme_advanced_buttons3 : '',
        theme_advanced_toolbar_location : 'top',
        theme_advanced_path: false,
        theme_advanced_toolbar_align : 'left',
        theme_advanced_statusbar_location : 'bottom',
        theme_advanced_resize_horizontal : false,
        add_form_submit_trigger : false,
        forced_root_block : false,
        force_br_newlines : true,
        force_p_newlines : false,
        theme_advanced_resizing: true});
}

function autoEdit1() {
    var id = noteid1;
    tinyMCE.triggerSave(true,true);
    var content = $("#notetxt_"+id).val();
    var user = $("#ownerid").val();
    //$.post("/notes/autoEdit1",{id: noteid1, title: $("#notetitle_"+id).val(), content: content, tag: $("#notetag_"+id).val(),userid: user, category: $("#categoryselect_"+id).val()}, function(data) {
    $.ajax({url: "/notes/autoEdit1", type: 'POST',dataType: 'xml',data: {id: noteid1, title: $("#notetitle_"+id).val(), content: content, tag: $("#notetag_"+id).val(),userid: user, category: $("#categoryselect_"+id).val()},success: function(data) {;
        handleSessionTimeout(data);
        if($(data).find('autoedit').attr('status') == 'OK') {
            dirty1 = 0;
            noteid1 = $(data).find('noteid').text();
            handleAutoEdit();
        } 
    }});
    //}); 
}

function formfocus() {
    if ( $("#logname").length > 0 ) { 
        document.getElementById("logname").focus();
    }
}

function loginSubmit()
{
    document.getElementById('UserLoginForm').submit();
}

function enterKeyPress(e)
{
    if(window.event) {
        key = window.event.keyCode;     //IE
    } else {
        key = e.which;     //firefox
    }
    var browser = navigator.appName; 
    if(key == 13 && browser == 'Microsoft Internet Explorer') {
        document.getElementById('UserLoginForm').submit(); 
    }
}

function searchFriendsKeyPress(e) {
     if(window.event) {
        key = window.event.keyCode;     //IE
    } else {
        key = e.which;     //firefox
    }
    if(key == 13) 
        searchSkriberFriends();
}

function keyPressAction(e, handler) {
    if(window.event) {
        key = window.event.keyCode;
    } else {
        key = e.which;
    }

    if(key == 13) {
        handler();
    }
}

function forgotSubmit()
{
    document.getElementById('UserForgotForm').submit();
}

function regDirect()
{
    window.location = '/users/register';
}

function isEnter(e)
{
    if(window.event) {
        key = window.event.keyCode;     //IE
    } else {
        key = e.which;     //firefox
    }
    if(key == 13) {
        return true;
    } else {
        return false;
    }  
}

function frgtDirect()
{
    window.location = '/users/forgot';
}

function updateDirect()
{
    window.location = '/users/update';
}

function showlistDirect(id){    
    window.location = '/notes/showList';
}

function tosAlert()
{
     myalert('Do agree to Skriber Terms of Service');
}

function homeDrt()
{
    window.location = '/';
}

function clearReg() {
    $("#UserName").val("");
    if($("#avail").length > 0) { $("#avail").remove(); } 
    $("#UserFullname").val("");
    $("#UserLastname").val("");
    $("#password").val("");
    $("#repassword").val("");
    $("#UserEmail").val("");
    $("#UserAddress").val("");
    $("#UserCity").val("");
    $("#UserPin").val("");
    $("#UserState").val("");
    $("#UserCountry").val("");
    $("#tos").attr("checked","");
    $("#UserName").focus();
}

function submitToggle()
{
    if(document.getElementById('tos').checked) {      
        obj1=document.getElementById('div1');
        obj1.style.display= 'block';
        obj2=document.getElementById('div2');
        obj2.style.display= 'none';
    } else {
        obj2=document.getElementById('div2');
        obj2.style.display= 'block';
        obj1=document.getElementById('div1');
        obj1.style.display= 'none';
    }
}

function loadPiece(href,divName) {   
    $("#"+divName).load(href, {cache: false}, function(responseText, textStatus, XMLHttpRequest){ 
        stopAjax();
        document.getElementById(divName).innerHTML = responseText;
        $("#currentpage").val(href);
        var divPaginationLinks = "#"+divName+" #pagination a";
        $(divPaginationLinks).click(function() {    
            var thisHref = $(this).attr("href");
            loadPiece(thisHref,divName);
            return false;
        });
    });
}    

function validateRegister() {
    if($("#UserRegisterForm").valid()) {
        var data = {name: $("#UserName").val(),firstname: $("#firstname").val(),lastname: $("#lastname").val(),password: $("#password").val(), email: $("#email").val(),address: $("#address").val(),country: $("#country").val(),pincode: $("#pincode").val(),city: $("#city").val(),state: $("#state").val(),random: $("#random").val()};
        startAjax("Please Wait ...");
        $.ajax({url: '/users/registerUser', type: 'POST', data: data, success: function(data) {  stopAjax(); registerResp(data);}});
    } else {
        return false;
    }
}

function registerResp(data) {
    var status = $(data).find('register_user').attr('status');   
    var res = "";
    if(status == 'OK') {
        var name = $(data).find('name').text();
        var firstname = $(data).find('firstname').text();
        var lastname = $(data).find('lastname').text();
        var email = $(data).find('email').text();
        var address = $(data).find('address').text();
        var city = $(data).find('city').text();
        var pincode = $(data).find('pincode').text();
        var state = $(data).find('state').text();
        var country = $(data).find('country').text();
        var activated = $(data).find('activated').text();
        var msg = "Check your mail to proceed <a style='font-size: 12px' href='/'>Click here to go home</a>";
        if(activated) {
            var msg ="<a style='font-size: 12px' href='/'>Click here to login</a>";
        }
        var res = "<div align='center'>"+msg+"<br>";
        res = res+"<table cellspacing=3 cellpadding=3><tr><td align=left>Username:</td><td align=left>"+name+"</td></tr><tr><td align=left>Fistname:</td><td align=left>"+firstname+"</td></tr><tr><td align=left>Lastname:</td><td align=left>"+lastname+"</td></tr><tr><td align=left>Email:</td><td align=left>"+email+"</td></tr><tr><td align=left>Address:</td><td align=left>"+address+"</td></tr><tr><td align=left>City:</td><td align=left>"+city+"</td></tr><tr><td align=left>Pincode:</td><td align=left>"+pincode+"</td></tr><tr><td align=left>State:</td><td align=left>"+state+"</td></tr><tr><td align=left>Country:</td><td align=left>"+country+"</div>";
        
/*
        var res = "<div class='frmhead'>You have Submitted the following Informations. "+msg+"</div>";
        res = res+"<br><ul><li>Username:"+name+"</li>";
        res = res+"<li>Fistname:"+fistname+"</li><li>Lastname:"+lastname+"</li><li>Email:"+email+"</li>";
        res = res+"<li>Address:"+address+"</li><li>City:"+city+"</li><li>Pincode:"+pincode+"</li>";
        res = res+"<li>Address:"+address+"</li><li>City:"+city+"</li><li>Pincode:"+pincode+"</li>";
        
//<tr><td><span class='outleft'>First Name</span></td><td width=5><span class='outcoln'>:</span></td><td><span class='outright'>"+firstname+"</span></td></tr><tr><td><span class='outleft'>Last Name</span></td><td width=5><span class='outcoln'>:</span></td><td><span class='outright'>"+lastname+"</span></td></tr><tr><td><span class='outleft'>E-mail</span></td><td width=5><span class='outcoln'>:</span></td><td><span class='outright'>"+email+"</span></td></tr><tr><td><span class='outleft'>Address</span></td><td width=5><span class='outcoln'>:</span></td><td><span class='outright'>"+address+"</span></td></tr><tr><td><span class='outleft'>City</span></td><td width=5><span class='outcoln'>:</span></td><td><span class='outright'>"+city+"</span></td></tr><tr><td><span class='outleft'>Postal Code</span></td><td width=5><span class='outcoln'>:</span></td><td><span class='outright'>"+pincode+"</span></td></tr><tr><td><span class='outleft'>State</span></td><td width=5><span class='outcoln'>:</span></td><td><span class='outright'>"+state+"</span></td></tr><tr><td><span class='outleft'>Country</span></td><td width=5><span class='outcoln'>:</span></td><td><span class='outright'>"+country+"</span></td></tr>
res += "</ul><br/>";
alert(res);
*/
    } else if(status == 'ERROR') {
        var res = "<div class'frmhead' style='padding: 20px;'>";
        var error = $(data).find('error').text();        
        res += error+"</div>";
    } else {
        var res = "<div class='frmhead'>An Error Occurred during registration. Please try again later</div>";
    }

    $("#userregister").html(res);
}

function updateSubmit()
{
    var pwd1=document.getElementById('newpassword').value; 
    var pwd2=document.getElementById('renewpassword').value;
    if(pwd1==pwd2) { 
        document.getElementById('UserUpdateForm').submit();
    } else {
          myalert('Passwords typed do not match, Please re-enter your passwords');
    }
}

function saveNoteResp(data) {
    stopAjax();
    handleSessionTimeout(data);
    ResetSave();
    if($(data).find('savenote').attr('status') == 'OK') {     
        var community = $(data).find('saved').attr('community');
        var n = $(data).find('notebook').text();
        dirty = 0;
        edit = false;        
        var name = $(data).find('notebookname').text();
        $("#notebooktitle").val(name);
        var dat = $("#mydate").val();

        if(community == 'false') {                        
            loadNoteBook(n,{browser:ua,cache: false});
            loadCalendar(dat,n,1,'null');
            //cancelNote();
        } else if(community == 'true') {           
            var crole = $('#communityrole').val();
            var cid = $("#communityid").val();
            $("#cnotebook").val(n);  
            loadNoteBook(n,{cache: false, page: '3', cid: cid, browser:ua,role: crole});
            loadCalendar(dat,n,3,'null');
        }
        $("#categorylist .notebook_selected").removeClass().addClass('notebook_default');
        $("#c_"+n).removeClass().addClass('notebook_selected');
    }
}

function addTab(id,container) {
    var title = $("#notebooktitle").val();    
    $('#tabcontainer ul li').removeClass('ui-tabs-selected');
    $("#tabcontainer > ul").tabs("select",0);
    $("#tabcontainer ul li.ui-tabs-selected span").html(title);                 
    $("#"+container).empty();
    //$('#tabcontainer > ul').tabs('add', "#"+container, title,1); 
    //$("#tabcontainer > ul").tabs("remove",0);       
    $("#"+container).css({'padding' : '0px', 'margin' : '0px'});
}

function tabExists(name) {
    var index = $("#tabcontainer a").index($("a[href=#"+name+"_container]"));
    return (index >= 0) ? true : false;
}

function loadPieceNotebook(href,data,divName,notebook) {      
    $("#"+divName).html("<div class='loadingg_blk'>Loading ...</div>");   
    $("#"+divName).load(href, data, function(responseText, textStatus, XMLHttpRequest){ 
        stopAjax();
        if(notebook == 'publicnotes')
        document.getElementById('publicnotes_container').innerHTML = responseText;
        if(data == 'sessiontimeout') {
            sessiontimeout();
        } else {
            $("#currentpage").val(href);
            $("#pageurl").val(href);

            var divPaginationLinks = "#"+divName+" #pagination a";
            $(divPaginationLinks).click(function() {    
                var thisHref = $(this).attr("href");
                thisHref = href+"/"+notebook+"/"+(thisHref.substring(thisHref.lastIndexOf('/')));
                loadPieceNotebook(thisHref,data, divName,notebook);
                $("#pageurl").val(thisHref);
                return false;
            });
        }
    });
}    


function selectNotebook(name,type) {
    $("#categorylist").find('tr').each(function() {
        var cid = $(this).attr('id'); 
        var notebook = cid.split('_')[1];
        var selected = $("#categorylist .notebook_selected").attr('id');
        $(this).removeClass();
        if(name == notebook) {           
            $(this).addClass('notebook_selected');
        } else { 
            $(this).addClass('notebook_default');
        }

        $(this).mouseover(function() { 
            if($(this).attr('class') == 'notebook_selected') 
                return false; 
            $(this).removeClass(); 
            $(this).addClass('notebook_hover');
        });

        $(this).mouseout(function() { 
            if($(this).attr('class') == 'notebook_selected') 
                return false; 
            $(this).removeClass(); 
            $(this).addClass('notebook_default');
        });

        $(this).click(function() { 
            if(($(this).attr('class') == 'notebook_selected')) 
                return false;  
            $("#categorylist .notebook_selected").removeClass().addClass('notebook_default'); 
            $(this).removeClass(); 
            $(this).addClass('notebook_selected'); 
            var notebooktitle = $("#cat_"+notebook).html();
    
            if(type) {
                $('#cnotebook').val(notebook);
                $('#notebooktitle').val(notebooktitle);
                loadNoteBook(notebook,{cache: false,browser: ua,page: '3'});         
            } else {
                $("#notebook").val(notebook);                 
                $("#notebooktitle").val(notebooktitle); 
                curr_notebook = notebook; 
                loadNoteBook(notebook,{cache: false,browser:ua}); 
            }
            var dat = $("#mydate").val(); 
            var page = $("#mypage").val(); 
            var frnd = ($("#friendid").length > 0) ? $("#friendid").val() : 'null'; 
            loadCalendar(dat,curr_notebook,page,frnd);
        });              
    });
}



function loadNoteBook(id,data) {                 
    curr_notebook = id;       
    var page = data['page'];
    if(page == '5') {
        container = 'publicnotes_container';
        loadPieceNotebook('/notes/loadNotebook/'+escape(id),data,container,id);
    } else if(page == '4') {
        container = 'publicnotes_container';
        loadPieceNotebook('/notes/loadNotebook/'+escape(id),data,container,id);
    } else if(page == '3') {
        data['role'] = $("#communityrole").val();
        data['cid'] = $("#communityid").val(); 
        container = 'communitynotes_container';
        $("#tabcontainer ul li.ui-tabs-selected span").html($("#notebooktitle").val());                 
        loadPieceNotebook('/notes/loadNotebook/'+escape(id),data,container,id);
        $("#"+container).css({'padding' : '0px', 'margin' : '0px'});
        $("#"+container).html("<div class='loadingblk'>Loading ....</div>");     
    } else if(id == 'sharednotes') {    
        container = "sharednotes_container";
        loadPieceNotebook('/notes/loadNotebook/'+escape(id),data,container,id);  
        //$("#tabcontainer > ul").tabs("select",1);                  
    } else if(id == 'Public Notes'  || id == 'publicnotes') {
        container = "publicnotes_container";
        loadPieceNotebook('/notes/loadNotebook/'+escape(id),data,container,id);
    } else {         
        container = 'mynotes_container';        
        addTab(id,container);                 
        loadPieceNotebook('/notes/loadNotebook/'+escape(id),data,container,id);     
        $("#"+container).css({'padding' : '0px', 'margin' : '0px'});
        $("#"+container).html("<div class='loadingblk'>Loading ....</div>");         
    }       
}

function loadCommunityNotebook(cid,notebook,role) {    
    container = 'tab_'+tab;
    tab = tab+1;
    
    if(role == 'ow' || role == 'co') {    
        title = $("#notebooktitle").val();
        $('#tabcontainer > ul').tabs('add', "#"+container, title,1); 
        $("#tabcontainer > ul").tabs("remove",0);       
    } else if(role == 'me') {
        title = $("#notebooktitle").val();  
        if(title=='Shared Notes') {
            $("#tabcontainer > ul").tabs("select",1);
        } else {
            $('#tabcontainer > ul').tabs('add', "#"+container, title,1); 
            $("#tabcontainer > ul").tabs("remove",0);                               
        }                             
        
        container = 'sharednotes_container';
    }
    $("#"+container).css({'padding' : '0px', 'margin' : '0px'});
    loadPieceNotebook('/notes/loadcommunityNotebook',{notebook: notebook,cid:cid,cache: false},container,notebook);
    $("#"+container).html("<div class='loadingblk'>Loading...</div>");       
    $("#cnotebook").val(notebook);
    $("#communityid").val(cid);
    $("#notebooktitle").val(title); 
}

function listnotebookResp(data,type,defalt) {
    var out = createCategoryList(data);
    var cnt = $(data).find("categories").attr("count");
    $("#notebk_cnt").html("NoteBooks ("+cnt+")");
    $("#category_list").html(out);
    selectNotebook(defalt,type);    
}

function listNotebooks(user,type,defalt) {    
    $.ajax({url: '/notes/listNotebooks/'+user, success: function(data) { 
        listnotebookResp(data,type,defalt);
        }
    });
}

function listCommunityNotebooks(cid,defalt, role) {
    //if(role == 'ow' || role == 'co') {
        $.ajax({url: '/notes/listCommunitynotebooks/'+cid, success: function(data) {
            var cnt = $(data).find("categories").attr("count");
            $("#notebk_cnt").html("NoteBooks ("+cnt+")");
            var out = createCategoryList(data);
            $("#category_list").html(out);            
            selectNotebook(defalt,1);
            }
        });

    /*} else if(role == 'me') {
        $.ajax({url: '/notes/listCommunitynotebooks/'+cid, success: function(data) {
            var out = createCategoryList(data);
            $("#category_list").html(out);            
            selectNotebook(defalt,1);        
            $("#categoryselect").empty().append('<option>Community Notes</option>');
            $("#add_categoryblk .addfrnd_btn").hide();
            }
        });
    }
    if(role == 'co' || role == 'me') {
        
    }*/
}

function closeTab(name) {
    var index = $("#tabcontainer a").index($("a[href=#"+name+"_container]"));     
}

function saveNote(community) {    
    dirty = 0;
    var data;
    window.clearTimeout(timeoutid);     
    allowautosave = false;
    tinyMCE.triggerSave(true,true);

    var category = $("#categoryselect").val();
    var categoryname = $('#categoryselect option:selected').text(); 

    if(community) {
        data = {cid: $("#communityid").val(),community: 'true',role: $('#communityrole').val(),title: $("#notetitle").val(), notetext: $("#notetext").val(), tags: $("#notetag").val(), category: category,categoryname: categoryname};
    } else {
        data = {community: 'false', title: $("#notetitle").val(), notetext: $("#notetext").val(), tags: $("#notetag").val(), category: category,categoryname: categoryname};
    }
    startAjax('Saving Note....');  

    if(edit) {
        ajaxPost('/notes/saveNote/'+noteid,data,saveNoteResp);
    } else {
        $.ajax({url:'/notes/saveNote', type: 'POST', dataType: 'xml',data: data, success: function(data) {saveNoteResp(data); }});    
    }    
}

function cancelNoteResp(data) {
    if($(data).find('canceledit').attr('status') == 'OK') {
        stopAjax();
    }
}

function ResetSave() {
    allowautosave = false;
    window.clearTimeout(timeoutid);

    $("#notetext").val('');
    $("#notetitle").val('');
    $("#notetag").val('');
    tinyMCE.getInstanceById('notetext').getBody().innerHTML=' '; 
}

function cancelNote(status) {    
    allowautosave = false;
    window.clearTimeout(timeoutid);

    if(edit) {
        if(status) 
        startAjax('Cancelling ...');
        ajaxCall('/notes/cancelEdit/'+noteid,{},cancelNoteResp);
        dirty = 0;
    } 
    $("#notetext").val('');
    $("#notetitle").val('');
    $("#notetag").val('');
    tinyMCE.getInstanceById('notetext').getBody().innerHTML=' '; 
}

function ajaxLoad(url,container) {
    startAjax('Loading Please Wait......');
    $.ajax({url: url, cache: false, 
            success: function(data) { 
            currenturl = $("#currentpage").val();
            loadPiece(currenturl,container);
            stopAjax();
    }});
}

function startAjax(msg) {
    $.blockUI(msg);    
}

function stopAjax() {
    $.unblockUI();
}

function categoryNotes(url,selected, container) {
    startAjax('Loading Notes........');
    $.ajax({url: url, cache: false, data: {selected: selected}, 
            success: function(data) {   
                handleSessionTimeout(data);
                $("#"+container).empty().html(data);
                $("#"+container+" #pagination a").click(function() {
                    var thisHref = $(this).attr("href");
                    var page = thisHref.substr(thisHref.lastIndexOf("/page:"));    
                    var href = "/notes/showList"+page;
                    $(this).attr("href",href);
                });
            }
    });
}

function showEdit(id) {
    window.location='/notes/editNote/'+id;
}

function deleteNote(id,type) {
    confrm('Do You Want to Delete?');
    $('#yes').click(function() {
        startAjax('Deleting Note ......');
        if(type == 0) {
            window.location = "/notes/deleteNote/"+id;
        } else {
            href = window.location;
            cid = href.toString().substring(href.toString().lastIndexOf('/')+1);
            window.location = "/notes/deleteCommunityNote/"+id+"/"+cid;
        }
    });
    $('#no').click(function() {
        stopAjax();
    });
}

function deleteNoteResp(data) {
    stopAjax();
    if($(data).find('deletenote').attr('status') == 'OK') {
        container = getCurrentContainer();    
        cid = $(data).find('cid').text();
        n = $(data).find('notebook').text();
        container = container.replace(/^#/, "");

        if(cid) {           
            loadNoteBook(n, {cache:false,page: '3', cid: $("#communityid").val(),role: $("#communityrole").val()});   
            $("#"+container).html("<div class='loadingblk'>Loading ....</div>");           
        } else {                                            
            loadPieceNotebook($("#pageurl").val(),{cache:false},container,n);     
            $("#"+container).html("<div class='loadingblk'>Loading ....</div>"); 
            $("#tabcontainer > ul").tabs("select",0);
        }
    } else {
        error = $(data).find('error').text();
        myalert(error);
    }
}

function deleteNote1(id,n,page) {
    confrm("Do You Want to Delete?");
    $("#yes").click(function() {
        startAjax("Deleting Note....");    
        if(page == '3') {    
            ajaxCall('/notes/deleteNote1',{id: id, notebook: n, cid: $("#communityid").val(), role: $("#communityrole").val()},deleteNoteResp);
        } else {
            ajaxCall('/notes/deleteNote1',{id:id,notebook:n},deleteNoteResp);
        }
    });
    $("#no").click(function() {
        stopAjax();
    });
}


function deleteNote2Resp(data) {
    stopAjax();
    if($(data).find('deletenote').attr('status') == 'OK') {
        container = getCurrentContainer();    
        cid = $(data).find('cid').text();
        n = $(data).find('notebook').text();
        container = container.replace(/^#/, "");
        loadPieceNotebook($("#pageurl").val(),{cache:false},container,n);     
        $("#"+container).html("<div class='loadingblk'>Loading ....</div>"); 
        $("#tabcontainer > ul").tabs("select",0);
    } else {
        error = $(data).find('error').text();
        myalert(error);
    }
}

function deleteNote2(id,n,page) {
    confrm("Do You Want to Delete?");
    $("#yes").click(function() {
        startAjax("Deleting Note....");    
        ajaxCall('/notes/deleteNote2',{id:id,notebook:n},deleteNote2Resp);
    });
    $("#no").click(function() {
        stopAjax();
    });
}

function deleteSharedNote(id) {
    confrm('Do You Want to Delete?'); 
    $('#yes').click(function() {
        ajaxLoad('/notes/deleteSharedNote/'+id,'sharednotes_container');
    });
    $('#no').click(function() {
        stopAjax();
    });
}

function deleteCategory(id) {
    confrm("Do You Want to Delete?"); 
     $('#yes').click(function() {
        startAjax('Deleting Category.......');
        $.ajax({ url: '/notes/deleteCategory/'+id, success: function(data) { handleSessionTimeout(data); $("#category_list").empty(); $("#category_list").html(data); stopAjax();}});
    });
    $('#no').click(function() {
        stopAjax();
    });
}

function confrm(alrt) {
    var question = "<table width=\'100%\' cellspacing=\'0\' cellpadding=\'0\'>"
                   +"<tr><td height=\'8px\' style=\'background-color: #11a3da;\'>"
                   +"<div style=\'float: right;color: #ffffff;font-weight: bold; cursor:pointer\' onclick=\'$.unblockUI()\'>X</div></td></tr>"
                   +"<tr><td height=\'8px\'>&nbsp;</td></tr>"
                   +"<tr><td align=\'center\'>"+alrt
                   +"<tr><td height=\'8px\'>&nbsp;</td></tr><tr><td align=\'center\'>"
                   +"<table><tr><td><div id=\'yes\' href=\'javascript: void(0);\' class=\'bg55\';>Ok</div></td>"
                   +"<td><div id=\'no\' href=\'javascript: void(0);\' class=\'bg55\'>Cancel</div></td></tr></table>"
                   //+"<img id=\'yes\' style=\'cursor:pointer; margin-right: 5px\' src=\'/img/ok.gif\' alt=\'Ok\'/>"
                   //+"<img id=\'no\' style=\'cursor:pointer; margin-left: 5px\' src=\'/img/cancel.gif\' alt=\'Cancel\'/>"  
                   +"</td></tr></table>";

    $.extend($.blockUI.defaults.overlayCSS, { backgroundColor: '#fff', opacity: '0.0'});
    $.extend($.blockUI.defaults.pageMessageCSS, { width:'300px', height:'auto', margin:'-50px 0 0 -125px', padding:'0px 0px 10px 0px', top:'50%', left:'50%', textAlign:'center', color:'#000', backgroundColor:'#fff', border:'3px solid #11a3da'});
    $.extend($.blockUI.defaults.displayBoxCSS, { width: '400px', height: '400px', top:'50%', left:'50%'});
    $.blockUI(question);
}
function ajaxShare(id) {
    var userids="";
    for(var i in arrOptions1)
        userids += i+",";
    if(userids.length)
        userids = userids.substr(0,userids.length-1);

    var sendmail = $("#sendmailoption").attr('checked');
    var sharedediting = $("#sharedediting").attr('checked');

    if(userids) {
        var id = $("#noteid").val(); 
        $.ajax({ url: "/notes/shareNote/"+id+"/"+userids, dataType: 'xml', data: {sendmail: sendmail,sharedediting: sharedediting}, cache: false, success: function(data) { handleSessionTimeout(data); shareResponse(data); } });
    } else {
        myalert("Please Enter Valid Information");
    }
}

function getCategory(id) {
    document.getElementById("categoryname1").value = "Loading......";
    $.ajax({url: "/notes/getCategory/"+id, dataType: 'xml', cache: false, success: function(data) { handleSessionTimeout(data);populateEditCategory(data);} });
}

function populateEditCategory(data) {
    var name = $(data).find('name').text();
    var description = $(data).find('description').text();
    document.getElementById('categoryname1').value = name;
    document.getElementById('categorydesc1').innerHTML = description;
}

function clearCategory() {
    $("#categoryname").val(''); 
    $("#categorydesc").val('');
}

function addCategory(settings) {
    var name = $("#categoryname").val();
    if(name) {
        var description = $("#categorydesc").val();
        startAjax('Saving ...');
        if(settings) {
            $("#category_list").empty();
            $.ajax({url: "/notes/addCategory1",type: 'POST', dataType: 'xml', data: {name:name, description: description},success:  function(data) { stopAjax();$("#category_list").html(data);clearCategory();}});
            //$.post("/notes/addCategory1", {name: name, description: description}, function(data) { stopAjax();$("#category_list").html(data);clearCategory();});
            
        } else {
            $.ajax({url: "/notes/addCategory",type: 'POST', dataType: 'xml', data: {name:name, description: description},success:  function(data) { stopAjax();handleSessionTimeout(data); categoryResponse(data,0);}});
//            $.post("/notes/addCategory", {name: name, description: description}, function(data) { stopAjax(); handleSessionTimeout(data); categoryResponse(data,0); });
        }
    } else {
        myalert("You should specify the category name!");
    }  
}

function addCommunityCategory(cid) {
    var name = $("#categoryname").val();
    if(name) {
        startAjax('Saving ...');
        var description = $("#categorydesc").val();
        $("#category_list").empty();
        
        $.post("/notes/addCategory/true", {name: name, description: description,cid: cid}, function(data) { stopAjax();handleSessionTimeout(data); categoryResponse(data,1); });
    } else {
        myalert("You should specify the category name");
    }
}

function clearList() {
    $("#categorylist").empty();
    $("#categoryselect").empty();    
}

function populateList(id,name,checked) {  
    out =  "<tr width=100% class='categorylisting' id='c_"+id+"'><td><img hspace=4 align='absbottom' src='/img/notebook.png'/>";     
    out += "<span id='cat_"+id+"'>"+name+"</span></td></tr>";
    return out;
}

function populateSelect(name,id) {
    select = "<option value="+id+">"+name+"</option>";
    $("#categoryselect").append(select); 
}

function createCategoryList(data) {
    clearList();
    var out = "<table width=100% cellpadding=2 cellspacing=3 align=left id=categorylist>"; 
    var page = $("#mypage").val();
    $(data).find('category').each(function() { 
        var id = this.getAttribute('id');
        var name = this.getAttribute('name');
        var checked= this.getAttribute('checked');
        populateSelect(name,id);
        if(page == '3') {
            latestcount = this.getAttribute('latestcount');
            name = name+"("+latestcount+")";
        } 
        out += populateList(id,name,checked);
    }
    );
    out += "</table>";
    return out;
}

function categoryResponse(data,type) {
    var arr;
    hideCategory("addCategory");
    $("#category_list").empty();
    var cnt = $(data).find("categories").attr("count");
    $("#notebk_cnt").html("NoteBooks ("+cnt+")");
    var out = createCategoryList(data);
    $("#category_list").append(out);   
    var n = (type == 1) ? $("#cnotebook").val() : $("#notebook").val(); 
    selectNotebook(n,type);    
}

function shareResponse(data) {
    handleSessionTimeout(data);
    var users = $(data).find('users').text();
    var success = $(data).find("shared").attr('status');
    cancelShare();
    if(success == "OK") {        
    } else if(success == "ERROR") {
        myalert($(data).find('error').text());             
    }    
}

function logout() {
    window.location='/users/logout';
}

function settings() {
    window.location='/users/update';
}

function c_settings(id) {
    //window.location = '/users/update/settings/'+id;
    window.location = '/notes/communitySettings/'+id;
}

function home() {
    window.location='/notes/showList';
}
function skr() {
    window.location = "/";
}
function removeControl(elem) {    
    tinyMCE.execCommand('mceFocus', false, elem);   
    tinyMCE.execCommand('mceRemoveControl', true, elem);    
}

function cancelEdit(id) {
    window.clearTimeout(timeoutid);
    allowautosave = false;
    removeControl('notetxt_'+id);        
    startAjax('Cancelling ...');
    ajaxCall('/notes/cancelEdit/'+id,{},cancelNoteResp);    
    $("#editblk").remove();
    $("#noteblk_"+id).show();     
    dirty = 0;
}

function findPosX(obj)
{
  var curleft = 0;
  if(obj.offsetParent)
    while(1) 
    {
      curleft += obj.offsetLeft;
      if(!obj.offsetParent)
        break;
      obj = obj.offsetParent;
    }
  else if(obj.x)
    curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
    while(1)
    {
      curtop += obj.offsetTop;
      if(!obj.offsetParent)
        break;
      obj = obj.offsetParent;
    }
  else if(obj.y)
    curtop += obj.y;
  return curtop;
}

function handleSessionTimeout(data) {    
    if($(data).find("error").attr('code') == '100') {   
        myalert('Your Session Expired, Please Login Again');
        $("#myalertok").attr('onclick',"");
        $("#myalertok").click(function() { window.location='/';});
        return false;
    }else {
        return true;
    }
}

function setSharedWith(id) {
    $("#sharedusers").html("Loading......");
    $.ajax({url: "/notes/getSharedwith/"+id, dataType: 'xml', cache: false, success: function(data) { 
    handleSessionTimeout(data);    
    $(data).find('user').each(function() { $("#sharedusers").html("Shared with: "+this.getAttribute('name'));})}});    
}

function showShareBlk(id,show) {
    setSharedWith(id);
    $("#sendmailoption").attr('checked',false);
    var x = findPosX(document.getElementById("note_"+id));
    var y = findPosY(document.getElementById("note_"+id));
    sm = $("#shareNote");
    sm.height(330);
    sm.width(535);
    sm.css('left', x+"px");
    sm.css('top', y+"px");
    sm.css('display','inline');
    sm.css('visibility','visible');
    //$(".sharetxt").val("To share, enter user ids separated by comma and click OK button");
    $(".sharetxt").css('color','#cccccc');
    $("#noteid").val(id);
 
    clearFrndList();
    initialFrndList();
    if(show) {
        $("#shared_editing").show();
        $("#shared_editing input").attr('checked',false);
    } else {
        $("#shared_editing").hide();
    }
}

function clearFrndList() {
    $("#spanOutput").empty();
    $("#spanOutputRight").empty();
    arrOptions1 = new Array();
}

function initialFrndList() {
    var frndlist = "";
    arrOptions = new Array();

    $(friendsresponse).find('friend').each(function(i) {
        var id = $(this).attr('id');
        var fullname = $(this).text(); 
        if (typeof(arrOptions1[id])=='undefined' || arrOptions1[id]===null) {       
            arrOptions[id] = fullname;
            frndlist += "<div id='OptionsList_"+i+"' name='"+id+"' class='spanNormalElement' thearraynumber = '"+i+"' onclick='javascript: selectItem(this);' style='display: block; width: 100%;'><span style='float:left;'>"+fullname+"</span><span style='visibility:hidden' class='closeright' onclick='moveSelectedtoLeft("+i+")'>x</span></div>";
        }       
    });    
    $("#spanOutput").html(frndlist);
}

function showAddCategory() {
    var c = findCenter("addCategory");
    //var x = findPosX(document.getElementById("add_categoryblk"))-100;
    //var y = findPosY(document.getElementById("add_categoryblk"))+40;
    sm = $("#addCategory");
    sm.css("left", c.x+"px");
    sm.css("top", c.y+"px");
    sm.css("width","300px");
    sm.css("height","150px");
    sm.css('display','inline');
    sm.css("visibility","visible");
    $("#categoryselect").hide();
    $("#categoryname").val("");
    $("#categorydesc").val("");
}

function showAddCommunity() {
    var x = findPosX(document.getElementById("community_blk"))-100;
    var y = findPosY(document.getElementById("community_blk"))+40;
    sm = $("#addCommunity");
    sm.css("left",x+"px");
    sm.css("top",y+"px");
    sm.css("width","300px");
    sm.css("height","250px");
    sm.css("display","inline");
    sm.css("visibility","visible");
    //$("#cmnty_type1").checked('true');
}

function showAddFriend() {
    var c = findCenter("addFriend");
    //var x = findPosX(document.getElementById("friends_blk"))-100;
    //var y = findPosY(document.getElementById("friends_blk"))+30;
    sm = $("#addFriend");
    sm.css("left", c.x+"px");
    sm.css("top", c.y+"px");
    sm.css("width","300px");
    sm.css("height","150px");
    sm.css('display','inline')
    sm.css("visibility","visible");
    $("#categoryselect").hide();
    $("#friendid").val("Use Firend's SkriberId");
    $("#friendid").css("color","#ccc");
    $("#friendmsg").val("");
}

function pageWidth() {
    return window.innerWidth != null? window.innerWidth: document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body != null? document.body.clientWidth:null;
}
	
function pageHeight() {
    return window.innerHeight != null? window.innerHeight: document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body != null? document.body.clientHeight:null;
}
	
function posLeft() {
    return typeof window.pageXOffset != 'undefined' ? window.pageXOffset:document.documentElement && document.documentElement.scrollLeft? document.documentElement.scrollLeft:document.body.scrollLeft? document.body.scrollLeft:0;
}
	
function posTop() {
    return typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;
}

function findCenter(id) {
    var c ={};
    ht = $("#"+id).height();
    wd = $("#"+id).width();
    var tp=posTop()+((pageHeight()-ht)/2) - 120;
    var lt=posLeft()+((pageWidth()-wd)/2)-150;
    c.x = lt;
    c.y = tp;
    return c;
}

function showInviteCommunity(cid) {
    var c = findCenter("inviteCommunity");
    //var x = findPosX(document.getElementById('community_blk')) - 100;
    //var y = findPosY(document.getElementById('community_blk')) + 40;
    $.ajax({url: '/notes/memberRole',data: {cid : cid},success: function(data) {
         role = $(data).find('role').text();
    if(role== "member") {
        $("#member").attr('checked','true');
    } else {
        $("#contributor").attr('checked','true');
    }
    }});
    sm = $("#inviteCommunity");
    sm.css("left",c.x+"px");
    sm.css("top",c.y+"px");
    sm.css("width","300px");
    sm.css("height","180px");
    sm.css("display","inline");
    $("#categoryselect").hide();
    sm.css("visibility","visible");
}

function hideFriend(id) {
    $("#"+id).hide();
    $("#categoryselect").show();
}

function showEditCategory(id) {
    var elem = document.getElementById(id);
    var x = findPosX(elem)-100;
    var y = findPosY(elem)+10;    
    sm = $("#editCategory");
    sm.css("left", x+"px");
    sm.css("top",y+"px");
    sm.css("width", "300px");
    sm.css("height", "150px");
    sm.css("display", 'inline');
    sm.css("visibility","visible");
    getCategory(elem.id);
    $("#categoryid").val(elem.id);
}

function hideCategory(id) {
    $("#categoryselect").show();
    $("#"+id).css("visibility","hidden");
}

function cancelShare() {
    $("#shareNote").css("visibility","hidden");
}

function touchResp(data) {
    if($(data).find('updatetime').attr('status') == 'OK') {
        var notebook = $(data).find('notebook').text();
        loadNoteBook(notebook,{cache: false});
    }
}

function setNoteTime(id,notebook) {
     var lnk = '/notes/updateTime/'+id;
     ajaxCall(lnk,{notebook: notebook},touchResp);
}

function showMore(id,height) {
    if($("#note_"+id).height() > 165) {
        $("#nentry_"+id).height(235);
        $("#note_"+id).height(165);
        $("#more_"+id).empty().html("More >>");
    } else {
        $("#nentry_"+id).height(height+85);
        $("#note_"+id).height(height+15);
        $("#more_"+id).empty();;
        $("#more_"+id).empty().html("<< Less");
    }
    $("#second_"+id).toggle();
}


function saveNotepdf(id) {
    //window.location =  '/notes/saveNotepdf/'+id;
    window.open('/notes/saveNotepdf/'+id);
}

function editNote(id) {    
    startAjax('Loading Note Editor...');    

    $.ajax({ 
        url: "/notes/editAjx/"+id, 
        dataType: 'xml', 
        data: {browser: ua,page: $("#mypage").val()},
        cache: false,
        error: function (xhr, desc, exceptionobj) {
           myalert('Remote call Error');},
        success: function(data) {
           handleSessionTimeout(data);
           noteid = id;
           editResp(data); } 
    });
}

function editResp(data) {
    var success = $(data).find("edited").attr('status');

    if(success == "OK") {        
        var id = $(data).find('id').text();
        var title = $(data).find('title').text();
        var text = $(data).find('text').text();   
        var tag = $(data).find('tags').text();        
        var userid = $(data).find('user').text();
        var catgid = $(data).find('categoryid').text();
        var catg = $(data).find('categoryname').text();
        
        if((title=='undefined') && (text=='undefined') && (tag=='undefined') && (catg=='undefined')) {
            myalert('Error while retrieving data');
        } else {
            $("#noteblk_"+id).hide();
            var Str = $("#note_editor").html();
            Str = Str.replace('notetitle','notetitle_'+id);
            Str = Str.replace('notetext','notetext_'+id);
            Str = Str.replace('notetag','notetag_'+id);
            Str = Str.replace('txtcontainer','txtcontainer_'+id);
            Str = Str.replace('categoryselect','categoryselect_'+id);
            Str = Str.replace('savenotefrm','savenotefrm_'+id);
            Str = Str.replace('/notes/saveNote','/notes/EditNote/'+id);
            Str = Str.replace('cancelNote()',"cancelEdit('"+id+"')");
            Str = Str.replace('saveNote(true)',"saveEditNote('"+id+"','"+userid+"')");
            Str = Str.replace('saveNote(false)',"saveEditNote('"+id+"','"+userid+"')");
            Str = Str.replace('saveCommunityNote()',"saveCommunityNote('"+id+"')");
            Str = "<div id='editblk'>"+Str;
            Str = Str+"<input type='hidden' id='prev_notebook' value='"+catgid+"'>";
            Str = Str+"</div>";
            $("#notetag_"+id).hide();
            closePopups();
            $("#nentry_"+id).append(Str);  
          
            $("#txtcontainer_"+id).empty();
            var content = "<textarea rows=3 cols=10 name='notetxt' id='notetxt_"+id+"' class='notetxtarea'></textarea>";
            $("#txtcontainer_"+id).html(content);
            $("#nentry_"+id).css('height','auto');
            $("#notetitle_"+id).val(title);
            $("#notetxt_"+id).val(text);
            $("#notetag_"+id).val(tag);
            $("#categoryselect_"+id).val(catgid);
            //removeControl(); 
            createEditor('notetxt_'+id,true);
            tinyMCE.execCommand('mceAddControl', false, 'notetxt_'+id);
            stopAjax();

            noteid1 = id;
            $("#ownerid").val(userid);
        }        
    } else if(success == "ERROR") {
        var msg = $(data).find('error').text();
        myalert(msg);
    }
}

function editResp1(data) { 
    var id = $(data).find('note').attr('id');
    var Str = $("#note_editor").html();
    Str = Str.replace('notetitle','notetitle_'+id);
    Str = Str.replace('notetext','notetext_'+id);
    Str = Str.replace('notetag','notetag_'+id);
    Str = Str.replace('txtcontainer','txtcontainer_'+id);
    Str = Str.replace('categoryselect','categoryselect_'+id);
    Str = Str.replace('savenotefrm','savenotefrm_'+id);
    Str = Str.replace('/notes/saveNote','/notes/EditNote1/'+id);
    Str = Str.replace('cancelNote()',"sharedNoteDirect('"+id+"')");
    Str = Str.replace('saveNote(false)',"saveEditNote1('"+id+"')");
    Str = Str+"<div id=div1></div>";
    $("#nentry_"+id).html(Str);
    $("#txtcontainer_"+id).empty();
    var content = "<textarea rows=3 cols=10 name='notetxt' id='notetxt_"+id+"' class='notetxtarea'></textarea>";
    $("#txtcontainer_"+id).html(content);
    $("#nentry_"+id).css('height','auto');
    var title = $(data).find('title').text();
    var text = $(data).find('text').text();
    var tag = $(data).find('tags').text();
    var catg = $(data).find('category').text();
    var catgname = $(data).find('categoryname').text();
    $("#notetitle_"+id).val(title);
    $("#notetxt_"+id).val(text);
    $("#notetag_"+id).val(tag);
    $("#categoryselect_"+id).empty().html("<option value='"+catg+"'>"+catgname+"</option>");
    //removeControl();            
    shared_edit = true;
    createEditor('notetxt_'+id,true);
    tinyMCE.execCommand('mceAddControl', true, 'notetxt_'+id);
    //stopAjax();
    var userid = $(data).find('userid').text();
    noteid = id;
    $("#ownerid").val(userid);    
}

function saveEditNote1(id) {    
    allowautosave = false;
    tinyMCE.triggerSave(true,true);

    $.post("/notes/sharedEdit",{ id: id, title: $("#notetitle_"+id).val(), description: $("#notetxt_"+id).val(), tag: $("#notetag_"+id).val(), select: $("#categoryselect_"+id).val()}, function(data) {
    removeControl('notetxt_'+id);     
    noteid1=0;
    if($(data).find('editnote').attr('status') == 'OK') 
        ajaxLoad('/notes/sharedNotes','sharednotes_container');
    else { myalert('error saving note'); }
    } );
}

function saveCommunityResp(data) {
    window.location.reload();
}

function saveCommunityNote(id,role) {
    tinyMCE.triggerSave(true,true);    
    ajaxPost('/notes/saveCommunityNote/',{id: id, title: $("#notetitle_"+id).val(), description: $("#notetxt_"+id).val(), tag: $("#notetag_"+id).val(), select: $("#categoryselect_"+id).val()}, saveCommunityResp);
}

function editNoteResp(data) {
    stopAjax()
    if(handleSessionTimeout(data)) {
    if($(data).find('editnote').attr('status') == 'OK') {
        edit = false;
        var notebook = $(data).find('notebook').text();
        var prevnot = $("#prev_notebook").val();  
        var notebooktitle = $(data).find('notebookname').text();
        $("#notebooktitle").val(notebooktitle);
        var id = $(data).find('editnote').attr('id');
        var note = $(data).find('note').text();
        var title = $(data).find('title').text();
        var tags = $(data).find('tags').text();
        if(prevnot == notebook) {
            removeControl('notetxt_'+id);        
            $("#note_"+id).html(note);
            $("#nentry_"+id+" .titletxt").html(title);
            $("#editblk").remove();
            $("#noteblk_"+id).show();
            $("#notetag_"+id).html("Tags: "+tags).show();
        } else {
            loadNoteBook(notebook,{cache: false,page: $("#mypage").val()});
            selectNotebook(notebook,0);   
        }                    
    }
    }
}
                                
function saveEditNote(id,userid) {
    tinyMCE.triggerSave(true,true);
    allowautosave = false;
    window.clearTimeout(timeoutid);
    var frm = "savenotefrm_"+id;  
    var data = { id: id, title: $("#notetitle_"+id).val(), text: $("#notetxt_"+id).val(), tag: $("#notetag_"+id).val(), categoryname: $('#categoryselect_'+id+' option:selected').text(), select: $("#categoryselect_"+id).val()};    
    startAjax('Saving Note ...');
    ajaxPost('/notes/editNote1',data,editNoteResp);
}

function isEditable() {    
    if($("#editblk").length > 0 || allowautosave) {
        return false;
    } else {
        return true;
    }
}

function editAlert() {
    myalert('Please save or cancel the opened note for edit.');
}

function invite() {
    var email = $("#invite_frnd").val();
    email = email.replace(/^\s|\s$/g, '');
    //if (email.search(/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/) == -1){
    if (email.search(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/) == -1){
        myalert("Not a valid e-mail address: "+email); 
    } else {
        startAjax("Please Wait ...");
        $.ajax({url: '/users/invite', data: {'emailid': email}, success: function(data) {inviteResp(data);}});
    } 
}

function inviteResp(data) {
    stopAjax(); 
    $("#invite_frnd").val('');

    if($(data).find('invite').attr('status') == 'OK') {
        var mail = $(data).find('to').text();  
        myalert("Successfully sent invitation to "+mail);
    } else {
        var errorcode = $(data).find('invite').attr('code');
        if(errorcode == '6') {
            var mail = $(data).find('to').text();            
            var skriberid = $(data).find('skriberid').text();
            myalert("<div style='padding: 10px;padding-bottom: 2px;'><b>"+mail+"</b> (Skriber id: <b>"+skriberid+"</b>) already exists in your Friend List</div>");     
        } else if(errorcode == '5') {
            var mail = $(data).find('to').text();                 
            var skriberid = $(data).find('skriberid').text();
            confrm("<div style='padding: 10px;padding-bottom: 2px;'><b>"+mail+"</b> (Skriber id: <b>"+skriberid+"</b>.) already exists <br> Do You want to add him ?</div>");
            $("#yes").click(function() {
                stopAjax();                
                startAjax('Please Wait ...');
                $.ajax({url: '/users/addFriend',type: 'POST', dataType: 'xml', data: {cache: false,id: skriberid}, success: function(data) {
                        friendResponse(data);      
                    }
                });       
            });
            $("#no").click(function() {
                stopAjax();
            });
        } else if(errorcode == '2') {
            myalert("Error while sending the Invitation request");
        }
    }
}

function IsEmail(email) {
            //var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            var regex = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
            if (regex.test(email)) return true;
            else return false;
} 


function inviteSubmit() {
    $("#inviteForm").submit();
}
   
function isInvite() {
    if($("#UserEmail").val()&&$("#UserSubject").val()&&$("#UserTxt").val()) {
        return true;
    } else {
        return false;
    }
}

function alertInvite() {
    myalert('Fields can not be left blank');
}
   
function myalert(alrt) {
    var question = "<table width=\'100%\' cellspacing=\'0\' cellpadding=\'0\'>"
                   +"<tr><td height=\'8px\' style=\'background-color: #11a3da;\'>"
                   +"<div style=\'float: right;color: #ffffff;font-weight: bold; cursor:pointer\' onclick=\'$.unblockUI()\'>X</div></td></tr>"
                   +"<tr><td height=\'8px\'>&nbsp;</td></tr>"
                   +"<tr><td align=\'center\'>"+alrt
                   +"<tr><td height=\'8px\'>&nbsp;</td></tr><tr><td align=\'center\'>" 
                   +"<div id=\'myalertok\' href=\'javascript: void(0);\' class=\'bg55\' onclick=\'$.unblockUI()\'>Ok</div>"
                   //+"<img id=\'myalertok\' style=\'cursor:pointer;\' src=\'/img/ok.gif\' alt=\'Ok\' onclick=\'$.unblockUI()\'/>"
                   +"</td></tr></table>";
    // styles for the overlay iframe
    $.extend($.blockUI.defaults.overlayCSS, { backgroundColor: '#fff', opacity: '0.0'});
    // styles for the message when blocking the entire page
    $.extend($.blockUI.defaults.pageMessageCSS, { width:'300px', height:'auto', margin:'-50px 0px 0px -125px', padding:'0px 0px 10px 0px', top:'50%', left:'50%', textAlign:'center', color:'#000', backgroundColor:'#fff', border:'3px solid #11a3da'});
    // styles for the displayBox
    $.extend($.blockUI.defaults.displayBoxCSS, { width: '400px', height: '400px', top:'50%', left:'50%'});
    $.blockUI(question);
}
function feedback() {
    window.location = '/notes/feedback';
}

function feedbackSubmit() {
    $("#feedbackForm").submit();
}

function isFeedback() {
    if($("#NoteTtl").val() && $("#NoteTxt").val()) {
        return true;
    } else {
        return false;
    }
}
function alertFeedback() {
    myalert('Fields can not be left blank');
}

function userprefSubmit() {
    if($("#UserTitle").val() && $("#UserTag").val() && $("#UserNoteslmt").val()) {
        $("#UserPrefForm").submit();
    } else { 
        myalert("Fields canot be left blank");
    }       
}
function pwdSubmit() { 
    if($("#oldpwd").val() && $("#newpassword").val() && $("#renewpassword").val()) { 
        if($("#newpassword").val() == $("#renewpassword").val()) {      
            $("#UserPwdForm").submit();
        } else {
            myalert("Passwords typed do not match...!");
        }
    } else { 
        myalert("Fields canot be left blank");
    }       
}

function publishResp(data) {
    stopAjax();
    if($(data).find('publishnote').attr('status') == 'OK') {
        var notebook = $(data).find('notebook').text();
        var id = $(data).find('id').text();
        
        confrm('The note has been published successfully<br> Do you want to see your published Notes?');
        $("#yes").click(function() {
            var user = $(data).find('user').text();
            window.location = '/webnotes/'+user;
        });
        $("#no").click(function() {
            $.unblockUI();            
            var elem = $("#published_"+id);
//            var html = "<img class='btn' src='/img/unpublish.gif' id='unpublished_"+id+"' onclick='javascript: unpublishNote(\""+id+"\",false)'>";
            var html = "<div id='unpublished_"+id+"' href='javascript: void(0);' class='bg55' onclick='javascript: unpublishNote(\""+id+"\",false)'>Unpubslish</div>";
            elem.parent().html(html);
        });
    }
}

function publishResp1(data) {
    stopAjax();
    if($(data).find('publishnote').attr('status') == 'OK') {        
        var id = $(data).find('id').text();
        
        confrm('The note has been published successfully<br> Do you want to see the published Notes?');
        $("#yes").click(function() {
            var user = $(data).find('cid').text();
            window.location = '/webnotes/'+user;
        });
        $("#no").click(function() {
            $.unblockUI();            
            var elem = $("#published_"+id);
            var html = "<div href='javascript: void(0);' id='unpublished_"+id+"' class='bg55' onclick='javascript: unpublishNote(\""+id+"\",false)'>Unpublish</div>";
            elem.parent().html(html);
        });
    }
}

function publishResp3(data) {
    stopAjax();
    if($(data).find('publishnote').attr('status') == 'OK') {
        var id = $(data).find('id').text();

        confrm('The note has been published successfully<br> Do you want to see the published Notes?');
        $("#yes").click(function() {
            var locn = $(data).find('location').text();
            window.location = locn;
        });
        $("#no").click(function() {
            $.unblockUI();
            var elem = $("#published_"+id);
            var html = "<div href='javascript: void(0);' id='unpublished_"+id+"' class='bg55' onclick='javascript: unpublishNote(\""+id+"\",false)'>Unpublish</div>";
            elem.parent().html(html);
        });
    }
}


function communityUnpublish(id,public_page) {
    confrm("Do you want to unpublish the note?");
    $("#yes").click(function() {
        $.unblockUI();
        var page = $("#mypage").val();
        if(public_page) {
            ajaxCall('/notes/communityUnpublish/'+id,{cache: false,page: page},cmntyUnpublishResp1);
        } else {
            ajaxCall('/notes/communityUnpublish/'+id,{cache: false,page:page},cmntyUnpublishResp);
        }
    });
    $("#no").click(function() {
        $.unblockUI();
    });
}

function cmntyUnpublishResp1(data) {
   window.location.reload();
}

function cmntyUnpublishResp(data) {
    var id = $(data).find('noteid').text();
    var page = $(data).find('page').text();
    var community = true;
    var html = "<div class='bg55' id='published_"+id+"' onclick='javascript: publishNote(\""+id+"\","+community+");'>Publish</div>";
    $("#unpublished_"+id).parent().html(html);
}


function unpublishNote(id,public_page) {
    confrm("Do you want to unpublish the note?");
    $("#yes").click(function() {
        $.unblockUI();
        var page = $("#mypage").val();
        if(public_page) {
            ajaxCall('/notes/unpublishNote/'+id,{cache: false,page: page},unpublishResp1);
        } else {
            ajaxCall('/notes/unpublishNote/'+id,{cache: false,page:page},unpublishResp);
        } 
    });
    $("#no").click(function() {
        $.unblockUI();
    });
}

function unpublishResp1(data) {
   window.location.reload();
}

function unpublishResp(data) {
    var id = $(data).find('noteid').text();
    var page = $(data).find('page').text();
    var community = false;
    if(page == '3') {
        community = true;
    }
    var html = "<div class='bg55' id='published_"+id+"' onclick='javascript: publishNote(\""+id+"\","+community+");'>Publish</div>";
    $("#unpublished_"+id).parent().html(html);        
}

function publishNote(id,community) {
    var page = $("#mypage").val();
    var user = $("#user_id").val();
    var org = $("#notebook").val();
    startAjax('Publishing Note ...');
    $.ajax({url: '/notes/loadPublished/'+id, success: function(data) {
        var cnt = $(data).find("published").each(function() {
            var name = $('name',this).text();
            var apnd = "<span>"+name+"</span>";
            $("#published_in").append(apnd);
        });
    }});   

    if(community) {    
        url = '/notes/publishNote/'+id;
        data = {community: community,cid: $("#communityid").val()};           
        ajaxCall(url,data,publishResp1);
    } else {
        data = {cache: false};
        var quest = "<table width=\'100%\' cellspacing=\'0\' cellpadding=\'0\'><tr><td height=\'12px\' style=\'background-color: #11a3da;\'><span style=\'float: left;color: #ffffff;font-weight: bold;margin-left:5px \'>Publish Note</span><span style=\'float: right;color: #ffffff;font-weight: bold; cursor:pointer\' onclick=\'$.unblockUI()\'>X</span></td></tr>";
    quest +="<tr><td height=\'10px\'></td></tr>"  
    quest +="<tr><td align=\'left\'><div style=\'margin-left: 20px\'><span>Published in: </span><span id=\'published_in\'></span><div></td></tr>"  
    quest +="<tr><td height=\'5px\'></td></tr>"  
    quest += "<tr><td height=\'25px\' align=\'right\'><div style=\'margin-right: 25px\'><span style=\'color: #000;font-weight: bold;margin-left:5px;\'>Communities: </span> <select id = \'publishlist\' style=\'width: 155px;\' onchange=\"publishSelect(\'"+id+"\',\'"+user+"\') \"><option value=\'myblog\'>My Blog</option></select></div></td></tr>";
    //quest +="<tr><td height=\'25px\' align=\'left\'><fieldset><legend style=\'color: #000;font-weight: bold;margin-left: 25px\'>Notebooks:</legend></td></tr>"
    quest += "<tr><td align=\'left\'><div style=\'margin-left: 25px; margin-right: 25px\'><fieldset><legend style=\'color: #000;font-weight: bold;margin-left: 25px: width: 80%\'>Notebooks:</legend><div style=\'margin-left: 5px\' id=\'publist\'><input type='radio' name='notebook' value="+id+" checked><span style='background: #ccc;padding: 2px 5px 2px 2px'>Public Notes</span><br></div></fieldset></div></td></tr>"; 
    quest += "<tr><td align=\'center\'><br>"
    quest += "<table><tr><td><div id=\'publish_yes\' href=\'javascript: void(0);\' class=\'bg55\'; onclick=\"publish_Note('"+id+"','"+user+"')\">Ok</div></td>"
    quest += "<td><div id=\'publish_no\' href=\'javascript: void(0);\' class=\'bg55\' onclick=\'$.unblockUI()\'>Cancel</div></td></tr></table>"
    quest += "</td></tr>";
    quest += "</table><input id =\'movenoteid\' type=\'hidden\' value='"+id+"'><input id =\'notebk_id\' type=\'hidden\' value='"+org+"'>";

    $.extend($.blockUI.defaults.overlayCSS, { backgroundColor: '#fff', opacity: '0.0'});
    $.extend($.blockUI.defaults.pageMessageCSS, { width:'400px', height:'auto', margin:'-50px 0 0 -125px', padding:'0px 0px 10px 0px', top:'30%', left:'30%', textAlign:'center', color:'#000', backgroundColor:'#fff', border:'3px solid #11a3da'});
    $.extend($.blockUI.defaults.displayBoxCSS, { width: '600px', height: '800px', top:'30%', left:'30%'});
    $.blockUI(quest);
    $.ajax({url: '/notes/listCommunities/'+user, success: function(data) {
        var cnt = $(data).find("community").each(function() {
            var id = $('id',this).text();
            var name = $('name',this).text();
            var did = $('did',this).text();
            var apnd = "<option value='"+id+"'>"+name+"</option>";
            $("#publishlist").append(apnd);
        });
    }});
        //ajaxCall(url,data,publishResp);
    }
    
}

function publishSelect(id,user) {
    var cid  = $('#publishlist option:selected').val();
    if(cid == 'myblog') {
        var val = "<input type='radio' name='notebook' value="+id+" checked><span style='background: #ccc;padding: 2px 5px 2px 2px'>Public Notes</span><br>";
        $("#publist").html(val);
    } else {
    $.ajax({url: '/notes/listNotebooks/',data: {cid: cid},success: function(data) {
        pubnoteResp(data,id,user);
    }});
    }
}

function pubnoteResp(data,id,user) {
    var page = $("#mypage").val();
    $("#publist").html('');
    var tab = $("#notebooktitle").val();
    var bk = (page =='1') ? $("#notebook").val() : $("#cnotebook").val();
    var df =$(data).find('categories').attr('default'); 
    $(data).find('category').each(function() { 
        var id = this.getAttribute('id');
        var name = this.getAttribute('name');
        if(id == df) {
           var select = "<input id='from_book' type='radio' name='notebook' value="+id+" checked><span style='background: #ccc;padding: 2px 5px 2px 2px'>"+name+"</span><input type='hidden' value='"+name+"' id='catxt_"+id+"'><br>";
        } else {
           var select = "<input type='radio' name='notebook' value="+id+" onClick=\" \">"+name+"<input type='hidden' value='"+name+"' id='catxt_"+id+"'><br>";
        }
        $("#publist").append(select);
    });
}


function publish_Note(id,user) {
    var cid  = $('#publishlist option:selected').val();
    url = '/notes/publishNote/';
    if(cid == 'myblog') {
        url += id;
        ajaxCall(url,data,publishResp);
    } else { 
        var cat = $("input[@name='notebook']:checked").val();
        var catxt = $("#catxt_"+cat).val();
        var org_cat = $("#notebk_id").val();
        $.ajax({url: '/notes/publishTocommunity/'+id, data: {user: user,cid: cid,cat: cat,catxt: catxt,original: org_cat}, success: function(data) {
           publishResp3(data);   
        }});
    }
}

function getSelectedCategories() {
    var categories = "";
    $("#categorylist").find('input').each(function() { 
        if($(this).attr('checked')) categories += $(this).attr('id')+"^^"; 
    });
    return categories;
}

function refreshNoteList(id,checked,community) {
    if(community == 1) {
    } else if(community == 0) {
        mynotes();
        $("#mynotes_container").hide(); 
        categoryNotes('/notes/notesCategories/'+id,checked,'mynotes_container');
        $("#mynotes_container").show();
    }
}

function refreshFrndList(id,checked,frnd) {
    window.location = '/notes/showFriend/'+frnd;  
}

function showEditCategory1(id) { 
    $.ajax({url: "/notes/showEditCategory/"+id,data: {cache: false},success: function(data) { $(".category_edit").hide();
    $("#category_list").empty().html(data); }});
}

function editCategory(id) {
     var name = $("#categoryname1").val();
     var description = $("#categorydesc1").val();
     $.post("/notes/editCategory", {id: id, name: name, description: description}, function(data) { $(".category_edit").show(); $("#category_list").empty().html(data);
});
}

function cancelEditCategory() {
    $(".category_edit").show();
    $.ajax({url: "/notes/getCategoryList", success: function(data) {$("#category_list").empty().html(data);} });
}

function updateCategoryList(id,checked) {
    $.post("/notes/updateCategoryList", {id: id, checked: checked}, function(data) {return;});
}

function addComment(id) {
     var str = "<div id='cmntblk' class='cmntblk'><form id='commentfrm' name='commentfrm' action='/notes/addComment' method='POST'><table cellspacing='1' cellpadding='4'><tr><td><table><tr><td valign='top'><span class='frmlabel'>Comments</span></td><td><textarea rows=2 cols=6 name='comment' id ='comment' class='resizable cmttxtarea'></textarea></td></tr>";
     str = str+"<tr><td>&nbsp;</td><td><input type='checkbox' id='sendmail_cmnt'><span class='small_text'>Send Notification Mail</span> </td></tr><tr><td>&nbsp;</td><td><span class='space_right'>";
     //str = str+"<img src='/img/save.gif' class='btn' onclick='javascript: saveComment();' alt='Save Comment'></span><span><img src='/img/cancel.gif' class='btn' onclick='javascript: cancelCmnt();' alt='Cancel Comment'></span>";
     str = str+"<table><tr><td><div href='javascript: void(0);' class='bg55' onclick='javascript: saveComment();'>Save</div></td>";
     str = str+"<td><div href='javascript: void(0);' class='bg55' onclick='javascript: cancelCmnt();'>Cancel</div></td></tr></table>";
     str = str+"</td></tr></table></td></tr></table><input id='idval' style='display: none' value='"+id+"'></form><div id='val' style='display: none'>"+id+"</div></div>";
         if($("#cmntlistblk").length > 1) {
             if($("#cmntblk").length > 0) {
                 $("#cmntblk").remove();
             }
             $("#cmntlistblk").append(str);  
         } else {  
             if($("#cmntblk").length > 0) {
                 $("#cmntblk").remove();
             }
             $("#tagcmntblk_"+id).after(str);       
         }
         $("textarea.resizable:not(.processed)").TextAreaResizer();        
}

function cancelCmnt() {	
    $("#cmntblk").remove();
}

function saveComment() {
    var cmnt = $("#comment").val();
    if(cmnt) {
        var id = $("#val").text();
        var mail = $("#sendmail_cmnt").attr('checked');
        startAjax("Saving Comment ... ");
        $.ajax({url: "/notes/addComment",type: 'POST', dataType: 'xml',data: {id: id, comment: cmnt, sendmail: mail}, success: function(data) {
           stopAjax();
           //if(handleSessionTimeout(data)) {
           var success = $(data).find("addcomment").attr('status');
           if(success == "OK") {
               var id = $(data).find('id').text();
               var num = $(data).find('count').text();
               var cmnt = "Comments("+num+")";
               $("#cmntcount_"+id).text(cmnt);
               $("#cmntblk").remove();
                   showComment(id);
           //}
           }
        }}); 
        //} );
    } else {
        myalert('Comment field can not be left blank');
    }
}

function pubaddComment(id) {
     var str = "<div id='cmntblk' class='cmntblk'><form id='commentfrm' name='commentfrm' action='/notes/addComment' method='POST'><table cellspacing='1' cellpadding='4'><tr><td><table><tr><td valign='top'><span class='frmlabel'>Comments</span></td><td><textarea rows=2 cols=6 name='comment' id ='comment' class='resizable cmttxtarea'></textarea></td></tr><tr><td>&nbsp;</td><td><span class='space_right'><img src='/img/save.gif' class='btn' onclick='javascript: pubsaveComment(\""+id+"\");' alt='Save Comment'></span><span><img src='/img/cancel.gif' class='btn' onclick='javascript: cancelCmnt();' alt='Cancel Comment'></span></td></tr></table></td></tr></table><input id='idval' style='display: none' value='"+id+"'></form><div id='val' style='display: none'>"+id+"</div></div>";
         if($("#cmntlistblk").length > 1) {
            if($("#cmntblk").length > 0) {
                 $("#cmntblk").remove();
             }
             //$("#cmntlistblk").append(str);  
             $("#cmntlistblk_"+id).append(str);
         } else {  
             if($("#cmntblk").length > 0) {
                 $("#cmntblk").remove();
             }
             //hidePopups();
             $("#pubtagcmntblk_"+id).after(str);      
         }
         $("textarea.resizable:not(.processed)").TextAreaResizer();        
}

function pubsaveComment(id) {
    var cmnt = $("#comment").val();
    if(cmnt) {
        $.post("/notes/addComment",{ id: id, comment: cmnt}, function(data) {
           var success = $(data).find("addcomment").attr('status');
           if(success == "OK") {
               var id = $(data).find('id').text();
               var num = $(data).find('count').text();
               var cnt = "Comments("+num+")";
               $("#pubcmntcount_"+id).text(cnt);
               var newcnt = '<a href=\'javascript: void(0);\' id=\'pubshowcmnt_'+id+'\' onclick=\'javascript: showpubComment("'+id+'");\'>'+cnt+'</a>';
               $("#pubshowcomment_"+id).html(newcnt);
               $("#cmntblk").remove();
               showpubComment(id);
           } else { 
               myalert("Error While Saving Comment");
           }
        } );
    } else {
        myalert('Comment field can not be left blank');
    }
}

function showComment(id) {
    hidePopups();
    $.ajax({
        url: "/notes/showComment/"+id,
        dataType: 'xml',
        cache: false,
        error: function (xhr, desc, exceptionobj) {
        myalert('Remote call Error');},
        success: function(data) {
        //handleSessionTimeout(data);
        showcmntResp(data); }
    });
}

function showcmntResp(data) {
    var success = $(data).find("showcomment").attr('status');
    if(success == "OK") {
        var id = $(data).find('id').text();
        var num = $(data).find('count').text();
        var str = "<div id='cmntlistblk'>";
        if(num) {
            str = genComments(num,str,data);
        } else {            
            str = str+"<div class='cmnttl'> There is no comments in the List</div>";
        } 
        var bkp =  $("#showcomment_"+id).html();  
        str = str+"<div id='cmntlistval' style='display:none'>"+id+"</div>"; 
        str = str+"<div id='cmntcountbkp' style='display:none'>"+bkp+"</div>"; 
        str = str+"</div>"; 
        $("#cmntcount_"+id).remove();
        var cmnt = "<a href='javascript: void(0);' onclick='javascript: hidePopups();'>Hide Comments</a>";
        $("#showcomment_"+id).html(cmnt);
        closePopups();
        $("#tagcmntblk_"+id).after(str);
    }
}

function showpubComment(id) {
    hidePopups();
    $.ajax({
        url: "/notes/showComment/"+id,
        dataType: 'xml',
        cache: false,
        error: function (xhr, desc, exceptionobj) {
        myalert('Your Session Expired, Please login again');},
        success: function(data) {
        showpcmntResp(data); }
    });
}

function showpcmntResp(data) {
    var success = $(data).find("showcomment").attr('status');
    if(success == "OK") {
        var id = $(data).find('id').text();
        var num = $(data).find('count').text();
        var str = "<div id='cmntlistblk'>";
        if(num) {
            str = genComments(num,str,data);
        } else {            
            str = str+"<div class='cmnttl'> There is no comments in the List</div>";
        } 
        var bkp =  $("#pubshowcomment_"+id).html();  
        str = str+"<div id='pubcmntlistval' style='display:none'>"+id+"</div>"; 
        str = str+"<div id='pubcmntcountbkp' style='display:none'>"+bkp+"</div>"; 
        str = str+"</div>"; 
        $("#pubcmntcount_"+id).remove();
        var cmnt = "<a href='javascript: void(0);' onclick='javascript: pubhidePopups();'>Hide Comments</a>";
        $("#pubshowcomment_"+id).html(cmnt);
        closePopups();
        $("#pubtagcmntblk_"+id).after(str);
    }
}

function genComments(num,str,data) { 
    for(var i=0; i<num ;i++) {
        var user = $(data).find('listname_'+i).text();
        var cmnts = $(data).find('listcoment_'+i).text();
        cmnts = cmnts.replace(/\n/g,'<br>');
        var tim = $(data).find('listdate_'+i).text();
        str = str+"<div class='cmntlist'>";
        str = str+"<div class='cmnttl'>Comment From "+user+", "+tim+"</div>";
        str = str+"<div  class='cmntxt'>"+cmnts+"</div>";
        str = str+"</div>";
    }
    return str;       
}

function closePopups() {
    if($("#cmntlistblk").length>0) {
        $("#cmntlistblk").remove();
    }
    if($("#cmntaddmsg").length > 0) {
        $("#cmntaddmsg").remove();
    }
    if($("#cmntlistblk").length>0) {
        $("#cmntlistblk").remove();
    }
    //if($("#cmntblk").length>0) {
      //  $("#cmntblk").remove();
    //}
}

function hidePopups() {
    var id = $("#cmntlistval").text();
    var cmnt = $("#cmntcountbkp").html();
    $("#showcomment_"+id).html(cmnt);
    closePopups();    
}

function pubhidePopups() {
    var id = $("#pubcmntlistval").text();
    var cmnt = $("#pubcmntcountbkp").html();
    $("#pubshowcomment_"+id).html(cmnt);
    closePopups();    
}

function sharedEditing(id) {
    $.ajax({url: "/notes/sharedEditing",data: {id: id}, dataType: 'xml', 
cache: false, success: function(data) { 
        handleSessionTimeout(data);
        if($(data).find('sharededit').attr('status') == 'ERROR') {
            myalert($(data).find('msg').text());
        } else {
            editResp1(data);
        } 
    }
    });
}

function sharedNoteDirect(id) {
    noteid1 = 0;
    $.ajax({url: "/notes/cancelSharedEdit/"+id, dataType: 'xml', cache: false,
            success: function(data) {
                removeControl('notetxt_'+id); 
                handleSessionTimeout(data);
                if($(data).find('canceledit').attr('status') == 'OK') { } 
                ajaxLoad('/notes/sharedNotes','sharednotes_container');         
            } });
}

function showmonthResp(data) {
   $("#mynotes_container").empty().html(data);
}
function getCurrentNotebook() {
    var notebook = $('#tabcontainer > ul li.ui-tabs-selected a span').html();   
    return notebook;
}

function getCurrentContainer() {
    var container = $('#tabcontainer > ul li.ui-tabs-selected a').attr('href');
    return container;    
}

function dayList(day) {
    notebook = getCurrentNotebook();
    if(notebook == 'Shared Notes' || notebook == 'Public Notes') {
    
    } else {                  
        var tmp = day.split("-");
        startAjax("Loading Notes on "+day+"...");  
//        notebook = escape(notebook);
        var dat = {'var1': tmp[2], 'var2': tmp[1], 'var3': tmp[0],'notebook': notebook};    
        loadDayList("/notes/dayList/",dat);    
    }      
}


function frndayList(day,frnd) {
    var tmp = day.split("-");
    startAjax("Loading Shared Notes on "+day+"...");
    var dat = {'var1': tmp[2], 'var2': tmp[1], 'var3': tmp[0], 'var4': frnd};
    loadfrnDayList("/notes/frndayList/",dat);
}

function cmntydayList(day,cid) {
    var tmp = day.split("-");
    startAjax("Loading Notes on "+day+"...");  
    var dat = {'var1': tmp[2], 'var2': tmp[1], 'var3': tmp[0], 'var4': cid};    
    loadcmntyDayList("/notes/cmntydayList/",dat);
}

function listCommunities(data) {
    var status =$(data).find('communities').attr('status');
    var ttl =$(data).find('communities').attr('total');
    var sessid = $(data).find('communities').attr('sessid');

    if(status == 'OK') {
        $("#communitylist").empty();        
        $("#community_count").html("Communities ("+$(data).find('communities').attr('total')+") ");
        var count = 0;
        if(ttl == '1') { 
            $("#communitylist").show(); 
        }
        var out = "<table cellspacing=3 cellpadding=0 class='frnds_tbl'>"; 
        $(data).find('community').each(function(i) { 
            if(i < 4) { 
                var name = $('name',this).text(); 
                var count = this.getAttribute('members');
                name += "("+count+")";
                var id = this.getAttribute('id');      
                var photo = this.getAttribute('photo');                   
                out += "<tr><td class='friend_photo'><div class='frndphoto_blk'><div class=\'thumb_photo\'>";
                out += "<img src="+photo+" height=50 width=50></div><div></td>";
                out += "<td class='friend_name'><div class='frndname_blk'>";
                out += "<a class='frndlnk' href='#' id ='communitylink_"+$(this).attr('id')+"' href='#' onclick='javascript: loadCommunity("+id+")'>"+name+"</a></div>";
                out += "</td></tr>";           
                count = i+1;
            } else {             
                out += "<tr><td colspan=2 class='moreblk' align=right><a href='#' id='communitymore'>More>></a></td></tr>";
                return false;
            }
        });    
        out += "</table>";
        $("#communitylist").append(out);
        $("#communitymore").click(function() {
            //showMoreCommunities(data);              
            window.location = "/notes/communities/"+sessid;         
        });
        if(count < 4) {            
            $("#extra").height((4-count)*50);
        }
    } else if(status == 'ERROR') {
        $("#communitylist").hide();
    }
}

function ajaxCall(url,data,callback) {
    $.ajax({
        url: url,        
        data: data,
        success: function(data) {
            callback(data);
        }
    });
}

function ajaxPost(url,data,callback) {
    $.ajax({url:url, type: 'POST', dataType: 'xml',data: data, success: function(data) { callback(data); }});
}

function loadCommunities(settings) {
    ajaxCall('/notes/loadCommunities',{cache: false,settings:settings},listCommunities);
}

function loadFrndCmnty(id) {
    ajaxCall('/notes/loadCommunities',{cache: false,id: id},listCommunities);
}

function loadMyCommunities(userid) {
    ajaxCall('/notes/loadCommunities',{cache: false,id: userid},listMyCommunities);
}

function listMyCommunities1(data) {
    stopAjax();

    var html = "<div id='Pagination11' align=center class='pagination' style='margin-bottom: 10px; margin-top: 10px; margin-left: 15px;'></div>";
    html += "<br><br><div id='moreclients11' style='padding: 10px;>";
    var communities = new Array();
    var sessid = $(data).find('communities').attr('sessid');
    $(data).find('community').each(function(i) {
        var name = $('name',this).text();
        var id = this.getAttribute('id');
        var photo = this.getAttribute('photo');
        var type = $('type',this).text();
        var owner = $('owner',this).text();
        communities[i] = new Array();
        communities[i]['name'] = name;
        communities[i]['id'] = id;
        communities[i]['photo'] = photo;
        communities[i]['description'] = $('description',this).text();
        communities[i]['type'] = type;
        communities[i]['count'] = this.getAttribute('members');
        communities[i]['owner'] = owner;
    }); 
    html += "</div>";
    $("#communities_result").show();
    $("#communities_result").empty().html(html);
    displayCommunityPage(0,communities,'moreclients11',sessid); 
    var total = $(data).find('communities').attr('total');
    pages = Math.ceil(total/20);

    $("#Pagination11").pagination(total, {
        num_edge_entries: 2,
        items_per_page: 20,
        num_display_entries: 4,
        callback: function(page_id,jq) {
            displayCommunityPage(page_id, communities,'moreclients11',sessid);
        }
    });
} 


function listMyCommunities(data) {
    var html = "<div id='Pagination' align='center' class='pagination' style='margin-bottom: 50px; margin-top: 20px; margin-left: 25px;'></div>";
    html += "<div id='moreclients' style='padding: 10px;'>";
    var communities = new Array();    
    var sessid = $(data).find('communities').attr('sessid');

    $(data).find('community').each(function(i) {
        var name = $('name',this).text();
        var id = this.getAttribute('id');
        var photo = this.getAttribute('photo');
        var type = $('type',this).text();
        var owner = $('owner',this).text();
        communities[i] = new Array();
        communities[i]['name'] = name;
        communities[i]['id'] = id;
        communities[i]['photo'] = photo;
        communities[i]['description'] = $('description',this).text();
        communities[i]['type'] = type;
        communities[i]['count'] = this.getAttribute('members');
        communities[i]['owner'] = owner;
    }); 
    html += "</div>";
    $("#mynotes_container").empty().html(html);
    displayCommunityPage(0,communities,'moreclients',sessid); 
    var total = $(data).find('communities').attr('total');
    pages = Math.ceil(total/20);

    $("#Pagination").pagination(total, {
        num_edge_entries: 2,
        items_per_page: 20,
        num_display_entries: 4,
        callback: function(page_id,jq) {
            displayCommunityPage(page_id, communities,'moreclients',sessid);
        }
    });
 
}

function displayCommunityPage(i,communities,container,sessid) {
    var start = i*20;
    var html = "";
    var i = 0;

    for(j=start; j < communities.length; ++j) {
        if(j < start+20) {
            html += "<div style='border: 1px solid #ccc; float: left; margin: 15px;'><table><tr>";
            var name = communities[j]['name'];
            var id = communities[j]['id'];
            var count = communities[j]['count'];
            var owner = communities[j]['owner'];
            html += "<td class='friend_photo'><div class='thumb_photo'><img src="+communities[j]['photo']+" height=50 width=50></div></td><td class='friend_name'><div class='frndname_blk'>";
            html += "<a class='frndlnk' href='/notes/community/"+id+"'>"+name+"&nbsp;("+count+")</a>";            
            html += "</div></td></tr></table></div>";
            ++i;
        } else {
           break;
        }
    }
    if(i < 4) i =4;
    $("#"+container).html(html);
    $("#"+container).height(i/4*130);
}

function loadCommunity(id) {    
    window.location = '/notes/community/'+id;
}

function addCommunityResponse(data) {
    stopAjax();
    if(handleSessionTimeout(data)) {
    if($(data).find('addcommunity').attr('status') == 'ERROR') {
        var msg = $(data).find('error').text();
        $("#community_msg").html(msg);
      //myalert('add community Error');
    } else {
        hideCategory('addCommunity');
        listCommunities(data);
    }
    }
}

function addCommunity() {
    name = $("#communityname").val();
    description = $("#communitydesc").val();
    type = $("input[@name='type']:checked").val();
    ajaxPost('/notes/addCommunity',{name: name,description: description,community_type: type}, addCommunityResponse);
}

function listCommunityFriends(data) {
    var status = $(data).find('communityfriends').attr('status');
    $("#communitylist").empty();
    $("#community_count").html("Members ("+$(data).find('communityfriends').attr('total')+") ");

    if(status == 'OK') {
        var out = "<table class='frnds_tbl'>";
        $(data).find('friend').each(function() {
            var id = $('id',this).text();
            var fullname = $('fullname',this).text();
            var photo = $('photo',this).text();
            if(fullname == "") fullname = id;
            out += "<tr><td class='friend_photo'><div class='frndphoto_blk'>";
            out += "<div class=\'thumb_photo\'>";
            out += "<img src="+photo+" height=50 width=50></div></div></td>";
            out += "<td class='friend_name'><div class='frndname_blk'><a href='/notes/showFriend/"+id+"'>"+fullname+"</a></div></td></tr>";
        });
        out += "</table>";
        $("#communitylist").append(out);
    }
}

function loadCommunityFriends(id) {    
    ajaxCall('/notes/loadCommunityFriends/'+id,{cache: false},loadfrndResp);
}

function loadCommunityMoreFriends(id,flg) {
    ajaxCall('/notes/loadCommunityFriends/'+id+'/'+flg,{cache: false},loadMyfriendsResp);
}

function loadCommunitySettings(id) {
    ajaxCall('/notes/loadCommunityFriends/'+id,{cache: false},listCommunitySettings);
}

function listCommunitySettings(data) {
    var cid = $("#cid").val();
    var def = "<form id=\'cmntySettings\' name=\'User\' action=\'/users/comunitySetings\' method=\'POST\'>";
    $("#c_defaults").empty();
    def += "<table cellpadding=3> <tr> <td cospan=2>&nbsp;</td> </tr><tr> <td><span class='frmlabel'>Name:</span></td><td><span><input type='text' style='width: 190px;' id='communityname'></span></td></tr>";
    def += "<tr><td><span class='frmlabel'>Description: </span></td> <td> <span><textarea id='communitydesc' style='width: 190px;' rows=2 cols=21></textarea></span></td> </tr>";
    def += "<tr><td><span class='frmlabel'>Type: </span></td> <td> <fieldset> <legend>Type of Community</legend> <div><input type='radio' name='type' id='cmnty_type1' value='1'>Public</div> <div><input type='radio' name='type' id='cmnty_type2' value='2'>Moderated</div> <div><input type='radio' name='type' id='cmnty_type3' value='3'>Private</div> </fieldset></td></tr>";
    def += "<tr><td><span class='frmlabel'>Member role: </span></td> <td> <fieldset> <legend>Member role</legend> <div><input type='radio' name='role' id='cmnty_role1' value='1'>Member<input type='radio' name='role' id='cmnty_role2' value='contributor'>Contributor</div></fieldset></td></tr>";
    def += "<tr> <td>&nbsp;</td> <td> <img class='btn' src='/img/save.gif' onClick='updateCommunity();'> <img class='btn' src='/img/cancel.gif' onClick='javascript:window.location=\"/notes/community/"+cid+"\"'> </td> </tr> </table></form>";
    $("#c_defaults").append(def);        
     
    var status = $(data).find('loadfriends').attr('status');
    $("#c_frndsettings").empty();
    $("#community_count").html("Members ("+$(data).find('loadfriends').attr('total')+") ");

    if(status == 'OK') {
        var frnds = new Array();
        $(data).find('friend').each(function(i) {
            var id = $(this).attr('id');
            var fullname = $(this).text();
            var role = $(this).attr('role');            
            var photo = $(this).attr('photo');
            frnds[i] = new Array();
            frnds[i]['id'] = id;
            frnds[i]['fullname'] = fullname;
            frnds[i]['role'] = role;
            frnds[i]['photo'] = photo;
        });
        displaycmntyMembers(0,frnds); 
        var total = $(data).find('loadfriends').attr('total');
        var lmt = 4;
        var pages = Math.ceil(total/lmt);
        if(pages > 1) {
        $("#cmntymemb_pagn").pagination(total, {
            num_edge_entries: 2,
            items_per_page: lmt,
            num_display_entries: pages,        
            callback: function(page_id,jq) { displaycmntyMembers(page_id, frnds); }
        });   
        }
    }
    loadCommunityDetails();
}


function displaycmntyMembers(page,members) {
    var out = "<div style='border: 1px solid #eeeeff;margin-top: 5px;padding: 1px'>";
    out += "<div class='cmntymemb_list'>Community MemberSettings</div><div style='padding: 1px'>";
    out += "<table width='100%'>";
    var start = page*4;

    for(j=start; j < members.length; ++j) {
       if(j < start+4) {
           if(members[j]['fullname'] == "") members[j]['fullname'] = members[j]['id'];
           out += "<tr><td width='6%'><div class=\'thumb_photo\'>";
           out += "<img src="+members[j]['photo']+" height=50 width=50></div></td>";
           out += "<td class='friend_name'><div class='frndname_blk'><a href='/notes/showFriend/"+members[j]['id']+"'>"+members[j]['fullname']+"</a>";
           if(members[j]['role'] == 'me' || members[j]['role'] == 'co') {
              if(members[j]['role'] == 'me') {
                  var cls = 'cmntymemb_left';
              } else {
                  var cls = 'cmntycont_left';
              }
              var rl = (members[j]['role']=='me') ? 'Member' : 'Contributor';
              out += '<span id=one_'+members[j]['id']+' class=\'cmntymemb_blk1\'>';
              out += '<span style=\'width: 200px;\' id=role_'+members[j]['id']+'>('+rl+')</span>';
              out += '<span id=roleedit_'+members[j]['id']+' class='+cls+'>';
              out += '<a href=\'javascript: void(0);\' onclick=\'javascript: editmemberRole("'+members[j]['id']+'","'+rl+'");\'>Edit</a></span></span>';
              out += '<span id=two_'+members[j]['id']+' class=\'cmntymemb_blk2\'><span style=\'width: 200px;\' id=trole_'+members[j]['id']+'></span><span id=troleedit_'+members[j]['id']+' style=\'margin-left: 10px;\'></span></span></div></td></tr>';
           } else {
              out += "(Owner)</div></td></tr>";
           }
       }
    }
    out += "</table></div></div>";
    $("#c_frndsettings").empty();
    $("#c_frndsettings").append(out); 
}


function editmemberRole(id,role) {
    $("#one_"+id).hide();
    $("#two_"+id).show(); 
    var rol = "<span><input type='radio' name='rol_"+id+"' id='cmntyrole1_"+id+"' value='1'>Member</span> <span><input type='radio' name='rol_"+id+"' id='cmntyrole2_"+id+"' value='2'>Contributor</span>";
    var edt = '<a href=\'javascript: void(0);\' onclick=\'javascript: updatememberRole("'+id+'");\'>Save</a>&nbsp;&nbsp;<a href=\'javascript: void(0);\' onclick=\'javascript: cancelmemberRole("'+id+'");\'>Cancel</a>';
    $("#trole_"+id).html(rol);
    if(role=="Member") {
       $("#cmntyrole1_"+id).attr("checked","checked");
    } else {
       $("#cmntyrole2_"+id).attr("checked","checked"); 
    }
    $("#troleedit_"+id).html(edt);
}

function cancelmemberRole(id) {
    $("#one_"+id).show();
    $("#two_"+id).hide();
}
 
function updatememberRole(id) {
    var role = $("input[@name='rol_"+id+"']:checked").val();
    var cid = $("#cid").val();
    startAjax("Updating the Member Role ...");
    $.ajax({url: '/notes/updatememberRole/'+cid+'/'+role+'/'+id, success: function(data) {membroleResp(data,cid,id);}});
}

function membroleResp(data,cid,id) {
     if($(data).find('updaterole').attr('status') == 'OK') {
         $("#two_"+id).hide();
         var rol = $(data).find('role').text();
         if(rol == 'me') {
             var cls = 'cmntymemb_left';
         } else {
             var cls = 'cmntycont_left';
         }
         rol = (rol == 'me') ? 'Member' : 'Contributor';
         var nrol = '<span id=role_'+id+'>('+rol+')</span><span id=roleedit_'+id+' class='+cls+'> <a href=\'javascript: void(0);\' onclick=\'javascript: editmemberRole("'+id+'","'+rol+'");\'>Edit</a></span>';
         $("#one_"+id).html(nrol);
         $("#one_"+id).show();
         stopAjax();
     } else {
         myalert("Error while updating the member role");
     } 
}

function loadCommunityDetails() {
    var cid = $("#cid").val();
    $.ajax({url: '/notes/loadcmntyDetails/'+cid, success: function(data) {loadcmntyDetailsResp(data,cid);}});
}
function loadcmntyDetailsResp(data,id) {
    if($(data).find('communitiesdetail').attr('status') == 'OK') {
        var idd = $(data).find('cid').text();  
        var name = $(data).find('name').text();
        var type = $(data).find('type').text();
        var role = $(data).find('role').text();
        var desc = $(data).find('description').text();
        $("#communityname").val(name);
        $("#communitydesc").val(desc);
        if(type == 'public') {
           $("#cmnty_type1").attr("checked", "checked"); 
        } else if(type == 'moderated') {
           $("#cmnty_type2").attr("checked", "checked"); 
        } else {
           $("#cmnty_type3").attr("checked", "checked");
        }
        if(role == 'member') {
           $("#cmnty_role1").attr("checked", "checked");
        } else {
           $("#cmnty_role2").attr("checked", "checked");
        } 
    } else {
        myalert("Error while loading Community Details");
    }
}

function updateCommunity() {
    var name = $("#communityname").val();
    var description = $("#communitydesc").val();
    var type = $("input[@name='type']:checked").val();
    var role = $("input[@name='role']:checked").val();
    var cid = $("#cid").val();
    startAjax("Updating the Community Deatails ...");
    ajaxPost('/notes/updateCommunity/'+cid,{name: name,description: description,community_type: type,role: role}, updateCommunityResponse);
}
 
function updateCommunityResponse(data) {
    if($(data).find('updatecommunity').attr('status') == 'OK') {
        //cid = $(data).find('id').text();
        //alert("The community details has been updated successfully");
        //window.location = "/notes/community/"+cid;
        stopAjax();
    } else {
        myalert("Error while updating Community Details");
    }
 
}

function joinCommunity(id) {
    window.location = '/notes/joinCommunity/'+id;
}

function inviteCommunityResp(data) {
    stopAjax();
    var success = $(data).find("invitecommunity").attr('status');
    var msg = $(data).find('msg').text();

    if(success == 'OK') {
        hideCategory('inviteCommunity');        
    }
    myalert(msg);
}

function inviteCommunity(community_id) {
    var userid = $("#inviteuserid").val();
    if(userid) {
        var msg = $("#invitemsg").val();        
        startAjax('Inviting ...');
        ajaxPost("/notes/inviteCommunity",{cache: false,userid: userid, communityid: community_id}, inviteCommunityResp);
    } else {
        myalert("UserId can not be empty");
    }
}

function addFriend() {
    var id = $("#friendid").val();
    if(id) { 
        var msg= $("#fiendmsg").val();
        startAjax('Sending Request...');
        $.ajax({url: "/users/addFriend",type: 'POST', dataType: 'xml', data: {cache: false,id:id,description:msg},success: function(data) {
            if(handleSessionTimeout(data)) {
                friendResponse(data);
            }
        }});
        //$.post("/users/addFriend", {cache: false,id: id, description: msg}, function(data) { handleSessionTimeout(data); friendResponse(data); });
    } else {
        myalert("You should specify the Id"); 
    }
}

function inviteFriend(id) {
    if(id) {
        var msg= 'Friend request';
        $.post("/users/addFriend", {cache: false,id: id, description: msg}, function(data) { handleSessionTimeout(data); friendResponse(data); });
    } else {
        myalert("Error in getting the Id");
    }
}

function friendResponse(data) {
    stopAjax();
    var success = $(data).find("addfriend").attr("status");
    if(success == "OK") {
        $("#addFriend").hide();
        myalert("Your request has been sent Successfully");
    } else {
        var sts = $(data).find('status').text();
        myalert(sts);
    } 
    $("#categoryselect").show();
}

function acceptFriend(id) {
    if(id) {
        $.post("/users/acceptFriend", {cache: false,id: id}, function(data) { handleSessionTimeout(data); acceptfrndResp(data); });
    } else {
        myalert("Error in getting the Id");
    } 
}  

function acceptfrndResp(data) {
    var frnd = $(data).find('friend').text();
    var user = $(data).find('user').text();
    if($(data).find('acceptfriend').attr('status') == 'OK') {
        $("#"+frnd).remove();
        loadFriends(user);        
    } else {
        myalert("Error while accepting friend's request");
    }
}

function rejectFriend(id) {
    if(id) {
        $.post("/users/rejectFriend", {id: id}, function(data) { handleSessionTimeout(data); rejectfrndResp(data); });
    } else {
        myalert("Error in getting the ID");
    }
}

function rejectfrndResp(data) {
    var frnd = $(data).find('friend').text();
    if($(data).find('rejectfriend').attr('status') == 'OK') {
        $("#"+frnd).remove();
        myalert(frnd+"'s Request has been rejected");
    } else {
        myalert("Error while rejecting friend's request");
    }
}
function loadFriends(id) {
    $.ajax({url: "/users/loadFriends", dataType: 'xml', data:{id:id},success: function(data) {loadfrndResp(data);}}); 
} 

function loadfrndResp(data) {
    if($(data).find('loadfriends').attr('status') == 'OK') { 
        var user = $(data).find('loadfriends').attr('user');
        var total = $(data).find('count').text();
        var totalcount = $(data).find('loadfriends').attr('totalcount');
        var ttl = $(data).find('loadfriends').attr('total');
        $("#sharednotes_title").html("Shared Notes ("+totalcount+")");
        var page = $("#mypage").val(); 
        if(page == '3') {
            $("#community_count").html("Memebers ("+total+")");
        } else if(page == '5') {
            $("#community_count").html("Contributors ("+ttl+")");
        } else {
            $("#friend_cnt").text("Friends ("+total+")");
        }
        var count = 0;
        if(total == '1') {
           $("#friends_list").show();
        }
        var lst ="<table cellspacing=\'3\' cellpadding=\'0\' class=\'frnds_tbl\'>";
        friendsresponse = data;
        $(data).find('friend').each(function(i) { 
        if(i < 4) { 
            var id = this.getAttribute('id');
            var photo = this.getAttribute('photo');
            var latestcount = this.getAttribute('latestcount');
            var online = this.getAttribute('online');
            var frnd = $(this).text();      
            frnd = (frnd)? frnd : id;            
            name = (page == '2' || page == '3' || page == '5') ? frnd : frnd+"("+latestcount+")";
            lst += "<tr>";
            lst += "<td class=\'friend_photo\'><div class=\'thumb_photo\'>";
            lst+= "<img src="+photo+" height=55 width=50></div></td>";
            lst += "<td class=\'friend_name\'><div class=\'frndname_blk\'>";
            lst += "<a class=\'frndlnk\' href=\'/notes/showFriend/"+id+"\' id=friend_"+id+">";
            lst += name+"</a>";
            if(online == 'true') {
                lst += "<br/><span style='color: green' class='note_small'>(online)</span>"; 
            } else {
                lst += "<br/><span style='color: gray' class='note_small'>(offline)</span>"; 
            }
            lst += "<div></td>";
            lst += "</tr>";
            count = i+1; 
        } else {
            lst += "<tr><td colspan=2 class='moreblk' align=right><a href='#' id='friendmore'>More>></a></td></tr>";
             return false;
        }
        });
        lst += "</table>";
        $("#friends_list").html(lst);
        $("#friendmore").click(function() {
            if(user) {
                window.location = '/users/searchFriends/'+user;           
            } else {                
                var cid = $(data).find('loadfriends').attr('cid');
                if(page == '5') { 
                    window.location = "/users/searchCommunityFriends/"+cid+'/true';
                } else { 
                    window.location = "/users/searchCommunityFriends/"+cid+'/false';
                }
            }
        });
    } else {
        $("#friends_list").hide();
    }
}

function loadContributors(id) {
    ajaxCall('/notes/loadContributors/'+id,{cache: false},loadfrndResp);
}

function loadCalendar(ondate,oncategory,onpage,id) {
    if(onpage == 3) { 
        data = {cid: $("#communityid").val(),cache: false,dat: ondate, notebook: oncategory, page: onpage,extraid: id};
    } else {
        data = {cache: false,dat: ondate, notebook: oncategory, page: onpage,extraid: id};   
    } 
    ajaxCall('/notes/loadCalendar',data,loadCalendarResp);
}

function sessiontimeout() {
   myalert('Your Session Expired Please Login Again');
   $("#myalertok").attr('onclick','');
   $("#myalertok").click(function() { window.location = '/'; });
}

function loadCalendarResp(data) {
    if(data == 'sessiontimeout') {
        myalert('Your Session Expired Please Login Again');
        $("#myalertok").attr('onclick','');
        $("#myalertok").click(function() { window.location = '/'; });
    } else {
        $("#calendar_blk").removeClass('loadingblk');
        $("#calendar_blk").html(data);
    }
}

function loadNotes(ondate,oncategory,onpage,id) {
    var data = {cache: false, dat: ondate, notebook: oncategory, page: onpage,extraid: id};
    loadNoteBook(oncategory,data);
}

function displayPage(i,communities,blk) { 
    var html = "";
    var start = i*20;
    var i = 0;

    for(j=start; j<communities.length; ++j) {
        if(j < start+20) {
            html += "<div style='border: 1px solid #ccc; float: left; margin: 15px;'><table><tr>";
            var name = communities[j]['name'];
            var id = communities[j]['id'];
            var count = communities[j]['count'];
            html += "<td class='friend_photo'><div class='thumb_photo'><img src="+communities[j]['photo']+" height=50 width=50></div></td><td class='friend_name'><div class='frndname_blk'>";
            html += "<a class='frndlnk' href='/notes/community/"+id+"'><b>"+name+"&nbsp;("+count+")</b></a></div></td></tr></table></div>";                     
        } else { 
            break;
        }
        ++i;
    }
     
    html += "</table>";
    var cont = "allcommunities";
    
    if(blk == "communities_result") {
        cont = "searchcommunityresult";
    }     
    $("#"+cont).html(html);
    $("#"+cont).height(i/4*130);
}

function dispunjoinedCommunities() {
    ajaxCall('/notes/loadCommunities/true',{cache: false},unjoinedCommunities);
}

function hideunjoinedCommunities() {
    $("#allcommunitiesblk").hide();
    $("#unj_list").html("<a href='javascript: void(0);' onclick='javascript:showunjoinedCommunities()'>Show Other Communities</a>");
}

function showunjoinedCommunities() {
    $("#allcommunitiesblk").show();
    $("#unj_list").html("<a href='javascript: void(0);' onclick='javascript:hideunjoinedCommunities()'>Hide</a>");
}

function unjoinedCommunities(data) {
    displayPaginationData(data,'allcommunitiesblk');   
    if($("#communitiesblk").height() < 340) $("#communities_blk").height(340);
}

function loadAllCommunities() {
    ajaxCall('/notes/loadCommunities',{cache: false},listAllCommunities);
}

function listAllCommunities(data) {
    displayPaginationData(data,'mycommunitiesblk');   
    if($("#communitiesblk").height() < 340) $("#communities_blk").height(340);
}

function displayPaginationData(data,container) {
    var html = "<div id='Pagination2' class='pagination' style='margin-left: 25px;width: 500px;'></div>";

    html += "<div id='searchcommunityresult'>";
     
    
    var communities = new Array();
    var sessid = $(data).find('communities').attr('sessid'); 
    $(data).find('community').each(function(i) {             
        var name = $('name',this).text(); 
        var id = this.getAttribute('id'); 
        var photo = this.getAttribute('photo');
        var count = this.getAttribute('members');
        var type = $('type',this).text(); 
        var owner = $('owner',this).text();  
        communities[i] = new Array();
        communities[i]['name'] = name;
        communities[i]['id'] = id;
        communities[i]['photo'] = photo;
        communities[i]['description'] = $('description',this).text();
        communities[i]['type'] = type;
        communities[i]['count'] = count;

        if(sessid == owner) {
            communities[i]['edit'] = true;
        } else {
            communities[i]['edit'] = false;
        }
    });    
    html += "</div>";

    if(container) {
        $("#"+container).empty().html(html);
    } else {
        $.extend($.blockUI.defaults.pageMessageCSS, { width:'400px', height:'auto', margin:'-50px 0 0 -125px', padding:'0px 0px 10px 0px', top:'50%', left:'50%', textAlign:'center', color:'#000', backgroundColor:'#fff', border:'3px solid #11a3da'});
        $.extend($.blockUI.defaults.displayBoxCSS, { width: '400px', height: '400px', top:'50%', left:'50%'});
        $.blockUI(html);
    }
    displayPage(0,communities,container);
    /*var total = $(data).find('communities').attr('total');
    var n = 4;
    n = 20;

    pages = Math.ceil(total/n);

    if(pages > 1) {
      if(container == "mycommunitiesblk") { 
            $("#Pagination1").pagination(total, {
            num_edge_entries: 2,
            items_per_page: 4,
	    num_display_entries: pages,        
            callback: function(page_id,jq) { displayPage(page_id,communities,container); }
            });       
        } else {
            $("#Pagination2").pagination(total, {
            num_edge_entries: 2,
            items_per_page: n,
            num_display_entries: pages,        
            callback: function(page_id,jq) { displayPage(page_id,communities,container); }
            }); 
        }
    }*/
}

function showMoreCommunities(data) {
    displayPaginationData(data,false);   
}

function newAddCommunity(id) {
    var blk = '<div id=\'addCommunity\' style=\'height: 200px; dispaly: block; visibilty: visible;\'> <form> <table cellpadding=3> <tr> <td>&nbsp;</td><td><div id=\'community_msg\' class=\'small_txt\'></div></td></tr><tr><td> <span class=\'small_txt\'>Name</span> </td><td> <span><input type=\'text\' style=\'width: 190px;\' id=\'communityname\'></span> </td>  </tr>  <tr> <td><span class=\'small_txt\'>Description: </span></td> <td>  <span><textarea id=\'communitydesc\' style=\'width: 190px;\' rows=2 cols=21></textarea></span> </td> </tr><tr> <td><span class=\'small_txt\'>Type:</span></td><td><fieldset> <legend>Type of Community</legend> <div><input type=\'radio\' name=\'type\' id=\'cmnty_type1\' value=\'1\' checked=\'checked\'>Public</div> <div><input type=\'radio\' name=\'type\' id=\'cmnty_type2\' value=\'2\'>Moderated</div> <div><input type=\'radio\' name=\'type\' id=\'cmnty_type3\' value=\'3\'>Private</div></fieldset> </td> </tr> <tr> <td>&nbsp;</td> <td> <img class=\'btn\' src=\'/img/save.gif\' onClick=\'newaddCommunity("'+id+'");\'>&nbsp;&nbsp;<img class=\'btn\' src=\'/img/cancel.gif\' onClick=\'hideaddCommunity("'+id+'");\'> </td> </tr> </table> </form></div>';
    //$("#"+id).html(blk);
    $("#"+id).append(blk);
    $("#community_msg").empty();
    if(id == 'dispcmnty') {
       var x = findPosX(document.getElementById("addcmnty"))-100;
       var y = findPosY(document.getElementById("addcmnty"))+20;
    } else { 
       var x = findPosX(document.getElementById("communitylist"))-105;
       var y = findPosY(document.getElementById("communitylist"))+5;
    }
    sm = $("#addCommunity");
    sm.css("left",x+"px");
    sm.css("top",y+"px");
    sm.css("width","300px");
    sm.css("height","250px");
    sm.css("display","inline");
    sm.css("visibility","visible");
    $("#communityname").val("");
    $("#communitydesc").val("");
}

function newaddCommunity(id) {
    startAjax('Saving ...');
    name = $("#communityname").val();
    description = $("#communitydesc").val();
    type = $("input[@name='type']:checked").val();
    if(id == "dispcmnty") {
        ajaxPost('/notes/addCommunity',{name: name,description: description,community_type: type}, addCommunityResp);
    } else {
        ajaxPost('/notes/addCommunity',{name: name,description: description,community_type: type}, addCommunityResponse);
    }
}

function newCommunity() {
    startAjax("Saving ...");
    var name = $("#communityname").val();
    if(name) {
        var description = $("#communitydesc").val();
        var type = $("input[@name='type']:checked").val();
        var role = $("input[@name='role']:checked").val();
        ajaxPost('/notes/addCommunity',{name: name, description: description, community_type: type, role: role}, newCommunityResp);
    } else {
        myalert("You have not specified the community name");
    }
}

function newCommunityResp(data) {
    if($(data).find('communities').attr('status') == 'OK') {
        window.location.reload();
    }
}

function addCommunityResp(data) {  
    stopAjax();
    var msg;
    handleSessionTimeout(data)
    var stats =$(data).find('communities').attr('status');
    if(stats == 'OK') {  
       loadAllCommunities(); 
    } else {
       msg = $(data).find('error').text(); 
       $("#community_msg").html(msg);
    }
}

function hideaddCommunity() {
    $("#addCommunity").hide();
}

function loadcmntyNotebooks(cid) {
    $.ajax({url: '/notes/listCommunitynotebooks/'+cid, success: function(data) {
            cmntynoteList(data,cid);
            
            }
        });
}


function cmntynoteList(data,id) {
    var dnotebkid = $(data).find("categories").attr("dnotebk");
    var out = '<div style=\'border: 1px solid #eeeeff;margin-top: 5px;padding: 1px; height: auto\'>';
    out += '<div class=\'cmntymemb_list\'>Community NotebookSettings</div>';
    out += '<div style=\'padding: 1px\'><table width=100% cellpadding=2 cellspacing=3>'; 
    $(data).find('category').each(function() { 
        var id = this.getAttribute('id');
        var name = this.getAttribute('name');
        var checked= this.getAttribute('checked');
        //out += "<tr><td class='friend_name'><img hspace=4 align='absbottom' src='/img/notebook.png'/>";
        out += '<tr><td class=\'friend_name\'>';
        out += '<input type=\'radio\' name=\'dflt\' id=\'cbk_'+id+'\' value=\''+id+'\' onchange=\'javascript: updateDnotebk("'+id+'");\'>';    
        out += '<span id=\'cnot1_'+id+'\'><span>'+name+'</span> &nbsp;&nbsp; &nbsp;&nbsp;<a href=\'javascript: void(0);\' onclick=\'javascript: editcmntyNotebk("'+id+'");\'>Edit</a></span>';
        out += '<span id=\'cnot2_'+id+'\' style=\'display: none\'><input id=\'cnotname_'+id+'\' type=\'text\' value=\''+name+'\'>';
        out += '&nbsp;&nbsp;<a href=\'javascript: void(0);\' onclick=\'javascript: updatecmntyNotebk("'+id+'");\'>Save</a>&nbsp;&nbsp;<a href=\'javascript: void(0);\' onclick=\'javascript: cancelcmntyNotebk("'+id+'");\'>Cancel</a> </span>';
        out += '</td></tr>';
        }
    );
    out += '</table></div></div>';
    $("#c_notesettings").html(out);           
    $("#cbk_"+dnotebkid).attr("checked","checked");
    $("#did").val(dnotebkid); 
}

function editcmntyNotebk(id) {
    $("#cnot1_"+id).hide();
    $("#cnot2_"+id).show(); 
} 

function updatecmntyNotebk(id) {
    var bk = $("#cnotname_"+id).val();
    startAjax("Updating the Notebook Name...");
    $.ajax({url: '/notes/updatecmntyNotebk/'+id+'/'+bk, success: function(data) {updteNotebkResp(data);}  });
}

function updteNotebkResp(data) {
    
    if($(data).find('updatenotebk').attr('status') == 'OK') {
        var name = $(data).find('name').text();
        var id = $(data).find('id').text();
        $("#cnot2_"+id).hide();
        var edt = '<span>'+name+'</span>&nbsp;&nbsp;&nbsp;&nbsp; <a href=\'javascript: void(0);\' onclick=\'javascript: editcmntyNotebk("'+id+'");\'>Edit</a></span>';
        $("#cnot1_"+id).html(edt);
        stopAjax(); 
        $("#cnot1_"+id).show();   
    } else {
        myalert("Error while updating the Notebook Name");
    }
}

function cancelcmntyNotebk(id) {
    $("#cnot1_"+id).show();
    $("#cnot2_"+id).hide();
}

function updateDnotebk(id) {
    var bk = $("#cnotname_"+id).val();
    confrm('Want to set '+bk+' as default Notebook?');
    $('#yes').click(function() {
        $.unblockUI();
        startAjax("Updating the default Notebook ...");
        var cid = $("#cid").val();
        $.ajax({url: '/notes/updateDefaultbk/'+id+'/'+cid, success: function(data) {updateDnotebkResp(data);}});
    });    
    $('#no').click(function() {
        $.unblockUI();
        var dflt = $("#did").val();
        $("#cbk_"+dflt).attr("checked","checked");    
    });
}

function updateDnotebkResp(data) {
    if($(data).find("updatebkid").attr("status") == "OK") {
        stopAjax();
        var bkid = $(data).find("bookid").text();
        $("#did").val(bkid); 
    } else {
        stopAjax();
        myalert("Error While updating the default Notebook");
    }
}

function shareNoteFrnd(uid,fid) {   
    tinyMCE.triggerSave(true,true);
    var savenoteform = document.savenotefrm;
    document.savenotefrm.submit();
}

function acceptCommunityResp(data) {
    if($(data).find('respcommunity').attr('status') == 'OK') {
        cid = $(data).find('communityid').text();
        $("#invitation_"+cid).hide();    
        loadCommunities();
    }
}

function rejectCommunityResp(data) {
    if($(data).find('respcommunity').attr('status') == 'OK') {
        cid = $(data).find('communityid').text();
        $("#invitation_"+cid).hide(); 
    }
}

function acceptCommunity(cid) {
    ajaxCall('/notes/respCommunity',{cache: false,cid: cid, status: 'acc'},acceptCommunityResp);    
}

function rejectCommunity(cid) {
    ajaxCall('/notes/respCommunity',{cache: false,cid: cid, status: 'rej'}, rejectCommunityResp);
}

function photoUpload() {
    var file = $("#file").val();
    var tmp = file.split(".");
    var ext = tmp[1];
    if(ext == 'png'|| ext == 'PNG'|| ext == 'gif'|| ext == 'GIF'|| ext == 'jpg'|| ext == 'JPG'|| ext == 'jpeg'|| ext == 'JPEG') {
        $("#uploader").submit();
    } else {
        myalert("Please select files of format png,gif or jpeg");
    }
}
function subscribeFriend(user,frnd) {
    ajaxCall('/users/subscribeFriend',{cache: false,userid: user, friendid: frnd},subscribeResp);
}

function subscribeResp(data) {
    if($(data).find('subscribefriend').attr('status') == 'OK') {
        $("#subscribe_message").remove();
    } else {
        myalert("Remote Call Error");
    }
}

function rejectSubscription(user,frnd) {
     ajaxCall('/users/rejectSubscription',{cache: false,userid: user, friendid: frnd},rejsubscribeResp);
}

function rejsubscribeResp(data) {
    if($(data).find('rejsubscribefriend').attr('status') == 'OK') {
        $("#subscribe_message").remove();
    } else {
        myalert("Remote Call Error");
    }
}

function moveNote(id,user) {
    
    var page = $("#mypage").val();
    var quest = "<table width=\'100%\' cellspacing=\'0\' cellpadding=\'0\'><tr><td height=\'12px\' style=\'background-color: #11a3da;\'><span style=\'float: left;color: #ffffff;font-weight: bold;margin-left:5px \'>Move Note</span><span style=\'float: right;color: #ffffff;font-weight: bold; cursor:pointer\' onclick=\'$.unblockUI()\'>X</span></td></tr>";
    quest +="<tr><td height=\'12px\'></td></tr>"  
    quest +="<tr><td height=\'25px\' align=\'left\'><div style=\'color: #000;font-weight: bold;margin-left: 25px\'>Notebooks:</div></td></tr>"  
    //quest += "<tr><td align=\'left\'><div style=\'margin-left: 20px\'> <select id = \'selectlist\' style=\'width: 155px;\' onchange=\"move(\'"+id+"\',\'"+user+"\',\'"+page+"\') \"><option value=\'mynote\'>My Notes</option></select></div><br></td></tr>";
    quest += "<tr><td align=\'left\'><div style=\'margin-left: 20px\' id=\'notmovelist\'></div><div style=\'margin-left: 20px;display: none\' id=\'commovelist\'></div></td></tr>"; 
    quest += "<tr><td align=\'center\'><br>"
    quest += "<table><tr><td><div id=\'yes\' href=\'javascript: void(0);\' class=\'bg55\'; onclick=\'moveselectNote()\'>Ok</div></td>"
    quest += "<td><div id=\'no\' href=\'javascript: void(0);\' class=\'bg55\' onclick=\'$.unblockUI()\'>Cancel</div></td></tr></table>"
    quest += "</td></tr>";
    quest += "</table><input id =\'movenoteid\' type=\'hidden\' value='"+id+"'><input id =\'moveuserid\' type=\'hidden\' value='"+user+"'><input id =\'movefromid\' type=\'hidden\' value=''><input id =\'movetoid\' type=\'hidden\' value=''>";

    $.extend($.blockUI.defaults.overlayCSS, { backgroundColor: '#fff', opacity: '0.0'});
    $.extend($.blockUI.defaults.pageMessageCSS, { width:'400px', height:'auto', margin:'-50px 0 0 -125px', padding:'0px 0px 10px 0px', top:'30%', left:'30%', textAlign:'center', color:'#000', backgroundColor:'#fff', border:'3px solid #11a3da'});
    $.extend($.blockUI.defaults.displayBoxCSS, { width: '600px', height: '800px', top:'30%', left:'30%'});
    $.blockUI(quest);
    $.ajax({url: '/notes/listCommunities/'+user, success: function(data) {
        var cnt = $(data).find("community").each(function() {
            var id = $('id',this).text();
            var name = $('name',this).text();
            var did = $('did',this).text();
            var apnd = "<option value='"+id+"'>"+name+"</option>";
            $("#selectlist").append(apnd);
        });
    }});
    move(id,user,page);
}

function move(id,user,page) {
    //var opt = $('#selectlist option:selected').text();
    //var val  = $('#selectlist option:selected').val();
    if( page == '1') { 
            $.ajax({url: '/notes/listNotebooks/'+user, success: function(data) {
                movenoteResp(data,id,user,page);
            }
            });
    } else {
            var cid = $("#communityid").val();
            $.ajax({url: '/notes/listNotebooks/',data: {cid: cid},success: function(data) {
                movenoteResp(data,id,user,page);
            }
            });
    }

}

function movenoteResp(data,id,user,page) {
    var page = $("#mypage").val();
    $("#notmovelist").html('');
    var tab = $("#notebooktitle").val();
    var bk = (page =='1') ? $("#notebook").val() : $("#cnotebook").val();
    //$("#selectlist").val(tab);
    $(data).find('category').each(function() { 
        var id = this.getAttribute('id');
        var name = this.getAttribute('name');
        if(bk == id) {
           $("#movefromid").val(id);
           var select = "<input id='from_book' type='radio' name='notebook' value="+id+" checked><span style='background: #ccc;padding: 2px 5px 2px 2px'>"+name+"</span><br>";
        } else {
           var select = "<input type='radio' name='notebook' value="+id+" onClick=\" \">"+name+"<br>";
        }
        $("#notmovelist").append(select);
        $("#notmovelist").show();
        $("#commovelist").hide();
    });
}

function moveselectNote() {
    var page = $("#mypage").val();
    var list = $("input[@name='notebook']:checked").val();
    //var list = $("input[@name='notebook']:checked").val();
    var old = $("#from_book").val();
    //startAjax('Moving ...');

    var note = $("#movenoteid").val();
    ajaxCall('/notes/moveNote',{noteid: note,listid: list,page :page},moveNoteResp);
}

function moveNoteResp(data,page) {
    //stopAjax();
    if($(data).find('movenote').attr('status') == 'OK') {
        noteid = $(data).find('note').text();
        //listid = $(data).find('list').text(); 
        title = $(data).find('title').text(); 
        $("#move_"+noteid).empty();
        $("#movebtn_"+noteid).show();
        //$("#notebooktitle").val(title);
        var page = $("#mypage").val();
        var listid = (page =='1') ? $("#notebook").val() : $("#cnotebook").val();
        //listid = $("#notebook").val(); 
        loadNoteBook(listid,{cache: false,page: $("#mypage").val()});
        //selectNotebook(listid,0);
    } else {
        myalert("Error while moving the note");
    }
}



function closeMove() {
    if($("#movelist").length > 0) {
        var prev =$("#movelist").parent().attr('id'); prev = prev.split("_");
        var previd = prev[1];
        $("#move_"+previd).empty();
        $("#movebtn_"+previd).show();
    }     
    return true;
}



function movesharedNote(id,user) {
        $.ajax({url: '/notes/listNotebooks/'+user, success: function(data) { 
            mvsharedResp(data,id,user);
        }
        });
}

function mvsharedResp(data,id,user) {
    var out = "";
    var out = "<input id =\'movenoteid\' type=\'hidden\' value='"+id+"'>";
    out += "<select id = \'movelist\' class= \'frm_select\' onChange=\'selectsharedNote()\'>";
    $("#movebtn_"+id).hide();
    $("#move_"+id).html(out);
    var did = 'shared';
    var dname = 'Shared Notes';
    var dselect = "<option value="+did+">"+dname+"</option>";
    $("#movelist").append(dselect);
    $("#movelist").val(did);
    $(data).find('category').each(function() { 
        var id = this.getAttribute('id');
        var name = this.getAttribute('name');
        var select = "<option value="+id+">"+name+"</option>";
        $("#movelist").append(select);
    }); 
}

function selectsharedNote() {
    var txt = $('#movelist option:selected').text(); 
    var list = $("#movelist").val();

    var note = $("#movenoteid").val();
    startAjax('Moving ...');
    ajaxCall('/notes/sharedMove',{noteid: note,listid: list, book: txt},sharemoveResp);
}

function sharemoveResp(data) {
    stopAjax();
    if($(data).find('sharedmove').attr('status') == 'OK') {
        var noteid = $(data).find('note').text();
        var listid = $(data).find('list').text(); 
        var listname = $(data).find('name').text(); 
        $("#move_"+noteid).empty();
        $("#movebtn_"+noteid).show();
        $("#notebook").val(listid);
        $("#notebooktitle").val(listname);
        loadNoteBook(listid,{cache: false,page: $("#mypage").val()});
        selectNotebook(listid,0);  
    } else {
        myalert("Error while moving the note");
    } 
}

function closesharedMove() {
    if($("#movelist").length > 0) {
        var prev =$("#movelist").parent().attr('id'); prev = prev.split("_");
        var previd = prev[1];
        $("#move_"+previd).empty();
        $("#movebtn_"+previd).show();
    }     
    return true;
}




function moderatedCallback(data) {
    if($(data).find('moderatedcommunity').attr('status') == 'OK') {
        $("#message1").hide();
    }
}

function moderatedCommunity(cid,member,allow) {
   ajaxCall('/notes/moderatedCommunity/'+allow,{cache:false,cid: cid, member: member},moderatedCallback);
}

function nameCheck() {
   if($("#UserName").val()) {
       var name = $("#UserName").val();
       if(name.length >= 4) {
           $.ajax({url: '/users/checkName/'+name, success: function(data) {namecheckResp(data);}});
       }
   }
}

function namecheckResp(data) {
    if($(data).find('username').attr('status') == 'OK') {
        var nm = $(data).find('name').text();
        $("#namechk").text(nm+" is Available");
        
        if($("#namechk").attr("class") == "error-message") {
            $("#namechk").removeClass("error-message");
        }
        $("#namechk").addClass("available");
        
        if($("#avail").length > 0) {
           $("#avail").val('true');
           $("#avail").remove();
           $("#hold").append("<input type='hidden' id='avail' value='true'>");
        } else {
           $("#hold").append("<input type='hidden' id='avail' value='true'>");
        }
    } else {
        var nm = $(data).find('name').text();
        $("#namechk").text(nm+" is not Available");
        if($("#namechk").attr("class") == "available") {
            $("#namechk").removeClass("available");
        }
        $("#namechk").addClass("error-message");
        if($("#avail").length > 0) {
           $("#avail").remove();
           $("#hold").append("<input type='hidden' id='avail' value=false");
        } else {
           $("#hold").append("<input type='hidden' id='avail' value=false");
        }
        
    }
}

function searchSkriberFriends() {
    var tag = $("#searchskriberfrnds").val();
    startAjax("Loading ...");
    ajaxCall("/users/searchSkriberFriends",{cache: false,tag: tag},searchSkriberResp);
}

function searchSkriberResp(data) {
    stopAjax();
    if($(data).find('search_response').attr('status') == 'OK') {        
        var tag = $(data).find('search_response').attr('tag');
        $("#wrapper .searchresult").show();

        if($(data).find('search_response').attr('count') == '0') {
            var msg = "There were no results to display for "+tag;
            var html = "<div id='morefriends' style='padding: 10px;'>";
            html += "<div style='padding: 25px;text-align: center;'>"+msg+"</div>";
            html +="</div>";
            $("#wrapper .searchresult").html(html);
        } else {
            createFriendsList(data);
        }
    } else {
        myalert("Error Search");
    }
}

function searchSkriberCommunities() {
    var tag = $("#searchcommunities").val();
    startAjax("Loading ...");
    ajaxCall("/notes/searchSkriberCommunities",{cache: false,tag: tag},listMyCommunities1);
}

function searchCommunitiesResp(data) {
    stopAjax();
    if($(data).find('communities').attr('status') == 'OK') {
        var tag = $(data).find('communities').attr('tag');
        $("#wrapper .searchresult").show();

        if($(data).find('communities').attr('count') == '0') {
            var msg = "There were no results to display for "+tag;
            var html = "<div id='morefriends' style='padding: 10px;'>";
            html += "<div style='padding: 25px; text-align: center;'>"+msg+"</div>";
            html += "</div>";
            $("#wrapper .searchresult").html(html);        
        } else {
            displayPaginationData(data,'communities_result'); 
        }
    }
}


function createFriendsList(data) {
    var html = "<div id='morefriends' style='padding: 10px;'>";
    var j=0;
    
    $(data).find('friend').each(function(i) {
        html += "<div style='float: left; border: 1px solid #ccc; margin: 15px;'>";
        html += "<table><tr>"; 
        var firstname = $(this).text();
        var lastname = $(this).attr('lastname');
        var userid = $(this).attr('name');
        var email = $(this).attr('email'); 
        
        var name = firstname+" "+lastname;
        html += "<td class='friend_photo'><div class='thumb_photo'><img src='"+$(this).attr('photo')+"' height=50 width=50></div></td><td class='friend_name'><div class='frndname_blk'>";
        html += "<a class='frndlnk' href='/notes/showFriend/"+userid+"'>"+name+"</a></div><div align=right style='margin-top: 10px'><a style='text-decoration: none;' href='javascript: inviteFriend(\""+userid+"\");'>Invite</a></div></td>";       
        html += "</tr></table>";
        html += "</div>";
        ++j;
    });
    html += "</div>";     
    $("#wrapper .searchresult").html(html);
    if(j < 4) j =4;
    $("#wrapper .searchresult").height(j/4*100);
}

function loadMyfriends(user) {
    ajaxCall('/users/loadFriends',{cache: false,id:user},loadMyfriendsResp);
}


function displayClientPage(i,clients) {
    var start = i*20;
    var html = "";
    var i = 0;

    for(j=start; j < clients.length; ++j) {
        if(j < start+20) {
            html += "<div style='border: 1px solid #ccc; float: left; margin: 15px;'><table><tr>";              
            var name = clients[j]['name'];
            var id = clients[j]['id'];
            html += "<td class='friend_photo'><div class='thumb_photo'><img src="+clients[j]['photo']+" height=50 width=50></div></td><td class='friend_name'><div class='frndname_blk'>";
            html += "<a class='frndlnk' href='/notes/showFriend/"+id+"'>"+name+"</a>";
            if(clients[j]['online'] == 'true') {
                html += "<br/><span style='color: green' class='note_small'>(online)</span>"; 
            } else {
                html += "<br/><span style='color: gray' class='note_small'>(offline)</span>"; 
            }
            html += "</div></td></tr></table></div>";
            ++i;
        } else {
           break;
        }
    }
    if(i < 4) i =4;
    $("#moreclients").html(html);
    $("#moreclients").height(i/4*130);
}


function loadMyfriendsResp(data) {
    var html = "<div id='Pagination' align=center class='pagination' style='margin-bottom: 50px; margin-top: 20px; margin-left: 25px;'></div>";
    html += "<div id='moreclients' style='padding: 10px;'>";
    var friends = new Array();

    $(data).find('friend').each(function(i) {
        var id = this.getAttribute('id');
        var name = $(this).text();
        var photo = this.getAttribute('photo');
        friends[i] = new Array();
        friends[i]['id'] = id;
        friends[i]['name'] = name;
        friends[i]['photo'] = photo;
        friends[i]['online'] = this.getAttribute('online');  
    });
    html += "</div>";
    $("#mynotes_container").empty().html(html);
    displayClientPage(0,friends);
    var total = $(data).find('count').text();
    pages = Math.ceil(total/20);

    $("#Pagination").pagination(total, {
        num_edge_entries: 2,
        items_per_page: 20,
        num_display_entries: 4,
        callback: function(page_id,jq) {
            displayClientPage(page_id, friends);
        }
    });
}

function SetProperties(xElem,xHidden,xserverCode,xignoreCase,xmatchAnywhere,xmatchTextBoxWidth,xshowNoMatchMessage,xnoMatchingDataMessage,xuseTimeout,xtheVisibleTime) {
    var props = {
        elem: xElem,
        hidden: xHidden,
        serverCode: xserverCode,
        regExFlags: ((xignoreCase) ? "i" : ""),
        regExAny: ((xmatchAnywhere) ? "^" : ""),
        matchAnywhere: xmatchAnywhere,
        matchTextBoxWidth: xmatchTextBoxWidth,
        theVisibleTime: xtheVisibleTime,
        showNoMatchMessage: xshowNoMatchMessage,
        noMatchingDataMessage: xnoMatchingDataMessage,
        useTimeout: xuseTimeout
    };
    AddHandler(xElem);
    return props;
}

var isOpera = (navigator.userAgent.toLowerCase().indexOf('opera') != -1);

function AddHandler(objText) {
    objText.onkeyup = GiveOptions;
    objText.onblur = function() {
        if(this.obj.useTimeout) StartTimeout();
    }
    if(isOpera) objText.onkeypress = GiveOptions;
}

var strLastValue = "";
var bMadeRequest;
var theTextBox;
var objLastActive;
var currentValueSelected = -1;
var bNoResults = false;
var isTiming = false;

function GiveOptions(e) {
    var intKey = -1;
    if(window.event) {
        intKey = event.keyCode;
        theTextBox = event.srcElement;
    } else {
        intKey = e.which;
        theTextBox = e.target;
    }    

    if(theTextBox.value.length == 0 && !isOpera) {        
        initialFrndList();
        return false;
    }

    if(intKey == 13) {
        GrabHighlighted();
        theTextBox.blur();
        return false;
    } else if(intKey == 38) {
        MoveHighlight(-1);
        return false;
    } else if(intKey == 40) {
        MoveHighlight(1);
        return false;
    }
     
    BuildList(theTextBox.value); 
    
}

function BuildChoices() {
    BuildList(strLastValue);
    bMadeRequest = false;
}

function BuildList(theText) {
    var theMatches = MakeMatches(theText);
    theMatches = theMatches.join().replace(/\,/gi,"");
    
    if(theMatches.length > 0) {
        document.getElementById("spanOutput").innerHTML = theMatches;
        document.getElementById("OptionsList_0").className = "spanHighElement";
        currentValueSelected = 0;
        bNoResults = false;
    } else {
        currentValueSelected = -1;
        bNoResults = true;
        if(theTextBox.obj.showNoMatchMessage)
            document.getElementById("spanOutput").innerHTML = "";
        else
            var x;
    }
}

var countForId = 0;

function MakeMatches(xCompareStr) {
    countForId = 0;
    var matchArray = new Array();
    var regExp = new RegExp(theTextBox.obj.regExAny + xCompareStr, theTextBox.obj.regExFlags);

    for(var i in arrOptions) {       
        var theMatch = arrOptions[i].match(regExp);

        if(theMatch) {            
            matchArray[matchArray.length] = CreateUnderline(i, xCompareStr,i);
        }
    }

    return matchArray;
}

var undeStart = "<span class='spanMatchText'>";
var undeEnd = "</span>";

var selectSpanStart = "<div style='width: 100%; display: block;' class='spanNormalElement'";
var selectSpanEnd = '</div>';

function CreateUnderline(xStr,xTextMatch,xVal) {
    selectSpanMid = "onclick='selectItem(this); '"+"id='OptionsList_"+countForId+"' name='"+xStr+"' theArrayNumber = '"+xVal+"'>";
    xStr = arrOptions[xStr];
    var regExp = new RegExp(theTextBox.obj.regExAny + xTextMatch, theTextBox.obj.regExFlags);
    var aStart = xStr.substring(aStart,aStart+xTextMatch.length);
    var matchedText = xStr.substring(aStart,aStart+xTextMatch.length);
    matchedText = "<span style='float:left'>"+matchedText+"</span><span class='closeright' onclick='moveSelectedtoLeft("+countForId+")' style='visibility:hidden'>x</span>";
    countForId++;
    return selectSpanStart+selectSpanMid+xStr.replace(regExp,undeStart + matchedText + undeEnd) + selectSpanEnd;
}

function selectItem(elem) {
    var id = $(elem).attr('id');
    xVal = id.split('_')[1];        
    
    if(elem.className == 'spanHighElement') {
        $(elem).removeClass('spanHighElement');       
        $(elem).addClass('spanNormalElement');
    } else {
        currentValueSelected = xVal;
        SetHighColor(null);
    }
}

function MoveHighlight(xDir) {
    if(currentValueSelected >= 0) {
        newValue = parseInt(currentValueSelected) + parseInt(xDir);
        if(newValue > -1 && newValue < countForId) {
            currentValueSelected = newValue;
            SetHighColor(null);
        }
    }
}

function SetHighColor(theTextBox) {
    if(theTextBox) {
        currentValueSelected = theTextBox.id.slice(theTextBox.id.indexOf('_')+1, theTextBox.id.length);
    }
    
    $('#OptionsList_'+currentValueSelected).attr('class', 'spanHighElement');
}

function SetText(xVal) {
    
}

function GrabHighlighted() {
}

function HideTheBox() {
    document.getElementById("spanOutput").style.display = "none";
    currentValueSelected = -1;
    EraseTimeout();
}

function EraseTimeout() {
    clearTimeout(isTiming);
    isTiming = false;
}

function StartTimeout() {
    //isTiming = setTimeout("HideTheBox()", theTextBox.obj.theVisibleTime);
}

function moveSelectedtoRight() {
    $("#spanOutput").find('div').each(function() {
        if($(this).attr('class') == 'spanHighElement') { 
            var id = $(this).attr('name');                       
            arrOptions1[id] = $(this).text(); 
            delete arrOptions[id];           
            $(this).clone().appendTo("#spanOutputRight");
            $(this).remove();
        }
    });
    $("#spanOutputRight .closeright").each(function() {
        $(this).css('visibility','visible');
    });
}

function moveSkriberIdtoRight() {
    var ids = $("#shareids").val();
    if(ids == "Enter Skriber IDs separated by comma") {
        myalert('Please Enter Skriber IDs');
        return;
    }
    var idarray = ids.split(",");
    for(var i in idarray) {
        var c = associativeArrayLength(arrOptions) + associativeArrayLength(arrOptions1);
        var id = idarray[i];
        arrOptions1[id] = id;
        var html = "<div id='OptionsList_"+c+"' class='spanHighElement' style='display:block;width:100%' onclick='javascript: selectItem(this);' name="+id+" skriberid='true' thearraynumber="+c+"><span style='float:left;'>"+id+"</span><span class='closeright' onclick='moveSelectedtoLeft("+c+");'>x</span></div>";
        $("#spanOutputRight").append(html);   
    }
    $("#shareids").val(''); 
}

function moveSelectedtoLeft(i) {
    var elem = $("#OptionsList_"+i);
    var id = elem.attr('name');

    if(elem.attr('skriberid') == 'true') {
        delete arrOptions1[id];
        elem.remove();
    } else {
        $("#OptionsList_"+i+" .closeright").css('visibility','hidden');
        arrOptions[id] = arrOptions1[id];
        delete arrOptions1[id];
        elem.clone().appendTo("#spanOutput");
        elem.remove();
    }
    /*$("#spanOutputRight").find('div').each(function() {
        if($(this).attr('class') == 'spanHighElement') {
            var id = $(this).attr('name');
            arrOptions[id] = $(this).text();
            delete arrOptions1[id];
            $(this).clone().appendTo("#spanOutput");
            $(this).remove(); 
        }    
    });*/
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function associativeArrayLength(arr) {
    var l = 0;
    for (var i in arr) {
        l++;
    }
    return l;
}

function savePersonalProfile() {
    var form = document.getElementById('profile1_form');
    var gender = getCheckedValue(form.gender);   
    
    var data =  {firstname: form.firstname.value,lastname: form.lastname.value, gender: gender, email: form.email.value, homephone: form.homephone.value, cellphone: form.cellphone.value, workphone: form.workphone.value, city: form.city.value, state: form.state.value, country: form.country.value,birthday: form.birthday.value, birthmonth: form.birthmonth.value, birthyear: form.birthyear.value};
    ajaxPost('/users/savePersonalProfile', data,savePersonalProfileResp);
}

function savePersonalProfileResp(data) {
    if($(data).find('savePersonalProfile').attr('status') == 'OK') {
        $("#tabcontainer > ul").tabs("select",1);
    }
}

function loadNotemanager(opt) {
    var data = {option: opt};
    $.ajax({url: '/systems/loadNotemanager',data: {option: opt},success: function(data) {
            managerResp(data,opt);
    }});
}

function managerResp(data,opt) {
        if(opt == 'total') {
            $("#total_manager").html(data);
        } else if(opt=='month') {
            $("#month_manager").html(data);
        } else {
            $("#days_manager").html(data);
        }
    //$("#tabcontainer > ul").tabs("select",1);        
}

function loadFriendcommune() {
    $.ajax({url: '/systems/loadFriendcommune',data: {},success: function(data) {
            frndmanagerResp(data);
    }});
}

function frndmanagerResp(data) {
    $("#frndcom_blk").html(data);
}

function saveBlogsettings(community) {
    var data = {title: document.UserPrefForm.title.value, tagline: document.UserPrefForm.tagline.value, pagelimit: document.UserPrefForm.pagelimit.value};
    startAjax('Saving ...');
    if(community) {
        var cid = document.UserPrefForm.communityid.value;
        var ctr = $('#is_contributors:checked').val();
        ctr = (ctr == 'on')? ctr: 'off';
        ajaxPost("/notes/blogPreference/"+cid+'/'+ctr,data,saveBlogResp);
    } else {
        ajaxPost("/users/preference",data,saveBlogsettingsResp);
    }
}

function saveBlogResp(data) {
    stopAjax();
    if($(data).find('blogpreference').attr('status') == 'OK') {
        var userid = $(data).find('cid').text();
        window.location = "/webnotes/"+userid;
    }

}

function saveBlogsettingsResp(data) {
    stopAjax();
    if($(data).find('preference').attr('status') == 'OK') {
        var userid = $(data).find('userid').text();
        window.location = "/webnotes/"+userid;
    }

}

function saveUrl(community) {
    var ttl = $("#title_url").val();
    var url = $("#blog_url").val();
    //var data = {title: document.linkForm.title_url.value, url: document.linkForm.url.value,};
    var data = {title: ttl, url: url};
    startAjax('Saving ...');
    if(community) {
        var cid = document.linkForm.cid.value;
        ajaxPost("/notes/saveUrl/"+cid,data,saveUrlResp);
    } else {
        ajaxPost("/users/saveUrl",data,saveUrlResp);
    }
}

function saveUrlResp(data) {
    stopAjax();
    if($(data).find('url').attr('status') == 'OK') {
        var userid = $(data).find('userid').text();
        var data = {userid: userid};
        ajaxPost("/users/loadLinks",data,linksSetResp);
        //window.location = "/webnotes/"+userid;
    }
}
function loadLinksResp(data) {
     if($(data).find('links').attr('status') == 'OK') {
        var cnt = $(data).find('links').attr('count');
        var out = "<div class='frnd_ttl' style='margin-top: 0px'><span class='frnds'>Links("+cnt+")</span></div>";
        out += "<div class='friends_list'>";
        out += "<table width=100% cellpadding=2 cellspacing=3 align=left>"; 
        $(data).find('link').each(function() {
            var title = $('title',this).text(); 
            var url = $('url',this).text();
            out +=  "<tr class='categorylisting'><td><span><img hspace=4 align='absbottom' src='/img/tango/16x16/emblems/emblem-symbolic-link.png'/></span>";     
            out += "<span><a href='"+url+"'>"+title+"</a></span></td></tr>";
        }); 
        out += "</table></div>";
        $("#links_blk").html(out);
     }
}
function loadLinks(id,page) {
    var data = {userid: id};
    if(page=='settings') {
        ajaxPost("/users/loadLinks",data,linksSetResp);
    } else {
        ajaxPost("/users/loadLinks",data,loadLinksResp);
    }
}

function linksSetResp(data) {
     if($(data).find('links').attr('status') == 'OK') {
        var cnt = $(data).find('links').attr('count');
        var user = $(data).find('links').attr('user');
        var table = $(data).find('links').attr('table');
       // var out = "<div class='frnd_ttl' style='margin-top: 0px'><span class='frnds'>Links("+cnt+")</span></div>";
        //out += "<div class='friends_list'>";
        var i=0;
        var out = "<div><table width=100% cellpadding=2 cellspacing=3 align=left height=auto>";
        //var out = "";
        $(data).find('link').each(function(i) {
            var id = $('id',this).text();
            var title = $('title',this).text();
            var url = $('url',this).text();
            out +=  "<tr class='categorylisting'><td width=700><span><img hspace=4 align='absbottom' src='/img/tango/16x16/emblems/emblem-symbolic-link.png'/></span>";
            out += "<span id='link1_"+id+"'><a href='"+url+"'>"+title+"</a></span>";
            out += "<span id='link2_"+id+"' style='display: none'><input type='text' id='linkttl_"+id+"' value='"+title+"'><input type='text' id='linkurl_"+id+"' value='"+url+"'></span>";
            out += "</td>";
            //if(table == 'blog_urls') {
                out += "<td><span id='editlink1_"+id+"'><a href='javascript: void(0);' onclick=\"editLink('"+id+"');\">Edit</a></span><span style='display: none' id='editlink2_"+id+"'><a href='javascript: void(0);' onclick=\"updateLink('"+id+"','"+user+"');\">Save</a>&nbsp;&nbsp;<a href='javascript: void(0);' onclick=\"cancelLink('"+id+"');\">Cancel</a></span></td>";
                out += "<td><a href='javascript: void(0);' onclick=\"deleteLink('"+id+"','"+user+"');\">Delete</a></td>";
            /*
            } else { 
                out += "<td><span id='editlink1_"+id+"'><a href='javascript: void(0);' onclick=\"editLink('"+id+"');\">Edit</a></span><span style='display: none' id='editlink2_"+id+"'><a href='javascript: void(0);' onclick=\"updateLink('"+id+"',);\">Save</a>&nbsp;&nbsp;<a href='javascript: void(0);' onclick=\"cancelLink('"+id+"');\">Cancel</a></span></td>";
                out += "<td><a href='javascript: void(0);' onclick=\"deletecmntyLink('"+id+"','community_urls');\">Delete</a></td>";
            }*/
            out += " </tr>";
            i++;
        });
        out += "</table>";
        out += "</div>";
        if(table == 'blog_urls') { 
            $("#linkSettings").html(out);
            $("#link_settings").css({"height":"500px"});
            $("#linkSettings").css('height','auto'); 
        } else {
            $("#cmntylinkSettings").html(out);
            $("#link_settings").css({"height":"500px"});
        }
     }
}

function editLink(id) {
    $("#link1_"+id).hide();
    $("#link2_"+id).show();
    $("#editlink1_"+id).hide();
    $("#editlink2_"+id).show();
}

function cancelLink(id) {
    $("#link1_"+id).show();
    $("#link2_"+id).hide();
    $("#editlink1_"+id).show();
    $("#editlink2_"+id).hide();

}

function updateLink(id,user) {
    var ttl = $("#linkttl_"+id).val();
    var url = $("#linkurl_"+id).val();
    var data = {id: id, title: ttl, url: url, user: user};
    startAjax('Saving ...');
    ajaxPost("/users/updateLink",data,updateLinkResp);
}

function updateLinkResp(data) {
    stopAjax();
    if($(data).find('url').attr('status') == 'OK') {
        var user = $(data).find('userid').text();
        loadLinks(user,'settings'); 
    } else {
        myalert("ajax Error");
    }
}

function deleteLink(id,user) {
     var data = {id: id, user: user};
    startAjax('Deleteing ...');
    ajaxPost("/users/deleteLink",data,deleteLinkResp);
}

function deleteLinkResp(data) {
    stopAjax();
    if($(data).find('url').attr('status') == 'OK') {
        var user = $(data).find('userid').text();
        loadLinks(user,'settings');
    } else {
        myalert("ajax Error");
    }
}

function addDelicious() {
    var nam = $("#del_name").val();
    var pwd = $("#del_password").val();
    var chk = $("input[@name='delicious']:checked").val();
    if(chk == 'on') { 
        var data = {name: nam, pwd: pwd};
        ajaxPost("/users/addDelicious",data,addDeliciousResp);
    } else {
        myalert("You should enable delicious for impoting bookmarks");
    }
}

function addDeliciousResp(data) {
    if($(data).find('delicious').attr('status') == 'OK') {
        var user = $(data).find('userid').text();
        window.location = '/webnotes/'+user;
    } else {
        myalert("Error while saving data");
    } 
} 

function loadDelicious(id) {
    var data = {userid: id};
    ajaxPost("/users/loadDelicious",data,loadDelResp);
}

function loadDelResp(data) {
     if($(data).find('links').attr('status') == 'OK') {
        var cnt = $(data).find('links').attr('count');
        if(cnt != '0') {
        //var out = "<div class='frnd_ttl' style='margin-top: 0px'><span class='frnds'>Delicious("+cnt+")</span></div>";
        var out = "<div class='frnd_ttl' style='margin-top: 0px'><span class='frnds'>Delicious</span></div>";
        out += "<div class='friends_list'>";
        out += "<table width=100% cellpadding=2 cellspacing=3 align=left>";
        $(data).find('link').each(function(i) {
            if(i < 10) {
            var href = $('href',this).text();
            var tag = $('tag',this).text();
            tag = (tag) ? tag : 'Delicious'+i;
            out +=  "<tr class='categorylisting'><td><span><img hspace=4 align='absbottom' src='/img/tango/16x16/emblems/emblem-symbolic-link.png'/></span>";
            out += "<span><a href='"+href+"'>"+tag+"</a></span></td></tr>";
            } else {
               return false;
            }
            i++;
        });
        out += "</table></div>";
        $("#delicious_blk").html(out);
        } else {
             $("#delicious_blk").remove();
        }
    }
}
