var need_collection_refresh = false;

function _init() {
    possible_langs = ['et', 'en', 'ru', 'de', 'fr', 'fi', 'sv'];
    for (i=0; i<possible_langs.length; i++) {
        l = possible_langs[i];
        el = $('#set_'+l);
        if (el.length > 0) {
            el.show();
            $('#chooser_'+l).addClass('selected');
            break;
        }
    }
    $('#langchooser div').click(function(event) {
        e = $(this);
        lcode = e.attr('id').replace('chooser_', '');
        if ( lcode == "new" ) {
            // adding new language
            //alllangs = [['et', 'eesti'], 'en', 'de', 'ru', 'sv', 'fi'];
            // alllangs defined in edit_form.php
            usedlangs = [];
            last = null;
            $('input[type=hidden][name^=langs]').each(function() {usedlangs.push(this.value);last = this;});
            poplangs = [];
            for ( i=0; i<alllangs.length; i++ ) {
                found = false;
                for ( j = 0; j<usedlangs.length; j++ ) {
                    if ( alllangs[i][0] == usedlangs[j] )
                        found = true;
                }
                if ( !found ) 
                    poplangs.push(alllangs[i]);
            }
            id = '#lang_newlangchooser';
            $(id).empty();
            for ( i=0; i<poplangs.length; i++ ) {
                e = $('<div>')
                    .attr('id', 'newlang_'+poplangs[i][0])
                    .addClass('mcs_clickable')
                    .text(poplangs[i][1])
                    .click(function() {
                            _addlanguage(this.id);
                            $(id).hide();
                        });
                $(id).append(e);
            }
            $(id).css('left', event.clientX+30);
            $(id).css('top', $(document).scrollTop() + event.clientY-20);
            $(id).show();
        } else {
            if ( e.hasClass('selected') ) {
                return;
            }
            $('#langchooser div').removeClass('selected');
            e.addClass('selected');
            $('.lingual').hide();
            $('#set_'+lcode).show();
        }
    });

    $('#collection_add_button').click(_start_collecting);
    $('#collection_confirm').click(_post_confirm);
}

function _addlanguage(id) {
    lcode = id.replace('newlang_', '');

    // clone langchooser
    lc = $('#chooser_new').next();
    prevlcode = lc.attr('id').replace('chooser_', '');
    nc = lc.clone(true);
    nc.removeClass('selected');
    nc.text($('#'+id).text());
    nc.attr('id', 'chooser_'+lcode);
    $('#chooser_new').after(nc);

    // clone content
    // sr = $('#multilinguals').children().next();
    sr = $('#multilinguals').children().slice(0,1);
    prevlcode = sr.attr('id').replace('set_', '');
    d = sr.clone();
    d.attr('id', 'set_'+lcode);
    d.find('input,textarea').each(
        function() {
            this.name = this.name.replace(prevlcode+'_', lcode+'_');
            this.id= this.id.replace(prevlcode+'_', lcode+'_');
    });
    d.find('label').each(
        function() {
            this.setAttribute("for", this.getAttribute("for").replace(prevlcode+'_', lcode+'_'));
    });
    d.css({'display': 'none'});
    $('#multilinguals').append(d);
    a = $('input[type=hidden][name^=langs]:last');
    a.after('<input type="hidden" value="'+lcode+'" name="langs[]" />');

    // add to mdLanguage selection
    mdle = $('#mdLanguage');
    if ( mdle ) {
        mdle.append($('<option>').attr('value', lcode).text($('#'+id).text()) );
    }
}

function translateJSON(val) {
    jQuery.getJSON(SERVER_URL+'pg/waramu/translate', 'value='+escape(val), 
            function(jsson, stat) {
            showvalues(jsson, stat, val);
            }
            );
}

function showvalues(val, stat, code) {
    el = $('#currDynArea');
    el.append(wrapCurriculum(val, code));
}

function wrapCurriculum(val, code) {
    vals = code.split(',');
    r = $('<div>').attr("id", 'curriculum_'+vals[1]);
    sp = $('<span>[X]</span>').attr({"id": "curriculum_remove", "title": removetext}).click(
            function() {
                removeValue(code);
            }
            );
    r.append(sp);
    r.append("&nbsp;"+val);
    return r;
}

function removeValue(coda) {
    spl = coda.split(',');
    $('#curriculum_'+spl[1]).remove();
    el = $('input[name=curriculumSubject\[\]]');
    for ( i=0; i<el.length; i++) {
        val = $(el[i]).val();
        if (val==coda) {
            $(el[i]).remove();
            break;
        }
    }
    updateLREkeywords();
}

function appendValue(elid, val) {
    el = $('#'+elid);
    el.val(el.val()+','+val);
}

function displayMappings() {
    el = $('#currDynArea');
    el.empty();
    el = $('input[name=curriculumSubject\[\]]');
    for ( i=0; i<el.length; i++) {
        val = $(el[i]).val();
        translateJSON(val);
    }
}

function displayTree() {
    var maskHeight = $(document).height();  
    var maskWidth = $(window).width();  

    //Set heigth and width to mask to fill up the whole screen  
    $('#mask').css({'width':maskWidth,'height':maskHeight});  

    //transition effect       
    $('#mask').fadeIn(1000);
    $('#mask').fadeTo("slow",0.8);

    var winH = $(window).height();  
    var winW = $(window).width();  

    id = '#curriculumSubjectSelector';
            
    //Set the popup window to center  
    $(id).css('top',  winH/2-$(id).height()/2);  
    $(id).css('left', winW/2-$(id).width()/2);  
    
    //transition effect  
    $(id).fadeIn(1000);   

    var curr = new Vocabulary('curriculumSubject', 'curriculumSubject', _value_selected);
    window.vocabulary = curr;
    curr.start();
}

function _value_selected(addval) {
    $('#curriculumSubject_values').append($('<input type="hidden" name="curriculumSubject[]" value="'+CSBP+','+addval+'" />'));
    $('#mask').click();
    displayMappings();
    updateLREkeywords();
}

function updateLREkeywords() { //TODO: needs an update to NS
    /*
    subject_ids = $('#curriculumSubject').val();
    $.getJSON(
        SERVER_URL+"pg/waramu/lrekeywords",
        {"subject_ids": subject_ids},
        function(lre_val) {
            $('#LREkeywords').val(lre_val);
        }
    );
    */
}

/**
 * Triggered from field_curriculumSubject 
 * */
function _init_curriculum() {
    displayMappings();
    $('#mask').click(function () {  
            $(this).hide();  
            $('.window').hide();  
            id = '#curriculumSubjectSelector';
            $(id).hide();
            });
    $('#curriculum_add').click(function(event) { 
            event.preventDefault();
            displayTree();
            });
}

function cloneElement(fid, beforeElement) {
    el = $('#'+fid);
    k = el.clone();
    k.removeAttr('id');
    $('#'+beforeElement).before(k);
}

/*
 *  check that necessary fields are filled, before submitting the form
 */
var formsubmitted = false;
function controlFields() {
    // at least one language has to have title, description and keywords
    // also resource should have curriculum subject
    var all_filled = false;
    // get languages
    var langs = $("div[id^='chooser_']");
    for (var i=0; i<langs.length; i++) {
        var lang_id = langs[i].id;
        if (lang_id != 'chooser_new') {
            var lang_code = lang_id.substring(8);
            var title = "a"; var desc = "d"; var keys = "k";
            if ($('#' + lang_code + '_title').length>0) {
                var title = jQuery.trim($('#' + lang_code + '_title').val());
            }
            if ($('#' + lang_code + '_desc').length>0) {
                var desc = jQuery.trim($('#' + lang_code + '_desc').val());
            }
            if ($('#' + lang_code + '_keywords').length>0) {
                var keys = jQuery.trim($('#' + lang_code + '_keywords').val());
            }
            if (title && desc && keys) {
                all_filled = true;
            }
        }
    }
    if (all_filled) {
        var subject = $('input[name=curriculumSubject\[\]]');
        if (subject.length == 0) {
            all_filled = false;
        }
    }
    if (all_filled && !formsubmitted) {
        // check also URL
        var urlcheck = true;
        if ($('#url')) {
            var old_url = $('#old_url').val();
            var new_url = $('#url').val();
            if (old_url != new_url) {
                $.getJSON(
                    SERVER_URL+"pg/waramu/checkurl",
                    {"url": new_url},
                    function(response) {
                        if (response == "false") {
                            alert(url_errortext);
                            urlcheck = false;
                        } else {
                            urlcheck = true;
                        }
                    }
                );
            }
        }
        if (urlcheck == true) {
            formsubmitted = true;
            document.saveform.submit();
        }
    } else if (!all_filled) {
        alert(required_fields_errortext);
    }
    return false;
}

function controlURL() {
    var old_url = $('#old_url').val();
    var new_url = $('#url').val();
    if (old_url != new_url) {
        $.getJSON(
            SERVER_URL+"pg/waramu/checkurl",
            {"url": new_url},
            function(response) {
                if (response == "false")
                    $('#resource_url_error').show();
                else
                    $('#resource_url_error').hide();
            }
        );
    }
}

// display popup area
function display_popup(mask_id, id) {
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    //Set heigth and width to mask to fill up the whole screen  
    $(mask_id).css({'width':maskWidth,'height':maskHeight});

    //transition effect       
    $(mask_id).fadeIn(1000);
    $(mask_id).fadeTo("slow",0.8);

    var winH = $(window).height();
    var winW = $(window).width();

    //Set the popup window to center  
    $(id).css('top',  winH/2-$(id).height()/2);
    $(id).css('left', winW/2-$(id).width()/2);

    //transition effect  
    $(id).fadeIn(1000);

}

// show helptext
function showHelptext(fid) {
    display_popup('#helpmask', '#helptext_area');
    var text = $("#"+fid+"_helptext").html();
    $('#helptext_area').html(text);
}

function _close_helpmask() {
    $('#helptext_area').hide();
    $('#helpmask').hide();
}

/**
 * Triggered from field_attachments 
 **/
function _init_attachments() {
    $('#files_add').click(function(event) { 
        event.preventDefault();
        //display_popup('#filesmask', '#upload_iframe');
        upload_window = window.open(SERVER_URL + "pg/waramu/upload_form?id="+$('#resourceid').val(), "w2uploader", "width=500,height=400");
        upload_window.focus();
        //populateFiles(rid);
    });
    $('#fileremove_mask').click(function() {
        _hideFileConfirm();
    });
}
        
        
function populateFiles(rid) {
    $.getJSON(
        SERVER_URL+"mod/waramu/actions/get_filelistJSON.php",
        {"rid": rid},
        function(data){
            $("#files_list").html("");
            $.each(data, function(i,item){
                r = $('<div>').attr('id', 'filefield');
                del_span = $('<span>').attr({"id": "file_remove", "onclick": "_removeConfirm('"+rid+"', '"+item['id']+"')", "title": removetext });
                del_span.html("[X]");
                r.append(del_span);
                r.append('&nbsp;'+item['filename']);
                $("#files_list").append(r);
            });
                    
        }
    );
}

function _removeConfirm(rid, fid) {
    $('#fileremove_button').bind("click", {rid: rid, fid: fid}, _removeFile);
    display_popup('#fileremove_mask', '#fileremove_confirm');
}

function _hideFileConfirm() {
    $('#fileremove_mask').hide();
    $('#fileremove_confirm').hide();
}

function _removeFile(event) {
    rid = event.data.rid;
    fid = event.data.fid;
    $.get(
        SERVER_URL+"mod/waramu/actions/remove_file.php",
        {"rid": rid, "fid": fid},
        function() {
            populateFiles(rid);
            _hideFileConfirm();
        }
    );
}
/**
 *  field_attachments end
 **/

/**
 * collections
 * */
function _start_collecting(event) {
    event.preventDefault();
    need_collection_refresh = false;
    $('#mask').click(function () {  
            $('#collarea_body').html('');
            $(this).hide();  
            $('.window').hide();  
            id = '#collarea';
            $(id).hide();
            _refresh_collarea();
            });
    display_popup("#mask", "#collarea");
    $.get(
            SERVER_URL+"pg/waramu/acoll",
            {'verb': 'userlist', "rid": $('input[name=resourceid]').val()},
            function(data){
                $('#collarea_header').show();
                $('#collarea_footer').show();
                $('#collarea_body').html(data);
            }
            )
}

function _refresh_collarea() {
    if (need_collection_refresh) {
        $.get(
            SERVER_URL+"pg/waramu/acoll",
            {'verb': 'listresourcecollections', 'rid': $('input[name=resourceid]').val()},
            function(data) {
                $('#collections_container').show();
                $('#collections_list_container').html(data);
            }
            )
    }
}

function _post_confirm(event) {
    $('#collarea_footer').hide();
    $('#collarea_header').hide();
    colls = $('input[name=collections\[\]]:checked');
    checked = [];
    unchecked = [];
    $.each(colls, function (i, v) {
        checked.push(v.getAttribute('value'));
    });
    $.post(SERVER_URL+"pg/waramu/acoll",
            {'verb': 'confirm', 'dd[]': checked, 'new': $('input[name=collection_name]').val(),
             'rid': $('input[name=resourceid]').val()},
            function(data) {
                $('#collarea_body').html(data);
            })
}

function _init_refsort() {
    $(document).ready(function() {
        $('#resource_list_sortable').sortable({
            items:'.resource_object',
            axis: 'y',
            update: function(event, ui) {
                $('#resource_list_sortable .resource_object input[name=items\[\]]').each(function(index, elem) {
                    eid = $(this).val();
                    $('#pos_'+eid).val(index+1);
                    });
            }
        });
        $('#resource_list_sortable div').disableSelection();
    });
}

$(document).ready(function() {
    _init();
});

