/*
 * jQuery pageSlide
 * Version 2.0
 * http://srobbin.com/jquery-pageslide/
 *
 * jQuery Javascript plugin which slides a webpage over to reveal an additional interaction pane.
 *
 * Copyright (c) 2011 Scott Robbin (srobbin.com)
 * Dual licensed under the MIT and GPL licenses.
*/

!(function($){
    // Convenience vars for accessing elements
    var $body = $('#main-wrap'),
        $bottomNav = $('.bottomnav'),
        $pageslide = $('#pageslide'),
        $viewPage = $('#view-page');
    
    var _sliding = false,   // Mutex to assist closing only once
        _lastCaller;        // Used to keep track of last element to trigger pageslide
    
    // If the pageslide element doesn't exist, create it
    if( $pageslide.length == 0 ) {
         $pageslide = $('<div />').attr( 'id', 'pageslide' )
                                  .css( 'display', 'none' )
                                  .appendTo( $body );
    }
    
    /*
     * Private methods 
     */
    function _load( url, useIframe, callback,element ) {
        // Are we loading an element from the page or a URL?
        if ( url.indexOf("#") === 0 ) {                
            // Load a page element                
            $(url).clone(true).appendTo( $pageslide.empty() ).show();
            if(callback)callback.call(this,$pageslide,element);
        } else {
            // Load a URL. Into an iframe?
            if( useIframe ) {
                var iframe = $("<iframe />").attr({
                                                src: url,
                                                frameborder: 0,
                                                hspace: 0
                                            })
                                            .css({
                                                width: "100%",
                                                height: "100%"
                                            });
                
                $viewPage.find('.content').html( iframe );
                $viewPage.clone(true).appendTo( $pageslide.empty() ).show();
                $viewPage.find('.content').empty();
                if(callback)callback.call(this,$viewPage,element);
            } else {
                $viewPage.find('.content').load(url, function(){
                    $viewPage.clone(true).appendTo( $pageslide.empty() ).show();
                    if($('#filter-default-tag').length) {
                        $('#filter-default-tag').fastLiveFilter('.add-default-tags-list', '.filter-item', '.tag');
                        addTagsTab();
                        $('#view-page .card').cardCheck({
                            item: $('#view-page input[type="checkbox"]'),
                        });
                    };
                    if(callback)callback.call(this,$viewPage,element);
                });
            }
            
            $pageslide.data( 'localEl', false );
            
        }
    }
    
    // Function that controls opening of the pageslide
    function _start( direction, speed ) {
        var slideWidth = $pageslide.outerWidth( true ),
            bodyAnimateIn = {},
            bottomnavAnimateIn = {},
            slideAnimateIn = {};
        
        // If the slide is open or opening, just ignore the call
        if( $pageslide.is(':visible') || _sliding ) return;         
        _sliding = true;
                                                                    
        switch( direction ) {
            case 'left':
                $pageslide.css({ left: 'auto', right: '-' + slideWidth + 'px' });
                bodyAnimateIn['width'] = '-=' + slideWidth;
                slideAnimateIn['right'] = '+=' + slideWidth;
                break;
            default:
                if($sidebarState && !$('.item-groups').length) {
                    $pageslide.css({ left: '-' + (slideWidth-241) + 'px', right: 'auto' });
                }else{
                    $pageslide.css({ left: '-' + (slideWidth-61) + 'px', right: 'auto' });
                };
                bodyAnimateIn['margin-left'] = '+=' + slideWidth;
                bottomnavAnimateIn['left'] = '+=' + slideWidth;
                if($(window).width() <= 1440 && slideWidth > 963 ) {
                    bodyAnimateIn['width'] = $body.width();
                }
                slideAnimateIn['left'] = '+=' + slideWidth;
                break;
        }
                    
        // Animate the slide, and attach this slide's settings to the element
        $body.animate(bodyAnimateIn, speed);
        $bottomNav.animate(bottomnavAnimateIn, speed);
        $pageslide.show().animate(slideAnimateIn, speed, function() {
            _sliding = false;
            $pageslide.children('.nano').nanoScroller({ scrollTop: 0, iOSNativeScrolling: true });
            if(typeof $.fn.pageslide.defaults.openFn === "function") {
                var returnValue = ($.fn.pageslide.defaults.iframe ? $viewPage : $pageslide);
                $.fn.pageslide.defaults.openFn.call(this,returnValue);
            };
        });
    }
      
    /*
     * Declaration 
     */
    $.fn.pageslide = function(options) {
        var $elements = this;
        // On click
        $elements.bind(clickEvent, function(e) {
            var $self = $(this),
                settings = $.extend({ href: $self.attr('href') }, options);

            // Prevent the default behavior and stop propagation
            e.preventDefault();
            e.stopPropagation();
            
            if ( $pageslide.is(':visible') && $self[0] == _lastCaller ) {
                // If we clicked the same element twice, toggle closed
                $.pageslide.close();
            } else {                 
                // Open
                $.pageslide( settings,$self );

                if($('.item-groups').length) {
                    $('.item-menu > a, .navbar-inner').removeClass("active");
                    $(this).parents('.navbar-inner').addClass('active').end().addClass('active');
                    if(!$.support.touch) {
                        if($('.item-menu > a').hasClass('active')) {
                            $('.item-menu').css({
                                'display': 'none',
                            });
                            $(this).parents('.item-menu').css({
                                'display': 'inline-block',
                            });
                        }
                    }

                    $pageName = $self.parents('.item-title').children('a').text();
                    $('.page-name').text($pageName);
                } else if($('.tags-groups').length) {
                    if($('.gallery').length) {
                        $(this).closest('.rgalbum').addClass('active-single').siblings().removeClass('active-single');
                        if($(this).closest('ul').hasClass('photo-action')) {
                            $('.checkbox').prop('checked', false);
                            $('.rgalbum').removeClass('active');
                            $('.deletephoto, .deselect, .addtags').addClass('hide');
                        }
                    } else {
                        $(this).closest('li').addClass("active").siblings().removeClass("active").parent('ul').siblings().children('li').removeClass("active");
                    }
                } else {
                    $(this).parents("tr").addClass("active").siblings().removeClass("active");;
                }
                $pageslide.focusFirstField(); // focus first form
                setTimeout(setScroll, 300);
                // Record the last element to trigger pageslide
                _lastCaller = $self[0];
            };

        });                   
    };
    
    /*
     * Default settings 
     */
    $.fn.pageslide.defaults = {
        speed:      300,        // Accepts standard jQuery effects speeds (i.e. fast, normal or milliseconds)
        direction:  'right',    // Accepts 'left' or 'right'
        modal:      false,      // If set to true, you must explicitly close pageslide using $.pageslide.close();
        iframe:     false,      // By default, linked pages are loaded into an iframe. Set this to false if you don't want an iframe.
        href:       null,       // Override the source of the content. Optional in most cases, but required when opening pageslide programmatically.
        W:          264,
        closeFn :   null,
        openFn :    null,
        loadComplete : null
    };
    
    /*
     * Public methods 
     */
    
    // Open the pageslide
    $.pageslide = function( options,element ) {     
        // Extend the settings with those the user has provided
        var settings = $.extend({}, $.fn.pageslide.defaults, options);
        var convertToFunction = function(fn){
            var x = new Function();
            x = fn;
            return x;
        }

        // Change Object to Function
        if(settings.openFn) {
            $.fn.pageslide.defaults.openFn = convertToFunction(settings.openFn);
        };

        if(settings.closeFn) {
            $.fn.pageslide.defaults.closeFn = convertToFunction(settings.closeFn);
        }
        if(settings.loadComplete) {
            $.fn.pageslide.defaults.loadComplete = convertToFunction(settings.loadComplete);
        }
        
        // Are we trying to open in different direction?
        if( ($pageslide.is(':visible') && $pageslide.data( 'W' ) != settings.W) || ($pageslide.is(':visible') && $pageslide.data( 'direction' ) != settings.direction) ) {
            $.pageslide.close(function(){
                $pageslide.css({'width': settings.W});
                _load( settings.href, settings.iframe, settings.loadComplete, element );
                _start( settings.direction, settings.speed );
            });
        } else {                
            _load( settings.href, settings.iframe, settings.loadComplete,element );
            if( $pageslide.is(':hidden') ) {
                $pageslide.css({'width': settings.W});
                _start( settings.direction, settings.speed );
            }
        }
        
        $pageslide.data( settings );


        
        if($('#add-tags').length) {
            $('.set_new').addClass('active in').siblings().removeClass('active in');
            $('#pageslide .selete_defat .search-query').attr('id','filter-default-tag');
            $('#filter-default-tag').fastLiveFilter('.add-defalt-tags-list', '.filter-item', '.tag');
            $('.add-defalt-tags-list .filter-item').removeClass('mark');
        };


    };

    // Close the pageslide
    $.pageslide.close = function( callback ) {
        var $pageslide = $('#pageslide'),
            slideWidth = $pageslide.outerWidth( true ),
            speed = $pageslide.data( 'speed' ),
            bodyAnimateIn = {},
            bottomnavAnimateIn = {};
            slideAnimateIn = {}
                        
        // If the slide isn't open, just ignore the call
        if( $pageslide.is(':hidden') || _sliding ) return;          
        _sliding = true;
        
        switch( $pageslide.data( 'direction' ) ) {
            case 'left':
                bodyAnimateIn['width'] = '+=' + slideWidth;
                slideAnimateIn['right'] = '-=' + slideWidth;
                break;
            default:
                bodyAnimateIn['margin-left'] = '-=' + slideWidth;
                bottomnavAnimateIn['left'] = '-=' + slideWidth;
                slideAnimateIn['left'] = '-=' + slideWidth;
                if($pageslide.find('.preview').length) {
                    $pageslide.find('.preview').cycle('destroy');
                    $pageslide.find('.preview img').removeAttr('style');
                }
                break;
        }

        if($('.item-groups').length) {
            $(".navbar-inner").removeClass("active");
            $('.item-menu > a, .navbar-inner').removeClass("active");
            if(!$.support.touch) {
                $('.item-menu').css({
                    'display': 'none',
                });
            }
        } else if($('.tags-groups').length) {
            $('.tags-groups').children('li').removeClass("active");
            $('.rgalbum').removeClass("active-single");
        } else {
            $("tr").removeClass("active");
        };
        
        $pageslide.animate(slideAnimateIn, speed);
        $bottomNav.animate(bottomnavAnimateIn, speed);
        $body.animate(bodyAnimateIn, speed, function() {
            $pageslide.hide();
            _sliding = false;
            if( typeof callback != 'undefined' ) callback();
            $body.css({'width': 'auto'});
            if(typeof $.fn.pageslide.defaults.closeFn === "function") {
                var returnValue = ($.fn.pageslide.defaults.iframe ? $viewPage : $pageslide);
                $.fn.pageslide.defaults.closeFn.call(this,returnValue);
            };
        }); 
    }

    // Close Callback
    $.pageslide.closeCallback = function(callback) {
        if(typeof callback === "function"){
            $.fn.pageslide.defaults.closeFn = callback;
        };
    };
    
    // Open Callback
    $.pageslide.openCallback = function(callback) {
        if(typeof callback === "function"){
            $.fn.pageslide.defaults.openFn = callback;
        };
    };

    //data load complete callback
    $.pageslide.loadComplete = function(callback) {
        if(typeof callback === "function"){
            $.fn.pageslide.defaults.loadComplete = callback;
        };
    };
    
    /* Events */
    
    // Don't let clicks to the pageslide close the window
    $pageslide.click(function(e) {
        e.stopPropagation();
    });

    // Close the pageslide if the document is clicked or the users presses the ESC key, unless the pageslide is modal
    $(document).bind('click keyup', function(e) {
        // If this is a keyup event, let's see if it's an ESC key
        if( e.type == "keyup" && e.keyCode != 27) return;
        
        // Make sure it's visible, and we're not modal      
        if( $pageslide.is( ':visible' ) && !$pageslide.data( 'modal' ) ) {          
            $.pageslide.close();
        }
    });
    function setScroll(){
        $pageslide.children('.nano').nanoScroller({ scrollTop: 0, iOSNativeScrolling: true }); // set nano scroll
    };
    
})(jQuery);