
/* utlis */

// if (typeof console == "undefined") {
//     window.console = {
//         log: function () {}
//     };
// }

// window.console = {
//        log: function () {}
// };

isLIVE = false;

switch (window.location.host.toLowerCase()) {

  case 'www.our-work.com.tw':
    isLIVE = false;
    break;

  case 'event.leecy.org.tw':
    isLIVE = true;
    break;
}

console.log('isLIVE : ' + isLIVE);

function gtag_pageView(_key) {
  //console.log("gtag_pageView: " + _key);
}

function gtag_ButtonClick(_key) {
  console.log("gtag_ButtonClick: " + _key);

  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    'event': 'customEvent',
    'eventCategory': 'Button',
    'eventAction': 'Click',
    'eventLabel': _key
  });
}

function setDefault(_textbox, _value) { // depend on jQuery
  $(_textbox).val(_value).css({ opacity: .4 });
  $(_textbox).focus(
    function () {
      if ($(this).val() == _value) {
        $(this).val('').css({ opacity: 1 });
      }
    })
    .blur(function () {
      if ($(this).val() == '') {
        $(this).val(_value).css({ opacity: .4 });
      }
    });
}

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function setParameterByName(name, value, url) {
  if (!url) url = window.location.href;
  var re = new RegExp("([?|&])" + name + "=.*?(&|$)", "i");
  separator = url.indexOf('?') !== -1 ? "&" : "?";
  if (url.match(re)) {
    return url.replace(re, '$1' + name + "=" + value + '$2');
  }
  else {
    return url + separator + name + "=" + value;
  }
}

function loadAnimate(_namespace, $container, _callback) {
  var $canvas, stage, exportRoot, anim_container, dom_overlay_container, fnStartAnimation;

  var key = Object.keys(this[_namespace].compositions)[0];
  var comp = this[_namespace].getComposition(key);
  var lib = comp.getLibrary();

  $canvas = $('<canvas></canvas>').attr({
    width: lib.properties.width,
    height: lib.properties.height
  }).appendTo($container);

  var loader = new createjs.LoadQueue(false);
  loader.addEventListener("fileload", function (evt) { handleFileLoad(evt, comp) });
  loader.addEventListener("complete", function (evt) { handleComplete(evt, comp) });
  loader.loadManifest(lib.properties.manifest);

  function handleFileLoad(evt, comp) {
    var images = comp.getImages();
    if (evt && (evt.item.type == "image")) { images[evt.item.id] = evt.result; }
  }
  function handleComplete(evt, comp) {
    var lib = comp.getLibrary();
    var ss = comp.getSpriteSheet();
    var queue = evt.target;
    var ssMetadata = lib.ssMetadata;
    for (i = 0; i < ssMetadata.length; i++) {
      ss[ssMetadata[i].name] = new createjs.SpriteSheet({ "images": [queue.getResult(ssMetadata[i].name)], "frames": ssMetadata[i].frames })
    }
    exportRoot = new lib[_namespace]();
    stage = new lib.Stage($canvas[0]);
    fnStartAnimation = function () {
      stage.addChild(exportRoot);
      createjs.Ticker.setFPS(lib.properties.fps);
      createjs.Ticker.addEventListener("tick", stage);
      exportRoot.stop();
      if (_callback != null) {
        _callback(exportRoot);
      }
    }

    this[_namespace].compositionLoaded(lib.properties.id);
    fnStartAnimation();
  }
}

function setCookie(name,value,days) {
  var expires = "";
  if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
function eraseCookie(name) {   
  document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

function POST(theUrl, theData) {
  console.log("API__DOMAIN: "+API__DOMAIN)
  const _url = API__DOMAIN + theUrl;
  // console.log(JSON.stringify(theData))
  return fetch(_url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(theData)
  })
  .then((response) => {
    return response.json(); 
  }).then((jsonData) => {
    // const { success, msg } = jsonData;
    // if (!success) {
    //   throw new Error(msg);
    // }
    console.log(jsonData)
    return jsonData;
  })
  // .catch((err) => {
  //   throw new Error(err);
  // });
}

function GET(theUrl) {
  // console.log("theUrl: "+theUrl)
  const _url = API__DOMAIN + theUrl;
  console.log("_url: "+_url)
  return fetch(_url, {})
    .then((response) => {
      return response.json(); 
    }).then((jsonData) => {
      console.log(jsonData)
      return jsonData;
    })
    // .catch((err) => {
    //   throw new Error(err);
    // });
}

const PRE__LIFFID = '2000769399-lGpVNobN'; // 測試liffId
const PRO__LIFFID = '2000844179-J80gOzVP'; // 正式liffId
const LIFFID = (isLIVE) ? PRO__LIFFID : PRE__LIFFID;

function liffInit() {
  console.log("LIFFID: "+LIFFID)
  return new Promise((resolve, reject) => {
    liff.init({
      liffId: LIFFID,
    }).then(() => {
      if (!liff.isLoggedIn() && !liff.isInClient()) {
        liff.login();
      } else {
        liff.getProfile().then((profile) => {
          resolve(profile);
        })
        .catch((err)=>{
          throw err;
        });
      }
    }).catch((err) => {
      reject(new Error(err));
    });
  });
}

function sleep(seconds) {
  return new Promise((resolve, reject) => {
    let _t = setTimeout(() => {
      clearTimeout(_t);
      _t - null;
      resolve();
    }, seconds);  
  });
}

const _PRE__HOST = 'event.leecy.org.tw'; // 目前正式&測試API打同一個
const _PRO__HOST = 'event.leecy.org.tw'; // 目前正式&測試API打同一個
const _URL = location.hostname;
const _host = (_URL.indexOf(_PRO__HOST) != -1) ? 'https://' + _PRO__HOST : 'https://' + _PRE__HOST;
const API__DOMAIN = _host;
console.log(API__DOMAIN)


var isIE = false;

utlis = function () {

  //private menbers


  //private methods
  function init() {
    console.log('all is loaded.');
  }

  //constructor

  {
    if ($('html').is('.ie6, .ie7, .ie8')) {
      isIE = true;
      // alert('.ie6, .ie7, .ie8');
    }

    $(document).ready(function () {
      init();
    });
  }

  //public

  return {

  }
}

utlis = new utlis();