
$.fn.realVal = function() {
    var obj = $(this[0]);
    if(obj.val) {
        if(obj.val() === obj.attr('defaultText')) {
            return '';
        }
        else {
            return obj.val();
        }
    }
    else {
        return null;
    }
};


function init_events_base(base_node, embed_url) {

    $('.ldt_link_embed',base_node).click(function(e) {
        e.preventDefault();
        var link = $(e.target);
        var json_url = link.attr("href");
        var player_id = link.attr("id");
        var ldt_id = player_id.substring(15);
        $('<a />', {
            href: embed_url+'?json_url='+escape(json_url)+'&player_id='+escape(player_id)+'&ldt_id='+escape(ldt_id),
            target: "_blank"
        }).nyroModal({
            filters: ['iframe'],
            sizes: {
                minW: '750',
                minH: '662'
            },
            callbacks: {
                afterShowCont: function(nm) {
                    nm.store.iframe.height(662);
                    nm.store.iframe.width(750);
                }
            }
            }).trigger('nyroModal');
        return false;
    });


    $('.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').qtip({ 
        style: { 
            'name': 'dark',
            'filter':'alpha(opacity=70)',
            '-moz-opacity':'0.7',
            '-khtml-opacity': '0.7',
            'opacity': '0.7',
            'border': {
                'width' : '0',
                'color': '#505050'
            }, 
            'tip': true
        } 
    });
}

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) {

    timeout = typeof(timeout) !== 'undefined' ? timeout : 0;
    target = $(target);
    
    // remove all qtip
    $(".qtip").remove();
    
    if(target.realVal().length > 0) {
        target.nextAll(".searchclear").show();
    }

    if(target.attr('timer')) {
        clearTimeout(target.attr('timer'));
    }

    target.attr(
        'timer',
        setTimeout(function() {
            target.next(".searchajaxloader").show();
            target.nextAll(".searchclear").hide();
            var filterVal = "_" + escape(target.realVal());
            url = url.replace('__FILTER__',filterVal);
            $.ajax({
                url: url,
                cache: false,
                success: function(data, status, request) {
                    $(container_selector).html(data);
                    target.next(".searchajaxloader").hide();
                    if(target.realVal().length > 0) {
                        target.nextAll(".searchclear").show();
                    }
                    init_events($(container_selector));
                    target.removeAttr('timer');
                }
            });    
        },
        300)
    );
}


function init_events_contents(base_node, embed_url, content_filter_url) {
    
    init_events_base(base_node, embed_url);
    
    $('.content_link_create').each(function(i){
        $(this).attr("target","_blank");
    });
    $('.content_link_create').nyroModal({
        filters: ['iframe'],
        sizes: {
            minW: 770,
            minH: 550
        },
        callbacks: {
            afterClose: function(nm) {
                searchCallback($('#searchprojectsinput'), "#contentslistcontainer", content_filter_url);
            },
            afterShowCont: function(nm) {
                nm.store.iframe.width(770);
                nm.store.iframe.height(550);
                nm.store.iframe.load(function() {
                    var form_status = $(this).contents().find("#content_form_status").val(); 
                    if(form_status === 'saved' || form_status === 'deleted' ) {
                        $.nmTop().close();
                    }
                });
            }
        }
    });
    $('.content_link_create',base_node).each(function(i, e) {
        nm = $(e).data('nmObj');
        $(e).data('nmObj', $.extend(true, nm, {
            close: testCreateAndClose(nm, nm.close)
        }));
    });  
    
    $('.contenttitlelink').each(function(i){
        $(this).attr("target","_blank");
    });
    $('.contenttitlelink').nyroModal({
        filters: ['iframe'],
        sizes: {
            minW: 770,
            minH: 550
        },
        callbacks: {
            afterClose: function(nm) {
                searchCallback($("#searchcontentsinput"),"#contentslistcontainer",content_filter_url,0);    
            },
            afterShowCont: function(nm) {
                nm.store.iframe.width(770);
                nm.store.iframe.height(550);
                nm.store.iframe.load(function() {
                      var form_status = $(this).contents().find("#content_form_status").val(); 
                      if(form_status === 'saved' || form_status === 'deleted') {
                          $.nmTop().close();
                      }
                  });
            }
        }
    });
    
}

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

    // These are the functions called when we display a project in an LDT modal window
    $('.ldt_link',base_node).each(function(i){
        $(this).attr("target","_iri");
    });
    $('.ldt_link',base_node).nyroModal({
        filters: ['iriIframe'],
        sizes: {
            minW: '1025',
            minH: '665'
        },
        showCloseButton: true,
        closeOnEscape:false,
        closeOnClick:false,
        callbacks: {
            afterShowCont: function(nm) {
                nm.store.iframe.width(1025);
                nm.store.iframe.height(665);
            },
            close: function(nm) {
                // We don't do anything here, we hack the callback directly from the close function.
            },
            afterClose: function(nm) {
                // Can't do that because searchprojectfilterurl is not defined in init_events_base params
                searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0);
            }
        }
    });


    $('.ldt_link',base_node).each(function(i, e) {
        nm = $(e).data('nmObj');
        $(e).data('nmObj', $.extend(true, nm, {
            close: testAndClose(nm.close)
        }));
    });    


    $('.ldt_link_create',base_node).each(function(i){
        $(this).attr("target","_iri");
    });
    $('.ldt_link_create',base_node).nyroModal({
         
        filters: ['iriIframe'],
        sizes: {
            minW: '600',
            minH: '500'
        },
        showCloseButton:true,
        closeOnEscape:false,
        closeOnClick:false,
        callbacks: {
            afterShowCont: function(nm) {
                nm.store.iframe.width(600);
                nm.store.iframe.height(600);
                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();
                    }
                    var swfobject = $(this).contents().find("#ldtInitSwf"); 
                    if (swfobject.length) {
                        nm['sizes']['initW'] = 1025;
                        nm['sizes']['initH'] = 665;
                        nm.resize();
                        nm.store.iframe.width(1025);
                        nm.store.iframe.height(665);
                    }
                });
            },
            afterClose: function(nm) {
                searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0);
            }
        }        
    });
    $('.ldt_link_create',base_node).each(function(i, e) {
        nm = $(e).data('nmObj');
        $(e).data('nmObj', $.extend(true, nm, {
            close: testAndClose(nm.close)
        }));
    });

    
    $('.publishedproject', base_node).click(function(e) {
        e.preventDefault();
        var target = $(e.target);
        var project_id = target.attr('id').replace('project_','');
        var url = unpublishprojecturl.replace('__PROJECT_ID__', project_id);
        $.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);
                }
            }
        });
    });
    
    $('.unpublishedproject', base_node).click(function(e) {
        e.preventDefault();
        var target = $(e.target);
        var project_id = target.attr('id').replace('project_','');
        var url = publishprojecturl.replace('__PROJECT_ID__', project_id);
        $.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);
                }
            }
        });
    });

    $('.projecttitlelink').each(function(i){
        $(this).attr("target","_blank");
    });
    $('.projecttitlelink').nyroModal({
        filters: ['iframe'],
        sizes: {
            minH:680, 
            minW:600
        },
        callbacks: {
            afterClose: function(nm) {
                searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0);
            },
            afterShowCont: function(nm) {
                nm.store.iframe.height(680);
                nm.store.iframe.width(600);
                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();
                      }
                  });
            }
        }
    });
    
}

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);
    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();
         }
    });        
     
    $('.searchfieldinput').each(function(i) {
         var sbox = $(this);
         if(sbox.val() !== '') {
             sbox.attr('defaultText', sbox.val());
         }
    
         sbox.focus(function() {
             box = $(this);
             if(box.val() === box.attr('defaultText')) {
                 box.val('');
                 box.toggleClass("searchfieldinput");
             }
         });
    
         sbox.blur(function() {
             var box = $(this);
             if(box.val() === '' && box.attr('defaultText')) {
                 box.val(box.attr('defaultText'));
                 box.toggleClass("searchfieldinput");
             }
         });
                  
    });

    $.each(input_list_init, function(index, value) {
        $(value['input_selector']).keyup(function (e) {
            searchCallback(e.target, value['container_selector'], value['url']);
        });
    });
    
    $('.searchclear').click(function(e) {
        var box = $(e.target).parent().find("input");
        box.val(box.attr('defaultText'));
        box.addClass("searchfieldinput");
        box.blur();
        box.keyup();
    });
    
    $('.searchclear').each(function(i) {
        $(this).hide();
    });
    
}

//
// 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) {
	
    window.upload_from_local_done = false;
    window.submit_asked = false;
    window.remove_temp_file_url = remove_url;
    
    $("#close_button").click(function (e) {
        e.preventDefault();
        parent.$.nmTop().close();
    });
    $("#submit_button_write").click(function(e) {
        $(".submitcontent-loader-content").show();
    });
    $(".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').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();
                    }
                }
                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){
            //$('#id_content-description').val($('#media_field_create') + '<img src="http://img.youtube.com/vi/'+vid+'/default.jpg" alt="Youtube Thumbnail"/>');
            $('#media_field_create').append('<img id="external_thumbnail" src="http://img.youtube.com/vi/'+vid+'/default.jpg" alt="Youtube Thumbnail"/>');
            $('#media_fields_div').height(150);
        }
    }
}
