﻿
String.prototype.format = function(){
  var pattern = /\{\d+\}/g;
  var args = arguments;
  return this.replace(pattern, function(capture) { return args[capture.match(/\d+/)]; });
};

(function($){
  $.fn.activityPulldown =
    function(config){
      //Don't do anything if there aren't any triggers.
      if ($(this).length<=0){
        return false;
      }
    
      var ctrl = this;
      var _uid, _href, _activityId, _dataset, _offset, _trigger, _nextIndex, _visible;
      var current=0, _activeIndex = 0, on = 0;
      var triggers = [], cache = [];
      var li = "<li{0}><a{1}><em>{2} <span>{3}</span>{4}</em> <p>{5}</p></a></li>";
      var config = $.extend({datasource:[],speed:250,topOffset:0,leftOffset:0,showTitle:true,api:"/api/activities.svc/activities"},config);

      this.ensureControl =
        (function(){
          if (!ctrl.wrapper || !ctrl.list){
            ctrl.wrapper =
            $('<div class="clip">'
            + '  <span class="background"></span>' 
            + '  <div class="available-activities">'
            + '    <div class="clip-wrapper">'            
            + '      <ul class="the-activities"></ul>'
            + '    </div>'
            + '    <div class="waiting"></div>'                     
            + '  </div>'
            + '</div>').appendTo('body');

            ctrl.menu = $('.available-activities', ctrl.wrapper);
            ctrl.list = $('.the-activities', ctrl.menu);  
            ctrl.title = $('.heading', ctrl.menu);
            
            if (!config.showTitle){
              ctrl.title.remove();
            }            
          }
        })();

      var clip = ctrl.wrapper;
      var menu = ctrl.menu;
        
      this.buildDataString =
        function(){
          var stamp = new Date().getTime();
          var qs = "apikey=0566e181-5b76-44e7-a41d-e556635d5dee&uid={0}&_"+stamp;
          return qs.format(_uid);
        };
        
      this.buildActivityHref =
        function(id){
          var href = "{0}&actid={1}";
          return href.format(_href, id); 
        };
      
      // #region Rendering
      var bottomOffset = menu.outerHeight(); 
      
      this.redrawList =
        function(){        
          clip.css({ display: 'block', visibility: 'hidden' });
          bottomOffset = menu.outerHeight(); 
          clip.css({ height: menu.outerHeight() + 'px', width: menu.outerWidth() + 'px' });
          menu.css({ bottom: bottomOffset});      
          clip.css({ display:'none', visibility:'visible'});                    
        };                     
                 
      this.dropDown = function(px){
        _trigger.addClass("active");
        ctrl.redrawList();                        
        var bottom = px ? (bottomOffset - px): 0;                                         
        clip.css({ display: 'block', left: _offset.left + config.leftOffset + 'px', top: _offset.top + config.topOffset + 'px' });
        menu.animate({bottom: 0}, config.speed, function(){on = 1;});
        _visible = true;
      };

      this.pullUp = function(callback){
        _trigger.removeClass("active");
        menu.animate({bottom:bottomOffset}, config.speed, 
        function(){
          clip.css({ display: 'none' });
          _visible = false;
          if (callback){callback();}
        });                          
      };
      
      this.toggle = 
      function(el){
        if (Boolean(on)){
          if (_activeIndex != _nextIndex){
            //triggers[_activeIndex].el.removeClass('active');   
            ctrl.pullUp(
              function(){                         
               on = 0;
               _activeIndex = _nextIndex;          
               ctrl.toggle();          
            });           
          }
          else{ctrl.pullUp(); on=0;}
        }
        else{ctrl.loadList()}
      };

      this.loadList =
        function(){
        ctrl.list.html(''); 
        if (!cache[_uid]){        
          clip.addClass('loading');
          ctrl.dropDown(20);
            setTimeout(function(){
            if (config.datasource.length>0){
              ctrl.databind(config.datasource)
              clip.removeClass('loading');
              ctrl.dropDown();                        
            }
            else{
              $.ajax({url:config.api, data:ctrl.buildDataString(_uid), dataType: 'json', type: 'GET', async:false, success: 
                function(data){                                
                  ctrl.databind(data.PayLoad);                
                  clip.removeClass('loading');
                  ctrl.dropDown();     
                }
              });
            }   
            }, 300);                        
        }
        else{                   
          ctrl.list.append(cache[_uid].html);
          ctrl.dropDown();
        }
      };

      this.databind = 
      function(data){
        $.each(data, function(i){
          var c = "({0}complete)";
          var n = this.tcompleteq;
          var t = this.totalq;

          c = (n!== 0)?c.format(n!==t?n+" ":"") : "";

          var n = li.format(
            this.status ? "" : " class=\"disabled\"",
            this.status ? " href=\"" + ctrl.buildActivityHref(this.aid) + "\"" : "",
            this.title, 
            c,
            (n!==t?" &raquo;":""),
            this.descr
          );              

          ctrl.list.append(n);
        });      
        cache[_uid] = {data:data, html:ctrl.list.html()};                                     
      };
        
      $(window).bind("resize", function(e){        
        var repos = triggers[_activeIndex].el.offset();
        clip.css({left: repos.left + config.leftOffset, top:repos.top + config.topOffset});                
      });
        
      return $(this).each(function(i){      
        var $this = $(this);
        var href = $(this).attr("href");

        triggers[i] = {el: $this}

        $this.addClass("can_toggle");
      
      var getQuerystring = function(key, default_) {
          if (default_ == null) default_ = "";
          key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
          var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
          var qs = regex.exec(href);
          if (qs == null)
              return default_;
          else
              return qs[1];
     
      }

        var uid = getQuerystring("uid");      
                
        $this.bind("click", {index:i}, function(e){
          e.preventDefault();
          _uid = uid;          
          _href = href;
          _offset = $this.offset();
          _trigger = $this;  
          _nextIndex = e.data.index

          ctrl.toggle();
                  
          _activeIndex = _nextIndex;
             
          e.preventDefault();
          return false;
        });
        
        $("body").click(function(){
          if (Boolean(on)){
            ctrl.toggle();
          }
        });
        
        clip.click(function(e){
          e.stopPropagation();
        });
        
        
      }); /* return */
}
})(jQuery);
