
function init_events_base(base_node, embed_url) {

    $('.imageline',base_node).each(function(i) {
        var tr = $(this);
        tr.mouseover(function() {
            $('.cellimgdiv',this).css('visibility', 'visible');
        }); 
        tr.mouseout(function() {
            $('.cellimgdiv',this).css('visibility', 'hidden');
        });
    });
    
    $('.cellimgdiv img, .qtiplink, .grouplink, .publishedproject, .unpublishedproject').qtip({
    	style: {
    		classes: 'ui-tooltip-dark ui-tooltip-rounded'
    	},
    	position: {
    		my: 'top left',
    		at: 'bottom left',
    	}
    });
    
    $('.infostooltip').each( function () {
        var desc = $(this).attr('data-desc');
        if (desc == 'None') {
            desc = '';
        }
        $(this).qtip({ 
            content : {
                text: '<b>' + $(this).attr('data-title') + '</b><br />' + desc
            },
        	style: {
        		classes: 'ui-tooltip-dark ui-tooltip-rounded qtipldt'
        	},
        	border: {
        		'width': 0,
        		'color': '#505050'
        	},
        	position: {
        		my: 'top left',
        		at: 'bottom left'
        	}
        });
    });
}

function testAndClose(close_fn) {
	
	return function(force) {
	    // Here we ask LDT if the current work is modified and if the user want to save it.
	    var ldtSwf =  $('#ldtInitSwf',$.nmTop().store.iframe.contents()).get(0);
	    // In the ldt_link_create case, the modal page can be the form, or the ldt swf. So we have to test.
	    if (!force && ldtSwf && ldtSwf.name==="ldtInitSwf" && ldtSwf.isModified()==="true") {
	        ldtSwf.askSave();
	    }
	    else {
            close_fn.apply(this);
	    }
	};
}

function testCreateAndClose(nm, close_fn) {
	
	return function(force) {
	    // We get the frames vars
        f = window.frames[0];
        form_status =  $('#content_form_status',$.nmTop().store.iframe.contents()).val();
	    // If form_status is "saved", we don't have to test anything, the form was was normally submitted.
        // If was status is "empty" AND an upload from local was done
        if(form_status!="saved" && f.upload_from_local_done==true && f.remove_temp_file_url){
            // ERASE FILE
            //alert("testCreateAndClose : " + "f = " + f + ", status = " + form_status + ", u = " + f.upload_from_local_done + ", s = " + f.submit_asked + ", url = " + f.remove_temp_file_url);
            $.ajax({
                type: "GET",
                url: f.remove_temp_file_url,
                data: "filename="+ $('#id_media-local_file_name',$.nmTop().store.iframe.contents()).val(),
                cache: false,
                success: function(data, status, request){
                    alert("remove success");
                }
            });
        }
        close_fn.apply(this);
	};
}

function searchCallback(target, container_selector, url, timeout, num_page, tag_filter) {

    timeout = typeof(timeout) !== 'undefined' ? timeout : 0;
    target = $(target);
    
    // remove all qtip
    $(".qtip").remove();
    
    //if(target.realVal().length > 0) {
    if(target.val().length > 0) {
        target.nextAll(".searchclear").show();
    }
    
    target.next(".searchajaxloader").show();
    target.nextAll(".searchclear").hide();
    //var filterVal = "_" + encodeURIComponent(target.realVal());
    var filterVal = "_" + encodeURIComponent(target.val());
    url = url.replace('__FILTER__',filterVal);
    url = url.replace('__ID_GROUP__',$('#id_group').val());
    var data_obj = null;
    if(num_page || tag_filter){
    	data_obj = {};
    	if(num_page){
    		data_obj["num_page"] = num_page;
    	}
    	if(tag_filter){
    		data_obj["tag_filter"] = tag_filter;
    	}
    }
    if(data_obj!=null){
        $.ajax({
            url: url,
            cache: false,
            type: 'GET',
            data: data_obj,
            success: function(data, status, request) {
            	$(container_selector).html(data);
                target.next(".searchajaxloader").hide();
                //if(target.realVal().length > 0) {
                if(target.val().length > 0) {
                    target.nextAll(".searchclear").show();
                }
                init_events($(container_selector));
                target.removeAttr('timer');
            },
    		error: function(jqXHR, textStatus, errorThrown) {
    			resp = $.parseJSON(jqXHR.responseText);
    			alert(resp.message);
    		}
        });
    }
    else{
        $.ajax({
            url: url,
            cache: false,
            success: function(data, status, request) {
            	$(container_selector).html(data);
                target.next(".searchajaxloader").hide();
                //if(target.realVal().length > 0) {
                if(target.val().length > 0) {
                    target.nextAll(".searchclear").show();
                }
                init_events($(container_selector));
                target.removeAttr('timer');
            }
        });
    }
}

function init_events_contents(base_node, embed_url, content_filter_url, project_filter_url) {
    
    init_events_base(base_node, embed_url);
    
    // Content pagination in workspace home
    $('.contents_page',base_node).click(function(e){
    	num_page = $(this).attr('alt');
    	if(num_page=="prev"){
    		num_page = parseInt($('#current_content_page').val()) - 1;
    	}
    	else if(num_page=="next"){
    		num_page = parseInt($('#current_content_page').val()) + 1;
    	}
    	searchCallback($("#searchcontentsinput"),"#contentslistcontainer",content_filter_url,0,num_page,$('#current_content_tag').val());
	});
    
    // Content pagination in workspace home with tag/category filter
    $("#content_tags_cloud",base_node).toggle(false);
    $("#content_tags",base_node).click(function(){
        $("#content_tags_cloud").slideToggle("fast");
    });
    $('.contents_tag',base_node).click(function(e){
    	$('#searchcontentsinput').val("");
    	$('#current_content_tag').val($(this).attr('alt'));
    	searchCallback($("#searchcontentsinput"),"#contentslistcontainer",content_filter_url,0,0,$('#current_content_tag').val());
	});
    $("#no_content_tag",base_node).click(function(){
    	searchCallback($("#searchcontentsinput"),"#contentslistcontainer",content_filter_url,0,0);
    });
    
}

function init_modal_window (class_name, windowW, windowH, frameW, frameH, base_node, searchprojectfilterurl) {
    $(class_name,base_node).each(function(i){
        $(this).attr("target","_iri");
    });
    
    $(class_name,base_node).nyroModal({
        filters: ['iriIframe'],
        sizes: {
            minW: '' + windowW,
            minH: '' + windowH
        },
        showCloseButton: true,
        closeOnEscape:false,
        closeOnClick:false,
        callbacks: {
            afterShowCont: function(nm) {
                var iframe = nm.store.iframe;
                iframe.load(function(){
                    var form_status = $(this).contents().find("#project_form_status").val(); 
                    if(form_status === 'saved' || form_status === 'deleted' ) {
                        $.nmTop().close();
                    }
                        
                });  
                
                nm.store.iframe.width(frameW);
                nm.store.iframe.height(frameH);
            },
            afterClose: function(nm) {
                // Can't do that because searchprojectfilterurl is not defined in init_events_base params
            	num_page = parseInt($('#current_project_page').val());
            	searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0, num_page);
            }
            
        }
    });
    
    $(class_name,base_node).each(function(i, e) {
        nm = $(e).data('nmObj');
        $(e).data('nmObj', $.extend(true, nm, {
            close: testAndClose(nm.close)
        }));
    });
}

function init_events_base_projects(base_node, embed_url, searchprojectfilterurl, publishprojecturl, unpublishprojecturl) {

    init_modal_window ('.ldt_link_open_ldt', 1035, 670, 1025, 660, base_node, searchprojectfilterurl);
    init_modal_window ('.ldt_link_create_project', 760, 400, 750, 390, base_node, searchprojectfilterurl);
    init_modal_window ('.ldt_link_copy_project', 500, 150, 500, 150, base_node, searchprojectfilterurl);
    
    // Project pagination in workspace home
    $('.projects_page',base_node).click(function(e){
    	num_page = $(this).attr('alt');
    	if(num_page=="prev"){
    		num_page = parseInt($('#current_project_page').val()) - 1;
    	}
    	else if(num_page=="next"){
    		num_page = parseInt($('#current_project_page').val()) + 1;
    	}
    	searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0, num_page);
	});
    
    $('.publishedproject', base_node).click(function(e) {
        e.preventDefault();
        display_loading_icon($(this));
        var target = $(e.target);
        var project_id = target.attr('id').replace('project_','');
        var url = unpublishprojecturl.replace('__PROJECT_ID__', project_id);
        num_page = parseInt($('#current_project_page').val());
        $.ajax({
            url: url,
            type: 'POST',
            data: {csrfmiddlewaretoken:global_csrf_token},
            // bug with jquery >= 1.5, "json" adds a callback so we don't specify dataType
            //dataType: 'json',
            success: function(json, textStatus, XMLHttpRequest) {
                if(json.res) {
                	searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0, num_page);
                }
            }
        });
    });
    
    $('.unpublishedproject', base_node).click(function(e) {
        e.preventDefault();
        display_loading_icon($(this));
        var target = $(e.target);
        var project_id = target.attr('id').replace('project_','');
        var url = publishprojecturl.replace('__PROJECT_ID__', project_id);
        num_page = parseInt($('#current_project_page').val());
        $.ajax({
            url: url,
            type: 'POST',
            data: {csrfmiddlewaretoken:global_csrf_token},
            // bug with jquery >= 1.5, "json" adds a callback so we don't specify dataType
            //dataType: 'json',
            success: function(json, textStatus, XMLHttpRequest) {
                if(json.res) {
                    searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0, num_page);
                }
            }
        });
    });

    $('.projecttitlelink').each(function(i){
        $(this).attr("target","_blank");
    });    
    
    $('.projecttitlelink').nyroModal({
        filters: ['iframe'],
        sizes: {
            minW: '750',
            minH: '400'
        },
        closeOnClick:false,
        callbacks: {
            afterClose: function(nm) {
                searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0);
            },
            afterShowCont: function(nm) {
                var iframe = nm.store.iframe;
                iframe.load(function(){                    
                    var form_status = $(this).contents().find("#project_form_status").val(); 
                    if(form_status === 'saved' || form_status === 'deleted') {
                          $.nmTop().close();
                    }
                  });

                nm.store.iframe.width(740);
                nm.store.iframe.height(390);
            }
        }
    });
    
}

function display_loading_icon (project) {
	project.attr('src', project_load_src);
}

function init_events_groups (base_node, embed_url, groupfilterurl) {
		
    $('.create_group',base_node).each(function(i){
        $(this).attr("target","_iri");
    });
    
    $('.create_group',base_node).each(function(i, e) {
        nm = $(e).data('nmObj');
        $(e).data('nmObj', $.extend(true, nm, {
            close: testAndClose(nm.close)
        }));
    });
    
}

function init_events_projects(base_node, embed_url, searchprojectfilterurl, publishprojecturl, unpublishprojecturl) {
    init_events_base(base_node, embed_url);
    init_events_base_projects(base_node, embed_url, searchprojectfilterurl, publishprojecturl, unpublishprojecturl);
}

function init_events_all(base_node, embed_url, searchcontentfilterurl, searchprojectfilterurl, publishprojecturl, unpublishprojecturl) {
    init_events_contents(base_node, embed_url, searchcontentfilterurl, searchprojectfilterurl);
    init_events_base_projects(base_node, embed_url, searchprojectfilterurl, publishprojecturl, unpublishprojecturl);
}


function searchFieldInit(input_list_init) {
    $(".searchfieldinputbase").keydown(function (e) {
         if(e.which === 27) {
              $(e.target).blur();
              $(e.target).next(".searchajaxloader").hide();
         }
    });

    $.each(input_list_init, function(index, value) {
        $(value['input_selector']).keyup(function (e) {
        	// Validate search only if key is enter or if the call does not come from keyboard
        	if(e.which===13 || e.which==undefined){
        		searchCallback(e.target, value['container_selector'], value['url']);
        	}
        });
    });
    
    $('.searchclear').click(function(e) {
        var box = $(e.target).parent().find("input");
        box.val("");
        box.addClass("searchfieldinput");
        box.blur();
        box.keyup();
    });
    
    $('.searchclear').each(function(i) {
        $(this).hide();
    });
    
}


function resize_modal_window (element, createcontent) {
    var nm = parent.$.nmTop();
    var iframe = $("iframe", window.parent.document);
    if ( $('#init_ldt_view', element).size() > 0) { // if contains ldt lpayer
    	var h = 660;
    	var w = 1025;
    } else {
    	var h = $(element).innerHeight() + 10;
    	var w = $(element).innerWidth() + 10;
	}
        
    nm.sizes.minH = h + 10;
    nm.sizes.minW = w;
    iframe.height(h);
    iframe.width(w);
    
    if ($.browser.mozilla && createcontent) {
    	$(".nyroModalCont", parent.window.document).height(h+10);
    } else {
    	nm.resize(true);
    }
}

//
//Functions used in the create content view.
//
function onCreateContentReady(url_upload, media_prefix, post_added_params, btn_label, success_label, wait_label, cancel_label, remove_url, ask_dur_url) {
	
    window.upload_from_local_done = false;
    window.submit_asked = false;
    window.remove_temp_file_url = remove_url;
    window.ask_duration_url = ask_dur_url;
    
    $("#close_button").click(function (e) {
        e.preventDefault();
        parent.$.nmTop().close();
    });    
    $("#submit_button_write").click(function(e) {
        $(".submitcontent-loader-content").show();
        resize_modal_window($("#add_content"), true);
    });
    $(".media_fields").hide();
    $("#media_field_"+$("#id_content-media_input_type").val()).show();
    $("#id_content-media_input_type").change(function(e) {
        $(".media_fields").hide();
        $("#media_field_"+$(e.target).val()).show();
    });
    // The textinput's id for external url is id_media-src
    $('#id_media-src').bind('textchange', function(e) { testUrlValue(e); });
    
    // We disable the default submit
    $('#my_form').bind('submit', function() {
        window.submit_asked = true;
        if($('#id_content-media_input_type').val()=="upload"){
            if(window.upload_from_local_done==false){
                // The form has sent but the uploading has not ended.
                if($('#upload_progress_info').children().size()>0){
                    $('#progress_info').remove();
                }
                $('#upload_progress_info').append('<p id="progress_info"><font color="red"><strong>' + wait_label + '.</strong></font><br/><a href="javascript:cancelSwfUpload()">' + cancel_label + '.</a></p>');
                return false;
            }
            else{
                return true;
            }
        }
        else{
            //alert("2. " + $('#id_content-media_input_type').val());
            return true;
        }
    });
    
    $("#upload_progress_bar").css({ width:"90%", height:"10" });
    
    $('#media_fields_div').height(80);
    
    // We init the swfupload object
    swfupload = new SWFUpload({
        debug: false,
        
        upload_url: url_upload,
        flash_url: media_prefix+"swf/swfupload.swf",
        
        post_params: post_added_params,
        
        button_placeholder_id: "upload_btn",
        button_width: "60",
        button_height: "16",
        button_cursor: SWFUpload.CURSOR.HAND,
        button_text : '<span class="btnText">' + btn_label + '</span>',
        button_text_style : ".btnText { font-size: 12; font-family: Arial; }",
        
        file_types : "*.flv;*.f4v;*.mp4;*.mov;*.mp3",
        file_types_description : "Media Files (flv, f4v, mov H264, mp4, mp3)",
        file_upload_limit : "1",
        file_queue_limit : "1",
        
        upload_error_handler : uploadError,
        upload_start_handler : function(file) {
            try {
                if($('#upload_progress_info').children().size()>0){
                    $('#progress_info').remove();
                }
                $('#upload_progress_info').append('<p id="progress_info"><a href="javascript:cancelSwfUpload()">' + cancel_label + '.</a></p>');
            }
            catch (ex) {
                //this.debug(ex);
            }
        },
        upload_progress_handler : uploadProgress,
        upload_success_handler : function() {
                try {
                    if($('#upload_progress_info').children().size()>0){
                        $('#progress_info').remove();
                    }
                    $('#upload_progress_info').append('<p id="progress_info">' + success_label + '.</p>');
                    $("#upload_progress_bar > div").css({ 'background': '#90ffa8' });
                    window.upload_from_local_done = true;
                    // Now that the file is uploaded, we submit the form if asked
                    if(window.submit_asked==true){
                        $('#my_form').submit();
                    }
                    else{
                        // We ask the uploaded media's duration
                        if(window.ask_duration_url){
                            $.ajax({
                                type: "GET",
                                url: window.ask_duration_url,
                                data: "filename="+ $('#id_media-local_file_name').val(),
                                cache: false,
                                success: function(data, status, request){
                                    if(data && data!=""){
                                        $('#id_content-duration').val(data);
                                    }
                                }
                            });
                        }
                    }
                }
                catch (ex) {
                    //this.debug(ex);
                }
            },
        file_queued_handler : displayUploadPath,
        file_dialog_complete_handler: function() { 
            window.submit_asked = false;
            this.startUpload();
        }
        //upload_complete_handler: function() { this.startUpload(); },
    });
}
function displayUploadPath(file) {
    try {
        $('#id_media-local_file_name').val(file.name);
    }
    catch (ex) {
        //this.debug(ex);
    }
}
function startLocalUpload(){
    swfupload.startUpload();
}
function uploadProgress(file, bytesLoaded, bytesTotal) {
    try {
        var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
        $("#upload_progress_bar").progressbar({ value: percent });
    }
    catch (ex) {
        //this.debug(ex);
    }
}
function cancelSwfUpload(){
    swfupload.cancelUpload();
    if($('#media_field_upload').has($('#cancelupload')).length==0){
        $('#cancelupload').remove();
    }
}
function uploadError(file, errorCode, message) {
    try {
        if($('#upload_progress_info').children().size()>0){
            $('#progress_info').remove();
        }
        switch (errorCode) {
        case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
            $('#upload_progress_info').append('<p id="progress_info">' + "Error Code: HTTP Error, File name: " + file.name + ", Message: " + message + '</p>');
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
            $('#upload_progress_info').append('<p id="progress_info">' + "Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message + '</p>');
            break;
        case SWFUpload.UPLOAD_ERROR.IO_ERROR:
            $('#upload_progress_info').append('<p id="progress_info">' + "Error Code: IO Error, File name: " + file.name + ", Message: " + message + '</p>');
            break;
        case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
            $('#upload_progress_info').append('<p id="progress_info">' + "Error Code: Security Error, File name: " + file.name + ", Message: " + message + '</p>');
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
            $('#upload_progress_info').append('<p id="progress_info">' + "Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message + '</p>');
            break;
        case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
            $('#upload_progress_info').append('<p id="progress_info">' + "Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message + '</p>');
            break;
        case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
            $('#upload_progress_info').append('<p id="progress_info">' + "Error Code: FILE_CANCELLED" + '</p>');
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
            $('#upload_progress_info').append('<p id="progress_info">' + "STOPPED" + '</p>');
            break;
        default:
            $('#upload_progress_info').append('<p id="progress_info">' + "unhandled error: File name: " + file.name + ", File size: " + file.size + ", Message: " + message + '</p>');
            break;
        }
    } catch (ex) {
        //this.debug(ex);
    }
}

// Test the value of the URL from the form to load a picture in case it is a youtube video
function testUrlValue(e){
    // First, we remove the current thumbnail if there is one.
    if($('#media_field_create').children().size()>2){
        $('#external_thumbnail').remove();
        $('#media_fields_div').height(80);
    }
    // If the pasted text is a youtube url, we get the default thumbnail of the video and display it.
    url = $('#id_media-src').val();
    if(url.match("youtube") && url.match("[\\?&]v=([^&#]*)")){
        results = url.match("[\\?&]v=([^&#]*)");
        vid = ( results === null ) ? url : results[1].substring(0,11);
        if(vid.length===11){
            var jsonp_url = 'https://gdata.youtube.com/feeds/api/videos/'+vid+'?v=2';
            $.ajax({
                type: "GET",
                url: jsonp_url,
                dataType: "jsonp",
                cache : false,
                data : {"alt" : "json-in-script"},
                jsonpCallback : 'dude',
                jsonp : 'callback',
                success: function(data, status, request) {
                    $('#id_content-duration').val(data.entry.media$group.media$content[0].duration*1000);
                    if(($('#id_content-title').val())==""){
                         $('#id_content-title').val(data.entry.title.$t);
                    }
                    $('#media_field_create').append('<img id="external_thumbnail" src="'+data.entry.media$group.media$thumbnail[0].url+'" alt="Youtube Thumbnail"/>');
                    $('#media_fields_div').height(150);  
                    $('#id_url_image').val(data.entry.media$group.media$thumbnail[0].url)
                }
            });
        }
    }
    else if(url.match("vimeo")){
        var match = /vimeo.*\/(\d+)/i.exec( url );
        if (match){
            vid=match[1];
            var jsonp_url="http://vimeo.com/api/v2/video/"+vid+".json";
            $.ajax({
                type: "GET",
                url: jsonp_url,
                dataType: "jsonp",
                cache : false,
                jsonpCallback : 'dude',
                jsonp : 'callback',
                success: function(data, status, request) {
                    $('#id_content-duration').val(data[0].duration*1000);
                    if(($('#id_content-title').val())==""){
                         $('#id_content-title').val(data[0].title);
                    }
                    $('#media_field_create').append('<img id="external_thumbnail" src="'+data[0].thumbnail_small+'" />');
                    $('#media_fields_div').height(150);
                    $('#id_url_image').val(data[0].thumbnail_small);
                }
            });
        }
    }
    else if(url.match("dailymotion")){
        id = url.substr(url.search("video/")+6);
        tableau=id.split("_");
        vid=tableau[0];
        jsonp_url= "https://api.dailymotion.com/video/"+vid;
        $.ajax({
            type: "GET",
            data : {"fields" : "id,duration,title,thumbnail_medium_url"},
            url: jsonp_url,
            dataType: "jsonp",
            cache : false,
            jsonp : 'callback',
            jsonpCallback : 'dude',
            success: function(data, status, request) {
                $('#id_content-duration').val(data.duration*1000);
                if(($('#id_content-title').val())==""){
                     $('#id_content-title').val(data.title);
                }
                $('#media_field_create').append('<img id="external_thumbnail" src="'+data.thumbnail_medium_url+'" />');
                $('#media_fields_div').height(190);
                $('#id_url_image').val(data.thumbnail_medium_url)
            }
        });
    }
}

function check_uncheck_all(name) {
	var check_all = gettext("check all");
	var uncheck_all = gettext("uncheck all");
	var id_name = "#global_checkbox_" + name;
	
	$(id_name).attr('title', uncheck_all);
	
	$(id_name).change(function () {
		var checkbox_names = ".checkbox_" + name;
		if ($(id_name).is(":checked")) {
			$(checkbox_names).prop('checked', true);
			$(id_name).attr('title', uncheck_all );
		} else {
			$(checkbox_names).prop('checked', false);
			$(id_name).attr('title', check_all);
		}
		$(checkbox_names).trigger("change");
	});		
}
