$(document).ready( function() {
     
	//$("form.markup textarea").markItUp(myTextileSettings);
	//$('.actionmenu').actionmenu();
	
    Utils.toggler('.toggler');
	
	
	
    Utils.load_content('a.ajax.reload_page', function(reciever, response) {
        reciever.html(response);
        $(document).trigger('reload_page');
      
    });
    Utils.load_content('a.ajax');
	Utils.load_content('a.ajax_smooth', function(reciever, response) {
		reciever.html(response);
		reciever.css('display', 'none');
		reciever.fadeIn('1000');
	});
    
    
	
	

    $('.dialogbox').dialogbox();
   
 

    /*$('a[rel*=facebox]').click(function() {
        $(this).dialog();   
        return false; 
    });*/
    $('a[rel*=facebox]').facebox();
    $('.fancybox').fancybox();
    $('.hoverbtn').hoverbtn();
    $('.ajaxtabs').ajaxtabs();


    
});



$.fn.dialogbox = function(opts) {
    
    var options = {
        unique: true
    }

    var opts = $.extend(options, opts);


    var invoker = $(this);
    var url = invoker.attr('href');
    invoker.unbind('click');
    invoker.bind('click', function() {
        
        // unbind the dialogbox behavior in case the invoker should be unique
        if (opts.unique) {
            invoker.unbind('click');
            invoker.bind('click', function() {return false});
        }
        
        $.ajax({
			type : 'GET',
			url : url,
			dataType : 'html',
			beforeSend: function() {
				
			},
			success : function(response) { 
                var html_obj = $(response);
                var dialog_header = html_obj.find('.dialog_header');
                var title = dialog_header.html();
                
                var dialog = $(response).dialog({
                    modal: true,
                    title: title,
                    open: function() {
                        $('.dialog_header').remove();
                    },
                    width: 500,
                    resizable: false,
                    beforeclose: function() {
                        // destroy dialog when close is invoked
                        $(this).dialog('destroy');
                        $(this).remove();
                        // add the dialogbox behavior in case unique mode is active    
                        if (opts.unique) {
                            invoker.dialogbox();
                        }        
                    }
                });		
                ;
                
            }  
		});
        
        return false;
    });
    
}



var display_loader = function(target, height) {
    $(target).html('<span style="margin-top:' + $(target).height()/2 +  'px" class="loading"></span>')
}






/**
 *  Sets the content of an element to 'invinsible' shows it on hover and
 *  sets it to invinsible again when mouse leaves
 */
$.fn.hoverbtn = function() {

    $(this).css({'border': '0px solid red','cursor': 'pointer'});
    $(this).children().css({'visibility': 'hidden'});


   /*
    $(this).hover(function(){
       $(this).children().css('visibility', 'visible');
    }, function(){
        $(this).children().css('visibility', 'hidden');
    });
    */

   $(this).live('mouseover', function(){
       $(this).children().css('visibility', 'visible');
   });
   $(this).live('mouseout', function(){
        $(this).children().css('visibility', 'hidden');
   });

   

}



/**
 *  Sets the content of an element to 'invinsible' shows it on hover and
 *  sets it to invinsible again when mouse leaves
 */
$.fn.ajaxtabs = function() {

    var tab_nav = $(this);

    tab_nav.each(function() {
        var tabs = $(this).find('a');
        tabs.each(function(){
            // disable all tabs
            // hide all tab contents
            $(this).removeAttr('id');
            $('#' + $(this).attr('href').split('#')[1]).css('display', 'none');
        });
        if (tabs.length > 0) {
            $(tabs[0]).attr('id', 'current');
            $('#' + $(tabs[0]).attr('href').split('#')[1]).css('display', 'block');
        }


        tabs.bind('click', function(){
            var invoker = $(this);


            tabs.each(function(){

                // disable all tabs
                // hide all tab contents
                $(this).removeAttr('id');
                $('#' + $(this).attr('href').split('#')[1]).css('display', 'none');
            });

            // enable current tab
            invoker.attr('id', 'current');
            var tab_content_container = $('#' + $(this).attr('href').split('#')[1]);
            //alert(tab_content_container.html());
            tab_content_container.css('display', 'block');
            return false;
        });
    });

    

}




Utils = {};
Utils.refresh = function(update, url) {
	$.ajax({
		type: 'POST',
    	url: url,
    	dataType: 'html',
    	beforeSend: function() {
			$(update).html('<div class="loader" style=" margin:auto; margin-bottom:123px; margin-top:333px; ">Loading</div>')
		},
    	success: function(response) {
			$(update).html(response);
		}
	});
	
}


Utils.toggler = function(selector) {

	$(selector).live('click', function() {

		var href = $(this).attr('href');
		var reciever = $('#' + href.split('#')[1]);

		reciever.toggle('slow');
		return false;
	});

}

Utils.display_picture = function(selector, target) {

	var invokers = $(selector);
	var target = $(target);

	$.each(invokers, function() {
		var elem = $(this);
		elem.bind('click', function() {
			target.html('<img src="' + elem.attr('href') + '"/>');
			return false;
		});
	});

}

/**
 *	Loads content via ajax in an area.
 *	The element specified by selector must be an a-tag.
 *
 *	href="/url/to/view/#<id>"
 *
 *	Sends an ajax-request and puts the result in $(#<id>)
 */
Utils.load_content = function(selector, callback) {

	var invokers = $(selector);
    var callback = callback;
    

	invokers.live('click', function() {
        
		var invoker = $(this);
		var href = invoker.attr('href');

		var url = href.split('#')[0];
		var reciever = $('#' + href.split('#')[1]);
        
		$.ajax( {
			type : 'GET',
			url : url,
			dataType : 'html',
			beforeSend: function() {
				display_loader(reciever);
			},
			success : function(response) { 
				if (callback != null)
					callback(reciever, response);
				else {

                    if (invoker.attr('rel') == 'replace')
                        reciever.replaceWith(response);
                    else
                        reciever.html(response);
				}
				
            }
            
		});

		return false;

	});

}

Utils.makeSortable = function(selector, url, opts) {

	var container = $(selector);

	container.sortable( {
		opacity : 0.7,
		handle : '.dragzone',
		scroll : true,
		forceHelperSize : true,
        connectWith: opts.connectWith,
		stop : function() {

            if (opts.finish != null)
                opts.finish();

			var data = [];

			$.each(container.children(), function() {
                // split to enable prefix to prevent id-collisions
                var id_attr = $(this).attr("id");
                var id = null;

                if (id_attr.search('_') == -1) {

                    id = id_attr;
                } else {
                    id = id_attr.split('_')[1];
                }
        		data.push(id);
			});

			$.ajax( {
				type : 'POST',
				url : url,
				data : {
					'elems' : $.toJSON(data)
				},
				success : function(msg) {
                    if (opts.callback != null)
                        opts.callback()
				}
			});
		}

	});
}

var confirm = function(elem) {
	var elem = $(elem);
	elem.empty();
	elem.append('Saved');
	elem.hide("puff", {}, 1000);

}
