document.domain = 'asabe.org';

$(function() {
  if(document.getElementById('logo')) {
    logo();
  }
  if(document.getElementById('primaryMenu')) {
    new primaryMenu();
  }
  if(document.getElementById('dashboard')) {
    new trigger();
    if(document.getElementById('selectedTrigger')) {
      selectedTrigger();
    }
  }
  if(document.getElementById('globalSearchSubmit')) {
    new globalSearch();
  }
  if(document.getElementById('tabs')) {
    new tabs();
  }
  if(document.getElementById('presentation')) {
    new presentation();
  }
  if(document.getElementById('featuredSlideshow')) {
    $('#featuredSlideshow').slideshow();
  }
  if(document.getElementById('membership')) {
    membership();
  }
  if(document.getElementById('latestTweet')) {
    new latestTweet();
  }
  $('input.placeholder, textarea.placeholder').placeholder();
  $('input.phPassword').placeholderPassword();
  $('div.tabSlider').tabSlider();
  $('.loginPassword').enterKey('.loginButton');
  $('.pageLoginPassword').enterKey('.pageLoginButton');

  var $iframe = $('#iFrame'),
      iframe = $iframe[0];
  $iframe.load(function () {
    iframe.style.height = (iframe.contentWindow.document.body.offsetHeight + 30) + 'px';
  });
});

function logo() {
  var $logo = $('#logo a'),
    $img = $logo.find('img'),
    src = $img.attr('src'),
    hover = $img.attr('data-hover'),
    img = new Image();
  
  img.src = hover;
  
  $(img).load(function() {
    $logo.hover(function() {
      $img.attr('src',hover);
    },function() {
      $img.attr('src',src);
    });
  });
}

function primaryMenu() {
  var $pm = $('#primaryMenu');
  $pm.after('<div id="primaryMenuToolTip"></div>');
  var $tt = $('#primaryMenuToolTip');
  
  $pm.find('a').hover(function() {
    var pos = $(this).position();
    var dis = $pm.position();
    $tt.html($(this).attr('data-tooltip')).css({left:pos.left + dis.left + 14,display:'block'});
  },function() {
    $tt.hide();
  }).each(function() {
    var $this = $(this);
    $this.attr('data-tooltip',$this.attr('title'));
    $(this).removeAttr('title');
  });
  $tt.hover(function() {
    $tt.show();
  },function() {
    $tt.hide();
  });
}

function globalSearch() {
  var $gsText = $('#globalSearchText');
  var $gsSubmit = $('#globalSearchSubmit');
  $gsSubmit.click(function(e) {
    e.preventDefault();
    submitSearch();
  });
  $gsText.keypress(function(e) {
    if(e.which == 13) {
      e.preventDefault();
      submitSearch();
    }
  });
  function submitSearch() {
    var text = $gsText.val();
    if(text.length > 1 && $gsText.hasClass('userinput')) {
      window.location = $gsSubmit.attr('href') + "?search=" + text;
    }
  }
}

function trigger() {
  var $triggers = $('a.triggerBtn');
  var len = $triggers.length
  if(len > 0) {
    $triggers.click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var $this = $(this);
      if($this.hasClass('triggerOpen')) {
        closeTriggers();
      }
      else {
        closeTriggers();
        $this.addClass('triggerOpen');
        $($this.attr('href')).show();
      }
    }).each(function() {
      $($(this).attr('href')).click(function(e) {
        e.stopPropagation();
      });
    });
    $('body').click(function() {
      closeTriggers();
    });
  }
  function closeTriggers() {
    $triggers.each(function() {
      var $this = $(this);
      $this.removeClass('triggerOpen');
      $($this.attr('href')).hide();
    });
  }
}

function selectedTrigger() {
  var $st = $('#selectedTrigger');
  var leftPos = 529 - $st.width() / 2;
  $st.css({left:leftPos});
}
  
function tabs() {
  var $a = $('#tabs a');
  var current = $a.eq(0).attr('href');

  $a.click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    if(current != href) {
      $a.filter('[href="'+current+'"]').parent().removeClass('active');
      $(this).parent().addClass('active');
      $(current).hide();
      $(href).show();
      current = href;
    }
  });
}

function presentation() {
  var $p = $('#presentation'),
    $lis = $p.find('ul.slides li'),
    height = 0,
    selected = 0,
    bullets = '<span class="bullets">',
    timer;

  $lis.each(function(i) {
    $this = $(this);
    if($this.height() > height) {
      height = $this.height();
    }
    if(i > 0) {
      $this.hide();
      bullets += '<span></span>';
    }
    else {
      bullets += '<span class="active"></span>';
    }
    $this.css('left','0px');
  });
  bullets += '</span>';
  $p.find('ul.slides').height(height + 18);
  $p.append(bullets);
  
  var $bul = $p.find('span.bullets span');
  $bul.each(function(i) {
    $(this).click(function() {
      clearInterval(timer);
      choose(i);
    });
  });
  
  function choose(num) {
    $lis.eq(selected).fadeOut();
    $lis.eq(num).fadeIn();
    $bul.eq(selected).removeClass();
    $bul.eq(num).addClass('active');
    selected = num;
  }
  
  timer = setInterval(function() {
    var num = selected + 1;
    if(num >= $lis.length) {
      num = 0;
    }
    choose(num);
  }, 7000);
}

function membership() {
  var delay = null;
  var $mem = $('#membership');
  $mem.find('ul.memContent>li').hover(function() {
    clearTimeout(delay);
    $mem.attr('class',this.className);
  },function() {
    clearTimeout(delay);
    delay = setTimeout(function() { $mem.attr('class','memDefault'); }, 150);
  });
}
  
function latestTweet(){
  var $feed = $('#latestTweet');
  var d = new Date();
  
  if(supports_html5_storage()) {
    var expireTime = parseInt(localStorage["tweetTime"],10) + 300000; // current time minus 5 minutes
    if(localStorage["tweetHtml"] && localStorage["tweetHtml"].length > 0 && expireTime > d.getTime()) {
      $feed.html(localStorage["tweetHtml"]);
    }
    else {
      retrieveTweet()
    }
  }
  else {
    retrieveTweet();
  }
  
  function retrieveTweet() {
    var user = $feed.attr('data-username');
    $.ajax({
      url: "http://twitter.com/statuses/user_timeline/"+user+".json?count=1",
      type: 'GET',
      crossDomain: true,
      dataType: 'jsonp',
      timeout: 1000,
      error: function(){ $feed.html('failed connection to twitter'); },
      success: function(json) {
        if(json.length > 0) {
          var html = "";
          $.each(json,function(i,item) {
            var text = item.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
              return '<a href="'+url+'">'+url+'</a>';
            }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
              return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
            });
            html += '<p>'+text+'</p><p class="date"><a href="http://twitter.com/'+item.user.screen_name+'/statuses/'+item.id+'">'+relative_time(item.created_at)+'</a> via '+item.source+'</p>';
          });
          $feed.html(html);
          if(supports_html5_storage()) {
            localStorage["tweetHtml"] = html;
            localStorage["tweetTime"] = d.getTime();
          }
        }
       }
    });
  }

  function supports_html5_storage() {
    try {
      return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
      return false;
    }
  }
}

  
function relative_time(time_value) {
  var values = time_value.split(" ");
  var time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

(function(window, $) {

$.fn.enterKey = function (target) {
  var $target = $(target);

  if (!$target.length) {
    return;
  }
  
  domTarget = $target[0];

  if (typeof domTarget === 'undefined') {
    return;
  }

  var href = $target.attr('href'),
    isA = domTarget.tagName === 'A',
    isInput = domTarget.tagName === 'INPUT',
    isButton = domTarget.tagName === 'BUTTON',
    isForm = domTarget.tagName === 'FORM';
  if (!isA && !isInput && !isButton && !isForm) {
    throw new Error('unsupported target');
  }
  return this.keypress(function (e) {
    if (e.keyCode === 13) {
      e.preventDefault();
      if (isA) {
        if (!domTarget.onclick || domTarget.onclick()) {
          if (href.indexOf('javascript') !== -1) {
            eval(unescape(href.replace(/^javascript:/i, '')));
          } else {
            window.location = href;
          }
        }
      } else if (isInput || isButton) {
        $target.click();
      } else if (isForm) {
        $target.submit();
      }
    }
  });
};

$.fn.placeholder = function(defaultValue) {
  return this.each(function() {
    var val = this.defaultValue;
    if(defaultValue) { val = defaultValue; }
    if(this.value != val) {
      $(this).removeClass('placeholder').addClass('userinput');
    }
    $(this).focus(function() {
      if(val == this.value) {
        this.value = "";
      }
      $(this).removeClass('placeholder').addClass('userinput');
    });
    $(this).blur(function() {
      if(this.value.replace(/\s/g,"").length < 1) {
        this.value = val;
        $(this).addClass('placeholder').removeClass('userinput');
      }
    });
  });
};

$.fn.placeholderPassword = function() {
  return this.each(function() {
    var ph = $(this);
    var pass = ph.next('input.userPassword');
    ph.focus(function() {
      ph.hide();
      pass.show().focus();
    });
    pass.blur(function() {
      if(pass.val().replace(/\s/g,"").length < 1) {
        pass.hide();
        ph.show();
      }
    });
  });
};
  
$.fn.videoModal = function(embedCodeSel,width,height) {
  var append = "";
  if(!document.getElementById('overlay')) {
    append += '<div id="overlay"></div>';
  }
  if(!document.getElementById('modalVideo')) {
    append += '<div id="modalVideo"></div>';
  }
  if(append.length > 0) {
    $('body').append(append);
  }
  var $overlay = $('#overlay');
  var $modalVideo = $('#modalVideo');
    $overlay.click(function() {
    closeVideoModal();
  });
  
  return this.each(function() {
    var $this = $(this);
    $this.click(function() {
      $overlay.show();
      if(width > 0) {
        $modalVideo.css({marginLeft:-width/2,width:width});
      }
      if(height > 0) {
        $modalVideo.css({marginTop:-height/2,height:height});
      }
      $modalVideo.html($(embedCodeSel).html()).show();
    }).css('cursor','pointer');
  });
  

  function closeVideoModal() {
    $overlay.hide();
    $modalVideo.hide().html('');
  }
};

$.fn.tabSlider = function(options) {
  return this.each(function() {
    var $ts = $(this),
      $ul = $ts.find('div.frame ul'),
      current = 0,
      slides = $ul.find('li').length;
    $ts.append('<span class="leftArrow"></span><span class="rightArrow"></span><span class="leftFade"></span><span class="rightFade"></span>');
    $ul.css({width:slides*250});
    
    $ts.find('span.leftArrow').click(function() {
      subtractOne();
    });
    $ts.find('span.rightArrow').click(function() {
      addOne();
    });
    
    function subtractOne() {
      current = current - 1;
      if(current < 0) {
        current = slides - 1;
      }
      slideTo();
    }
    function addOne() {
      current = current + 1;
      if(current >= slides) {
        current = 0;
      }
      slideTo();
    }
    function slideTo() {
      $ul.stop().animate({left:-current*250},500,'swing');
    }
  });
};

$.fn.slideshow = function(options) {
  var opts = $.extend({}, $.fn.slideshow.defaults, options);
  
  return this.each(function() {
    var $home = $(this);
    var $images = $home.find(opts.images);
    var $content = $home.find(opts.content);
    $content.eq(1).css({left: 0});
    if($content.length < 2) {
      return;
    }
    var current = 0;
    var timer;
    var isAnimating = -1;
    var queue = -1;
    var clicked = false;
    var hover = false;
    var switchDirection = false;
    
    var width = $images.width();
    
    var $bullets = ' <span id="'+opts.bulletsId+'">';
    var height = 0;
    $content.each(function(i) {
      var $this = $(this);
      if(height < $this.height()) {
        height = $this.height();
      }
      if(i == 0) {
        $bullets += '<span class="active"></span>';
      }
      else {
        $bullets += '<span></span>';
        $this.css({display:'none',left: 0});
      }
    });
    $bullets += '</span>';
    if(opts.bulletsAppend) {
      $home.find(opts.bulletsAppend).append($bullets);
    }
    else {
      $home.append($bullets);
    }
    $bullets = $('#'+opts.bulletsId+' span');
    if(height > 171) {
      $home.height(height + 15);
    }
    $home.find('div.ftsImageWrap').append('<span class="'+opts.leftButtonClass+'"></span><span class="'+opts.rightButtonClass+'"></span>');
    
    function slideTo(num) {
      queue = -1;
      clearTimeout(timer);
      if(num >= $images.length) { num = 0; switchDirection = true; }
      if(num < 0) { num = $images.length - 1; switchDirection = true; }
      if(isAnimating == -1) {
        if(num != current) {
          isAnimating = num;
          $bullets.eq(current).removeClass('active');
          $bullets.eq(num).addClass('active');
          if((num > current && !switchDirection) || (num < current && switchDirection)) {
            switchDirection = false;
            slideDirection(num,-width,width);
          }
          else {
            switchDirection = false;
            slideDirection(num,width,-width);
          }
        }
        else {
          queue = -1;
        }
      }
      else {
        queue = num;
      }
    }
    function slideDirection(num,to,from) {
      $images.eq(current).animate({left:to},opts.animSpeed,opts.ease, function() {
        $(this).hide();
      });
      $images.eq(num).css({display:'block',left:from}).animate({left:0},opts.animSpeed,opts.ease,function() {
        current = num;
        isAnimating = -1;
        if(queue > -1) {
          slideTo(queue);
        }
        else if(!clicked && !hover) {
          startRotate(opts.delay);
        }
      });
      $content.eq(current).fadeOut(opts.animSpeed - 200);
      $content.eq(num).fadeIn(opts.animSpeed - 200);
    }
    function startRotate(delay) {
      clearTimeout(timer);
      timer = setTimeout(function() { slideTo(current + 1); },delay);
    }
    
    $bullets.each(function(i) {
      $(this).click(function() {
        clicked = true;
        slideTo(i);
      });
    });
    $home.find('span.'+opts.leftButtonClass).show().click(function() {
      clicked = true;
      if(isAnimating > -1) {
        slideTo(isAnimating - 1);
      }
      else {
        slideTo(current - 1);
      }
    });
    $home.find('span.'+opts.rightButtonClass).show().click(function() {
      clicked = true;
      if(isAnimating > -1) {
        slideTo(isAnimating + 1);
      }
      else {
        slideTo(current + 1);
      }
    });
    $home.hover(function() {
      hover = true;
      clearTimeout(timer);
    },function() {
      hover = false;
      if(!clicked) {
        startRotate(opts.delay - 2000);
      }
    });
    startRotate(opts.delay);
  });
};
$.fn.slideshow.defaults = {
  images: "ul.ftsImages li",
  content: "ul.ftsContent>li",
  leftButtonClass: "ftsLeft",
  rightButtonClass: "ftsRight",
  bulletsId: "ftsBullets",
  bulletsAppend: 'h3.ftsLabel',
  animSpeed: 1000,
  delay: 6000,
  ease: 'easeInOutQuart'
};

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

    return this.each(function() {
        
        var $this = $(this);
        if(!opts.allowOver) {
            $this.keydown(function(e) {
                if(this.value.length >= opts.limit) {
                    if(document.selection && document.selection.createRange().text.length > 0) {
                        return;
                    }
                    else if(this.selectionEnd - this.selectionStart > 0) {
                        return;
                    }
                    var key = e.which;
                    if(key > 46 || key == 13 || key == 32) {
                        e.preventDefault();
                    }
                }
            });
        }
        $this.bind('keyup onchange', function() {
            var val = clean(this.value);
            if(!opts.allowOver && val.length > opts.limit) {
                val = val.substr(0, opts.limit);
            }
            if(this.value != val) {
                this.value = val;
                this.scrollTop = this.scrollHeight;
            }
            setCount(val.length);
            setRemaining(val.length);
        });
        setTimeout(function() {
                setCount($this.val().length);
                if(!$this.hasClass('placeholder')) {
                  setRemaining($this.val().length);
                }
            }, 10);
        
    });
    
    function setCount(length) {
        if(opts.count) {
            opts.count.innerHTML = length;
            adjustStyle(opts.count, length);
        }
    }
    function setRemaining(length) {
      if(opts.remaining) {
          opts.remaining.innerHTML = opts.limit - length;
          adjustStyle(opts.remaining, length);
      }
    }
    function adjustStyle(object, length) {
        if(length > opts.limit) {
            $(object).addClass(opts.overClass);
        }
        else {
            $(object).removeClass(opts.overClass);
        }
    }
    function clean(value) {
        return value.replace(opts.regex, '');
    }
};
$.fn.textLimit.defaults = {
    limit: 200,
    regex: /<[^ ]\/?[^>]+>/gi,
    allowOver: false,
    count: null,
    remaining: null,
    overClass: 'error'
};

})(this, jQuery);

jQuery.extend( jQuery.easing,
{
  easeInQuad: function (x, t, b, c, d) {
    return c*(t/=d)*t + b;
  },
  easeOutQuad: function (x, t, b, c, d) {
    return -c *(t/=d)*(t-2) + b;
  },
  easeInOutQuad: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t + b;
    return -c/2 * ((--t)*(t-2) - 1) + b;
  },
  easeInCubic: function (x, t, b, c, d) {
    return c*(t/=d)*t*t + b;
  },
  easeOutCubic: function (x, t, b, c, d) {
    return c*((t=t/d-1)*t*t + 1) + b;
  },
  easeInOutCubic: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t + b;
    return c/2*((t-=2)*t*t + 2) + b;
  },
  easeInQuart: function (x, t, b, c, d) {
    return c*(t/=d)*t*t*t + b;
  },
  easeOutQuart: function (x, t, b, c, d) {
    return -c * ((t=t/d-1)*t*t*t - 1) + b;
  },
  easeInOutQuart: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
    return -c/2 * ((t-=2)*t*t*t - 2) + b;
  },
  easeInQuint: function (x, t, b, c, d) {
    return c*(t/=d)*t*t*t*t + b;
  },
  easeOutQuint: function (x, t, b, c, d) {
    return c*((t=t/d-1)*t*t*t*t + 1) + b;
  },
  easeInOutQuint: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
    return c/2*((t-=2)*t*t*t*t + 2) + b;
  },
  easeInSine: function (x, t, b, c, d) {
    return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
  },
  easeOutSine: function (x, t, b, c, d) {
    return c * Math.sin(t/d * (Math.PI/2)) + b;
  },
  easeInOutSine: function (x, t, b, c, d) {
    return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
  },
  easeInExpo: function (x, t, b, c, d) {
    return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
  },
  easeOutExpo: function (x, t, b, c, d) {
    return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
  },
  easeInOutExpo: function (x, t, b, c, d) {
    if (t==0) return b;
    if (t==d) return b+c;
    if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
    return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
  },
  easeInCirc: function (x, t, b, c, d) {
    return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
  },
  easeOutCirc: function (x, t, b, c, d) {
    return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
  },
  easeInOutCirc: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
    return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
  },
  easeInElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
  },
  easeOutElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
  },
  easeInOutElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
  },
  easeInBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c*(t/=d)*t*((s+1)*t - s) + b;
  },
  easeOutBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
  },
  easeInOutBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158; 
    if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
    return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
  },
  easeInBounce: function (x, t, b, c, d) {
    return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
  },
  easeOutBounce: function (x, t, b, c, d) {
    if ((t/=d) < (1/2.75)) {
      return c*(7.5625*t*t) + b;
    } else if (t < (2/2.75)) {
      return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
    } else if (t < (2.5/2.75)) {
      return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
    } else {
      return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
    }
  },
  easeInOutBounce: function (x, t, b, c, d) {
    if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
    return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
  }
});

/* add JSON capabilities for all browsers */
(function($){function toIntegersAtLease(n)
{return n<10?'0'+n:n;}
Date.prototype.toJSON=function(date)
{return date.getUTCFullYear()+'-'+
toIntegersAtLease(date.getUTCMonth()+1)+'-'+
toIntegersAtLease(date.getUTCDate());};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'}
$.quoteString=function(string)
{if(escapeable.test(string))
{return'"'+string.replace(escapeable,function(a)
{var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"'}
return'"'+string+'"';}
$.toJSON=function(o,compact)
{var type=typeof(o);if(type=="undefined")
return"undefined";else if(type=="number"||type=="boolean")
return o+"";else if(o===null)
return"null";if(type=="string")
{return $.quoteString(o);}
if(type=="object"&&typeof o.toJSON=="function")
return o.toJSON(compact);if(type!="function"&&typeof(o.length)=="number")
{var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i],compact));}
if(compact)
return"["+ret.join(",")+"]";else
return"["+ret.join(", ")+"]";}
if(type=="function"){throw new TypeError("Unable to convert object of type 'function' to json.");}
ret=[];for(var k in o){var name;var type=typeof(k);if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;val=$.toJSON(o[k],compact);if(typeof(val)!="string"){continue;}
if(compact)
ret.push(name+":"+val);else
ret.push(name+": "+val);}
return"{"+ret.join(", ")+"}";}
$.compactJSON=function(o)
{return $.toJSON(o,true);}
$.evalJSON=function(src)
{return eval("("+src+")");}
$.secureEvalJSON=function(src)
{var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");}})(jQuery);

