/*
 * $Id: jquery.faba5.util-1.0.js 2325 2011-08-19 07:10:42Z markus.tripp@fabasoft.com $
 * 
 * Copyright © Fabasoft R&D GmbH, A-4020 Linz, 1995-2011.
 * 
 * All rights reserved. All hardware and software names used are registered trade names and/or registered trademarks of  
 * the respective manufacturers.
 * 
 * The user of this computer program acknowledges that the above copyright notice, which constitutes the Universal 
 * Copyright Convention, will be attached at the position in the function of the computer program which the author has 
 * deemed to sufficiently express the reservation of copyright. It is prohibited for customers, users and/or third  
 * parties to remove, modify or move this copyright notice.
 * 
 * This computer program is protected by copyright law and international treaties. Unauthorized reproduction or 
 * redistribution of this program, or any portion of it, may result in severe civil and criminal penalties.
 * 
 * The use of this software requires a valid license agreement for this software. This license agreement specifies 
 * especially permitted use through the licensing model. A license agreement must already exist prior to installing the 
 * software as the installation process of this software does not include the conclusion of a license agreement.
 */

(function ($) {

    var dialogValuesMethods = {
        fill: function() {
            var data = $(this).data('fdialogValues') || {};
            
            return this.each(function() {
                $(this).find('.fdialogValue').each(function() {
                    var name = $(this).attr('name');
                    $(this).val(data[name]);
                });
            });
        },
        update: function() {
            var data = $(this).data('fdialogValues');
            if (data == undefined) {
                data = {};
                $(this).data('fdialogValues', data);
            }
            
            return this.each(function() {
                $(this).find('.fdialogValue').each(function() {
                    var name = $(this).attr('name');
                    var value = $(this).val();
                    
                    if (name && value) {
                        data[name] = value;
                    }
                });
            });
        }
    };
    
    var blindMethods = {
        show: function(blindOptions, visibleOptions) {
            var blindSettings = {
                background: 'black',
                opacity: '.4',
                position: 'absolute',
                top: '0',
                left: '0',
                'z-index': '999',
                width: '100%',
                height: $(window).height()
            };
            
            var visibleSettings = {
                'z-index': parseInt(blindSettings['z-index']) + 1,
                position: 'relative'
            };
            
            if (blindOptions) {
                $.extend(blindSettings, blindOptions);
            }
            
            if (visibleOptions) {
                $.extend(visibleSettings, visibleOptions);
            }
            
            if ($('#fblind').length > 0) {
                $('#fblind').remove();
            }
            
            var blind = $('<div id="fblind"></div>');
            blind.css(blindSettings).appendTo('body').fadeIn();

            $(window).resize(function() {
                blind.height($(window).height());
            });
            
            $(document).scroll(function(){
                blind.css('top', $(document).scrollTop() + 'px');
            });
            
            return this.each(function() {
                $(this).css(visibleSettings).addClass('fblind');
            });
        },
        hide: function() {
            $('#fblind').remove();

            return this.each(function() {
                $(this).css('z-index', '0').removeClass('fblind');
            });
        },
        toggle: function(options) {
            if ($('#fblind').length == 0) {
                show(options);
            } else {
                hide(options);
            }
        }
    };
    
    $.fn.dialogValues = function(method) {
        if (dialogValuesMethods[method]) {
            return dialogValuesMethods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
    };

    $.fn.blind = function(method) {
        if (blindMethods[method]) {
            return blindMethods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
    };
    
    $.fn.options = function(list, isDynamic, callback) {
        
        return this.each(function() {
            if (!list.is(':visible')) {
                if (isDynamic) {
                    list.menu().appendTo('body').hide();
                }
                
                var offset = $(this).offset();
                var topOffset = $(this).outerHeight();
                var leftOffset = $(this).outerWidth() - list.outerWidth();
                
                list.css({
                    top: offset.top + topOffset,
                    left: offset.left + leftOffset,
                    position: 'absolute',
                    'white-space': 'nowrap',
                    'text-align': 'right'
                }).slideDown(function() {
                    $(document).bind('click.options', function() {
                        $(document).unbind('click.options');
                        list.slideUp(function() {
                            if (isDynamic) {
                                list.remove();
                            }
                            if (callback) {
                                callback.apply(this);
                            }
                        });
                    });
                });
            }
        });
    };
    
    $.fn.message = function(text, options) {
        var settings = {
            type: 'finfo',
            delay: 5000,
            autoHide: true
        };
        
        if (options) {
            $.extend(settings, options);
        }

        return this.each(function() {
            var message = $('<div class="fmessage"></div>').hide().addClass(settings.type).html(text).prependTo($(this)).slideDown();
            
            if (settings.autoHide) {
                message.delay(settings.delay).slideUp();
            }
        });
    };
    
    $.fn.pageSortable = function() {
        return this.each(function() {
            $(this).sortable({
                stop: function(event, ui) {
                    var el = $(ui.item);
                    var id = el.attr('id');
                    
                    var data = {};
                    
                    data.parent = el.closest('ul').data('parent');
                    if (!data.parent) {
                        data.parent = el.data('parent');
                    }
                    
                    data.after = el.prev('li').attr('id');
                    
                    pageMove(id, data, el);
                }
            }).disableSelection();
            
            $(this).find('.fsortableOutdent').click(function() {
                var el = $(this).closest('li');
                var id = el.attr('id');
                
                var ul = el.parent();
                var parent = ul.parent().parent();
                
                var data = {
                    parent: parent.data('parent'),
                    after: ul.data('parent')
                };
                
                if (data.parent) {
                    pageMove(id, data, el, null, ul.parent());
                }
                
                return false;
            });
            
            $(this).find('.fsortableIndent').click(function() {
                var el = $(this).closest('li');
                var id = el.attr('id');
                
                var prev = el.prev('li');
                if (prev) {
                    pageMove(id, {parent: prev.attr('id')}, el, prev);
                }
                
                return false;
            });
            
            updateIndents($(this));
        });
    };
    
    var pageMove = function(id, data, el, prev, after) {
        var path = $('html').data('path');
        var url =  path + '/api/page/move/' + id + '.json';
        if (!data.after) {
            data.after = 'last';
        }
            
        $.ajax({
            type: 'GET',
            url: url,
            data: data,
            success: function(data) {
                if (el) {
                    updateIndents(el.parent());
                    
                    if (prev) {
                        var moveTo = prev.find('ul');
                        if (moveTo.length == 0) {
                            moveTo = $('<ul/>').data('parent', prev.attr('id')).data('root', false);
                            prev.append(moveTo);
                        }
                        
                        moveTo.append(el);
                        updateIndents(moveTo);
                    }
                    
                    if (after) {
                        el.insertAfter(after);
                        updateIndents(after.parent());
                    }
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $('body').message('Error moving page', {type: 'ferror'});
            }
        });
    };
    
    var updateIndents = function(el) {
        var isRoot = el.data('root');
        el.children().each(function(index, element) {
            if (index == 0) {
                $(element).children('.fsortableIndent').hide();
            } else {
                $(element).children('.fsortableIndent').show();
            }
            
            if (isRoot) {
                $(element).children('.fsortableOutdent').hide();
            } else {
                $(element).children('.fsortableOutdent').show();
            }
        });
    };
}) (jQuery);
