

/*
 * This is Bootstrap script for loading UniLogin's javascript Site API.
 */

/* Create UniLogin main namespace */
var UniLogin = {
  isReady: {},
  isLoading: {},
  cbs: {
    core: []
  }
};

UniLogin.API = function(command, args) {
  if (!UniLogin.jquery.isPlainObject(args))
    args = {};
  if (UniLogin.Profile.token != null)
    args['token'] = UniLogin.Profile.token;

  var params = [];
  UniLogin.jquery.each(args, function(key, value) {
    params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  });
  if (params.length != 0)
    params = '?' + params.join('&');
  return 'https://uid.si/site/' + command + '/' + params;
};
/* Profile part of Site API is important, so this namespace is defined here.
 * Additional functions are defined in apropriate module.
 */
UniLogin.Profile = {
  authenticated: false,
  has_active_email: false,
  hasAuthenticatedSession: false,
  token: null,
  seen_cookies_dialog: true,
  gender: 'None',
  birthdate: new Date('')
};

UniLogin.initialize = function(isLoggedIn, config) {
  if (config == undefined || config.login == undefined || config.logout == undefined)
    return;

  if (isLoggedIn && !UniLogin.Profile.hasAuthenticatedSession) {
    document.getElementsByTagName('html')[0].style.display = 'none';
    window.location.replace(config.logout);
  } else if (!isLoggedIn && UniLogin.Profile.hasAuthenticatedSession) {
    document.getElementsByTagName('html')[0].style.display = 'none';
    window.location.replace(config.login);
  } else if (config.claimToken != false && !UniLogin.Profile.authenticated && UniLogin.Profile.hasAuthenticatedSession) {
    if (config.claimToken == undefined || config.claimToken == true) {
      /* No AJAX on page, relogin the user */
      window.location.href = config.logout;
    } else {
      /* Deffered token claiming without refreshing the page */
      var cb = (function(cb) { return function(token) {
        cb(token);
        UniLogin.Profile.token = token;
      };})(config.claimToken);
      UniLogin.ready('Core', (function(cb) { return function() {
        UniLogin._makeQuery('create_token', undefined, cb);
      };})(cb));
    }
  }
};
UniLogin._cleanQueue = function(module) {
  module = module.toLowerCase();
  UniLogin.isReady[module] = true;
  UniLogin.isLoading[module] = false;
  if (!UniLogin.cbs[module])
    return;
  var cb;
  while (cb = UniLogin.cbs[module].pop())
    cb();
};

UniLogin._transfers = {};
UniLogin._makeQuery = function(command, args, cb) {
  if (!UniLogin.jquery.isPlainObject(args))
    args = {};
  if (args['transferId'] == undefined)
    args['transferId'] = UniLogin._createTransfer(cb);
  UniLogin.jquery('body').append('<script type="text/javascript" src="' + UniLogin.API(command, args) + '"></script>');
};
UniLogin._createTransfer = function(cb) {
  var id = new Date();
  id = id.getTime();
  /* Append three iterating numbers */
  id *= 1000;

  /* Find first free id */
  while (UniLogin._transfers[id] != undefined)
    id += 1;
  /* Found a free spot */
  if (cb == undefined)
    UniLogin._transfers[id] = true;
  else
    UniLogin._transfers[id] = cb;
  return id;
};
UniLogin._finishTransfer = function(data, id) {
  var id = parseInt(id);
  var cb = UniLogin._transfers[id];
  UniLogin._transfers[id] = undefined;

  if (cb != true)
    cb(data);
};

(function() {
  /* onReady script from http://ryanmorr.com/archives/ondomready-no-browser-sniffing */
  var onReady = function(fn, ctx){
    var ready, timer;
    var onChange = function(e){
      if(e && e.type == "DOMContentLoaded"){
        fireDOMReady();
      }else if(e && e.type == "load"){
        fireDOMReady();
      }else if(document.readyState){
        if((/loaded|complete/).test(document.readyState)){
          fireDOMReady();
        }else if(!!document.documentElement.doScroll){
          try{
              ready || document.documentElement.doScroll('left');
          }catch(e){
              return;
          }
          fireDOMReady();
        }
      }
    };

    var fireDOMReady = function(){
      if(!ready){
        ready = true;
        fn.call(ctx || window);
        if(document.removeEventListener)
            document.removeEventListener("DOMContentLoaded", onChange, false);
        document.onreadystatechange = null;
        window.onload = null;
        clearInterval(timer);
        timer = null;
      }
    };

    if(document.addEventListener)
      document.addEventListener("DOMContentLoaded", onChange, false);
    document.onreadystatechange = onChange;
    timer = setInterval(onChange, 5);
    window.onload = onChange;
  };

  /* Load jQuery and other parts of the API */
  onReady(function() {
    var head = document.getElementsByTagName('HEAD');
    if (head.length == 0) {
      /* Page does not have a head */
      return;
    }
    head = head[0];
    /* Function for putting jQuery in non-conflict mode and loading other scripts */
    var loadOther = function() {
      /* Load jQuery UI */
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = 'https://uid.si/static/js/jquery-ui-1.8.14.js';
      script.onload = function() {
        /* Clear out the callback queue */
        UniLogin._cleanQueue('Core');
      };
      UniLogin.jquery('head')[0].appendChild(script);
    };

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://uid.si/static/js/jquery-site-1.7.1.js';
    script.onload = loadOther;
    head.appendChild(script);

    /* Load CSS for UniLogin dialogs (no need to have any events bind on it) */
    var include = document.createElement('link');
    include.type = 'text/css';
    include.rel = 'stylesheet';
    include.href = 'https://uid.si/static/site_api/dialog.css';
    head.appendChild(include);
  });
})();

/* Module registry */
UniLogin._registry = {
  
  profile: {
    name: 'profile',
    style: false,
    version: 0
  },
  
  storage: {
    name: 'storage',
    style: false,
    version: 91111
  }
  
};


UniLogin.ready = function(module, func) {
  module = module.toLowerCase();
  if (UniLogin.isReady[module]) {
    func();
    return;
  }

  if (UniLogin.cbs[module] == undefined)
    UniLogin.cbs[module] = [];
  UniLogin.cbs[module].push(func);
  /* Core module is loading in any case */
  if (module == 'core')
    return;

  /* Initiate load, if it is not already loading */
  var load = function(module) {
    if (UniLogin.isLoading[module])
      return;
    UniLogin.isLoading[module] = true;
    var head = UniLogin.jquery('head')[0];
    var include = '';
    var module = UniLogin._registry[module];
    
    /* Load the library */
    include = document.createElement('script');
    include.type = 'text/javascript';
    include.src = 'https://uid.si/static/site_api/' + module.name + '.js?rev=' + module.version;
    head.appendChild(include);
  };

  /* Initiate the load (if capable) */
  if (UniLogin.isReady['core']) {
    load(module);
  } else {
    UniLogin.cbs['core'].push((function(module, f) { return function() {
      f(module);
    };})(module, load));
  }
};




