// Portal utility functions
var snapURL = "http://snap.uci.edu/";

function isBrowserOK()
{
  browserName    = navigator.appName;
  browserVersion = parseFloat( navigator.appVersion );
  if ( browserName == "Netscape" && browserVersion < 4.78 )
  {
    alert( 'You are using an outdated Netscape browser version ' + browserVersion + '\n' +
           'Please upgrade your browser version to 4.78 or 4.79\n' +
           'to get optimal performance with SNAP!' );
  }
  else if ( browserName == "Netscape" && browserVersion >= 5.0 )
  {
    alert( 'You are using Netscape browser version ' + browserVersion + ' or greater.\n' +
           'Some applications may not work with this browser.\n' +
           'Please use Netscape browser version 4.78 or 4.79\n' +
           'to get optimal performance with SNAP!' );
  }
}


function expandNode( form, nodeID )
{
  form.current_node_id.value = nodeID;
  //alert( 'Current Node ID=' + form.current_node_id.value );
  form.submit();
}

function collapseNode( form, nodeID )
{
  form.current_node_id.value = nodeID;
  form.task.value = 'collapse';
  form.submit();
}

function openWin(url, winObjName, width, height)
{
  var newWin = window.open(url, winObjName, 'width=' + width + ',height=' + height
      + ',toolbar=no,resizable=yes,scrollbars=yes');
  newWin.focus();
}

function openBrWindow(theURL,winName,features)
{
  window.open(theURL,winName,features);
}

//~~~~ begin UCI code ~~~~
function openFullScreenWin(url, winObjName)
{
  window.open(url, winObjName, 'width=' + screen.availWidth + ',height=' + screen.availHeight
      + ',toolbar=yes,location=yes,status=yes,menubar=yes,resizable=yes,scrollbars=yes,top=0,left=0');
}

// opens a window with hieght=80% of sreen hieght, and width=80% of screen width
// Using percentages is helpful to open windows that are proportional to screen resolution
function openSmallerScreenWin(url, winObjName)
{
  /*
  window.open(url, winObjName, 'width=' + getRelativeWidth( 80 )  + ',height=' + getRelativeHeight( 80 )
      + ',toolbar=yes,location=yes,status=yes,menubar=yes,resizable=yes,scrollbars=yes,top=0,left=0');
      */
  openPercentageWin(url, winObjName, 80, 80);
}

function openPercentageWin(url, winObjName, percentWidth, percentHeight)
{
  window.open(url, winObjName, 'width=' + getRelativeWidth( percentWidth )  + ',height=' + getRelativeHeight( percentHeight )
      + ',toolbar=yes,location=yes,status=yes,menubar=yes,resizable=yes,scrollbars=yes,top=0,left=0');
}

// define a variable for the detached window:
var detachWin = null;

function openDetachWindow(theURL, doReload, doPrint)
{
  var features = 'toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=640,height=480';
  detachWin = window.open(theURL, 'detachedChannel', features);
  if ( doPrint )
  {
    window.setTimeout( 'printDetachedWindow( true,' + doReload + ' )', 2000);
  }
  else if ( doReload )
  {
    window.location.reload();
  }
}

function printDetachedWindow( doClose, doReload )
{
  if( detachWin && !detachWin.closed )
  {
    detachWin.print();
    if ( doReload )
    {
      detachWin.opener.location.reload();
    }
    if ( doClose )
    {
      //detachWin.close();
      detachWin.setTimeout( 'close()', 3000);
    }
  }
}

/* opens up a window with channel preview */
function previewChannel(form)
{
  var index = form.selectedChannel.selectedIndex;
  var chID = form.selectedChannel[ index ].value;
  var url = 'tag.idempotent.render.userLayoutRootNode.uP?uP_detach_target=' + chID;
  openDetachWindow(url, false, false);
}

function getRelativeWidth( percent )
{
  var relWidth = screen.availWidth * (percent/100);
  return relWidth;
}

function getRelativeHeight( percent )
{
  var relHeight = screen.availHeight * (percent/100);
  return relHeight;
}

//~~~~~~~~~~~~~~ begin ALERTS POP UP WINDOW ~~~~~~~~~~~~~~~~~~~~~~
function enableCriticalAlertsWindow()
{
  /*
  var errMsg = "Due to your browser settings the 'SNAP Critical Alerts' window cannot be opened!\n" +
      "Please contact your Computer Support to allow \"pop up\" windows for this site.\n\n" +
      "Please click the OK button to proceed to SNAP.";
  var winOptions = "width=" + getRelativeWidth( 30 ) + ",height=" + getRelativeHeight( 30 ) + ",toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=yes";
  var jspURL = "criticalAlerts.jsp";
  if( window.alertsWin && !alertsWin.closed )
  {
    alertsWin.opener = this;
  }
  else
  {
    alertsWin = window.open(jspURL, "alertsWin", winOptions);
    // error processing
    if ( alertsWin == null || alertsWin == undefined )
    {
      // output an error message???
      alert( errMsg );
    }
    else
    {
      minimize( alertsWin );
    }
  }
  */
}

function disableCriticalAlertsWindow()
{
  /*
  var winOptions = "width=100,height=100,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=yes";
  var jspURL = "criticalAlerts.jsp";
  if( window.alertsWin && !alertsWin.closed )
  {
    alertsWin.close();
  }
  else
  {
    alertsWin = window.open("", "alertsWin", winOptions);
    alertsWin.close();
  }
  */
}

function minimize( myWindow )
{
  myWindow.resizeTo( getRelativeWidth( 30 ), getRelativeHeight( 30 ) );
  myWindow.moveTo( 0, 0 );
  myWindow.blur();
  var snapWin = myWindow.opener;
  if ( !snapWin )
  {
    snapWin = open( snapURL );
    myWindow.opener = snapWin;
  }
  //snapWin.moveTo( 0, 0 );
  //snapWin.resizeTo( screen.availWidth, screen.availHeight );
  snapWin.focus();
}

function maximize( myWindow )
{
  myWindow.resizeTo( getRelativeWidth( 70 ), getRelativeHeight( 70 ) );
  myWindow.moveTo( 100, 100 );
  if ( myWindow.opener )
  {
    myWindow.opener.window.blur();
  }
  myWindow.focus();
}

function checkWebauthCookie( myWindow )
{
  var webauthC = getCookie( "ucinetid_auth" );
  if ( webauthC == null || webauthC.length < 64 )
  {
    myWindow.close();
  }
}

function getCookie( name )
{
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while ( i < clen )
  {
    var j = i + alen;
    if ( document.cookie.substring( i, j ) == arg )
    {
      return getCookieVal( j );
    }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
}

function getCookieVal( offset )
{
  var endstr = document.cookie.indexOf( ";", offset );
  if ( endstr == -1 )
  {
    endstr = document.cookie.length;
  }
  return unescape( document.cookie.substring( offset, endstr ) );
}

/** this function only works in Mozilla/Netscape
    and only if Java plugin is present
 */
function beep()
{
  try
  {
    if ( navigator.javaEnabled != null && navigator.javaEnabled() )
    {
      java.awt.Toolkit.getDefaultToolkit().beep();
      java.awt.Toolkit.getDefaultToolkit().beep();
      java.awt.Toolkit.getDefaultToolkit().beep();
    }
  }
  catch( e ) {}
}
//~~~~~~~~~~~~~~ end ALERTS POP UP WINDOW ~~~~~~~~~~~~~~~~~~~~~~

// check the browser version
//isBrowserOK();

// by Warren
// used for channel subscription pages
function getObj(name) {
  if ( document.getElementById( name ) ) {
    return document.getElementById( name );
  }
  else if ( document.all ) {
    return document.all[name];
  }
  else if ( document.layers ) {
    return document.layers[name];
  }
}


function updateChanDesc( pAllChannels, pSelectedValue ) {
  if ( pSelectedValue == '' ) {
    getObj( 'chanDesc' ).innerHTML = 'No channel selected';
  }
  else {
    getObj( 'chanDesc' ).innerHTML = pAllChannels[pSelectedValue].description;
  }
}

function previewChannelByChanId(form)
{
  var index = form.selectedChannel.selectedIndex;
  if ( index != -1 ) {
    var chID = form.selectedChannel[ index ].value;
    if ( !chID || chID == '' || chID.indexOf( 'category contains no channels' ) != -1 ) {
      alert( 'No channel selected.' );
    }
    else {
      var chIDAsCtf = 'ctf' + chID.substring( 'chan'.length );
      var url = 'tag.idempotent.render.' + chIDAsCtf + '.uP';
      openDetachWindow(url, false, false);
    }
  }
  else {
    alert( 'No channel selected.' );
  }
}

// DOM Functionality
function alterStyle(element, attribute, value) {
  if (element.style)
    try {element.style[attribute] = value;} catch(e) { alert("alterStyle Error setting "+attribute+" to "+value)}
  else 
    element[attribute] = value;
}

// OnEvent Listener Registration
function addEvent(obj, eventType, func) {
  if (obj.addEventListener){
    obj.addEventListener(eventType, func, false);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+eventType, func);
    return r;
  } else {
    return false;
  } 
}

// CSS Value Parsing
function getCSSValue(el, property, toInt)
{
  if (typeof(toInt) == 'undefined') {
    toInt = false;
  }
  
  var styleValue;
  if (typeof(window.getComputedStyle) == 'function') {
    styleValue = window.getComputedStyle(el, null)[property];
  } else {
    styleValue = el.currentStyle[property];
  }
  if (toInt) {
    return isNaN(parseInt(styleValue)) ? 0 : parseInt(styleValue);
  } else {
    return typeof(styleValue) != 'undefined' ? styleValue : '';
  }
} 

// Search Text
QLSearchText = "Search";
QLUnmodifiedFlag = false;
BLACK = "#000"; // "black" would also work
GRAY = "#999"; //IE doesn't accept "gray"

// Search Functions
function LoadSearchForm() {
  if (document.snapsearch == null) { return; }
  var textEl = document.snapsearch.qt;
  if (textEl.value == "" || textEl.value == QLSearchText) {
    QLUnmodifiedFlag = true;
    textEl.value = QLSearchText;
    alterStyle(textEl, "color", GRAY);
  }
}
// Call from the window onload script
addEvent(window, 'load', LoadSearchForm);

function FocusSearchForm() {
  var textEl = document.snapsearch.qt;
  if (QLUnmodifiedFlag && textEl.value == QLSearchText) {
    textEl.value = "";
    QLUnmodifiedFlag = false;
    alterStyle(textEl, "color", BLACK);
  }
}

function BlurSearchForm() {
  var textEl = document.snapsearch.qt;
  if (textEl.value == "") {
    QLUnmodifiedFlag = true;
    textEl.value = QLSearchText;
    alterStyle(textEl, "color", GRAY);
  }
}

function VerifySearchForm() {
  var textEl = document.snapsearch.qt;
  var invalidText = (textEl.value == "" || QLUnmodifiedFlag || textEl.value == QLSearchText);
  var radioElementList = document.snapsearch.Type;
  if (invalidText) {
    document.snapsearch.qt.value = QLSearchText;
    alert('It appears that you attempted to search without entering search text. Please enter a word, name or phrase and try again.')
    return false;
  } else if (radioElementList[1].checked) {
    document.ucisearch.QuickLink.value = textEl.value;
    document.ucisearch.Type.value = "Full Search";
    document.ucisearch.submit();
    return false;
  } else if (radioElementList[2].checked) {
    document.ucisearch.QuickLink.value = textEl.value;
    document.ucisearch.Type.value = "Directory";
    document.ucisearch.submit();
    return false;
  } else {
    return true;
  }
}

// Get Readable Date
function GetReadableDate() {
  var months=new Array(13);
  months[1]='January';
  months[2]='February';
  months[3]='March';
  months[4]='April';
  months[5]='May';
  months[6]='June';
  months[7]='July';
  months[8]='August';
  months[9]='September';
  months[10]='October';
  months[11]='November';
  months[12]='December';
  var time=new Date();
  var lmonth=months[time.getMonth() + 1];
  var date=time.getDate();
  var year=time.getYear();
  if (year < 1000) {year = 1900 + year;} 
  return lmonth+' '+date+', '+year;
}


// A quick and dirty AJAX Function independant of library in use
function loadXMLDoc(url, callback) {
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    var req = new XMLHttpRequest();
    req.onreadystatechange = function() {callback(req);};
    req.open("GET", url, true);
    req.send(null);
  // branch for IE/Windows ActiveX version
  } else if (window.ActiveXObject) {
    var req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange = function() {callback(req);};
      req.open("GET", url, true);
      req.send();
    }
  }
}

// CMenuChannel Show/Hide list items
function toggleMenuItems(menuNodeID, linkNode) {
  var menuNode = document.getElementById(menuNodeID);
  var shown = (getCSSValue(menuNode, "display") == 'block');
  if (shown) {
    menuNode.style.display = 'none';
    menuNode.parentNode.style.listStyleImage = 'url('+snapURL+'/media/edu/uci/adcom/portal/channels/CMenuChannel/collapsed.gif)';
  } else {
    menuNode.style.display = 'block';
    menuNode.parentNode.style.listStyleImage = 'url('+snapURL+'/media/edu/uci/adcom/portal/channels/CMenuChannel/expanded.gif)';
  }
  var url = linkNode.href;
  // Send ajax command. Ignore the result.
  loadXMLDoc(url,
    function(request){
      if (request.readyState == 4) { // complete
        if (request.status == 200) { // successful
          //ignore
        } else {
          window.location = url;
        }
      }
      return;
    });
  /*
  dojo.io.bind({
		url: url,
		load: function(type, data, evt){
	    return;
		},
		error: function(type, error){
      window.location = url;
      return;
    },
		mimetype: "text/html"
	});
  */
  
  if (shown) {
    linkNode.href = linkNode.href.replace("task=collapse", "task=expand");
  } else {
    linkNode.href = linkNode.href.replace("task=expand", "task=collapse");
  }
  
  return false; // don't follow the link if js is enabled
}


// the following 2 functions are used to load javascript files dynamically
// (allows us to optionally load them with a delay)
function $import(src){
  var scriptElem = document.createElement('script');
  scriptElem.setAttribute('src',src);
  scriptElem.setAttribute('type','text/javascript');
  document.getElementsByTagName('head')[0].appendChild(scriptElem);
}

// import with a random query parameter to avoid caching
function $importNoCache(src){
  var ms = new Date().getTime().toString();
  var seed = "?" + ms; 
  $import(src + seed);
}

//~~~~ end UCI code ~~~~


