
$.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 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();
                    }
                });
            }
        }
    });
    
    $('.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();
    });
    
}
