/**
 * @name pubs
 * @description Description of pubs
 *
 * @author Duy A. Nguyen (aduyng at gmail.com)
 *
 *
 */

$(function(){
    pubs.init();
});

function split( val ) {
    return val.split( /,\s*/ );
}
function extractLast( term ) {
    return split( term ).pop();
}

function showHelp(options){
    if( typeof options.title == undefined){
        options.title = "Help";
    }

    if( typeof options.message == undefined ){
        return false;
    }

    //inject the help message html
    var newDate = new Date();
    var uniqueId = 'dialog-' + newDate.getTime();

    this.dlg = $('<div class="dialog" id="' + uniqueId + '">' + options.message + '</div>');
    $(document).append(this.dlg);

    this.dlg.dialog({
        title: options.title,
        modal: false,
        resizable: options.resizable == undefined ? false: true,
        width: options.width == undefined ? 500 : options.width,
        height: options.height == undefined ? 300 : options.height,
        open: function(e, u){
            if( options.onOpen != undefined ){
                options.onOpen(e, u);
            }
        },
        close: function(e, u){
            if( options.onClose!= undefined ){
                options.onClose(e, u);
            }
        },
        buttons: {
            OK: function(){
                //remove the injected dialog
                $('#' + uniqueId).dialog('destroy');
                $('#' + uniqueId).remove();
            }
        }
    });
};
    
var pubs = {
    addFormInitialized: false,
    init: function(){
        $('.pubs-input').focus(function(event){
            $(event.target).select();
        });

        //initialize the bulk import dialog
        pubsBulkImportDlg.init();

        //initialize advanced management dialog
        pubsAdvMgtDialog.init();
    },
    showHelp: function(){
        var guideUrl = "./help/publications.php";
        var options = {
            title: 'Publications/Creative Works section help',
            message: '<p>A step by step help guide for this section and list of frequently asked questions can be found <a href="' + guideUrl +'" target="_blank" style="color: blue">here</a>: ' +
            ' If the help guide was not helpful for you, please give us your comment or question in the box below so that we can assist you futher.</p>' +                
            '<textarea id="pubs-help-feedback-textbox" cols="3" rows="5" style="width: 100%; height: 140px;"></textarea> ' +
            '<input type="button" id="pubs-help-button" value="Send question/feeback"/></p>',
            width: 500,
            height: 360,
            resizable: false,
            onOpen: function(){
                $('#pubs-help-button').click(pubs.submitFeedback);            
            }
        };
        showHelp(options);
    },
    submitFeedback: function(){
        var textbox = $('#pubs-help-feedback-textbox');

        if( textbox.val().length == 0 ){
            alert("The feeback must not be empty!");
            textbox.focus();
            return;
        }

        $.ajax({
            url: PUB_PATH + "post/send-feedback.php",
            data: {
                feedback: textbox.val(),
                emailAddress: $('#pub-help-email').val(),
                displayName: $('#pub-help-display-name').val()
            },
            success: function(resp) {
                if( resp.status == 0){
                    textbox.val('');
                }
                alert(resp.message);
            },
            type: "post",
            dataType: "json",
            async: false
        });
    },
    initTinyMCE: function(elementId){
        //        console.log(elementId);
        tinyMCE.init({
            theme : "advanced",
            mode : "exact",
            elements : elementId,
            auto_focus: elementId,
            plugins : "paste",
            theme_advanced_toolbar_location : "top",
            theme_advanced_buttons1 : "bold,italic,underline,sub,sup,charmap,undo,redo,pastetext,pasteword,link,selectall,removeformat,cleanup,code",
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : "",
            width: "100%",
            relative_urls : false
        });
    },
    setTinyMCEFocus: function(elementId){
        tinyMCE.execInstanceCommand(elementId, "mceFocus");
    },
    showEditPubForm: function(pubId, pubCitation, pubYear, pubDoi, notMoving){
        if( pubId ){
            $('#pub-' + pubId).hide();
        }
        var uniqueId = new Date().getTime();
        
        //creating element
        var newFormHTML = $('#pubs-edit-form-template-placeholder').html();
        newFormHTML = newFormHTML.replace(/-template/ig, "-" + uniqueId);

        var newForm = $(newFormHTML);
        

        var show = false;
        var pub = {
            pubId: 0,
            year: pubYear ? pubYear : '',
            citation: pubCitation?pubCitation:'',
            typeId: DEFAULT_PUB_TYPE_ID,
            statusId: DEFAULT_PUB_STATUS_ID,
            tags: [],
            doi: pubDoi?pubDoi:'',
            isRefereed: false,
            isHidden: false

        };

        //get data from server
        if( pubId != 0){
            $.ajax({
                url: PUB_PATH + "get/get_pub.php",
                data: {
                    pubId: pubId
                },
                success: function(resp) {
                    //                    $('#pubs-edit-form-message-' + pubId).text(resp.message);
                    //close the form
                    if( resp.status == 'OK'){
                        show = true;
                        pub = resp.pub;
                    //                        pubs.gotoPubList();
                    }else{
                        alert(resp.message);
                    }
                },
                type: "get",
                dataType: "json",
                async: false
            });
        }else{
            show = true;
        }

        if( !show ){
            delete newForm;
            return false;
        }
//        console.log(pub);
        //append the new form to the place holder
        $('#pubs-forms-placeholder').append(newForm);
        var form = $('#pubs-edit-form-' + uniqueId);
//        var form = newForm;
        form.find('.pubs-input-id').val(pub.pubId);
        if( pub.year != 0 ){
            form.find('.pubs-input-year').val(pub.year);
            form.find('.pubs-input-year-forthcoming').attr('checked', false);
            form.find('.pubs-input-year').removeAttr('disabled');

        }else{
            form.find('.pubs-input-year').val('');
            form.find('.pubs-input-year-forthcoming').attr('checked', true);
            form.find('.pubs-input-year').attr('disabled', 'disabled');
        }
        //        console.log(pub);
        form.find('.pubs-input-citation').val(pub.citation);
        form.find('.pubs-input-type' ).val(pub.typeId);
        form.find('.pubs-input-status' ).val(pub.statusId);
        form.find('.pubs-input-tags' ).val(pub.tags.join(', '));
        form.find('.pubs-input-doi' ).val(pub.doi);

        if(pub.isHidden){
            form.find('.pubs-input-hidden' ).attr('checked', 'checked');
        }else{
            form.find('.pubs-input-hidden' ).removeAttr('checked');
        }
        
        if( pub.isRefereed == 1 || pub.isRefereed === true)
            form.find('.pubs-input-refereed-yes' ).attr('checked', true);
        else{
            form.find('.pubs-input-refereed-no' ).attr('checked', true);
			//console.log(form.find('.pubs-input-refereed-no' ));
		}
			
        
        //form.find('.pubs-input-hidden' ).attr('checked', pub.isHidden);

        //initialize tinyMCE
        pubs.initTinyMCE(form.find('.pubs-input-citation').attr('id'));
        
        form.find(".pubs-input-tags").bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        }).autocomplete({
            minLength: 0,
            source: function( request, response ) {
                // delegate back to autocomplete, but extract the last term
                response( $.ui.autocomplete.filter(
                    AVAILABLE_TAGS, extractLast( request.term ) ) );
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });
         
        newForm.show('fast');
        if( notMoving === true){
            $('html, body').animate({
                scrollTop:newForm.position().top
            }, 'fast');
        }
        
        return false;

    //        pubs.addFormInitialized = true;
    },
    //    showEditPubForm: function(pubId){
    //        var formSelector = '#pubs-edit-form-' + pubId;
    //        pubs.createEditPubForm(pubId);
    //
    //        var show = false;
    //
    //        var pub = {
    //            year: '',
    //            citation: '',
    //            typeId: DEFAULT_PUB_TYPE_ID,
    //            statusId: DEFAULT_PUB_STATUS_ID,
    //            tags: [],
    //            doi: '',
    //            isRefereed: false,
    //            isHidden: false
    //
    //        };
    //
    //        if( pubId != 0 ){
    //            $.ajax({
    //                url: PUB_PATH + "get/get_pub.php",
    //                data: {pubId: pubId},
    //                success: function(resp) {
    //                    $('#pubs-edit-form-message-' + pubId).text(resp.message);
    //                    //close the form
    //                    if( resp.status == 'OK'){
    //                        show = true;
    //                        pub = resp.pub;
    //
    //                    }
    //
    //                },
    //                type: "get",
    //                dataType: "json",
    //                async: false
    //            });
    //        }else{
    //            show = true;
    //        }
    //
    ////        console.log(pub);
    //
    //        $(formSelector).find('.pubs-input-year').val(pub.year);
    //        $(formSelector).find('.pubs-input-citation' ).val(pub.citation);
    //        $(formSelector).find('.pubs-input-type' ).val(pub.typeId);
    //        $(formSelector).find('.pubs-input-status' ).val(pub.statusId);
    //        $(formSelector).find('.pubs-input-tags' ).val(pub.tags.join(', '));
    //        $(formSelector).find('.pubs-input-doi' ).val(pub.doi);
    //        $(formSelector).find('.pubs-input-refereed' ).attr('checked', pub.isRefereed);
    //        $(formSelector).find('.pubs-input-hidden' ).attr('checked', pub.isHidden);
    //
    //        if( show ){
    //
    //            //assign returned data to corresponding controls
    //            $('#pubs-publist').slideUp('fast', function(){
    //               $(formSelector).show('fast', function(){
    //                    //$('#pubs-input-year-0').select().focus();
    ////                    tinyMCE.execInstanceCommand("pubs-input-citation-" + pubId, "mceFocus");
    //                });
    //            });
    //        }
    //        return show;
    //    },
    onYearForthComingClick: function (sender){
        var container = $(sender).parent().parent().parent();
        var pubId = container.attr('id').replace(/^.+-(\d+)$/ig, '$1' );
        var targetId = '#pubs-input-year-' + pubId;
        //check for required fields
        if( $(sender).attr('checked') == true){
            $(targetId).val('');
            $(targetId).attr('disabled', 'disabled');
        }else{
            $(targetId).removeAttr('disabled');
            $(targetId).focus();
        }
    },
    extractYearFromCitation: function(sender){
        var container = $(sender).parent().parent().parent();

        //extract the id from container id
        var pubId = container.attr('id').replace(/^.+-(\d+)$/ig, '$1' );

        var forthComingCheckbox = $('#pubs-input-year-forthcoming-' + pubId);
        if( forthComingCheckbox.length > 0 && forthComingCheckbox.attr('checked')){
            $(sender).val('');
            return;
        }
        //check for required fields
        var year = $('#pubs-input-year-' + pubId).val();
        var citation = tinyMCE.get('pubs-input-citation-' + pubId).getContent({
            format : 'raw'
        });
        
        if(year.length == 0){
            var d = new Date();
            var currentYear = d.getFullYear();

            var extractedYear = pubs.extractYear(citation);

            if( extractedYear ){

                $(sender).val(extractedYear);
            }else{
                $(sender).val(currentYear);
            }
        }
    },
    extractYear: function(citation){
        if( citation != null && citation.length > 0 ){
            var matches = /(19|20)\d\d/gi.exec(citation);
            if(matches != null && matches.length > 0){
                return matches[0];
            }
        }
        return null;
    },
    setStatusCondition: function(statusId){
        $('#pubs-cond-status-id').val(statusId);
        pubs.getPubList(null, true);
        pubs.gotoPubList();
        return false;
    },
    setTypeCondition: function(typeId){
        $('#pubs-cond-type-id').val(typeId);
        pubs.getPubList(null, true);
        pubs.gotoPubList();
        return false;
    },
    setRefereedCondition: function(isRefereed){
        $('#pubs-cond-is-refereed').val(isRefereed);
        pubs.getPubList(null, true);
        pubs.gotoPubList();
        return false;
    },
    setYearCondition: function(year){
        $('#pubs-cond-year').val(year);
        pubs.getPubList(null, true);
        pubs.gotoPubList();
        return false;
    },
    clearFilterConditions: function(){
        $('#pubs-cond-year').val("");
        $('#pubs-cond-status-id').val(0);
        $('#pubs-cond-type-id').val(0);
        $('#pubs-cond-is-refereed').val(-1);
        $('#pubs-cond-includes-hidden-records').attr('checked', true);
        pubs.getPubList();
        pubs.gotoPubList();
        return false;
    },
    saveEditPubForm: function(sender){
        var container = $(sender).parent().parent();
        //extract the id from container id
        var uniqueId = container.attr('id').replace(/^.+-(\d+)$/ig, '$1' );
        var form = $('#pubs-edit-form-' + uniqueId);
        var pubId = form.find('.pubs-input-id').val();
        //check for required fields
        var year = 'forthcoming';

        if(!form.find('.pubs-input-year-forthcoming').attr('checked')){
            year = form.find('.pubs-input-year').val();

            if( year.length == 0 || !/^\d{4}$/.test(year)){
               alert('The year of publication is missing or invalid!');
                return false;
            }
        }


//        var year = form.find('.pubs-input-year').val();
        var citation = tinyMCE.get('pubs-input-citation-' + uniqueId).getContent();

        if( citation.length == 0){
            alert('Citation is required!');
            return false;
        }


        



        var data = {};

        data.pubId = pubId;
        data.citation = citation;
        data.year = year;
        data.typeId = form.find('.pubs-input-type' ).val();
        data.statusId = form.find('.pubs-input-status' ).val();
        data.tags = form.find('.pubs-input-tags' ).val();
        data.doi = form.find('.pubs-input-doi' ).val();
        data.isRefereed = form.find('.pubs-input-refereed-yes' ).attr('checked')? 1 : 0;
        data.isHidden = form.find('.pubs-input-hidden' ).attr('checked')? 1 : 0;
        data.pid = PUB_PID;
        data.tags = form.find('.pubs-input-tags' ).val();
        
        //        console.log(data);
        //        return;

        $.ajax({
            url: PUB_PATH + "post/save_pub.php",
            data: data,
            beforeSend: function(){
                form.find('.pubs-edit-form-message').text('Saving...').show();
            },
            complete: function(){

            },
            success: function(resp) {
                //form.find('.pubs-edit-form-message').text(resp.message);
                //close the form
                if( resp.status == 'OK'){
                    //                    console.log(resp.tags);
                    if( resp.tags ){
                        AVAILABLE_TAGS = resp.tags;
                    }
                    
                    container.hide();
                    pubs.getPubList();
                    alert(resp.message);
                }
                
            //console.log(resp);
            },
            type: "post",
            dataType: "json",
            async: false
        });
        

        return false;
        

    },
    removePub: function(pubId){
        if( confirm('Your selected publication will be permanently deleted. Are you sure you want to proceed?') ){
            $.ajax({
                url: PUB_PATH + "get/delete_pub.php",
                data: {
                    pubId: pubId
                },
                success: function(response) {
                    if( response.status == 'OK'){
                        pubs.getPubList();
                    }
                },
                type: "get",
                dataType: "json",
                async: false
            });
        }
    },
    cancelEditPubForm: function(sender){
        var container = $(sender).parent().parent();
        container.hide();
        container.remove();
        pubs.getPubList();
        
    },
    parseCitation: function(sender){
        var container = $(sender).parent().parent().parent();
        
        var pubId = container.attr('id').replace(/^.+-(\d+)$/ig, '$1' );
        
        var data = {};

        //get content inside the tinymce
        data.citation = tinyMCE.get('pubs-input-citation-' + pubId).getContent();

        if( data.citation.length > 0){
            $.ajax({
                url: PUB_PATH + "post/parse_pub_citation.json.php",
                data: data,
                success: function(response) {
                //                    console.log(response);
                },
                type: "post",
                dataType: "json",
                async: false
            });
        }else{
            alert('Please enter citation to parse');
        }
        return false; 
    },
    cleanupCitationCallback: function(type, value){
        switch (type)
        {
            case "get_from_editor":
                break;
            case "insert_to_editor":
                break;
            case "submit_content":
                value.innerHTML = cleanupPubCitation(value.innerHTML);
                break;
            case "get_from_editor_dom":
                break;
            case "insert_to_editor_dom":
                value.innerHTML = cleanupPubCitation(value.innerHTML);
                break;
            case "setup_content_dom":
                break;
            case "submit_content_dom":
                //			value.innerHTML = cleanupPubCitation(value.innerHTML);
                break;
        }

        return value;
    },
    cleanupPubCitation: function (citation, multiple){
        var cleanCitation = citation;
        multiple = multiple? 1: 0;
        $.ajax({
            url: PUB_PATH + "post/cleanup_pub_citation.json.php",
            data: {
                citation: citation,
                multiple: multiple
            },
            success: function(response) {
                cleanCitation = response;
            },
            type: "post",
            dataType: "json",
            async: false
        });
        return cleanCitation;
    },
    getPubList: function(defaultYear, flashingMessage){
        var yearElement = $('#pubs-cond-year');
        var statusElement = $('#pubs-cond-status-id');
        var typeElement = $('#pubs-cond-type-id');
        var isRefereedElement = $('#pubs-cond-is-refereed');
        //        var tagsElement = $('#pubs-cond-tags');
        var includesHiddenRecordsElement = $('#pubs-cond-includes-hidden-records');

        var params = {};
        params.viewOnly = PUB_ONLY_VIEW;
        
        if( yearElement.length > 0 ){
            if( yearElement.val() != "")
                params.year = yearElement.val();
        }else if(defaultYear){
            params.year = defaultYear;
        //            alert('here');
        }
//                console.log(params);

        if( statusElement.length > 0 ){
            params.statusId = statusElement.val();
        }

        if( typeElement.length > 0 ){
            params.typeId = typeElement.val();
        }

        if( isRefereedElement.length > 0 ){
            params.isRefereed = isRefereedElement.val();
        }
        
        if(includesHiddenRecordsElement.length == 0){
            params.includesHiddenRecords = 'YES';
        }else{
            params.includesHiddenRecords = includesHiddenRecordsElement.attr('checked') ? 'YES' : 'NO';
        }

        //        if( !page ){
        //            page = 0;
        //        }

        params.pid = PUB_PID;
        //        params.page = page;
        //console.log(params);
        $.ajax({
            cache: false,
            url: PUB_PATH + "get/get_pubs.php",
            data: params,
            beforeSend: function(){
                $('#pubs-publist').html("Loading...");
            //$('#pubs-publist').slideUp('fast');
            },
            success: function(response) {
                //console.log(response);
                $('#pubs-publist').html(response);
                if( flashingMessage ){
                    $('.pubs-publist-message').addClass( "ui-state-highlight", 500);
                }
            },
            type: "get"
        });
    },
    gotoPubList: function(){
        //window.location.href = window.location.href.replace(/#.+/gi, '') + '#ppl_publication_header';
        //        $('html, body').animate({scrollTop:0}, 'slow');

        $('html, body').animate({
            scrollTop:$('#ppl_publication_header').position().top
        }, 'slow')
    },
    showBulkImportDialog: function(){
        pubsBulkImportDlg.show(pubs.getPubList);
    },
    showAdvManagementDialog: function(){
        pubsAdvMgtDialog.open(pubs.getPubList);
    }

    
};


var pubsBulkImportDlg = {
    container: null,
    dialogInitialized: false,
    onCloseCallback: null,
    separator: "_______________________________________________________________",
    init: function(){
        pubsBulkImportDlg.container = $('#pubs-bulk-import-dialog');

    //$('#pubs-bulk-import-input').bind('keyup', pubsBulkImportDlg.onTextBoxKeyUp)
    },
    onTextBoxKeyUp: function(){
        var text = $('#pubs-bulk-import-input').val();
        var matches = text.match(/([^\n]+)/g);
        if( matches != null )
            $('#pubs-bulk-import-count').text('Number of publications detected: ' + matches.length);
        
    },
    show: function(onCloseCallback){
        pubsBulkImportDlg.onCloseCallback = onCloseCallback;
        
        if( !pubsBulkImportDlg.dialogInitialized ){
            
            pubsBulkImportDlg.container.dialog({
                title: 'Bulk import Publications/Creative Works',
                modal: true,
                resizable: false,
                width: 800,
                height: 570,
                buttons: {
            /*                    'Import': function(){
                        pubsBulkImportDlg.onImportButtonClicked();
                        
                        pubsBulkImportDlg.container.dialog('close');
                        if( pubsBulkImportDlg.onCloseCallback )
                            pubsBulkImportDlg.onCloseCallback(true);
                    },
                    'Cancel': function(){
                        pubsBulkImportDlg.container.dialog('close');
                        if( pubsBulkImportDlg.onCloseCallback )
                            pubsBulkImportDlg.onCloseCallback(false);
                    }
*/                }

            });

            //attach change event on publication type
            pubsBulkImportDlg.onPubTypeChanged();
            $('#pubs-bulk-import-type-id').bind('change', pubsBulkImportDlg.onPubTypeChanged);

            $('#pubs-bulk-import-dialog-tabs').tabs({
                select: pubsBulkImportDlg.onTabSelected
            });
            $('#pubs-bulk-import-dialog-next-button').click(pubsBulkImportDlg.onNextButtonClicked);
            $('#pubs-bulk-import-dialog-back-button').click(pubsBulkImportDlg.onBackButtonClicked);
            $('#pubs-bulk-import-dialog-import-button').click(pubsBulkImportDlg.onImportButtonClicked);

            pubs.initTinyMCE('pubs-bulk-import-input');

            pubsBulkImportDlg.dialogInitialized = true;
        }else{
            pubsBulkImportDlg.container.dialog('open');
        }
        $('#pubs-bulk-import-dialog-tabs').tabs('select', 0);
        $('#pubs-bulk-import-type-id').val('');
        $('#pubs-bulk-import-count').text('');
    //tinyMCE.get('pubs-bulk-import-input').setContent('');
    },
    onNextButtonClicked: function(){
        


        $('#pubs-bulk-import-dialog-tabs').tabs('select', 1);
    },
    onTabSelected: function(event, ui){
        switch( ui.index ){
            //review tab
            case 1:
                pubsBulkImportDlg.parseCitation();
                break;
            //other services tab
//            case 2: 
//                if( $('#pubs-bulk-import-search-term').val().length == 0 && $($(document.head).find('meta[name="DC.Creator"]')[2]).attr('content'))
//                    $('#pubs-bulk-import-search-term').val($($(document.head).find('meta[name="DC.Creator"]')[2]).attr('content'));
//                break;
                    
        }
        
    },
    parseCitation: function(){
        var citation = tinyMCE.get('pubs-bulk-import-input').getContent();

        var externalCitations = [];
        
        $('#pubs-bulk-import-dialog-review-pub-container').html('');

        if( citation.length > 0){
            citation = citation.replace(/<p[^>]*>/gi, '');


            var splitedCitations = citation.split(/<\/p>|<br \/>/i);
            //console.log(splitedCitations);
            //return;
            var html = '<ol>';
            $(splitedCitations).each(function(index, c){
                c = $("<div/>").html(c).text();
                c = $.trim(c);

                if(/^(\w+):[ ]*([^ ]+)$/gi.test(c)){
                    var uniqueId = 'pubs-citation-parsing-' + ((new Date()).getTime() + index);
                    externalCitations.push({
                        citation: c,
                        uniqueId: uniqueId
                    });
                    c += ' (parsing...)';
                    html += '<li class="ui-widget-content ui-corner-all pubs-import-dialog-citation-review"><span class="ui-icon ui-icon-close pubs-import-dialog-citation-review-remove-button"></span><span id="' + uniqueId + '">' + c + '</span></li>'
                }else if(c.length > 0){
                    html += '<li class="ui-widget-content ui-corner-all pubs-import-dialog-citation-review"><span class="ui-icon ui-icon-close pubs-import-dialog-citation-review-remove-button"></span>' + c + '</li>'
                }
                
            });
            html += '</ol>';
            $('#pubs-bulk-import-dialog-review-pub-container').html(html);

            if( externalCitations.length > 0 ){
                //call server to parse the external citation
                $.ajax({
                    url: PUB_PATH + "post/parse_external_citations.php",
                    data: {
                        records: externalCitations
                    },
                    beforeSend: function(){
                        $('#pubs-bulk-import-dialog-import-button').attr('disabled', 'disabled');
                    },
                    complete: function(){
                        $('#pubs-bulk-import-dialog-import-button').removeAttr('disabled');
                    },
                    success: function(response) {
                        $(response).each(function(index, record){
                            if( record.generatedCitation == null ){
                                $('#' + record.uniqueId).remove();
                            }else{
                                $('#' + record.uniqueId).html(record.generatedCitation);
                            }
                        });

                    },
                    type: 'post',
                    dataType: 'json',
                    cache: false
                });
            }

            //bind remove button
            $('.pubs-import-dialog-citation-review-remove-button').click(function(event){
                $(event.target).parent().remove();
            });
        }
    },
    onBackButtonClicked: function(){
        $('#pubs-bulk-import-dialog-tabs').tabs('select', 0);
    },
    onPubTypeChanged: function(){
        //console.log(event);
        var pubTypeId = $('#pubs-bulk-import-type-id').val();

        pubsBulkImportDlg.getCitationFormats(pubTypeId);
    },
    getCitationFormats: function(pubTypeId){
        $.ajax({
            url: PUB_PATH + "get/get_pub_formats.json.php",
            data: {
                pubTypeId: pubTypeId
            },
            beforeSend: function(){
                $('#pubs-bulk-import-citation-format-container').text('Loading...');
            },
            success: function(response) {
                //                console.log(response);
                var html = '<select id="pubs-bulk-import-citation-format">';
                $(response).each(function(i, row){
                    html += '<option value="' + row.id + '">' + row.name + '</option>';
                });
                html += '</select>';
                $('#pubs-bulk-import-citation-format-container').html(html);
            },
            type: 'get',
            dataType: 'json',
            async: false,
            cache: false
        });
    },
    onImportButtonClicked: function(){
        var splitedCitations = $('#pubs-bulk-import-dialog-review-pub-container').find('.pubs-import-dialog-citation-review');
        if( splitedCitations.length > 0){
            alert('NOTE: This action will not save your publications. Your publications will be queued in your profile for editing and will need to be edited and saved individually.');
            
            $(splitedCitations).each(function(index, li){
                citation = $(li).html();
                if( citation.length > 0){
                    pubs.showEditPubForm(0, citation, pubs.extractYear(citation));
                }
            });
        }
        
        pubsBulkImportDlg.container.dialog('close');
        if( pubsBulkImportDlg.onCloseCallback )
            pubsBulkImportDlg.onCloseCallback(true);
    },
    performSearch: function(){
        var params = {
            term: $('#pubs-bulk-import-search-term').val(),
            service: $('#pubs-bulk-import-search-service').val()
        };
        
        $.ajax({
            url: PUB_PATH + "lookup-services/index.php",
            data: params,
            beforeSend: function(){
                $('#pubs-bulk-import-search-button').attr('value', 'Searching...').attr('disabled', true);
            },
            complete: function(){
                $('#pubs-bulk-import-search-button').attr('value', 'Search').attr('disabled', false);  
            },
            success: function(response) {
                if( response.status != 0 ){
                    alert(response.message);
                    return;
                }
                
                //clear the previous results
                var container = $('#pubs-bulk-import-service-rows');
                container.empty();
                var template = $('#pubs-bulk-import-service-row-template');
                
                /**************** ADDING A HEAD ROW *************************/
                var row = template.clone();
                row.attr('id', row.attr('id').replace('template', 'head'));
                row.addClass('ui-widget-header');
                row.find('.pubs-bulk-import-service-row-citation').html(response.items.length + ' record(s) returned').click(function(){
                    row.find('.pubs-bulk-import-service-select-checkbox').attr('checked', !row.find('.pubs-bulk-import-service-select-checkbox').attr('checked')).change();
                    
                });
                row.find('.pubs-bulk-import-service-select-checkbox').change(function(){
                    var checked = $(this).attr('checked');
                    $('#pubs-bulk-import-service-rows').find('.pubs-bulk-import-service-select-checkbox').attr('checked', checked);
                });
                row.show();
                container.append(row);

                
                
                $.each(response.items, function(index, item){
                    var row = template.clone();
                    row.attr('id', row.attr('id').replace('template', index));
                    row.find('.pubs-bulk-import-service-row-citation').html(item.citation).click(function(){
                        row.find('.pubs-bulk-import-service-select-checkbox').attr('checked', !row.find('.pubs-bulk-import-service-select-checkbox').attr('checked'));
                    });
                    row.find('.pubs-bulk-import-service-row-year').val(item.year);
                    row.find('.pubs-bulk-import-service-row-doi').attr('href', item.doi).html(item.doi);
                    row.show();
                    
                    container.append(row);
                });
                
            },
            type: 'get',
            dataType: 'json',
            async: true,
            cache: false
        });
    },
    onDoneButtonClicked: function(){
            var rows = $('.pubs-bulk-import-service-row');
            var count = 0;
            rows.each(function(index, element){
                var e = $(element);
                if( e.attr('id') != 'pubs-bulk-import-service-row-head'){
                    if( e.find('.pubs-bulk-import-service-select-checkbox').attr('checked') ){
                        count++;
                        pubs.showEditPubForm(0, 
                            e.find('.pubs-bulk-import-service-row-citation').html(), 
                            e.find('.pubs-bulk-import-service-row-year').val(),
                            e.find('.pubs-bulk-import-service-row-doi').attr('href')
                        );
                    }
                }
            });
            if( count > 0){
                alert('NOTE: This action will not save your publications. Your publications will be queued in your profile for editing and will need to be edited and saved individually.');
            }
            
        pubsBulkImportDlg.container.dialog('close');
        if( pubsBulkImportDlg.onCloseCallback )
            pubsBulkImportDlg.onCloseCallback(true);
    }

};

var pubsAdvMgtDialog = {
    container: null,
    dialogInitialized: false,
    onCloseCallback: null,
    init: function(){
        pubsAdvMgtDialog.container = $('#pubs-advmgt-dialog');
        pubsAdvMgtDialog.dialogInitialized =  false;

        //initialize the bulk update dialog
        pubsAdvMgtBulkUpdateDialog.init();
    },
    onChildDialogCancelCallback: function(result){
//        console.log(result);
        if( result ){
            pubsAdvMgtDialog.getPubList();
        }

    },
    open: function(onCloseCallback){
        pubsAdvMgtDialog.onCloseCallback = onCloseCallback;
        if( !pubsAdvMgtDialog.dialogInitialized ){
            pubsAdvMgtDialog.container.dialog({
                title: 'Publication Advanced Management',
                modal: true,
                resizable: true,
                width: 1000,
                height: 500,
                buttons: {
                    'Bulk Update': function(){
                        var selectedCheckboxes = pubsAdvMgtDialog.getSelectedCheckboxes();
                        if( selectedCheckboxes.length == 0 ){
                            alert('Please select at least one item');
                            return;
                        }

                        pubsAdvMgtBulkUpdateDialog.open(selectedCheckboxes, pubsAdvMgtDialog.onChildDialogCancelCallback);
                    },
                    'OK': function(){
                        
                        pubsAdvMgtDialog.container.dialog('close');
                        if( pubsAdvMgtDialog.onCloseCallback )
                            pubsAdvMgtDialog.onCloseCallback();
                    }
                }
            });
            
            pubsAdvMgtDialog.dialogInitialized = true;
        }
        //set current filter conditions to the dialog
        //        $('#pubs-advmgt-cond-year').val($('#pubs-cond-year').val());
        //        $('#pubs-advmgt-cond-status-id').val($('#pubs-cond-status-id').val());
        //        $('#pubs-advmgt-cond-type-id').val($('#pubs-advmgt-cond-type-id').val());
        //        $('#pubs-advmgt-cond-is-refereed').val($('#pubs-advmgt-cond-is-refereed').val());
        //        $('#pubs-advmgt-cond-includes-hidden-records').attr('checked', $('#pubs-advmgt-cond-includes-hidden-records').attr('checked'));

        //load list of publications
        pubsAdvMgtDialog.getPubList(    $('#pubs-cond-year').val(),
            $('#pubs-cond-status-id').val(),
            $('#pubs-cond-type-id').val(),
            $('#pubs-cond-is-refereed').val(),
            $('#pubs-cond-includes-hidden-records').attr('checked')
            );
        if( pubsAdvMgtDialog.dialogInitialized ){
            pubsAdvMgtDialog.container.dialog('open');
        }
    },
    getPubList: function(defaultYear, defaultStatusId, defaultTypeId, defaultIsRefereed, defaultIncludeHiddenRecords){
        var yearElement = $('#pubs-advmgt-cond-year');
        var statusElement = $('#pubs-advmgt-cond-status-id');
        var typeElement = $('#pubs-advmgt-cond-type-id');
        var isRefereedElement = $('#pubs-advmgt-cond-is-refereed');
        //        var tagsElement = $('#pubs-cond-tags');
        var includesHiddenRecordsElement = $('#pubs-advmgt-cond-includes-hidden-records');

        var params = {};

         if( yearElement.length > 0 ){
            if( yearElement.val() != "")
                params.year = yearElement.val();
        }else if(defaultYear){
            params.year = defaultYear;
        //            alert('here');
        }
        //        console.log(typeof defaultYear, params.year);

        if( defaultStatusId ){
            params.statusId = defaultStatusId;
        }else if( statusElement.length > 0 ){
            params.statusId = statusElement.val();
        }

        if( defaultTypeId ){
            params.typeId = defaultTypeId;
        }else if( typeElement.length > 0 ){
            params.typeId = typeElement.val();
        }

        if( defaultIsRefereed ){
            params.isRefereed = defaultIsRefereed;
        }else if( isRefereedElement.length > 0 ){
            params.isRefereed = isRefereedElement.val();
        }

        if( defaultIncludeHiddenRecords ){
            params.includesHiddenRecords = defaultIncludeHiddenRecords ? 'YES' : 'NO';
        }else if(includesHiddenRecordsElement.length == 0){
            params.includesHiddenRecords = 'YES';
        }else{
            params.includesHiddenRecords = includesHiddenRecordsElement.attr('checked') ? 'YES' : 'NO';
        }


        params.pid = PUB_PID;

        $.ajax({
            cache: false,
            url: PUB_PATH + "get/get_advmgt_pubs.php",
            data: params,
            beforeSend: function(){
                $('#pubs-advmgt-publist').html("Loading...");
            //$('#pubs-publist').slideUp('fast');
            },
            success: function(response) {
                //console.log(response);
                $('#pubs-advmgt-publist').html(response);

                //initialize the movable publications
                $('#pubs-advmgt-publist').find(".pubs-publist-year-content" ).sortable({
                    containment: 'parent',
                    forcePlaceholderSize: true,
                    
                    handle: '.pubs-advmgt-moving-handler',
                    placeholder: 'ui-state-highlight',
                    update: pubsAdvMgtDialog.onPublicationReordered
                });
                $('#pubs-advmgt-publist').find(".pubs-publist-year-content" ).disableSelection();
            },
            type: "get"
        });
    },
    onPublicationReordered: function(event, ui){
        var pubIds = $(ui.item).parent().sortable('toArray');
        var params = {
            pid: PUB_PID,
            pubIds: []
        };
        
        $(pubIds).each(function(index, object){
            params.pubIds.push(object.replace('pub-advmgt-', ''));
        });
        
        $.ajax({
            cache: false,
            url: PUB_PATH + "post/update_order.php",
            data: params,            
            success: function(response) {
            //                console.log(response);
            //                pubsAdvMgtDialog.getPubList();
            },
            type: "post"
        });

    },
    clearFilterConditions: function(){
        $('#pubs-advmgt-cond-year').val("");
        $('#pubs-advmgt-cond-status-id').val(0);
        $('#pubs-advmgt-cond-type-id').val(0);
        $('#pubs-advmgt-cond-is-refereed').val(-1);
        $('#pubs-advmgt-cond-includes-hidden-records').attr('checked', true);
        pubsAdvMgtDialog.getPubList();
    },
    onYearCheckboxSelected: function(sender, year){
        var checked = $(sender).attr('checked');
        $('#pubs-advmgt-year-content-' + year).find('input[type=checkbox]').attr('checked', checked);
    },
    getSelectedCheckboxes: function(){
        return pubsAdvMgtDialog.container.find('.pubs-advmgt-checkbox:checked');
    }
};

var pubsAdvMgtBulkUpdateDialog = {
    container: null,
    selectedPubCheckboxes: null,
    onCloseCallback: null,
    init: function(){
        
    },
    clearFields: function(){
        $('#pubs-advmgt-checkbox-year').attr('checked', false);
        $('#pubs-advmgt-input-year').attr('disabled', true);
        $('#pubs-advmgt-input-year').val('');

        //type
        $('#pubs-advmgt-checkbox-type').attr('checked', false);
        $('#pubs-advmgt-input-type').attr('disabled', true);

        //status
        $('#pubs-advmgt-checkbox-status').attr('checked', false);
        $('#pubs-advmgt-input-status').attr('disabled', true);

        //tags
        $('#pubs-advmgt-checkbox-tags').attr('checked', false);
        $('#pubs-advmgt-input-tags').attr('disabled', true);
        $('#pubs-advmgt-input-tags').val('');

        //refereed
        $('#pubs-advmgt-checkbox-refereed').attr('checked', false);
        $('#pubs-advmgt-input-refereed').attr('disabled', true);

        //hidden
        $('#pubs-advmgt-checkbox-hidden').attr('checked', false);
        $('#pubs-advmgt-input-hidden').attr('disabled', true);
    },
    open: function(selectedCheckboxes, onCloseCallback){
        pubsAdvMgtBulkUpdateDialog.onCloseCallback = onCloseCallback;
        //reset the fields
        pubsAdvMgtBulkUpdateDialog.clearFields();


        pubsAdvMgtBulkUpdateDialog.container = $('#pubs-advmgt-bulk-update-dialog');
        //count the number of selected publication
        pubsAdvMgtBulkUpdateDialog.selectedPubCheckboxes = selectedCheckboxes;
        
        pubsAdvMgtBulkUpdateDialog.container.dialog({
            title: 'Bulk update ' + pubsAdvMgtBulkUpdateDialog.selectedPubCheckboxes.length + ' selected publication(s)',
            modal: true,
            resizable: false,
            width: 500,
            height: 350,
            buttons: {
                'Update': function(){
                    if( pubsAdvMgtBulkUpdateDialog.onUpdateButtonClicked() ){
                        pubsAdvMgtBulkUpdateDialog.container.dialog('close');
                        if( pubsAdvMgtBulkUpdateDialog.onCloseCallback){
                            pubsAdvMgtBulkUpdateDialog.onCloseCallback(true);
                        }
                    }
                },
                'Cancel': function(){
                    pubsAdvMgtBulkUpdateDialog.container.dialog('close');
                    if( pubsAdvMgtBulkUpdateDialog.onCloseCallback){
                        pubsAdvMgtBulkUpdateDialog.onCloseCallback(false);
                    }
                }
            }
        });

        $('#pubs-advmgt-input-tags').bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        }).autocomplete({
            minLength: 0,
            source: function( request, response ) {
                // delegate back to autocomplete, but extract the last term
                response( $.ui.autocomplete.filter(
                    AVAILABLE_TAGS, extractLast( request.term ) ) );
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });

    },
    onUpdateButtonClicked: function(){
        var params = {
            pubIds: []
        };
        $(pubsAdvMgtBulkUpdateDialog.selectedPubCheckboxes).each(function(index, checkbox){
            params.pubIds.push($(checkbox).val());
        });
        params.pid = PUB_PID;
        //year
        if( $('#pubs-advmgt-checkbox-year').attr('checked') ){
            params.year = $('#pubs-advmgt-input-year').val();
        }
        //type
        if( $('#pubs-advmgt-checkbox-type').attr('checked') ){
            params.typeId = $('#pubs-advmgt-input-type').val();
        }
        //status
        if( $('#pubs-advmgt-checkbox-status').attr('checked') ){
            params.statusId = $('#pubs-advmgt-input-status').val();
        }
        //tags
        if( $('#pubs-advmgt-checkbox-tags').attr('checked') ){
            params.tags = $('#pubs-advmgt-input-tags').val();
        }
        //refereed
        if( $('#pubs-advmgt-checkbox-refereed').attr('checked') ){
            params.isRefereed = $('#pubs-advmgt-input-refereed').val();
        }
        //hidden
        if( $('#pubs-advmgt-checkbox-hidden').attr('checked') ){
            params.isHidden = $('#pubs-advmgt-input-hidden').val();
        }
        var result = false;
        
        $.ajax({
            async: false,
            cache: false,
            url: PUB_PATH + "post/bulk_update.php",
            data: params,
            success: function(response) {
                if( response.status == 'OK'){
                    result = true;
                }
                alert(response.message);
             
            },
            type: "post",
            dataType: 'json'
        });

        return result;
    },
    toggleField: function(sender, targetElementId){
        var e = $('#' + targetElementId)
        if( $(sender).attr('checked') ){
            e.attr('disabled', false);
            e.select();
            e.focus();
        }else{
            e.attr('disabled', true);
            
        }
        
    }

}
