<commit_before>(function() {
  'use strict';

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function scrollTo(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    console.log("Move element ", element);
    console.log("to position ", to);

    var animateScroll = function(){
        currentTime += increment;
        var val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollTop = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
  }

  //t = current time
  //b = start value
  //c = change in value
  //d = duration
  Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
  };

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  };

  $(document).ready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    // scrollElements = $('[data-scroll-element]');
    scrollElements = document.querySelectorAll('[data-scroll-element]');

    inValidRange = function(offset, limit) {
      return offset >= 0 && offset < limit;
    };

    setVisibility = function(element, nextOffset, limit) {
      console.log("Set visibility");
      console.log("nextOffset", nextOffset);
      console.log("limit", limit);
      if(inValidRange(nextOffset, limit)) {
        // element.removeClass('disabled');
        my_removeClass(element, 'disabled');
      } else {
        // element.addClass('disabled');
        my_addClass(element, 'disabled');
      }
    };

    setVisibilityAll = function(elements, newOffset) {
      console.log("setVisibilityAll");
      var
        scrollElement,
        increment,
        nextOffset,
        limit;

      each(elements, function(el) {
        scrollElement = document.querySelector(el.dataset.scrollElement);
        increment  = parseInt(el.dataset.scrollIncrement);
        nextOffset = newOffset + increment;
        limit      = parseInt(scrollElement.dataset.scrollLimit);

        setVisibility(el, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element.scrollTop = 0;
      element.dataset.scrollOffset = 0;
    };

    $('[data-clipboard-target]').each(function() {
      var
          clipboard,
          notification;

      clipboard = new Clipboard(this);

      var notify = function(clipboardNotification, notificationText) {
          notification = $($(clipboardNotification));
          notification.text(notificationText);
          notification.addClass('in').delay(1400).queue(function() {
              notification.removeClass('in');
              $(this).dequeue();
          })
      };

      var notifySuccess = function(e) {
          notify(e.trigger.dataset.clipboardNotification, "Copied!");
      };

      var notifyFailure = function(e) {
          //if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
          notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
      };

      clipboard.on('success', notifySuccess);
      clipboard.on('error', notifyFailure);
    });

    each(scrollElements, function(el) {
      var
        $this,
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      element = document.querySelector(el.dataset.scrollElement);
      increment = parseInt(el.dataset.scrollIncrement);
      limit     = parseInt(element.dataset.scrollLimit.valueOf());
      offset    = parseInt(element.dataset.scrollOffset.valueOf());

      // console.log("increment", increment);
      // console.log("limit", limit);
      // console.log("offset", offset);

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;
      // console.log(nextOffset);
      setVisibility(el, nextOffset, limit);

      // Force IE to forget previous scroll top value
      resetScroll(element);

      el.addEventListener('click', function() {
        offset = parseInt(element.dataset.scrollOffset);

        newOffset = offset + increment;

        if (inValidRange(newOffset, limit)) {
          element.scrollTop = document.getElementById(newOffset).offsetTop;
          // scrollTo(document.getElementById(newOffset), 0, 400);
          // element.scrollTop(document.getElementById(newOffset).offsetTop);
          element.dataset.scrollOffset = newOffset;
          console.log("Element scollOffset", element.dataset.scrollOffset);

          setVisibilityAll(scrollElements, newOffset);
        }
      });

      // $this.on('click', function() {
      //   offset = element.dataset.scrollOffset;
      //
      //   newOffset = offset + increment;
      //
      //   console.log("newOffset", newOffset);
      //   if (inValidRange(newOffset, limit)) {
      //     element.animate({
      //         scrollTop: $('#' + newOffset).position().top
      //     }, 400);
      //     element.data('scroll-offset', newOffset);
      //
      //     setVisibilityAll(scrollElements, newOffset);
      //   }
      // });
    })
    // scrollElements.each();

    $('[data-open-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('open-panel'));

      $this.on('click', function() {
        element.addClass('open');
      });
    });

    $('[data-close-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('close-panel'));

      $this.on('click', function() {
        element
          .one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() {
            $this.trigger('panel:closed');
          }).removeClass('open');
      });
    });

    $('[data-scroll-reset]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('scroll-reset'));

      $this.on('click', function() {
        $this.one('panel:closed', function() {
          resetScroll(element);
          setVisibilityAll(scrollElements, 0);
        });
      });
    });

    $('[data-moment]').each(function() {
      var $this;

      $this = $(this);

      var time = moment(parseInt($this.text()));
      $this.text(time.fromNow());
    });
  });

  var setContainerHeight = function(containerEl) {
    // TODO: Refactor this to make simpler
    var
      bodyEl,
      bodyHeight,
      bodyHeightWithoutTitle,
      titleEl,
      panelEl,
      referralsEl,
      referralsTitleEl,
      panelHeight,
      css,
      stylesheet;

    bodyEl           = $('.squatch-body');
    titleEl          = bodyEl.find('.squatch-title');
    panelEl          = $('#squatch-panel');
    referralsEl      = $('.squatch-referrals');
    referralsTitleEl = $('.squatch-referrals-title');

    bodyHeight = bodyEl.outerHeight();
    bodyHeightWithoutTitle = bodyHeight - titleEl.outerHeight(true) - titleEl.position().top;
    panelHeight = panelEl.outerHeight();

    if (referralsEl.is(':visible')) {
      panelHeight -= referralsEl.outerHeight();
    }

    if (referralsTitleEl.is(':visible')) {
      panelHeight -= referralsTitleEl.outerHeight();
    }

    containerEl.css('height', bodyHeight + panelHeight);

    stylesheet = document.createElement('style');
    stylesheet.type = 'text/css';

    css = '#squatch-panel.open {' +
      '-webkit-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-ms-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-o-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      'transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '}' +
      'html.lt-ie9 #squatch-panel.open {' +
      'top: -' + bodyHeightWithoutTitle + 'px;' +
      '}';

    if (stylesheet.styleSheet){
      // IE
      stylesheet.styleSheet.cssText = css;
    } else {
      // W3C Standard
      stylesheet.appendChild(document.createTextNode(css));
    }

    document.querySelector('head').appendChild(stylesheet);
  };

  var containerEl = $('.squatch-container-popup');
  if (containerEl.length) {
    var setContainerHeightForPopup = setContainerHeight.bind(undefined, containerEl);
    var windowEl = $(window);

    // Workaround for popup height being incorrectly set during iframe resizing.
    // This is due to the popup being displayed inconsistently - with responsive styles activated, sometimes the mobile view will be displayed, even on a desktop monitor with more than 500 pixels width. The solution may be to set the iframe width to the full browser width, rather than the width of the widget theme.
    // There is another hack in _popup.less as well
    // TODO: Find a solution for this and enable responsive styles again.
    windowEl.on('load', function (i) {
      var setContainerHeightIfWideEnough = function () {
        var width = windowEl.width();

        if (width === 500) {
          setContainerHeightForPopup();
        } else {
          setTimeout(function() {
            setContainerHeightIfWideEnough();
          }, 50);
        }
      };

      setContainerHeightIfWideEnough();
    });

    // The content has a different height in mobile
    // TODO: Find a a solution for responsive in popups and re-enable this
    // var mql = window.matchMedia('(max-width: 500px)');
    // mql.addListener(setContainerHeightForPopup);
  }
})();
<commit_msg>Fancy scrolltop<commit_after>(function() {
  'use strict';

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function scrollTo(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){
        currentTime += increment;
        var val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollTop = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
  }

  //t = current time
  //b = start value
  //c = change in value
  //d = duration
  Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
  };

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  };

  $(document).ready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    // scrollElements = $('[data-scroll-element]');
    scrollElements = document.querySelectorAll('[data-scroll-element]');

    inValidRange = function(offset, limit) {
      return offset >= 0 && offset < limit;
    };

    setVisibility = function(element, nextOffset, limit) {
      console.log("Set visibility");
      console.log("nextOffset", nextOffset);
      console.log("limit", limit);
      if(inValidRange(nextOffset, limit)) {
        // element.removeClass('disabled');
        my_removeClass(element, 'disabled');
      } else {
        // element.addClass('disabled');
        my_addClass(element, 'disabled');
      }
    };

    setVisibilityAll = function(elements, newOffset) {
      console.log("setVisibilityAll");
      var
        scrollElement,
        increment,
        nextOffset,
        limit;

      each(elements, function(el) {
        scrollElement = document.querySelector(el.dataset.scrollElement);
        increment  = parseInt(el.dataset.scrollIncrement);
        nextOffset = newOffset + increment;
        limit      = parseInt(scrollElement.dataset.scrollLimit);

        setVisibility(el, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element.scrollTop = 0;
      element.dataset.scrollOffset = 0;
    };

    $('[data-clipboard-target]').each(function() {
      var
          clipboard,
          notification;

      clipboard = new Clipboard(this);

      var notify = function(clipboardNotification, notificationText) {
          notification = $($(clipboardNotification));
          notification.text(notificationText);
          notification.addClass('in').delay(1400).queue(function() {
              notification.removeClass('in');
              $(this).dequeue();
          })
      };

      var notifySuccess = function(e) {
          notify(e.trigger.dataset.clipboardNotification, "Copied!");
      };

      var notifyFailure = function(e) {
          //if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
          notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
      };

      clipboard.on('success', notifySuccess);
      clipboard.on('error', notifyFailure);
    });

    each(scrollElements, function(el) {
      var
        $this,
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      element = document.querySelector(el.dataset.scrollElement);
      increment = parseInt(el.dataset.scrollIncrement);
      limit     = parseInt(element.dataset.scrollLimit.valueOf());
      offset    = parseInt(element.dataset.scrollOffset.valueOf());

      // console.log("increment", increment);
      // console.log("limit", limit);
      // console.log("offset", offset);

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;
      // console.log(nextOffset);
      setVisibility(el, nextOffset, limit);

      // Force IE to forget previous scroll top value
      resetScroll(element);

      el.addEventListener('click', function() {
        offset = parseInt(element.dataset.scrollOffset);

        newOffset = offset + increment;

        if (inValidRange(newOffset, limit)) {
          scrollTop(element, document.getElementById(newOffset).offsetTop, 400);
          // element.scrollTop = document.getElementById(newOffset).offsetTop;
          element.dataset.scrollOffset = newOffset;
          console.log("Element scollOffset", element.dataset.scrollOffset);

          setVisibilityAll(scrollElements, newOffset);
        }
      });

      // $this.on('click', function() {
      //   offset = element.dataset.scrollOffset;
      //
      //   newOffset = offset + increment;
      //
      //   console.log("newOffset", newOffset);
      //   if (inValidRange(newOffset, limit)) {
      //     element.animate({
      //         scrollTop: $('#' + newOffset).position().top
      //     }, 400);
      //     element.data('scroll-offset', newOffset);
      //
      //     setVisibilityAll(scrollElements, newOffset);
      //   }
      // });
    })
    // scrollElements.each();

    $('[data-open-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('open-panel'));

      $this.on('click', function() {
        element.addClass('open');
      });
    });

    $('[data-close-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('close-panel'));

      $this.on('click', function() {
        element
          .one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() {
            $this.trigger('panel:closed');
          }).removeClass('open');
      });
    });

    $('[data-scroll-reset]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('scroll-reset'));

      $this.on('click', function() {
        $this.one('panel:closed', function() {
          resetScroll(element);
          setVisibilityAll(scrollElements, 0);
        });
      });
    });

    $('[data-moment]').each(function() {
      var $this;

      $this = $(this);

      var time = moment(parseInt($this.text()));
      $this.text(time.fromNow());
    });
  });

  var setContainerHeight = function(containerEl) {
    // TODO: Refactor this to make simpler
    var
      bodyEl,
      bodyHeight,
      bodyHeightWithoutTitle,
      titleEl,
      panelEl,
      referralsEl,
      referralsTitleEl,
      panelHeight,
      css,
      stylesheet;

    bodyEl           = $('.squatch-body');
    titleEl          = bodyEl.find('.squatch-title');
    panelEl          = $('#squatch-panel');
    referralsEl      = $('.squatch-referrals');
    referralsTitleEl = $('.squatch-referrals-title');

    bodyHeight = bodyEl.outerHeight();
    bodyHeightWithoutTitle = bodyHeight - titleEl.outerHeight(true) - titleEl.position().top;
    panelHeight = panelEl.outerHeight();

    if (referralsEl.is(':visible')) {
      panelHeight -= referralsEl.outerHeight();
    }

    if (referralsTitleEl.is(':visible')) {
      panelHeight -= referralsTitleEl.outerHeight();
    }

    containerEl.css('height', bodyHeight + panelHeight);

    stylesheet = document.createElement('style');
    stylesheet.type = 'text/css';

    css = '#squatch-panel.open {' +
      '-webkit-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-ms-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-o-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      'transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '}' +
      'html.lt-ie9 #squatch-panel.open {' +
      'top: -' + bodyHeightWithoutTitle + 'px;' +
      '}';

    if (stylesheet.styleSheet){
      // IE
      stylesheet.styleSheet.cssText = css;
    } else {
      // W3C Standard
      stylesheet.appendChild(document.createTextNode(css));
    }

    document.querySelector('head').appendChild(stylesheet);
  };

  var containerEl = $('.squatch-container-popup');
  if (containerEl.length) {
    var setContainerHeightForPopup = setContainerHeight.bind(undefined, containerEl);
    var windowEl = $(window);

    // Workaround for popup height being incorrectly set during iframe resizing.
    // This is due to the popup being displayed inconsistently - with responsive styles activated, sometimes the mobile view will be displayed, even on a desktop monitor with more than 500 pixels width. The solution may be to set the iframe width to the full browser width, rather than the width of the widget theme.
    // There is another hack in _popup.less as well
    // TODO: Find a solution for this and enable responsive styles again.
    windowEl.on('load', function (i) {
      var setContainerHeightIfWideEnough = function () {
        var width = windowEl.width();

        if (width === 500) {
          setContainerHeightForPopup();
        } else {
          setTimeout(function() {
            setContainerHeightIfWideEnough();
          }, 50);
        }
      };

      setContainerHeightIfWideEnough();
    });

    // The content has a different height in mobile
    // TODO: Find a a solution for responsive in popups and re-enable this
    // var mql = window.matchMedia('(max-width: 500px)');
    // mql.addListener(setContainerHeightForPopup);
  }
})();
<|endoftext|>


<commit_before>function ValidURL(str) {
  var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/;

  if(!urlPattern.test(str)) {
    return false;
  } else {
    return true;
  }
}

function parse(domLink) {
	var url = domLink.getAttribute("href");
	if(url && url.indexOf("ppt.cc")!=-1) {
		var key = url.substr(url.length-4, url.length);
		var xhr = new XMLHttpRequest();
			xhr.open("GET", "http://ppt.cc/decode.php?c="+key, true);
			xhr.onreadystatechange = function() {
				if (xhr.readyState == 4) {
					var resp = xhr.responseText.split(/\s/);
					if(resp.length>=2 && ValidURL(resp[1])) { //short url from ppt.cc
						insertIFrame(domLink, resp[1]);
					} else if(resp.length>=2 && resp[1].indexOf("!data/")==0) { //image from ptt.cc
						insertImage(domLink, url);
					}
				}
			};
		xhr.send();
	}else if(url && url.indexOf("goo.gl")!=-1) {
		var xhr = new XMLHttpRequest();
			xhr.open("GET", "https://www.googleapis.com/urlshortener/v1/url?shortUrl="+url, true);
			xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
					var resp = JSON.parse(xhr.responseText);
					if(resp.longUrl) {
						insertIFrame(domLink, resp.longUrl);
					}
				}
			};
		xhr.send();

	} else if(url.indexOf("imgur")==-1 && url.indexOf("ptt.cc")==-1){ //imgur is already parsed in ptt
		insertIFrame(domLink, url);
	}
}

function insertIFrame(domLink, url) {
	if(url.indexOf("flickr.com")!=-1)
		url = url+"/player";
	domLink.innerHTML = domLink.innerHTML + "
";

}

function insertImage(domLink, url) {
	if(url.indexOf("http://ppt.cc/")!=-1)
		url = url+"@.jpg";
	domLink.innerHTML = domLink.innerHTML + "
";
}

if (document.title.indexOf("- 批踢踢實業坊") != -1) {
	var links = document.getElementsByTagName("A");
	for(var i=5;i<links.length;i++){
		parse(links[i]);
	}
}<commit_msg>remove flickr's lightbox url part<commit_after>function ValidURL(str) {
  var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/;

  if(!urlPattern.test(str)) {
    return false;
  } else {
    return true;
  }
}

function parse(domLink) {
	var url = domLink.getAttribute("href");
	if(url && url.indexOf("ppt.cc")!=-1) {
		var key = url.substr(url.length-4, url.length);
		var xhr = new XMLHttpRequest();
			xhr.open("GET", "http://ppt.cc/decode.php?c="+key, true);
			xhr.onreadystatechange = function() {
				if (xhr.readyState == 4) {
					var resp = xhr.responseText.split(/\s/);
					if(resp.length>=2 && ValidURL(resp[1])) { //short url from ppt.cc
						insertIFrame(domLink, resp[1]);
					} else if(resp.length>=2 && resp[1].indexOf("!data/")==0) { //image from ptt.cc
						insertImage(domLink, url);
					}
				}
			};
		xhr.send();
	}else if(url && url.indexOf("goo.gl")!=-1) {
		var xhr = new XMLHttpRequest();
			xhr.open("GET", "https://www.googleapis.com/urlshortener/v1/url?shortUrl="+url, true);
			xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
					var resp = JSON.parse(xhr.responseText);
					if(resp.longUrl) {
						insertIFrame(domLink, resp.longUrl);
					}
				}
			};
		xhr.send();

	} else if(url.indexOf("imgur")==-1 && url.indexOf("ptt.cc")==-1){ //imgur is already parsed in ptt
		insertIFrame(domLink, url);
	}
}

function insertIFrame(domLink, url) {
	if(url.indexOf("flickr.com")!=-1 && url.indexOf("lightbox")!=-1)
		url = url.replace(/lightbox\/?/,"");
	if(url.indexOf("flickr.com")!=-1)
		url = url+"/player";
	domLink.innerHTML = domLink.innerHTML + "
";

}

function insertImage(domLink, url) {
	if(url.indexOf("http://ppt.cc/")!=-1)
		url = url+"@.jpg";
	domLink.innerHTML = domLink.innerHTML + "
";
}

if (document.title.indexOf("- 批踢踢實業坊") != -1) {
	var links = document.getElementsByTagName("A");
	for(var i=5;i<links.length;i++){
		parse(links[i]);
	}
}<|endoftext|>


<commit_before>/* jshint maxparams: 6 */
'use strict';

liveblog.require = {};
var merge = function(obj, source) {
    if (typeof source !== 'object') {
        return;
    }
    for (var key in source) {
        if (source.hasOwnProperty(key)) {
            if (typeof source[key] === 'object'){
                obj[key] = obj[key] ? obj[key] : {};
                merge(obj[key], source[key]);
            } else {
                obj[key] = source[key];
            }
        }
    }
};
var qs = window.location.href;
// if liveblog.dev parameter is there add additional properties.
if ((qs.indexOf('liveblog[dev]') !== -1) || liveblog.dev) {

    // search first into localstorage for liveblog.
    try {
        merge(liveblog, JSON.parse(localStorage.getItem('liveblog')));
    } catch (e){}

    // parse the current location href
    //     for the query parametes that starts with liveblog.
    //     override those properies over the existing global liveblog obj.
    //     parse only first and second level of the object.
    qs.replace(/liveblog\[([^?=&\]]+)\](\[([^?=&\]]+)\])?(=([^&#]*))?/g, function (match, key, hasSub, subkey, hasEquality, value) {
        value = decodeURIComponent(value);
        if (hasSub) {
            liveblog[key] = liveblog[key] ? liveblog[key] : {};
            liveblog[key][subkey] = hasEquality ? value : true;
        } else {
            liveblog[key] = hasEquality ? value : true;
        }
    });
}

// regex to catch all relevant parts of an url.
//   parameter[1] = protocol if there is one.
//   parameter[2] = hostname.
//   parameter[3] = port if there is one.
var urlRegex = /^(http[s]?:)?\/{2}([0-9.\-A-Za-z]+)(?::(\d+))?/,
    // regex to catch if the urlString has a http(s) or a relative protocol.
    protocolRegex = /^(http[s]?:)?\/{2}/;

// fix a urlString, forceing a relative protocol if the protocol http(s).
//   a url for browser always need a relative protocol see https bug @LB-1154
liveblog.browserUrl = function(urlString) {
    urlString = protocolRegex.test(urlString) ? urlString : '//' + urlString;
    urlString = urlString.replace(urlRegex, function(all, protocol, hostname, port) {
        return '//' +
                hostname +
                (port && (port !== '80' && port !== '443') ? ':' + port : '');
    });
    return urlString;
};
// fix servers frontend url
liveblog.servers.frontend = liveblog.browserUrl(liveblog.servers.frontend ?
                                                        liveblog.servers.frontend :
                                                        liveblog.servers.rest);
// fix the rest
liveblog.servers.rest = liveblog.browserUrl(liveblog.servers.rest ?
                                                        liveblog.servers.rest :
                                                        liveblog.servers.frontend);

// after aditional properties where added remake the baseUrl for loader and require.
liveblog.baseUrl = liveblog.require.baseUrl = liveblog.servers.frontend + liveblog.paths.scripts;
// min is if we need to load the production files.
liveblog.min = !liveblog.dev || liveblog.emulateprod;

var loadMain = function() {
    if (liveblog.min) {
        // if is the production then object liveblog.require was already setup.
        liveblog.loadJs('build/main');
    } else {
        /*jshint unused:false*/
        // set the require object for development mode.
        var require = liveblog.require;
        liveblog.loadJs('node_modules/requirejs/require').setAttribute('data-main', liveblog.baseUrl + 'main');
    }
};
// this is the callback after the version was loaded.
liveblog.callbackVersion = function(ver) {
    // add version to require urlArgs.
    liveblog.require.urlArgs = 'version=' + ver.major + '.' + ver.minor + '.' + ver.revision;
    if (liveblog.delay) {
        setTimeout(loadMain, parseInt(liveblog.delay, 10) * 1000);
    } else {
        loadMain();
    }
};

liveblog.loadJs('version');
<commit_msg>LB-1580: Build JS for production<commit_after>/* jshint maxparams: 6 */
'use strict';

liveblog.require = {};
var merge = function(obj, source) {
    if (typeof source !== 'object') {
        return;
    }
    for (var key in source) {
        if (source.hasOwnProperty(key)) {
            if (typeof source[key] === 'object'){
                obj[key] = obj[key] ? obj[key] : {};
                merge(obj[key], source[key]);
            } else {
                obj[key] = source[key];
            }
        }
    }
};

var qs = window.location.href;
// check if there is a query string with liveblog[dev] or liveblog.dev
//   and if so overide the one in global liveblog object.
var qsReg = 'liveblog[\\[\\.]dev[\\]]?(=([^&#]*))?';
qs.replace(new RegExp(qsReg, 'g'), function (match, hasEquality, value) {
    liveblog.dev = hasEquality ? (value.toLowerCase() === 'true' ? true : false) : true;
});

// if liveblog.dev parameter is there add additional properties.
if (liveblog.dev) {
    // search first into localstorage for liveblog.
    try {
        merge(liveblog, JSON.parse(localStorage.getItem('liveblog')));
    } catch (e){}

    // parse the current location href
    //     for the query parametes that starts with liveblog.
    //     override those properies over the existing global liveblog obj.
    //     parse only first and second level of the object.
    qs.replace(new RegExp(qsReg.replace('dev[\\]]?', '([^?=&\\]]+)[\\]]?([\\[\\.]([^?=&\\]]+)[\\]\\.]?)?'), 'g'),
        function (match, key, hasSub, subkey, hasEquality, value) {
        value = decodeURIComponent(value);
        if (hasSub) {
            liveblog[key] = liveblog[key] ? liveblog[key] : {};
            liveblog[key][subkey] = hasEquality ? value : true;
        } else {
            liveblog[key] = hasEquality ? value : true;
        }
    });
}

// regex to catch all relevant parts of an url.
//   parameter[1] = protocol if there is one.
//   parameter[2] = hostname.
//   parameter[3] = port if there is one.
var urlRegex = /^(http[s]?:)?\/{2}([0-9.\-A-Za-z]+)(?::(\d+))?/,
    // regex to catch if the urlString has a http(s) or a relative protocol.
    protocolRegex = /^(http[s]?:)?\/{2}/;

// fix a urlString, forceing a relative protocol if the protocol http(s).
//   a url for browser always need a relative protocol see https bug @LB-1154
liveblog.browserUrl = function(urlString) {
    urlString = protocolRegex.test(urlString) ? urlString : '//' + urlString;
    urlString = urlString.replace(urlRegex, function(all, protocol, hostname, port) {
        return '//' +
                hostname +
                (port && (port !== '80' && port !== '443') ? ':' + port : '');
    });
    return urlString;
};
// fix servers frontend url
liveblog.servers.frontend = liveblog.browserUrl(liveblog.servers.frontend ?
                                                        liveblog.servers.frontend :
                                                        liveblog.servers.rest);
// fix the rest
liveblog.servers.rest = liveblog.browserUrl(liveblog.servers.rest ?
                                                        liveblog.servers.rest :
                                                        liveblog.servers.frontend);

// after aditional properties where added remake the baseUrl for loader and require.
liveblog.baseUrl = liveblog.require.baseUrl = liveblog.servers.frontend + liveblog.paths.scripts;
// min is if we need to load the production files.
liveblog.min = !liveblog.dev || liveblog.emulateprod;

var loadMain = function() {
    if (liveblog.min) {
        // if is the production then object liveblog.require was already setup.
        liveblog.loadJs('build/main');
    } else {
        /*jshint unused:false*/
        // set the require object for development mode.
        var require = liveblog.require;
        liveblog.loadJs('node_modules/requirejs/require').setAttribute('data-main', liveblog.baseUrl + 'main');
    }
};
// this is the callback after the version was loaded.
liveblog.callbackVersion = function(ver) {
    // add version to require urlArgs.
    liveblog.require.urlArgs = 'version=' + ver.major + '.' + ver.minor + '.' + ver.revision;
    if (liveblog.delay) {
        setTimeout(loadMain, parseInt(liveblog.delay, 10) * 1000);
    } else {
        loadMain();
    }
};

liveblog.loadJs('version');
<|endoftext|>


<commit_before>define(function(require) {
    'use strict';

    var zrUtil = require('zrender/core/util');

    function MagicType(model) {
        this.model = model;
    }

    MagicType.defaultOption = {
        show: true,
        type: [],
        // Icon group
        icon: {
            line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
            bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
            stack: 'M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z', // jshint ignore:line
            tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
        },
        title: {
            line: '切换为折线图',
            bar: '切换为柱状图',
            stack: '切换为堆叠',
            tiled: '切换为平铺'
        },
        option: {},
        seriesIndex: {}
    };

    var proto = MagicType.prototype;

    proto.getIcons = function () {
        var model = this.model;
        var availableIcons = model.get('icon');
        var icons = {};
        zrUtil.each(model.get('type'), function (type) {
            if (availableIcons[type]) {
                icons[type] = availableIcons[type];
            }
        });
        return icons;
    };

    var seriesOptGenreator = {
        'line': function (seriesType, seriesId, seriesModel, model) {
            if (seriesType === 'bar') {
                return zrUtil.merge({
                    id: seriesId,
                    type: 'line',
                    // Preserve data related option
                    data: seriesModel.get('data'),
                    stack: seriesModel.get('stack'),
                    markPoint: seriesModel.get('markPoint'),
                    markLine: seriesModel.get('markLine')
                }, model.get('option.line') || {}, true);
            }
        },
        'bar': function (seriesType, seriesId, seriesModel, model) {
            if (seriesType === 'line') {
                return zrUtil.merge({
                    id: seriesId,
                    type: 'bar',
                    // Preserve data related option
                    data: seriesModel.get('data'),
                    stack: seriesModel.get('stack'),
                    markPoint: seriesModel.get('markPoint'),
                    markLine: seriesModel.get('markLine')
                }, model.get('option.bar') || {}, true);
            }
        },
        'stack': function (seriesType, seriesId, seriesModel, model) {
            if (seriesType === 'line' || seriesType === 'bar') {
                return zrUtil.merge({
                    id: seriesId,
                    stack: '__ec_magicType_stack__'
                }, model.get('option.stack') || {}, true);
            }
        },
        'tiled': function (seriesType, seriesId, seriesModel, model) {
            if (seriesType === 'line' || seriesType === 'bar') {
                return zrUtil.merge({
                    id: seriesId,
                    stack: ''
                }, model.get('option.tiled') || {}, true);
            }
        }
    };

    var radioTypes = [
        ['line', 'bar'],
        ['stack', 'tiled']
    ];

    proto.onclick = function (ecModel, api, type) {
        var model = this.model;
        var seriesIndex = model.get('seriesIndex.' + type);
        // Not supported magicType
        if (!seriesOptGenreator[type]) {
            return;
        }
        var newOption = {
            series: []
        };
        var generateNewSeriesTypes = function (seriesModel) {
            var seriesType = seriesModel.subType;
            var seriesId = seriesModel.id;
            var newSeriesOpt = seriesOptGenreator[type](
                seriesType, seriesId, seriesModel, model
            );
            if (newSeriesOpt) {
                // PENDING If merge original option?
                zrUtil.defaults(newSeriesOpt, seriesModel.option);
                newOption.series.push(newSeriesOpt);
            }
        };

        zrUtil.each(radioTypes, function (radio) {
            if (zrUtil.indexOf(radio, type) >= 0) {
                zrUtil.each(radio, function (item) {
                    model.setIconStatus(item, 'normal');
                });
            }
        });

        model.setIconStatus(type, 'emphasis');

        ecModel.eachComponent(
            {
                mainType: 'series',
                query: {
                    seriesIndex: seriesIndex
                }
            }, generateNewSeriesTypes
        );
        api.dispatchAction({
            type: 'changeMagicType',
            currentType: type,
            newOption: newOption
        });
    };

    var echarts = require('../../../echarts');
    echarts.registerAction({
        type: 'changeMagicType',
        event: 'magicTypeChanged',
        update: 'prepareAndUpdate'
    }, function (payload, ecModel) {
        ecModel.mergeOption(payload.newOption);
    });

    require('../featureManager').register('magicType', MagicType);

    return MagicType;
});<commit_msg>Modify boundaryGap when toggling chartType between line and bar<commit_after>define(function(require) {
    'use strict';

    var zrUtil = require('zrender/core/util');

    function MagicType(model) {
        this.model = model;
    }

    MagicType.defaultOption = {
        show: true,
        type: [],
        // Icon group
        icon: {
            line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
            bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
            stack: 'M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z', // jshint ignore:line
            tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
        },
        title: {
            line: '切换为折线图',
            bar: '切换为柱状图',
            stack: '切换为堆叠',
            tiled: '切换为平铺'
        },
        option: {},
        seriesIndex: {}
    };

    var proto = MagicType.prototype;

    proto.getIcons = function () {
        var model = this.model;
        var availableIcons = model.get('icon');
        var icons = {};
        zrUtil.each(model.get('type'), function (type) {
            if (availableIcons[type]) {
                icons[type] = availableIcons[type];
            }
        });
        return icons;
    };

    var seriesOptGenreator = {
        'line': function (seriesType, seriesId, seriesModel, model) {
            if (seriesType === 'bar') {
                return zrUtil.merge({
                    id: seriesId,
                    type: 'line',
                    // Preserve data related option
                    data: seriesModel.get('data'),
                    stack: seriesModel.get('stack'),
                    markPoint: seriesModel.get('markPoint'),
                    markLine: seriesModel.get('markLine')
                }, model.get('option.line') || {}, true);
            }
        },
        'bar': function (seriesType, seriesId, seriesModel, model) {
            if (seriesType === 'line') {
                return zrUtil.merge({
                    id: seriesId,
                    type: 'bar',
                    // Preserve data related option
                    data: seriesModel.get('data'),
                    stack: seriesModel.get('stack'),
                    markPoint: seriesModel.get('markPoint'),
                    markLine: seriesModel.get('markLine')
                }, model.get('option.bar') || {}, true);
            }
        },
        'stack': function (seriesType, seriesId, seriesModel, model) {
            if (seriesType === 'line' || seriesType === 'bar') {
                return zrUtil.merge({
                    id: seriesId,
                    stack: '__ec_magicType_stack__'
                }, model.get('option.stack') || {}, true);
            }
        },
        'tiled': function (seriesType, seriesId, seriesModel, model) {
            if (seriesType === 'line' || seriesType === 'bar') {
                return zrUtil.merge({
                    id: seriesId,
                    stack: ''
                }, model.get('option.tiled') || {}, true);
            }
        }
    };

    var radioTypes = [
        ['line', 'bar'],
        ['stack', 'tiled']
    ];

    proto.onclick = function (ecModel, api, type) {
        var model = this.model;
        var seriesIndex = model.get('seriesIndex.' + type);
        // Not supported magicType
        if (!seriesOptGenreator[type]) {
            return;
        }
        var newOption = {
            series: []
        };
        var generateNewSeriesTypes = function (seriesModel) {
            var seriesType = seriesModel.subType;
            var seriesId = seriesModel.id;
            var newSeriesOpt = seriesOptGenreator[type](
                seriesType, seriesId, seriesModel, model
            );
            if (newSeriesOpt) {
                // PENDING If merge original option?
                zrUtil.defaults(newSeriesOpt, seriesModel.option);
                newOption.series.push(newSeriesOpt);
            }
            // Modify boundaryGap
            var coordSys = seriesModel.coordinateSystem;
            if (coordSys.type === 'cartesian2d') {
                var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
                if (categoryAxis) {
                    var axisDim = categoryAxis.dim;
                    var axisIndex = seriesModel.get(axisDim + 'AxisIndex');
                    var axisKey = axisDim + 'Axis';
                    newOption[axisKey] = newOption[axisKey] || [];
                    for (var i = 0; i <= axisIndex; i++) {
                        newOption[axisKey][axisIndex] = newOption[axisKey][axisIndex] || {};
                    }
                    newOption[axisKey][axisIndex].boundaryGap = type === 'bar' ? true : false;
                }
            }
        };

        zrUtil.each(radioTypes, function (radio) {
            if (zrUtil.indexOf(radio, type) >= 0) {
                zrUtil.each(radio, function (item) {
                    model.setIconStatus(item, 'normal');
                });
            }
        });

        model.setIconStatus(type, 'emphasis');

        ecModel.eachComponent(
            {
                mainType: 'series',
                query: seriesIndex == null ? null : {
                    seriesIndex: seriesIndex
                }
            }, generateNewSeriesTypes
        );
        api.dispatchAction({
            type: 'changeMagicType',
            currentType: type,
            newOption: newOption
        });
    };

    var echarts = require('../../../echarts');
    echarts.registerAction({
        type: 'changeMagicType',
        event: 'magicTypeChanged',
        update: 'prepareAndUpdate'
    }, function (payload, ecModel) {
        ecModel.mergeOption(payload.newOption);
    });

    require('../featureManager').register('magicType', MagicType);

    return MagicType;
});<|endoftext|>


<commit_before>var topicsController = (function () {

    function byId(context) {
        var topicId = context.params['topicId'];
        categoryModel.currentId(+context.params['categoryId']);
        sectionModel.currentId(+context.params['sectionId'])

        appManager.loadView("category", context, false, categoryModel.byId, categoryModel.currentId())
       .then(function () {
           sidebarController.config;

           eventManager.attachShowSection(context);
           eventManager.attachAddSection(context);

           return appManager.loadView("section", context, Constants.CATEGORY_CONTENT_WRAPPER, sectionModel.getById, sectionModel.currentId());;
       })
        .then(function () {
            return appManager.loadView('topic', context, Constants.CATEGORY_CONTENT_WRAPPER, topicModel.byId, topicId);
        })
        .then(function (data) {
            topicModel.Properties = data;
            eventManager.attachCommentAdd();
            eventManager.attachLikeEvent();
            eventManager.attachDislikeEvent();
        }, function (err) {
            toastr.error(err);
            console.log(err);
        });
    }

    function add(context) {
        if (appManager.checkIfLogged() === false) {
            toastr.warning('You must be logged in to add topics');
        }
        else {
            appManager.loadView("add-topic", context, Constants.CATEGORY_CONTENT_WRAPPER)
                .then(function (res) {
                    $("#add-example").on("click", function (e) {
                        e.preventDefault();
                        $("#topic-examples").load("partials/add-example.html");
                    });

                    $("#btn-topic-add").on("click", function (e) {
                        e.preventDefault();
                        console.log("clickedeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");

                        var newExample = {
                            description: $("#tb-example-description").val(),
                            content: $("#tb-example-content").val()
                        };

                        var video_id = $("#tb-topic-video").val().split("v=")[1];
                        var ampersandPosition = video_id.indexOf("&");
                        if (ampersandPosition != -1) {
                            video_id = video_id.substring(0, ampersandPosition);
                        }

                        var newTopic = {
                            title: $("#tb-topic-title").val(),
                            content: $("#tb-topic-content").val(),
                            videoId: video_id,
                            sectionId: sectionModel.currentId().toString(),
                            examples: [
                                newExample
                            ]
                        };

                        topicModel.add(newTopic)
                            .then(function (id) {
                                // var id = topicModel.currentId() ? topicModel.currentId() : 1;
                                topicModel.currentId(id);
                                uploadController.upload(id);

                            }, function (err) {
                                console.log(err);
                            }).then(function () {
                                notificationController.publish('new topic added');
                            });

                    });
                }, function (err) {
                    //console.log(err);
                });
        }

    }

    function edit(context) {
        var topicId = context.params['id'];
        appManager.loadView('edit-topic', context, Constants.CATEGORY_CONTENT_WRAPPER, topicModel.byId, topicId)
        .then(function () {

            $saveBtn = $('#btn-edit-topic-save');

            $('.btn-edit-topic').on('click', function (e) {
                var $target = $(e.currentTarget),
                $parent = $target.parent(),
                targetId = $target.attr('id'),
                editBtnId = 'btn-change-topic-' + targetId,
                inputId = '.tb-topic-edit-' + targetId;

                // $parent, itemName, properties)
                htmlElementCreator.createForm($parent, 'tb-topic-edit', [targetId]);
                $('.tb-topic-edit-content').attr('maxlength', '500');
                //  htmlElementCreator.createButton($parent, 'Ok', editBtnId);

            });

            $saveBtn.on('click', function () {

                uploadController.upload(topicModel.currentId());
                //var formData = new FormData();

                //var opmlFile = $('#opmlFile')[0];

                //formData.append("opmlFile", opmlFile.files[0]);
                // topicModel.Properties.ZipFiles.push(formData);

                // editing already ezisting examples
                var updatedExamplesContent = $('.tb-topic-edit-example-content'),
                    updatedExamplesDescription = $('.tb-topic-edit-description'),
                    examples = $('.example');
                updatedExamples = [];

                for (var i = 0; i < examples.length; i++) {

                    updatedExamples.push({
                        Id: topicModel.Properties.Examples[i].Id,
                        Content: $($(examples[i]).find('.tb-topic-edit-example-content')).val() || topicModel.Properties.Examples[i].Content,
                        Description: $($(examples[i]).find('.tb-topic-edit-description')).val() || topicModel.Properties.Examples[i].Description
                    })
                }

                var updatedTopic = {
                    Title: topicModel.Properties.Title,
                    Content: $('.tb-topic-edit-content').val() || topicModel.Properties.Content,
                    VideoId: $('.tb-topic-edit-video-url').val() || topicModel.Properties.VideoId,
                    SectionId: sectionModel.currentId(), // or topicModel.SectionId
                    //  Zip: topicModel.Properties.ZipFiles,
                    Examples: updatedExamples
                }

                topicModel.edit(topicModel.currentId(), updatedTopic);
                console.log(updatedTopic);
            });
        });
    }

    return {
        byId: byId,
        add: add,
        edit: edit
    }
}());<commit_msg>[Client] Fixed bugs<commit_after>var topicsController = (function () {

    function byId(context) {
        var topicId = context.params['topicId'];
        categoryModel.currentId(+context.params['categoryId']);
        sectionModel.currentId(+context.params['sectionId'])

        appManager.loadView("category", context, false, categoryModel.byId, categoryModel.currentId())
       .then(function () {
           sidebarController.config;

           eventManager.attachShowSection(context);
           eventManager.attachAddSection(context);

           return appManager.loadView("section", context, Constants.CATEGORY_CONTENT_WRAPPER, sectionModel.getById, sectionModel.currentId());;
       })
        .then(function () {
            return appManager.loadView('topic', context, Constants.CATEGORY_CONTENT_WRAPPER, topicModel.byId, topicId);
        })
        .then(function (data) {
            topicModel.Properties = data;
            eventManager.attachCommentAdd();
            eventManager.attachLikeEvent();
            eventManager.attachDislikeEvent();
        }, function (err) {
            toastr.error(err);
            console.log(err);
        });
    }

    function add(context) {
        if (appManager.checkIfLogged() === false) {
            toastr.warning('You must be logged in to add topics');
        }
        else {
            appManager.loadView("add-topic", context, Constants.CATEGORY_CONTENT_WRAPPER)
                .then(function (res) {
                    $("#add-example").on("click", function (e) {
                        e.preventDefault();
                        $("#topic-examples").load("partials/add-example.html");
                    });

                    $("#btn-topic-add").on("click", function (e) {
                        e.preventDefault();
                        console.log("clickedeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");

                        var newExample = {
                            description: $("#tb-example-description").val(),
                            content: $("#tb-example-content").val()
                        };

                        var video_id = $("#tb-topic-video").val().split("v=")[1];
                        var ampersandPosition = video_id.indexOf("&");
                        if (ampersandPosition != -1) {
                            video_id = video_id.substring(0, ampersandPosition);
                        }

                        var newTopic = {
                            title: $("#tb-topic-title").val(),
                            content: $("#tb-topic-content").val(),
                            videoId: video_id,
                            sectionId: sectionModel.currentId().toString(),
                            examples: [
                                newExample
                            ]
                        };

                        topicModel.add(newTopic)
                            .then(function (id) {
                                // var id = topicModel.currentId() ? topicModel.currentId() : 1;
                                topicModel.currentId(id);
                                uploadController.upload(id);

                            }, function (err) {
                                console.log(err);
                            }).then(function () {
                                notificationController.publish('new topic added');
                            });

                    });
                }, function (err) {
                    //console.log(err);
                });
        }

    }

    function edit(context) {
        var topicId = context.params['id'];
        if (appManager.checkIfLogged() === false) {
            toastr.warning('You must be logged in to edit topics');
        }
        else {
            appManager.loadView('edit-topic', context, Constants.CATEGORY_CONTENT_WRAPPER, topicModel.byId, topicId)
            .then(function () {

                $saveBtn = $('#btn-edit-topic-save');

                $('.btn-edit-topic').on('click', function (e) {
                    var $target = $(e.currentTarget),
                    $parent = $target.parent(),
                    targetId = $target.attr('id'),
                    editBtnId = 'btn-change-topic-' + targetId,
                    inputId = '.tb-topic-edit-' + targetId;

                    // $parent, itemName, properties)
                    htmlElementCreator.createForm($parent, 'tb-topic-edit', [targetId]);
                    $('.tb-topic-edit-content').attr('maxlength', '500');
                    //  htmlElementCreator.createButton($parent, 'Ok', editBtnId);

                });

                $saveBtn.on('click', function () {

                    uploadController.upload(topicModel.currentId());
                    //var formData = new FormData();

                    //var opmlFile = $('#opmlFile')[0];

                    //formData.append("opmlFile", opmlFile.files[0]);
                    // topicModel.Properties.ZipFiles.push(formData);

                    // editing already ezisting examples
                    var updatedExamplesContent = $('.tb-topic-edit-example-content'),
                        updatedExamplesDescription = $('.tb-topic-edit-description'),
                        examples = $('.example');
                    updatedExamples = [];

                    for (var i = 0; i < examples.length; i++) {

                        updatedExamples.push({
                            Id: topicModel.Properties.Examples[i].Id,
                            Content: $($(examples[i]).find('.tb-topic-edit-example-content')).val() || topicModel.Properties.Examples[i].Content,
                            Description: $($(examples[i]).find('.tb-topic-edit-description')).val() || topicModel.Properties.Examples[i].Description
                        })
                    }

                    var updatedTopic = {
                        Title: topicModel.Properties.Title,
                        Content: $('.tb-topic-edit-content').val() || topicModel.Properties.Content,
                        VideoId: $('.tb-topic-edit-video-url').val() || topicModel.Properties.VideoId,
                        SectionId: sectionModel.currentId(), // or topicModel.SectionId
                        //  Zip: topicModel.Properties.ZipFiles,
                        Examples: updatedExamples
                    }

                    topicModel.edit(topicModel.currentId(), updatedTopic);
                    console.log(updatedTopic);
                });
            });
        }
    }

    return {
        byId: byId,
        add: add,
        edit: edit
    }
}());<|endoftext|>


<commit_before>(function (window, Cryptoloji, undefined) {
  'use strict'

  Cryptoloji.states.landing = {
    canEnter: function () {
      console.log(Cryptoloji.storage.get('message'))
      // verify a message is present in the storage
      if (_.isUndefined(Cryptoloji.storage.get('message')) || _.isEmpty(Cryptoloji.storage.get('message'))) {
        // if not redirect to not found state
        Cryptoloji.stateman.go('404')
        return false
      }
      return true
    },
    enter: function () {

      fillMessage()

      $(".section_landing").addClass("section-show")
      Cryptoloji.stateman.emit('footer:show')

      var time = .3
      var delay = .4
      TweenLite.set($("[landing-state]"), {display: "none"})
      TweenLite.set($("[landing-state='1']"), {display: "block", opacity: 0})
      // text
      TweenLite.to($("#landing_state_1_text"), time, {opacity: 1, delay: delay})
      // svg
      TweenLite.to($("#landing_state_1_encrypted_message"), time, {opacity: 1, delay: delay * 2})
      // button
      TweenLite.to($("#landing_state_1_button"), time, {opacity: 1, delay: delay * 3})

      $("#landing_state_1_button").on("click", function(){
        TweenLite.set($("[landing-state]"), {display: "none"})
        TweenLite.set($("[landing-state='2']"), {display: "block", opacity: 0})
        TweenLite.set($("#landing_state_2_question_mark"), {opacity: 0})
        // text
        TweenLite.to($("#landing_state_2_text"), time, {opacity: 1, delay: delay})
        // svg
        TweenLite.to($("#landing_state_2_svg"), time, {opacity: 1, delay: delay * 2})
        TweenLite.set($("#landing_state_2_svg>svg>g"), {"opacity": 0, scale: .8, transformOrigin:'center center'})
        $("#landing_state_2_svg>svg>g").each(function(i){
          var self = this
          var tim = .4
          TweenLite.to($(this), .4, {opacity: 1, scale: 1, delay: i*tim+1})
          if(i < $("#landing_state_2_svg>svg>g").length - 1){
            TweenLite.to($(this), .4, {opacity: 0, scale: .8, delay: i*tim+(tim*3)/5+1})
          }
        })

        // button
        TweenLite.to($("#landing_state_2_button"), time, {opacity: 1, delay: delay * 3})
      })

    },
    leave: function () {
      $(".section_landing").removeClass("section-show")
      Cryptoloji.stateman.emit('footer:hide')
    }
  }

  function fillMessage () {
    var message = Cryptoloji.storage.get('message')
    $('#landing_state_1_encrypted_message').html(Cryptoloji.UI.toTwemoji(message))
    Cryptoloji.utils.resizeEmojis(message, .5, '#landing_state_1_encrypted_message')
  }

})(window, window.Cryptoloji);

<commit_msg>fix logic animation landing<commit_after>(function (window, Cryptoloji, undefined) {
  'use strict'

  function landing_animation_shuffle(timing, initdelay) {
    TweenLite.set($("#landing_state_2_svg>svg>g"), {"opacity": 0, scale: .8, transformOrigin:'center center'})
    $("#landing_state_2_svg>svg>g").each(function(i){
      var self = this
      var tim = timing
      TweenLite.to($(this), .4, {opacity: 1, scale: 1, delay: i*tim+initdelay})
      if(i < $("#landing_state_2_svg>svg>g").length - 1){
        TweenLite.to($(this), .4, {opacity: 0, scale: .8, delay: i*tim+(tim*3)/5+initdelay})
      }
    })
  }

  // $('.svg_wrapper_landing_key').on("click", function(){
  //   landing_animation_shuffle(.4, 0)
  // })

  Cryptoloji.states.landing = {
    canEnter: function () {
      console.log(Cryptoloji.storage.get('message'))
      // verify a message is present in the storage
      if (_.isUndefined(Cryptoloji.storage.get('message')) || _.isEmpty(Cryptoloji.storage.get('message'))) {
        // if not redirect to not found state
        Cryptoloji.stateman.go('404')
        return false
      }
      return true
    },
    enter: function () {

      fillMessage()

      $(".section_landing").addClass("section-show")
      Cryptoloji.stateman.emit('footer:show')

      var time = .3
      var delay = .4
      TweenLite.set($("[landing-state]"), {display: "none"})
      TweenLite.set($("[landing-state='1']"), {display: "block", opacity: 0})
      // text
      TweenLite.to($("#landing_state_1_text"), time, {opacity: 1, delay: delay})
      // svg
      TweenLite.to($("#landing_state_1_encrypted_message"), time, {opacity: 1, delay: delay * 2})
      // button
      TweenLite.to($("#landing_state_1_button"), time, {opacity: 1, delay: delay * 3})

      $("#landing_state_1_button").on("click", function(){
        TweenLite.set($("[landing-state]"), {display: "none"})
        TweenLite.set($("[landing-state='2']"), {display: "block", opacity: 0})
        TweenLite.set($("#landing_state_2_question_mark"), {opacity: 0})
        // text
        TweenLite.to($("#landing_state_2_text"), time, {opacity: 1, delay: delay})
        // svg
        TweenLite.to($("#landing_state_2_svg"), time, {opacity: 1, delay: delay * 2})

        landing_animation_shuffle(.4, 1)

        // button
        TweenLite.to($("#landing_state_2_button"), time, {opacity: 1, delay: delay * 3})
      })

    },
    leave: function () {
      $(".section_landing").removeClass("section-show")
      Cryptoloji.stateman.emit('footer:hide')
    }
  }

  function fillMessage () {
    var message = Cryptoloji.storage.get('message')
    $('#landing_state_1_encrypted_message').html(Cryptoloji.UI.toTwemoji(message))
    Cryptoloji.utils.resizeEmojis(message, .5, '#landing_state_1_encrypted_message')
  }

})(window, window.Cryptoloji);

<|endoftext|>


<commit_before>/*
 * angucomplete-alt
 * Autocomplete directive for AngularJS
 * This is a fork of Daryl Rowland's angucomplete with some extra features.
 * By Hidenari Nozaki
 *
 * Copyright (c) 2014 Hidenari Nozaki and contributors
 * Licensed under the MIT license
 */

'use strict';

angular.module('angucomplete-alt', [] ).directive('angucompleteAlt', ['$parse', '$http', '$sce', '$timeout', function ($parse, $http, $sce, $timeout) {
  var KEY_DW = 40,
      KEY_UP = 38,
      KEY_ES = 27,
      KEY_EN = 13,
      KEY_BS =  8,
      KEY_DEL =  46,
      MIN_LENGTH = 3,
      PAUSE = 500,
      BLUR_TIMEOUT = 300;

  return {
    restrict: 'EA',
    scope: {
      selectedObject: '=',
      localData: '=',
      remoteUrlRequestFormatter: '=',
      remoteUrlResponseFormatter: '=',
      id: '@',
      placeholder: '@',
      remoteUrl: '@',
      remoteUrlDataField: '@',
      titleField: '@',
      descriptionField: '@',
      imageField: '@',
      inputClass: '@',
      pause: '@',
      searchFields: '@',
      minlength: '@',
      matchClass: '@',
      clearSelected: '@',
      overrideSuggestions: '@'
    },
    template:
      '
' +
      '  <input id="{{id}}_value" ng-model="searchStr" type="text" placeholder="{{placeholder}}" class="{{inputClass}}" ng-focus="resetHideResults()" ng-blur="hideResults()"/>' +
      '
' +
      '
Searching...
' +
      '
No results found
' +
      '
' +
      '
' +
      '        ' +
      '

' +
      '
' +
      '

' +
      '
{{ result.title }}
' +
      '

' +
      '
{{result.description}}
' +
      '
' +
      '
' +
      '
',
    link: function(scope, elem, attrs) {
      var inputField,
          minlength = MIN_LENGTH,
          searchTimer = null,
          lastSearchTerm = null,
          hideTimer;

      scope.currentIndex = null;
      scope.searching = false;
      scope.searchStr = null;

      var callOrAssign = function(value) {
        if (typeof scope.selectedObject === 'function') {
          scope.selectedObject(value);
        }
        else {
          scope.selectedObject = value;
        }
      };

      var returnFunctionOrIdentity = function(fn) {
        return fn && typeof fn === 'function' ? fn : function(data) { return data; };
      };

      var responseFormatter = returnFunctionOrIdentity(scope.remoteUrlResponseFormatter);

      var setInputString = function(str) {
        callOrAssign({originalObject: str});

        if (scope.clearSelected) {
          scope.searchStr = null;
        }
        scope.showDropdown = false;
        scope.results = [];
      };

      var isNewSearchNeeded = function(newTerm, oldTerm) {
        return newTerm.length >= minlength && newTerm !== oldTerm;
      };

      var extractTitle = function(data) {
        // split title fields and run extractValue for each and join with ' '
        return scope.titleField.split(',')
          .map(function(field) {
            return extractValue(data, field);
          })
          .join(' ');
      };

      var extractValue = function(obj, key) {
        var keys, result;
        if (key) {
          keys= key.split('.');
          result = obj;
          keys.forEach(function(k) { result = result[k]; });
        }
        else {
          result = obj;
        }
        return result;
      };

      var findMatchString = function(target, str) {
        var result, matches, re = new RegExp(str, 'i');
        if (!target) { return; }
        matches = target.match(re);
        if (matches) {
          result = target.replace(re,
              ''+ matches[0] +'');
        }
        else {
          result = target;
        }
        return $sce.trustAsHtml(result);
      };

      if (scope.minlength && scope.minlength !== '') {
        minlength = scope.minlength;
      }

      if (!scope.pause) {
        scope.pause = PAUSE;
      }

      if (!scope.clearSelected) {
        scope.clearSelected = false;
      }

      if (!scope.overrideSuggestions) {
        scope.overrideSuggestions = false;
      }

      scope.hideResults = function() {
        hideTimer = $timeout(function() {
          scope.showDropdown = false;
        }, BLUR_TIMEOUT);
      };

      scope.resetHideResults = function() {
        if (hideTimer) {
          $timeout.cancel(hideTimer);
        }
      };

      scope.processResults = function(responseData, str) {
        var i, description, image, text;

        if (responseData && responseData.length > 0) {
          scope.results = [];

          for (i = 0; i < responseData.length; i++) {
            if (scope.titleField && scope.titleField !== '') {
              text = extractTitle(responseData[i]);
            }

            description = '';
            if (scope.descriptionField) {
              description = extractValue(responseData[i], scope.descriptionField);
            }

            image = '';
            if (scope.imageField) {
              image = extractValue(responseData[i], scope.imageField);
            }

            if (scope.matchClass) {
              text = findMatchString(text, str);
              description = findMatchString(description, str);
            }

            scope.results[scope.results.length] = {
              title: text,
              description: description,
              image: image,
              originalObject: responseData[i]
            };

          }

        } else {
          scope.results = [];
        }
      };

      scope.searchTimerComplete = function(str) {
        // Begin the search
        var searchFields, matches, i, match, s, params;

        if (str.length >= minlength) {
          if (scope.localData) {
            searchFields = scope.searchFields.split(',');

            matches = [];

            for (i = 0; i < scope.localData.length; i++) {
              match = false;

              for (s = 0; s < searchFields.length; s++) {
                match = match || (scope.localData[i][searchFields[s]].toLowerCase().indexOf(str.toLowerCase()) >= 0);
              }

              if (match) {
                matches[matches.length] = scope.localData[i];
              }
            }

            scope.searching = false;
            scope.processResults(matches, str);

          } else if (scope.remoteUrlRequestFormatter) {
            params = scope.remoteUrlRequestFormatter(str);
            $http.get(scope.remoteUrl, {params: params}).
              success(function(responseData, status, headers, config) {
                scope.searching = false;
                scope.processResults(
                  extractValue(responseFormatter(responseData), scope.remoteUrlDataField), str
                );
              }).
            error(function(data, status, headers, config) {
              console.log('error');
            });

          } else {
            $http.get(scope.remoteUrl + str, {}).
              success(function(responseData, status, headers, config) {
                scope.searching = false;
                scope.processResults(
                  extractValue(responseFormatter(responseData), scope.remoteUrlDataField), str
                );
              }).
            error(function(data, status, headers, config) {
              console.log('error');
            });
          }
        }

      };

      scope.hoverRow = function(index) {
        scope.currentIndex = index;
      };

      scope.selectResult = function(result) {
        // Restore original values
        if (scope.matchClass) {
          result.title = extractTitle(result.originalObject);
          result.description = extractValue(result.originalObject, scope.descriptionField);
        }

        if (scope.clearSelected) {
          scope.searchStr = null;
        }
        else {
          scope.searchStr = lastSearchTerm = result.title;
        }
        callOrAssign(result);
        scope.showDropdown = false;
        scope.results = [];
      };

      inputField = elem.find('input');

      scope.keyPressed = function(event) {
        if (!(event.which === KEY_UP || event.which === KEY_DW || event.which === KEY_EN)) {
          if (!scope.searchStr || scope.searchStr === '') {
            scope.showDropdown = false;
            lastSearchTerm = null;
          } else if (isNewSearchNeeded(scope.searchStr, lastSearchTerm)) {
            lastSearchTerm = scope.searchStr;
            scope.showDropdown = true;
            scope.currentIndex = -1;
            scope.results = [];

            if (searchTimer) {
              $timeout.cancel(searchTimer);
            }

            scope.searching = true;

            searchTimer = $timeout(function() {
              scope.searchTimerComplete(scope.searchStr);
            }, scope.pause);
          }
        } else {
          event.preventDefault();
        }
      };

      inputField.on('keyup', scope.keyPressed);

      elem.on('keydown', function (event) {
        if(event.which === KEY_DW && scope.results) {
          if ((scope.currentIndex + 1) < scope.results.length) {
            scope.$apply(function() {
              scope.currentIndex ++;
            });
          }
        } else if(event.which === KEY_UP && scope.results) {
          if (scope.currentIndex >= 1) {
            scope.$apply(function() {
              scope.currentIndex --;
            });
          }
        }
      });

      elem.on('keyup', function (event) {
        if (event.which === KEY_EN && scope.results) {
          if (scope.currentIndex >= 0 && scope.currentIndex < scope.results.length) {
            scope.selectResult(scope.results[scope.currentIndex]);
            scope.$apply();
            event.preventDefault();
          } else {
            event.preventDefault();
            if (scope.overrideSuggestions) {
              setInputString(scope.searchStr);
              scope.$apply();
            }
            else {
              scope.results = [];
              scope.$apply();
            }
          }

        } else if (event.which === KEY_ES) {
          scope.results = [];
          scope.showDropdown = false;
          scope.$apply();
        } else if (event.which === KEY_BS || event.which === KEY_DEL) {
          callOrAssign(null);
          scope.$apply();
        }
      });
    }
  };
}]);

<commit_msg>Fix: hoverRow was not working<commit_after>/*
 * angucomplete-alt
 * Autocomplete directive for AngularJS
 * This is a fork of Daryl Rowland's angucomplete with some extra features.
 * By Hidenari Nozaki
 *
 * Copyright (c) 2014 Hidenari Nozaki and contributors
 * Licensed under the MIT license
 */

'use strict';

angular.module('angucomplete-alt', [] ).directive('angucompleteAlt', ['$parse', '$http', '$sce', '$timeout', function ($parse, $http, $sce, $timeout) {
  var KEY_DW = 40,
      KEY_UP = 38,
      KEY_ES = 27,
      KEY_EN = 13,
      KEY_BS =  8,
      KEY_DEL =  46,
      MIN_LENGTH = 3,
      PAUSE = 500,
      BLUR_TIMEOUT = 300;

  return {
    restrict: 'EA',
    scope: {
      selectedObject: '=',
      localData: '=',
      remoteUrlRequestFormatter: '=',
      remoteUrlResponseFormatter: '=',
      id: '@',
      placeholder: '@',
      remoteUrl: '@',
      remoteUrlDataField: '@',
      titleField: '@',
      descriptionField: '@',
      imageField: '@',
      inputClass: '@',
      pause: '@',
      searchFields: '@',
      minlength: '@',
      matchClass: '@',
      clearSelected: '@',
      overrideSuggestions: '@'
    },
    template:
      '
' +
      '  <input id="{{id}}_value" ng-model="searchStr" type="text" placeholder="{{placeholder}}" class="{{inputClass}}" ng-focus="resetHideResults()" ng-blur="hideResults()"/>' +
      '
' +
      '
Searching...
' +
      '
No results found
' +
      '
' +
      '
' +
      '        ' +
      '

' +
      '
' +
      '

' +
      '
{{ result.title }}
' +
      '

' +
      '
{{result.description}}
' +
      '
' +
      '
' +
      '
',
    link: function(scope, elem, attrs) {
      var inputField,
          minlength = MIN_LENGTH,
          searchTimer = null,
          lastSearchTerm = null,
          hideTimer;

      scope.currentIndex = null;
      scope.searching = false;
      scope.searchStr = null;

      var callOrAssign = function(value) {
        if (typeof scope.selectedObject === 'function') {
          scope.selectedObject(value);
        }
        else {
          scope.selectedObject = value;
        }
      };

      var returnFunctionOrIdentity = function(fn) {
        return fn && typeof fn === 'function' ? fn : function(data) { return data; };
      };

      var responseFormatter = returnFunctionOrIdentity(scope.remoteUrlResponseFormatter);

      var setInputString = function(str) {
        callOrAssign({originalObject: str});

        if (scope.clearSelected) {
          scope.searchStr = null;
        }
        scope.showDropdown = false;
        scope.results = [];
      };

      var isNewSearchNeeded = function(newTerm, oldTerm) {
        return newTerm.length >= minlength && newTerm !== oldTerm;
      };

      var extractTitle = function(data) {
        // split title fields and run extractValue for each and join with ' '
        return scope.titleField.split(',')
          .map(function(field) {
            return extractValue(data, field);
          })
          .join(' ');
      };

      var extractValue = function(obj, key) {
        var keys, result;
        if (key) {
          keys= key.split('.');
          result = obj;
          keys.forEach(function(k) { result = result[k]; });
        }
        else {
          result = obj;
        }
        return result;
      };

      var findMatchString = function(target, str) {
        var result, matches, re = new RegExp(str, 'i');
        if (!target) { return; }
        matches = target.match(re);
        if (matches) {
          result = target.replace(re,
              ''+ matches[0] +'');
        }
        else {
          result = target;
        }
        return $sce.trustAsHtml(result);
      };

      if (scope.minlength && scope.minlength !== '') {
        minlength = scope.minlength;
      }

      if (!scope.pause) {
        scope.pause = PAUSE;
      }

      if (!scope.clearSelected) {
        scope.clearSelected = false;
      }

      if (!scope.overrideSuggestions) {
        scope.overrideSuggestions = false;
      }

      scope.hideResults = function() {
        hideTimer = $timeout(function() {
          scope.showDropdown = false;
        }, BLUR_TIMEOUT);
      };

      scope.resetHideResults = function() {
        if (hideTimer) {
          $timeout.cancel(hideTimer);
        }
      };

      scope.processResults = function(responseData, str) {
        var i, description, image, text;

        if (responseData && responseData.length > 0) {
          scope.results = [];

          for (i = 0; i < responseData.length; i++) {
            if (scope.titleField && scope.titleField !== '') {
              text = extractTitle(responseData[i]);
            }

            description = '';
            if (scope.descriptionField) {
              description = extractValue(responseData[i], scope.descriptionField);
            }

            image = '';
            if (scope.imageField) {
              image = extractValue(responseData[i], scope.imageField);
            }

            if (scope.matchClass) {
              text = findMatchString(text, str);
              description = findMatchString(description, str);
            }

            scope.results[scope.results.length] = {
              title: text,
              description: description,
              image: image,
              originalObject: responseData[i]
            };

          }

        } else {
          scope.results = [];
        }
      };

      scope.searchTimerComplete = function(str) {
        // Begin the search
        var searchFields, matches, i, match, s, params;

        if (str.length >= minlength) {
          if (scope.localData) {
            searchFields = scope.searchFields.split(',');

            matches = [];

            for (i = 0; i < scope.localData.length; i++) {
              match = false;

              for (s = 0; s < searchFields.length; s++) {
                match = match || (scope.localData[i][searchFields[s]].toLowerCase().indexOf(str.toLowerCase()) >= 0);
              }

              if (match) {
                matches[matches.length] = scope.localData[i];
              }
            }

            scope.searching = false;
            scope.processResults(matches, str);

          } else if (scope.remoteUrlRequestFormatter) {
            params = scope.remoteUrlRequestFormatter(str);
            $http.get(scope.remoteUrl, {params: params}).
              success(function(responseData, status, headers, config) {
                scope.searching = false;
                scope.processResults(
                  extractValue(responseFormatter(responseData), scope.remoteUrlDataField), str
                );
              }).
            error(function(data, status, headers, config) {
              console.log('error');
            });

          } else {
            $http.get(scope.remoteUrl + str, {}).
              success(function(responseData, status, headers, config) {
                scope.searching = false;
                scope.processResults(
                  extractValue(responseFormatter(responseData), scope.remoteUrlDataField), str
                );
              }).
            error(function(data, status, headers, config) {
              console.log('error');
            });
          }
        }

      };

      scope.hoverRow = function(index) {
        scope.currentIndex = index;
      };

      scope.selectResult = function(result) {
        // Restore original values
        if (scope.matchClass) {
          result.title = extractTitle(result.originalObject);
          result.description = extractValue(result.originalObject, scope.descriptionField);
        }

        if (scope.clearSelected) {
          scope.searchStr = null;
        }
        else {
          scope.searchStr = lastSearchTerm = result.title;
        }
        callOrAssign(result);
        scope.showDropdown = false;
        scope.results = [];
      };

      inputField = elem.find('input');

      scope.keyPressed = function(event) {
        if (!(event.which === KEY_UP || event.which === KEY_DW || event.which === KEY_EN)) {
          if (!scope.searchStr || scope.searchStr === '') {
            scope.showDropdown = false;
            lastSearchTerm = null;
          } else if (isNewSearchNeeded(scope.searchStr, lastSearchTerm)) {
            lastSearchTerm = scope.searchStr;
            scope.showDropdown = true;
            scope.currentIndex = -1;
            scope.results = [];

            if (searchTimer) {
              $timeout.cancel(searchTimer);
            }

            scope.searching = true;

            searchTimer = $timeout(function() {
              scope.searchTimerComplete(scope.searchStr);
            }, scope.pause);
          }
        } else {
          event.preventDefault();
        }
      };

      inputField.on('keyup', scope.keyPressed);

      elem.on('keydown', function (event) {
        if(event.which === KEY_DW && scope.results) {
          if ((scope.currentIndex + 1) < scope.results.length) {
            scope.$apply(function() {
              scope.currentIndex ++;
            });
          }
        } else if(event.which === KEY_UP && scope.results) {
          if (scope.currentIndex >= 1) {
            scope.$apply(function() {
              scope.currentIndex --;
            });
          }
        }
      });

      elem.on('keyup', function (event) {
        if (event.which === KEY_EN && scope.results) {
          if (scope.currentIndex >= 0 && scope.currentIndex < scope.results.length) {
            scope.selectResult(scope.results[scope.currentIndex]);
            scope.$apply();
            event.preventDefault();
          } else {
            event.preventDefault();
            if (scope.overrideSuggestions) {
              setInputString(scope.searchStr);
              scope.$apply();
            }
            else {
              scope.results = [];
              scope.$apply();
            }
          }

        } else if (event.which === KEY_ES) {
          scope.results = [];
          scope.showDropdown = false;
          scope.$apply();
        } else if (event.which === KEY_BS || event.which === KEY_DEL) {
          callOrAssign(null);
          scope.$apply();
        }
      });
    }
  };
}]);

<|endoftext|>