$.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',base_node).nyroModal({
       	type: 'iframe',
       	forceType: 'iframe',
       	windowResize: false,
   		height:662, 
   		width:1022,
   		bgColor: 'rgb(239, 239, 239)',
   		padding: 5,
   		titleFromIframe: false,
        beforeHideContent: function(elts, settings, callback){
	        try {
	             var res = $('#ldtInitSwf',$('#nyroModalIframe').contents());
	             if(res.length > 0)
	             {
	             	   res.get(0).forceSave();
	             }
	        }
	        catch(err)
	        {
	         // do nothing
	        }                   
	        callback();
   		},

      	});
    	

	$('.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);
		/*$.nyroModalSettings({
		 	ajax: { data: ({ json_url:json_url, player_id:player_id }) }
		  	});*/
		   $.nyroModalManual({
		       type: 'iframe',
		       forceType: 'iframe',
		       titleFromIframe: false,
		       height:662, 
               width:750,
               bgColor: 'rgb(239, 239, 239)',
               padding: 5,
		       url: embed_url+'?json_url='+escape(json_url)+'&player_id='+escape(player_id)+'&ldt_id='+escape(ldt_id),
		   });
		   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 searchCallback(target, container_selector, url, timeout) {

	timeout = typeof(timeout) != 'undefined' ? timeout : 0;
	var 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').nyroModal({
	    type: 'iframe',
	    forceType: 'iframe',
	    height:500, 
	    width:765,
	    bgColor: 'rgb(239, 239, 239)',
	    padding: 5,
	    titleFromIframe: false,
	    endRemove: function(elts, settings) {
	    	searchCallback($("#searchcontentsinput"),"#contentslistcontainer",content_filter_url)
		},
	  	endShowContent: function(elts, settings) {
		  	$('#nyroModalIframe', elts.content).load(function() {
			  	var form_status = $(this).contents().find("#content_form_status").val(); 
			  	if(form_status == 'saved' || form_status == 'deleted' ) {
			  		$.nyroModalRemove();
			  	}
		  	});
		}
	});
	
	$('.contenttitlelink').nyroModal({
	    type: 'iframe',
	    forceType: 'iframe',
	    height:500, 
	    width:765,
	    bgColor: 'rgb(239, 239, 239)',
	    padding: 5,
	    titleFromIframe: false,
	    endRemove: function(elts, settings) {
	    	searchCallback($("#searchcontentsinput"),"#contentslistcontainer",content_filter_url,0);
		},
	  	endShowContent: function(elts, settings) {
		  	$('#nyroModalIframe', elts.content).load(function() {
			  	var form_status = $(this).contents().find("#content_form_status").val(); 
			  	if(form_status == 'saved' || form_status == 'deleted') {
			  		$.nyroModalRemove();
			  	}
		  	});
		}
	});


}

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

 	$('.ldt_link_create',base_node).nyroModal({
        type: 'iframe',
        forceType: 'iframe',
        windowResize: false,
        height:680, 
        width:500,
        bgColor: 'rgb(239, 239, 239)',
        padding: 5,
        titleFromIframe: false,
	    endRemove: function(elts, settings) {
 			searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0);
		},
        beforeHideContent: function(elts, settings, callback){
             try {
	              var res = $('#ldtInitSwf',$('#nyroModalIframe').contents());
	              if(res.length > 0)
	              {
	              	   res.get(0).forceSave();
	              }
             }
             catch(err)
             {
              // do nothing
             }                   
             callback();
        	},
        endShowContent: function(elts, settings){
    		var iframe = $('#nyroModalIframe', elts.content);
			iframe.load(function(){
			  	var form_status = $(this).contents().find("#project_form_status").val(); 
			  	if(form_status == 'saved' || form_status == 'deleted' ) {
			  		$.nyroModalRemove();
			  	}
				var swfobject = $(this).contents().find("#ldtInitSwf"); 
				if (swfobject.length) {
					$.nyroModalSettings({
						height: swfobject.height() + 31,
						width: swfobject.width() + 21
					});
				}
			});
        	}
    	});

	
	$('.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',
			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',
			dataType: 'json',
			success: function(json, textStatus, XMLHttpRequest){
				if(json.res) {
					searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0);
				}
			}
		});
	});

	$('.projecttitlelink').nyroModal({
	    type: 'iframe',
	    forceType: 'iframe',
        height:680, 
        width:500,
	    bgColor: 'rgb(239, 239, 239)',
	    padding: 5,
	    titleFromIframe: false,
	    endRemove: function(elts, settings) {
			searchCallback($('#searchprojectsinput'), "#projectslistcontainer", searchprojectfilterurl, 0);
		},
	  	endShowContent: function(elts, settings) {
		  	$('#nyroModalIframe', elts.content).load(function() {
			  	var form_status = $(this).contents().find("#project_form_status").val(); 
			  	if(form_status == 'saved' || form_status == 'deleted') {
			  		$.nyroModalRemove();
			  	}
		  	});
		}
	});
	
}

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

}
