// JSTOR Augmented Browsing Service (JABS) browser script

var _local_scripts = {"scripts":[{"pages":"*","script":"$('div#body table tbody tr td div.pagination b').before('<span>* <\/span>');","groups":"*"}]};
var _remote_scripts = {"scripts":[{"pages":"*","script":"dfrcounter","groups":"*"}]};

// Some convenience methods
String.prototype.trim = function(){return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}
String.prototype.startsWith = function(str){return (this.match("^"+str)==str)}
String.prototype.endsWith = function(str){return (this.match(str+"$")==str)}

function getPath() {
	var path = location.pathname;
	return path;
}

function getUserid() {
  var userid = $('div#myJstorUserid').text();
  if (!userid) {
    userid = 'anonymous';
  }
  return userid;
}

function getIdentityInfo() {
  var cookie = getCookie("groups");
  //alert('cookie='+cookie);
  if (cookie) {
	var split = cookie.split(',');
    if (split.length > 0) {
      _userid = split[0];
      var groups_seq = [];
      for (_i = 1; _i < split.length; +_i++) {
        groups_seq.push(split[_i]);
      }
      _groups = groups_seq.join();
	}
  } else {
    _userid = getUserid();
    if (_userid == 'anonymous') {
      _groups = 'anonymous';
    } else {
      _groups = 'myjstor';
      var groupsFromServer = urlopen('/abs/groups?user='+_userid);
      if (groupsFromServer) {
        _groups += ','+groupsFromServer;
      }
    }
	setCookie('groups', _userid + ',' + _groups);
  }
}

function getCookie( check_name ) {
  // first we'll split this cookie up into name/value pairs
  // note: document.cookie only returns name=value, not the other components
  var a_all_cookies = document.cookie.split( ';' );
  var a_temp_cookie = '';
  var cookie_name = '';
  var cookie_value = '';
  var b_cookie_found = false; // set boolean t/f default f
  for ( i = 0; i < a_all_cookies.length; i++ ) {
    // now we'll split apart each name=value pair
    a_temp_cookie = a_all_cookies[i].split( '=' );
    // and trim left/right whitespace while we're at it
    cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
    // if the extracted name matches passed check_name
    //alert('name='+cookie_name);
    if ( cookie_name == check_name ) {
      b_cookie_found = true;
      // we need to handle case where cookie has no value but exists (no = sign, that is):
      if ( a_temp_cookie.length > 1 ) {
        cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
      }
      // note that in cases where cookie is initialized but no value, null is returned
      return cookie_value;
      break;
    }
    a_temp_cookie = null;
    cookie_name = '';
  }
  if ( !b_cookie_found ) {
    return null;
  }
}

function cookieSet(name) {
  return document.cookie.indexOf(name) != -1;
}

function setCookie(name, value) {
  // session cookie
  document.cookie = name + "=" + escape(value) + "; expires=; path=/";
}

// Run applicable local scripts
function runLocalScripts() {
  for (_sctr=0; _sctr < _local_scripts.scripts.length; _sctr++) {
	var pages = _local_scripts.scripts[_sctr].pages;
	var groups = _local_scripts.scripts[_sctr].groups;
	var script = _local_scripts.scripts[_sctr].script;
    if (scriptIsRunnable(pages, groups)) {
    	eval(script);
    }
  }
}

//Get scripts from feature server
function getRemoteScripts() {
  var scripts_to_download = [];
  for (_sctr=0; _sctr < _remote_scripts.scripts.length; _sctr++) {
    var pages = _remote_scripts.scripts[_sctr].pages;
    var groups = _remote_scripts.scripts[_sctr].groups;
    var script = _remote_scripts.scripts[_sctr].script;
    if (scriptIsRunnable(pages, groups)) {
      scripts_to_download.push(script);
    }
  }
  if (scripts_to_download.length > 0) {
    var url = "/abs/addons?uri="+encodeURIComponent(document.URL)+"&groups="+encodeURIComponent(_groups)+"&scripts="+encodeURIComponent(scripts_to_download.join());
    async_request = GetXmlHttpObject();
    if (async_request == null) {
      //alert ("Your browser does not support XMLHTTP!");
      return;
    }
    async_request.onreadystatechange = stateChanged;
    async_request.open("GET", url, true);
    async_request.send(null);
  }
}

// Run any remote scripts
function runRemoteScripts(scripts) {
  if (scripts) {
    for (_sctr=0; _sctr < scripts.items.length; _sctr++) {
      _script = scripts.items[_sctr];
      eval(_script);
    }
  }
}

var async_request;

function urlopen(url) {
  request = GetXmlHttpObject();
  request.open("GET", url, false);
  request.setRequestHeader("User-agent", "jabs");
  request.setRequestHeader("Accept", "text/plain,text/xml,application/json");
  request.send(null);
  return request.responseText;
}

function GetXmlHttpObject() {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    return new XMLHttpRequest();
  }
  if (window.ActiveXObject) {
    // code for IE6, IE5
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
  return null;
}

function stateChanged() {
  if (async_request.readyState == 4) {
    if (async_request.status == 200) {
      eval('var scripts = '+async_request.responseText);
      if (_ready == true) {
        runRemoteScripts(scripts);
      } else {
        _remote_scripts_to_run = scripts;
      }
    } else {
      //alert("Problem retrieving XML data:" + xmlhttp.statusText);
    }
  }
}

// Check if script is runnable based on page and group
function scriptIsRunnable(pages, groups) {
  var pageMatch = pageMatches(pages);
  var groupMatch = groupMatches(groups);
  return pageMatch && groupMatch;
}

// Is script applicable for page
function pageMatches(pages) {
  var page_seq = pages.split(',');
  for (_ctr=0; _ctr<page_seq.length; _ctr++) {
    if (page_seq[_ctr] == '*') {
      return true;
    } else if (_path.trim().startsWith(page_seq[_ctr])) {
      return true;
    }
  }
  return false;
}

// Is script applicable for group
function groupMatches(page_groups) {
  var page_group_seq = page_groups.split(',');
  var user_group_seq = _groups.split(',');
  for (_ctr1=0; _ctr1<page_group_seq.length; _ctr1++) {
    if (page_group_seq[_ctr1] == '*') {
      return true;
    } else {
      for (_ctr2=0; _ctr2<user_group_seq.length; _ctr2++) {
        if (page_group_seq[_ctr1] == user_group_seq[_ctr2]) {
          return true;
        }
      }
    }
  }
  return false;
}

function betaFeaturesCheckbox() {
  if ($('#checkbox input:checked').val() == 'true') {
    addGroup('beta');
  } else {
    removeGroup('beta');
  }
  location.reload();
}

function addGroup(groupName) {
  updateGroup('add', groupName);
}
function removeGroup(groupName) {
  updateGroup('remove', groupName);
}
function inGroup(groupName) {
  var groups_seq = _groups.split(',');
  for (_ctr = 0; _ctr < groups_seq.length; _ctr++) {
    if (groupName == groups_seq[_ctr]) {
      return true;
    }
  }
  return false;
}

function updateGroup(action, groupName) {
  var groupsFromServer = urlopen('/abs/groups?action='+action+'&user='+_userid+'&group='+groupName);
  if (groupsFromServer) {
    _groups = 'myjstor,'+groupsFromServer;
  } else {
    _groups = 'myjstor';
  }
  setCookie('groups', _userid + ',' + _groups);
}


var _ready = false;
var _remote_scripts_to_run = null;
var _userid = null;
var _groups = null;
var _path = getPath();

if (cookieSet('groups')) {
  getIdentityInfo();
  getRemoteScripts();
}

function onReady() {
  _ready = true;
  if (!_userid) {
    getIdentityInfo();
    runLocalScripts();
    getRemoteScripts();
  } else {
    runLocalScripts();
    runRemoteScripts(_remote_scripts_to_run);
  }
}

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


