/*
Title:      Milkfish jQuery Version 0.21
Author:     info@milkfishstudio.com
Copyright:  2010, Milkfish Studio, LLC.  All rights resevered (please don't re-use without permission).
*/
// INDEX PAGE 
/*---------------------------------------------------------------*/

(function($) {

   $.fn.MFSIndex = function(options) {

      var opts = $.extend({}, $.fn.MFSIndex.defaults, options);

      return this.each(function() {

         var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
         var $self = $(this),
             hrefCheck = '',
             intv2 = null,
             formElement = $('input:text, textarea');

         $self.append(o.text);
         $('.container').MFSStage({
            column: o.column
         });
         $('#project-container').MFSGallery();
         $('#works').MFSFilters({
            filters: o.filters
         });
         $('#team').find('img').MFSLazycheck();

         formElement.each(function(){
            var element = $(this);
            element.attr('rel', element.val());
         });

         $('a[rel="site"]').live('click', function(event) {
            var thisURL = $(this).attr('href');
            $.fn.MFSIndex.defaults.site = true;
            $.history.load(thisURL);
            return false;
         });

         $.history.init(function(href) {
            if (href != "") $.fn.MFSGallery.ViewSelected(href);
            else $.MFSNavigate();
         },
         {
            unescape: true
         });

         $(window).bind('scroll', function() {
            var array = ['home', 'works', 'information', 'team', 'contact'];
            clearInterval(intv2);
            for(var i = 0; i < array.length; i++) {
               var computedArea = $('#' + array[i] + '-wrapper').height() + $('#' + array[i]).offset().top + $(window).height();
               if($(window).scrollTop() < computedArea - 132) {
                  intv2 = setInterval(function() {
                     setMenu(i, array[i]);
                  }, 40);
                  break;
               }
            }
         });
         
         // Set main menu state
         function setMenu(index, string) {
            clearInterval(intv2);
            if(index != 0) {
               $('#main-nav').find('.current').removeClass('current')
               $('#main-nav').find('.unset').removeClass('unset');
               $('#main-nav').find('a#main-' + index).addClass('current');
            } else {
               $('#main-nav').find('.current').removeClass('current')
               $('#main-nav').find('#main-1').addClass('unset');
            }
            $.MFSNavigate(string);
         }
         
         //console.log(window.location.href);
      });
   };

   $.fn.MFSIndex.defaults = {
      column: 154,
      text: '',
      filters: [],
      site: false,
      isScrolling: false
   };

})(jQuery);

// NAVIGATION
/*---------------------------------------------------------------*/

(function($) {

   $.MFSNavigate = function(href) {

      var mainTarget = $('#header'),
          hrefTarget = mainTarget.find('a[rel="site"]'),
          hrefList = [],
          hrefCheck = null,
          counter = 0,
          counterList = null,
          $this = $(document);
      
      hrefTarget.each(function(index) {
         $(this).attr('id', 'main-' + index);
         hrefList.push($(this).attr('href'));
      });

      hrefCheck = (href != undefined) ? '/' + href + '/' : hrefList[0];
      counter = hrefList.indexOf(hrefCheck);

      $this.unbind('keydown');
      $this.bind('keydown', keyCode);
      
      function keyCode(event) {

         // letter S — function down
         if (event.keyCode == '83') {
            counter++;
            if (counter == hrefList.length) counter = 0;
            $.history.load(hrefList[counter]);
            event.preventDefault();
         }

         // letter W — function up
         if (event.keyCode == '87' && !event.metaKey) {
            if (counter == 0) counter = hrefList.length;
            counter--;
            $.history.load(hrefList[counter]);
            event.preventDefault();
         }

         if (event.keyCode == '68' && $.fn.MFSGallery.defaults.viewPage == true) {
         //if (event.keyCode == '68') {
            var list = $.MFSWorks.current.list,
            counterList = $.MFSWorks.current.counter;
            if(counterList != list.length - 1) {
               if(!$.MFSGallery.isLoading) {
                  $.history.load(list[counterList + 1][3]);
               }
            }
         }

         if (event.keyCode == '65' && $.fn.MFSGallery.defaults.viewPage == true) {
         //if (event.keyCode == '65') {
            var list = $.MFSWorks.current.list,
                counterList = $.MFSWorks.current.counter;
            if(counterList != 0) {
               if(!$.MFSGallery.isLoading) {
                  $.history.load(list[counterList - 1][3]);
               }
            }
         }
         
         // apple keyboard command + w // close tab support
         
         if (event.keyCode == '87' && event.metaKey) { event.stopPropagation(); }
      }
      
      $('input:text, textarea').bind('focus blur', function(event) {
         var element = $(this),
             relElement = element.attr('rel');
             
         if(event.type == 'focus') {
            $this.unbind('keydown');
            element.val('');
         }
         
         if(event.type == 'blur') {
            $this.unbind('keydown');
            $this.bind('keydown', keyCode);
            if (element.val() == '') element.val(relElement);
         }
         
      });
      
      // REGEXP /[^a-z\s]/gi remove all slash
   };
   
   $.MFSWorks = function(list, selected) {
      var navigateElement = $('#navigate'),
          counter = 0,
          titleNext = $('#title-next'),
          titlePrevious = $('#title-previous'),
          nextProject = $('#next'),
          previousProject = $('#previous'),
          interval = null;
          
      if (navigateElement.data().setProject == null || navigateElement.data().setProject == true) {
         navigateElement.setProject = false;
         nextProject.unbind('click');
         previousProject.unbind('click');
         titlePrevious.text('');
         titleNext.text('');
      }
      
      for (var i = 0; i <= list.length - 1; i++) {
         // get selected position in the array break if found match string
         if (list[i][3].indexOf(selected) == 0) {
            counter = i;
            // For keyboard values
            $.MFSWorks.current.counter = counter;
            $.MFSWorks.current.list = list;
            break;
         } 
      }
         
      // Previous Project Button
      if(counter != 0) {
         previousProject.bind('click', function() {
            if(!$.MFSGallery.isLoading) $.history.load(list[counter - 1][3]);
            return false;
         }).hover(function() {
            titlePrevious.show();
         },
         function() {
           titlePrevious.hide();
         });
         titlePrevious.text(list[counter - 1][1]);   
      } else {
         previousProject.bind('click', function() {
            return false;
         });
         titlePrevious.text('');
      }
      
      // Next Project Button
      if(counter != list.length - 1) {
         nextProject.bind('click', function() {
            if(!$.MFSGallery.isLoading) $.history.load(list[counter + 1][3]);
            return false; 
         }).hover(function() {
            titleNext.show();
         },
         function() {
            titleNext.hide();
         });
         titleNext.text(list[counter + 1][1]);
      } else {
         nextProject.bind('click', function() {
            return false;
         });
         titleNext.text('');
      }
   };
   
   $.MFSWorks.current = {
      counter: 0,
      list: null,
      inputValue: null,
   }
   
})(jQuery);

// GALLERY
/*---------------------------------------------------------------*/

(function($) {

   $.fn.MFSGallery = function(options) {

      var opts = $.extend({}, $.fn.MFSGallery.defaults, options);

      return this.each(function() {
         var o = $.meta ? $.extend({},
         opts, $this.data()) : opts;
         var $self = $(this),
             $body = $('body'),
             $item = $self.find('div'),
             intvl = 0,
             hover = null;

         $item.each(function(i) {
            var $this = $(this),
                $temp = $this.find('a').attr('href'),
                //$orig = $this.find('.orig'),
                $gray = $this.find('.gray'),
                $overlay = $this.find('.overlay'),
                _array = $temp.split('/');

            $this.find('img').MFSLazycheck();
            //$gray.hide();
            $overlay.hide();
            $this.attr('id', _array[2]);
            $this.bind('click', {
               target: $this,
               url: $temp,
               name: _array[2]
            },
            view)
            .hover(function() {
               if ($(this).hasClass('active') == false) {
                  // $gray.stop().fadeTo('normal', 1);
                  // $gray.show();
                  // $orig.stop().fadeTo('normal', 0).hide();
                  $overlay.show();
               }
               /*
               $item.addClass('blur');
               $(this).removeClass('blur');
               hover = true;
               */
            },
            function() {
               if ($(this).hasClass('active') == false) {
                  // $gray.stop().fadeTo('normal', 0.4);
                  // $orig.stop().fadeTo('normal', 1, function() {
                     // $gray.hide();
                  // }).show();
                  $overlay.hide();
               }
               /*
               hover = false;
               var intvb = setInterval(function() {
                  clearInterval(intvb);
                  if(!hover) $item.removeClass('blur');
               }, 2000);
               */
            });

            if (i == $item.length - 1) {
               $self.MFSThumbnails();
            }
         });
         // View inside project
         function view(event) {
            var _event = event.data,
                _target = _event.target,
                _url = _event.url,
                _name = _event.name,
                _loading = check(),
                _link = $.fn.MFSGallery.defaults.activeLink;

            //console.log(_link + ' ' + _name);
            if (_link != _name) {
               if (!_loading) {
                  active(_target);
               } else {
                  change(_target);
               }
               _link = _name;
               $.fn.MFSGallery.defaults.activeLink = _link;
               $.history.load(_url);
            }
            return false;
         }

         // Activate thumbnail on click
         function active(target) {
            var _target = target;
            if (_target.hasClass('active') == false) {
               _target.addClass('active');
               _target.find('.overlay').show();
               //_target.find('.orig').hide();
               _target.MFSLoader();
               $.fn.MFSGallery.defaults.targetElement = _target;
            }
         }

         // Change if already been activated
         function change(target) {
            var $active = $self.find('.active');
            /*
            $active.find('.orig').css({
               opacity: '1',
               display: 'block'
            });
            */
            $active.find('.overlay').hide();
            //$active.find('.gray').hide();
            $active.MFSLoader();
            $active.removeClass('active');
            active(target);
         }

         // Check if there is element .active
         function check() {
            var _temp = $self.find('.active').length;
            _temp = (_temp != 0) ? true : false;
            return _temp;
         }
      });
   }

   $.fn.MFSGallery.defaults = {
      activeLink: 'Peter Kamuning',
      currentLoading: false,
      targetElement: null,
      viewPage: false
   }

   $.fn.MFSGallery.ViewSelected = function(href) {
      var $self = $('#project-wrapper'),
          _href = href.split('/'),
          _len = _href.length,
          _list = [],
          _temp = '',
          _int1 = 0,
          _int2 = 0,
          _target = $.fn.MFSGallery.defaults.targetElement;
      
      for (var i = 0; i <= _len - 1; i++) {
         var _temp = _href[i];
         if (_temp != "") _list.push(_temp);
      }
      
      var _id = _list.length,
         _href = _list;

      switch (_id) {

      case 1:
         var _new = $('#' + _href[0]);
         $.MFSNavigate(_href[0]);
         
         if ($.fn.MFSIndex.defaults.site == true) {
            _new.MFSScrolling({
               speed: 800
            });
         } else {
            $.fn.MFSIndex.defaults.site = true;
            $('#project-container').MFSThumbnails();
            _int1 = setInterval(setPosition, 800);
         }

         $('title').titleChange({
            newTitle: _href[0]
         });
         break;

      case 2:
         if(!$.MFSGallery.isLoading) {
            var _title = _href[1];
            $('#page-loader').MFSLoader({spriteDirectory:'/images/spinner-black.png'});
            $.MFSGallery.isLoading = true;
            _int1 = setInterval(function() { page(_href[1]) }, 100);
            _title = _title.replace(/-/g, ' '); //remove all dash and replace with space
            $('title').titleChange({
               newTitle: _href[0] + ' / ' + _title
            });
            $.MFSNavigate(_href[0]);
            $.MFSWorks($.fn.MFSList.defaults.elementList, '/' + _href[0] + '/' + _href[1] + '/');
         }
         break;
      }

      // View inside page project
      function page(string) {

         clearInterval(_int1);
         var details = $('#project-details'),
             newString = 'load-' + string,
             newPage = null;
             
         //$('body').css("overflow", "hidden");
         
         details.append('<div id="'+ newString + '">');
         newPage = details.find('#' + newString);
         newPage
         .hide()
         .load('/' + _href[0] + '/' + _href[1] + ' #loaded', function() {
            if(!$('#project-container').is(':hidden')) $('#project-container').hide();
            $.fn.MFSGallery.defaults.viewPage = true;
            if($.MFSGallery.theOldPage != null) $.MFSGallery.theOldPage.remove();
            $.fn.MFSGallery.defaults.activeLink = 'Peter Kamuning is back...';
            $.fn.MFSFilters.defaults.items.hide();
            $(this).find('#close-project').bind('click', close);
            $('#thumbnails').bind('click', close);
            $('#navigate').show();

            if (typeof _target === 'object') {
               var $old = $('.active');
               /*
               $old.find('.orig').css({
                  opacity: '1',
                  display: 'block'
               });
               */
               $old.find('.overlay').hide();
               //$old.find('.gray').hide();
               $old.MFSLoader();
               $old.removeClass('active');
            }
            
            //$(this).find('img').MFSLazycheck();
            $(this).fadeIn();
            $('#page-loader').find('.loader').remove();
            $('div#works').MFSScrolling({ 
               speed: 500
            });
            $.MFSGallery.isLoading = false;
            $.MFSGallery.theOldPage = $(this);
            //$('body').css("overflow", "auto");
         });
      }

      // Set New Position
      function setPosition() {
         _new.MFSScrolling({
            speed: 1000
         });
         clearInterval(_int1);
      }

      // Closing the project currently on view
      function close() {
         $('#close-project').unbind('click', close); // fix on stacked up scrolling
         $('#thumbnails').unbind('click', close);    // fix on stacked up scrolling
         $.history.load('/works/');
         _int2 = setInterval(show, 500);
         $.MFSGallery.theOldPage = null;
         $.fn.MFSIndex.defaults.site = true;
         $.fn.MFSGallery.defaults.viewPage = false;
         
         return false;
      }

      // Show Element after viewing the project page
      function show() {
         clearInterval(_int2);
         $('#navigate').hide();
         $.fn.MFSFilters.defaults.items.show();
         $('div#works').MFSScrolling({
            speed: 100,
            complete: function() {
               $.fn.MFSThumbnails.check();
            }
         });
         $('#project-details').empty();
         $('#project-container').fadeIn();
      }
   };
   
   $.MFSGallery = {
      isLoading: false,
      isViewPage: false,
      theOldPage: null
   }

})(jQuery);

// UPDATE TITLE
/*---------------------------------------------------------------*/

(function($) {

   $.fn.titleChange = function(options) {

      var opts = $.extend({},
      $.fn.titleChange.defaults, options);

      return this.each(function() {
         var o = $.meta ? $.extend({},
         opts, $this.data()) : opts;
         var $this = $(this),
             _title = $this.text(),
             _title = _title.split('/'),
             _newTitle = o.newTitle;
         
         /* IE8 problem */
         if(!$.browser.msie) 
            $this.text(_title[0] + ' / ' + _newTitle.titleCase());
      });
   }

   $.fn.titleChange.defaults = {
      newTitle: ''
   };

})(jQuery);

// STAGE RESIZE
/*---------------------------------------------------------------*/

(function($) {

   $.fn.MFSStage = function(options) {
      
      var opts = $.extend({}, $.fn.MFSStage.defaults, options);

      return this.each(function() {
         
         var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
         var $self = $(this),
             $window = $(window);
         
         $self.hide();
         resizeStage();
         $window.smartresize(resizeStage);

         // Resize Stage and calculation
         function resizeStage() {
            var windowWidth = $window.width(),
                numberColumn = Math.floor(windowWidth / o.column);

            if (numberColumn == o.maxColumn) {
               $self.css({
                  width: ((o.maxColumn - 1) * o.column) + 'px'
               });
            } else {
               $self.css({
                  width: numberColumn * o.column + 'px'
               });
            }
            $('#header-wrapper').MFSSplash();
            if ($.fn.MFSIndex.defaults.site) {
               $.fn.MFSThumbnails.check();
            }
            $self.show();
         }
      });

   }
   
   $.fn.MFSStage.defaults = {
      maxColumn: 9,
      column: 154
   }

})(jQuery);

// LAZY CHECK
/*---------------------------------------------------------------*/

(function($) {

   $.fn.MFSLazycheck = function(options) {

      var opts = $.extend({}, $.fn.MFSLazycheck.defaults, options);

      return this.each(function() {
         var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
         var $this = $(this);
         $this.lazyload({
            placeholder: o.img,
            effect: 'fadeIn',
            event: 'scroll'
         });
      });
   }

   $.fn.MFSLazycheck.defaults = {
      img: '/images/grey.gif'
   };

})(jQuery);

// SCROLLING PAGE
/*---------------------------------------------------------------*/

(function($) {

   $.fn.MFSScrolling = function(options) {

      var opts = $.extend({},
      $.fn.MFSScrolling.defaults, options);

      return this.each(function() {
         var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
         var $self = $(this),
             windowScrollTop = $(window).scrollTop(),
             currentOffsetTop = $self.offset().top;

         if(windowScrollTop != currentOffsetTop) {
            $.scrollTo($self, o.speed, {
               queue: false,
               axis: 'y',
               easing: o.easing,
               onAfter: function() {
                  if ($.isFunction(o.complete)) {
                     o.complete.apply(this);
                  }
               }
            });
         }
      });
   }

   $.fn.MFSScrolling.defaults = {
      speed: 800,
      easing: 'easeInOutQuint',
      complete: null
   };

})(jQuery);

// THUMBNAILS 
/*---------------------------------------------------------------*/

(function($) {

   $.fn.MFSThumbnails = function(options) {

      var opts = $.extend({}, $.fn.MFSThumbnails.defaults, options);

      return this.each(function() {
         var o = $.meta ? $.extend({},
         opts, $this.data()) : opts;
         var $self = $(this),
             _column = o.column,
             _item = o.item,
             _data = $self.data('masonry');

         if (_data != null) _data = null; // if data exist remove
         arrange($self, _column, _item); // calls function to relayout
      });
   }

   // Call masonry if needed
   function arrange(elements, column, item) {
      var $self = elements,
         $div = $self.find('div'),
         _hidden = $self.is(':hidden');

      // if the container is hidden.
      // Masonry will not execute for new arrangement.
      if (!_hidden) {
         $self.masonry({
            columnWidth: column,
            itemSelector: item,
            resizeable: false,
            animate: true,
            saveOptions: false,
            animationOptions: {
               duration: 300,
               complete: function() {
                  var _anime = $div.is(':animated');
                  //if(!animated) do something here...
               }
            }
         });
      }
   }

   $.fn.MFSThumbnails.check = function() {
      var _target = $('#project-container'),
         _div = _target.find('div'),
         _hidden = (_div.hasClass('hidden') == true) ? 'div:not(.hidden)' : undefined;

      _target.MFSThumbnails({
         item: _hidden
      });
   }

   $.fn.MFSThumbnails.defaults = {
      column: 154,
      item: undefined
   };

})(jQuery);

// FILTERS 
/*---------------------------------------------------------------*/

(function($) {

   $.fn.MFSFilters = function(options) {

      var opts = $.extend({}, $.fn.MFSThumbnails.defaults, options);

      return this.each(function() {

         var o = $.meta ? $.extend({},
         opts, $this.data()) : opts;
         var $self = $(this),
            _filters = o.filters;
         $self.after('<ul id="filters" class="fluid-container group" />');
         var _target = $self.offsetParent().find('#filters');
         $.fn.MFSFilters.defaults.items = _target;

         // Start Setting up filters
         for (var i = 0; i <= _filters.length - 1; i++) {
            var _current = (i == 0) ? 'class="current">' : '>';
            _target.append('<li><a href="#" ' + _current + _filters[i] + '</a></li>');
            if (i == _filters.length - 1) setFilters();
         }

         // Filters the function
         function setFilters() {
            var _link = _target.find('a');
            if ($.fn.MFSList.defaults.elementList == null) $('#project-container').MFSList();
            _link.bind('click', function() {
               _target.find('.current').removeClass('current');
               $(this).addClass('current');
               var _val = $(this).text().toLowerCase().replace(' ', '-'),
                  _all = _filters[0].toLowerCase().replace(' ', '-'); // show all thumbnails
               if (_val == _all) {
                  $('#titleWorks').text('Selected Works');
                  $('#project-container div.hidden').fadeIn('slow').removeClass('hidden');
               } else {
                   $('#titleWorks').text('Selected Works' + ' / ' + $(this).text());
                  $('#project-container div').each(function() {
                     if (!$(this).hasClass(_val)) {
                        $(this).fadeOut('normal').addClass('hidden');
                     } else {
                        $(this).fadeIn('normal').removeClass('hidden');
                     }
                  });
               }
               
               // call again the thumbnails for new layout setup by masonry
               $('#project-container').MFSThumbnails({
                  item: 'div:not(.hidden)'
               }).MFSList();
               
               $('#works').MFSScrolling({
                  speed: 800
               });
               return false;
            });
         }
      });
   }

   $.fn.MFSFilters.defaults = {
      filters: [],
      items: null
   }

})(jQuery);

// SPLASH PAGE 
/*---------------------------------------------------------------*/

(function($) {

   $.fn.MFSSplash = function(options) {

      var opts = $.extend({}, $.fn.MFSSplash.defaults, options);

      return this.each(function() {

         var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

         var $self = $(this),
             $window = $(window),
             $splash = $self.find('#splash'),
             $image = $self.find('.image'),
             $img = $splash.find('img'),
             browserHeight = $window.height(),
             containerWidth = $('.container').width(),
             newImage = new Image(),
             imageSource = new String(),
             imageAlternate = new String(),
             imageRatio = o.imageHeight / o.imageWidth;

         $self.height(browserHeight);
         $img.hide();
         imageSource = $img.attr('src');
         imageAlternate = $img.attr('alt');

         if ($.fn.MFSSplash.defaults.imageLoaded == false) {
            $.fn.MFSSplash.defaults.imageLoaded = true;
            $img.attr('src', o.dummyImage);
            $(newImage).load(function() {
               $image.append($(this));
               $(this).attr('id', 'new-image');
               $(this).attr('alt', imageAlternate);
               $(this).hide();
               resizeImage($image.find('img'));
               $img.remove();
            }).attr('src', imageSource);
         } else {
            resizeImage($img);
         }

         // Resize image proportionally
         function resizeImage(target) {
            var targetElement = target;
            if ((browserHeight / containerWidth) > imageRatio) {
               targetElement.height(browserHeight);
               targetElement.width(browserHeight / imageRatio);
            } else {
               targetElement.width(containerWidth);
               targetElement.height(containerWidth * imageRatio);
            }
            targetElement.css({
               left: (containerWidth - targetElement.width()) / 2
            });
            targetElement.css({
               top: (browserHeight - targetElement.height()) / 2
            });
            if (targetElement.is(':hidden')) targetElement.fadeIn('fast');
         }

      });
   }
   $.fn.MFSSplash.defaults = {
      imageHeight: 768,
      imageWidth: 1024,
      dummyImage: '/images/grey.gif',
      imageLoaded: false,
   }

})(jQuery);

// LIST VIEW
/*---------------------------------------------------------------*/

(function($) {

   $.fn.MFSList = function(options) {

      var opts = $.extend({}, $.fn.MFSList.defaults, options);

      return this.each(function() {
         var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
         var $self = $(this),
             targetElement = $self.find('div:not(.hidden)'),
             elementLength = targetElement.length,
             elementList = [];

         targetElement.each(function(index) {
            var containerID = $(this).attr('id'),
                projectLink = $(this).find('a').attr('href'),
                projectTitle = $(this).find('a').attr('title');
                
            elementList[index] = new Array(4);
            elementList[index][0] = index;
            elementList[index][1] = projectTitle;
            elementList[index][2] = containerID;
            elementList[index][3] = projectLink;
         });
         $.fn.MFSList.defaults.elementList = elementList;
         //console.log($.fn.MFSList.defaults.elementList);
      });
   }

   $.fn.MFSList.defaults = {
      elementList: null
   };

})(jQuery);

// LOADER 
/*---------------------------------------------------------------*/

(function($) {

   $.fn.MFSLoader = function(options) {

      var opts = $.extend({}, $.fn.MFSLoader.defaults, options);

      return this.each(function() {

         var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

         var $self = $(this),
             $loader = new Object(),
             counter = 0,
             intvl = 0;

         if (!$self.data().loading || $self.data().loading == undefined) {
            // Add new loader if none exist
            $loader = $self.prepend('<span class="loader"/>'),
            $loader = $self.find('.loader');
            $loader.hide();

            if (o.testLoader) {
               $loader.bind('click', function() {
                  $loader.fadeOut();
               });
            }
            // Add data loading = true;
            $self.data().loading = true;
            initialize();

         } else {
            // if loader exists remove it
            clearInterval(intvl);
            $self.find('.loader').remove();
         }

         // Start loader here
         function initialize() {
            intvl = setInterval(startAnimation, o.speedRotation);
            $loader.fadeIn();
         }

         // Animate loader by changing css background position
         function startAnimation() {
            // Animation
            counter++;
            if (counter == o.frameCount) counter = 0;
            $loader.css({
               background: 'url(' + o.spriteDirectory + ') ' + (-counter * o.spriteSize) + 'px 0'
            });
            if (o.testLoader) console.log($self.attr('id') + ' - ' + counter);
            endAnimation(); // check if the loader is hidden
            // console.log(intvl);
         }

         // Check if the loader still exists
         function endAnimation() {
            if ($loader.is(':hidden')) {
               $self.data().loading = false; // if data loading to false
               clearInterval(intvl);
               if ($.isFunction(o.complete)) o.complete.apply(this);
            }
         }
      });
   }

   $.fn.MFSLoader.defaults = {
      spriteDirectory: '/images/spinner.png',
      spriteSize: 25,
      speedRotation: 70,
      frameCount: 8,
      testLoader: false,
      complete: null
   };

})(jQuery);

String.prototype.titleCase = function() {
   var newstr = "",
      words = this.split(" ");
   for (keyvar in words) {
      newstr += ' ' + words[keyvar].substr(0, 1).toUpperCase() + words[keyvar].substr(1, words[keyvar].length);
   }
   return newstr;
}

