!function ($) {
  // Convenience vars for accessing elements
  var $pageslide = $('#pageslide'),
      $body = $('#main-wrap'),
      $bottomNav = $('.bottomnav'),
      $element;
  if($pageslide.length == 0) {
    var _html = '<div id="pageslide"><div class="page-title clearfix"><a class="pull-right" href="javascript:$.pageslide.close()"><i class="icons-arrow-left-2"/></a><span/></div><div class="view-page"><div class="nano"><div class="content"/></div></div></div>';
    $pageslide = $(_html).css('display', 'none').appendTo( $body );
  } else {
    $pageslide.css('display', 'none')
  }

  var _sliding = false,   // Mutex to assist closing only once
      _lastCaller;        // Used to keep track of last element to trigger pageslide
  // $(window).resize(function(event) {
  //   if($pageslide.is(':visible')) {
  //     console.log("ddd")
  //     $pageslide.find('.nano').height($('body').height() - $('#orbit-bar').height() - $pageslide.find('.page-title').outerHeight(true));
  //   }
  // });
  function _checkTitle(settings) {
    if(settings.pageTitle) {
      $pageslide.find('.page-title').show().children('span').text(settings.pageTitle);
      $pageslide.find('.view-page').css('top', 48);
    } else {
      $pageslide.find('.page-title').hide();
      $pageslide.find('.view-page').css('top', 0);
    }
  }
  function _load(settings) {
    // Are we loading an element from the page or a URL?
    if ( settings.href.indexOf("#") === 0 ) {
      // Load a page element
      window.console.log("in HTML");
      var _contentHtml = $(settings.href).html();
      var dtd = $.Deferred();
      function appendHtml(dtd) {
        $pageslide.find('.content').html(_contentHtml);
        if($pageslide.find('.content').find('*').length !== 0) {
          dtd.resolve();
        } else {
          dtd.reject();
        }
        return dtd;
      }
      $.when(appendHtml(dtd))
      .done(function() {
        $pageslide.find('.nano').nanoScroller({ scrollTop: 0, iOSNativeScrolling: true });
        if(settings.loadComplete)settings.loadComplete.call(this, $pageslide, $element);
      })
      .fail(function() {});
    } else {
      // Load a URL. Into an iframe?
      if(settings.iframe) {
        window.console.log("iFrame");
        var iframe = $('<iframe id="pageslide_iframe" />').attr({
                                        src: settings.href,
                                        frameborder: 0,
                                        hspace: 0
                                      })
                                      .css({
                                        width: "100%",
                                        height: "100%"
                                      });
        $pageslide.find('.content').css('overflow', 'hidden').html(iframe).show();
        if(settings.loadComplete)settings.loadComplete.call(this, $pageslide, $element);
      } else {
        window.console.log("Load");
        $pageslide.find('.content').load(settings.href, function(response, status, xhr){
          if(status == 'success') {
            $pageslide.show();
            if(settings.loadComplete)settings.loadComplete.call(this, $pageslide, $element);
            $pageslide.find('.nano').nanoScroller({ scrollTop: 0, iOSNativeScrolling: true });
          } else {
            var msg = '<div style="text-align: center;"><i class="icons-warning" style="font-size: 5em;"></i><h4>Oops!</h4>System may be wrong<br/> or please try again later</div>'
            $pageslide.find('.content').html(msg);
          }
        });
      }
      $pageslide.data( 'localEl', false );
    }
    if($pageslide.find('.error-cover').length) $pageslide.find('.error-cover').remove();
    _checkTitle(settings);
  }


  
  // Function that controls opening of the pageslide
  function _start(settings) {
    var slideWidth = $pageslide.outerWidth(true),
        bodyMove = $sidebarState && !$('.item-groups').length ? slideWidth - 241 : settings.direction == 'right' ? slideWidth - 61 : slideWidth,
        bodyAnimateIn = {},
        bottomnavAnimateIn = {},
        slideAnimateIn = {};
    
    // If the slide is open or opening, just ignore the call
    if($pageslide.is(':visible') || _sliding) return;         
    _sliding = true;
                                  
    switch(settings.direction) {
      case 'left':
        $pageslide.css({left: 'auto', right: '-' + slideWidth + 'px'});
        bodyAnimateIn['padding-right'] = '+=' + bodyMove;
        slideAnimateIn['right'] = '+=' + slideWidth;
        break;
      default:
        $pageslide.css({left: '-' + slideWidth + 'px', right: 'auto'});
        bodyAnimateIn['margin-left'] = '+=' + bodyMove;
        bottomnavAnimateIn['left'] = '+=' + bodyMove;
        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, settings.speed);
    $bottomNav.animate(bottomnavAnimateIn, settings.speed);
    $pageslide.show().animate(slideAnimateIn, settings.speed, function() {
      _sliding = false;
      if(typeof settings.openFn === "function") {
        settings.openFn.call(this, $pageslide, $element);
      };
    });
  }


  $.fn.pageslide = function(options) {
    var $elements = this;
      
    // On click
    $elements.click( function(e) {
      var $self = $(this),
          settings = $.extend({href: $self.attr('href'), pageTitle: $self.data('title')}, options);

      $element = $self;    
      // 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);
        // 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,
      pageTitle: '',
  };

  /*
   * Public methods 
   */
  
  // Open the pageslide
  $.pageslide = function(options) {     
    // Extend the settings with those the user has provided
    var settings = $.extend({}, $.fn.pageslide.defaults, options),
        pageCss = {},
        convertToFunction = function(fn){
          var x = new Function();
          x = fn;
          return x;
        };

    pageCss['width'] = settings.W;
    pageCss['margin-left'] = $sidebarState && !$('.item-groups').length ? 241 : settings.direction == 'right' ? 61 : 0;

    // 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(pageCss);
        _checkTitle(settings)
        _load(settings);
        _start(settings);
      });
    } else {
      _checkTitle(settings)
      _load(settings);
      if($pageslide.is(':hidden')) {
        $pageslide.css(pageCss);
        _start(settings);
      }
    }
    
    $pageslide.data(settings);
  }
  
  // Close the pageslide
  $.pageslide.close = function(callback) {
    var $pageslide = $('#pageslide'),
        slideWidth = $pageslide.outerWidth(true),
        bodyMove = $sidebarState && !$('.item-groups').length ? slideWidth - 241 : $.fn.pageslide.defaults.direction == 'right' ? slideWidth - 61 : slideWidth
        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['padding-right'] = '-=' + bodyMove;
        slideAnimateIn['right'] = '-=' + slideWidth;
        break;
      default:
        bodyAnimateIn['margin-left'] = '-=' + bodyMove;
        bottomnavAnimateIn['left'] = '-=' + bodyMove;
        slideAnimateIn['left'] = '-=' + slideWidth;
        break;
    }
    
    $pageslide.animate(slideAnimateIn, speed);
    $bottomNav.animate(bottomnavAnimateIn, speed);
    $body.animate(bodyAnimateIn, speed, function() {
      if($pageslide.data('href') == '#') {
        $pageslide.attr('style', '')
                  .hide()
                  .find('.content')
                  .attr('style', '')
                  .end()
                  .find('.view-page')
                  .attr('style', '')
                  .end()
                  .find('.pane')
                  .remove()
                  .end()
                  .find('.page-title')
                  .attr('style', '')
                  .children('span');
      } else {
        $pageslide.attr('style', '')
                  .hide()
                  .find('.content')
                  .attr('style', '')
                  .empty()
                  .end()
                  .find('.view-page')
                  .attr('style', '')
                  .end()
                  .find('.pane')
                  .remove()
                  .end()
                  .find('.page-title')
                  .attr('style', '')
                  .children('span')
                  .empty();
      }
      _sliding = false;
      if($pageslide.find('.error-cover').length) $pageslide.find('.error-cover').remove();
      if(typeof callback != 'undefined') callback();
      if(typeof $.fn.pageslide.defaults.closeFn === "function") {
          $.fn.pageslide.defaults.closeFn.call(this, $pageslide, $element);
      };
    });
  }

  // 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();
    }
  });
}(window.jQuery);

function setForm(data) {
  $.each(data, function(key, value) {
    $("#pageslide form #" + key).val(value);
  });
}

function resetForm() {
  $("#pageslide form").find("input[type=text], input[type=number], textarea")
                      .val("")
                      .end()
                      .find("select")
                      .prop('selectedIndex', 0)
                      .end()
                      .find("input[type=checkbox]")
                      .prop('checked', false)
                      .end()
                      .find("input[type=radio]")
                      .prop('checked', false);
}