/* Common functions for tutorial pages
   1.0   08-Oct-2005   tmcnaney  Created
   1.1   05-Dec-2005   tmcnaney  Added functions to process cookies
   2.0   16-May-2007   tmcnaney  Updated for WF4 HOW
   3.0   01-Jul-2007   tmcnaney  Added autoresize for TOC, email feedback
   3.1   05-Jul-2007   tmcnaney  Fixed cookiePath processing
   3.2   12-Jul-2007   tmcnaney  Moved global variables to variables.js
                                 new_window now uses availWidth, availHeight
   4.0   03-Aug-2007   tmcnaney  Moved keyboard navigation from theme
                                 extended pageUpdate to support localization
   4.1   20-Nov-2007   tmcnaney  Copied from WF4 HOW and added support for tutorials
                                 with no TOC (single topic - hide Topics drop down and footer link)
                                 Added test string for IE7
 */

/* DO NOT INCLUDE ANYTHING IN THIS FILE WHICH REQUIRES LOCALIZATION */

// Browser test strings
// var ie4 = (document.all && !document.getElementById);
var ie5 = (document.all && document.getElementById);
var ie7 = (document.all && window.XMLHttpRequest);
var ns4 = (document.layers);
var ns6 = (!document.all && document.getElementById);
var ff2 = (document.all && window.getComputedStyle);

// Disable browser back button by clearing browser history
// history.forward();

// scan for events
if (document.layers) document.captureEvents(Event.KEYPRESS);                  // Netscape
if (document.all || window.getComputedStyle) document.onkeypress=key_press;   // IE or Firefox

// keyboard navigation - values are set in variables.js
function key_press(e) { 
   if (document.layers || window.getComputedStyle) {
      if (e.which==homekey || e.which==homekey2) window.location=(home=="" ? self.location : home);
      if (e.which==nextkey || e.which==nextkey2) window.location=(next=="" ? self.location : next); 
      if (e.which==backkey || e.which==backkey2) window.location=(back=="" ? self.location : back); 
      if (e.which==versionkey || e.which==versionkey2) window.alert(versionInfo);
   } else if (document.all) {
      if (event.keyCode==homekey || event.keyCode==homekey2) window.location=(home=="" ? self.location : home); 
      if (event.keyCode==nextkey || event.keyCode==nextkey2) window.location=(next=="" ? self.location : next); 
      if (event.keyCode==backkey || event.keyCode==backkey2) window.location=(back=="" ? self.location : back); 
      if (event.keyCode==versionkey || event.keyCode==versionkey2) window.alert(versionInfo);
   }
} // end of key_press

// Get current time, pad single digits with 0
function getCurrentTime() {
   var today = new Date();
   var currentHour = today.getHours();
   var currentMin = today.getMinutes();

   // pad currentTime for single digits
   var currentTime = ((currentHour >= 10) ? currentHour : "0"+currentHour) + ':' + ((currentMin >= 10) ? currentMin : "0"+currentMin);

return currentTime;

} // end of getCurrentTime

// set month to short name
function getCalendarDate() {

   var months = new Array(12);
   months[0] = "Jan";
   months[1] = "Feb";
   months[2] = "Mar";
   months[3] = "Apr";
   months[4] = "May";
   months[5] = "Jun";
   months[6] = "Jul";
   months[7] = "Aug";
   months[8] = "Sep";
   months[9] = "Oct";
   months[10] = "Nov";
   months[11] = "Dec";

   var now = new Date();

   var monthnumber = now.getMonth();
   var monthname = months[monthnumber];
   var monthday = now.getDate();
   var year = now.getFullYear();
  
   var dateString = monthday + '-' + monthname + '-' + year;

return dateString;

} // function getCalendarDate

function lastUpdated() {
   var lastModDate = new Date(document.lastModified);

   var lastUpdate = "updated: "
       lastUpdate += lastModDate.getMonth() + 1
       lastUpdate += "/"
       lastUpdate += lastModDate.getDate()
       lastUpdate += "/"
       lastUpdate += lastModDate.getFullYear()

   document.write("<span class='lastupdated'>" + lastUpdate + "</span>");

} // end of lastUpdated

// Reset default text in the status bar to empty string
function resetStatus() {
   defaultStatus = "";
}

// Window pop-up function to control size and position
// w, h values of 0 will maximize in that direction
function new_window(source,w,h) {
   var width=w;
   var height=h;
   var x;

   if ( width == 0 )
      width = screen.availWidth;

   if ( height == 0 )
      height = screen.availHeight;

   // upper-right justify window
   var x = screen.availWidth - width;

   var options="resizable=yes,status=no,toolbar=no,scrollbars=yes,top=0,left=" + x + ",width=" + width + ",height=" + height;

   var win = window.open(source,"",options);

} // end of new_window

// functions to process Cookies

// default DAYS to preserve cookies
var cookieLife = 1;

// determine path - make sure cookies are not proliferated for each sub-page
// assume http:/ /server.ptc.com/products/proe/wildfire4/wf4_how/tutorial/*.htm
//        0     1 2              3        4    5         6       7        8 (length = 8+1)
var URLsplit = self.location.href.split('/');
var cookieDomain = URLsplit[2];
if ( URLsplit[0] == 'http:' ) {
   var cookiePath = '';
   for (var i=3; i<=URLsplit.length-3; i++) 
      cookiePath += '/' + URLsplit[i];
}
if ( URLsplit[0] == 'file:' ) var cookiePath = '';

function setCookie(name, value, expires, path, domain, secure) {
/*
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie in days (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */

// time calculations use milliseconds
   var today = new Date();
   today.setTime( today.getTime() );

   if (expires) {
      expires = expires * 1000 * 60 * 60 * 24;
   }

   var expires_date = new Date( today.getTime() + (expires) );

   document.cookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires_date.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
} // end of setCookie

function getCookie(name) {
/*
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 * or null if cookie does not exist.
 */
   var offset;
   var end;
   var search = name + "="
   if (document.cookie.length > 0) { 
      offset = document.cookie.indexOf(search);
      if (offset != -1) { 
         offset += search.length;
         end = document.cookie.indexOf(";", offset);
         if (end == -1) end = document.cookie.length;

      return unescape(document.cookie.substring(offset, end));
      }
   }
} // end of getCookie

function deleteCookie(name, path, domain) {
/*
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */

   if (getCookie(name)) {
      document.cookie = name + "=" +
         ((path) ? "; path=" + path : "") +
         ((domain) ? "; domain=" + domain : "") +
         "; expires=Thu, 01-Jan-70 00:00:01 GMT";
   }
} // end of deleteCookie

function saveScroll() {
// capture current vertical scroll position of contents page main DIV
// advisor page doesn't have the same frame layout...
   if ( top.topicNumber == top.topicTotal ) return;
   
   var y = top.contents.document.getElementById('page_content').scrollTop;

// specify expiration in terms of DAYS
// forget scrollbar position in 10 mins.
   var expire = 10 / (60 * 24);
   top.setCookie('scrollPos', y, expire, top.cookiePath);
} // end of saveScroll

// resize and move window to tutorial position
// open new window with no decoration
function layoutWindow(width) {

   // determine if user disabled with AutoResize checkbox
   if (document.getElementById('autoresizeFlag')) {
      var test=getCookie('autoresizeFlag');
      if ( test == "true" ) {
	 document.getElementById('autoresizeFlag').checked = true;
      } else {
         document.getElementById('autoresizeFlag').checked = false;
      }
      var enabled=document.getElementById('autoresizeFlag').checked;
      if (!enabled) return;
   }

   // tutorialWidth is a global value inherited by this function
   if (width != undefined) 
      var tutorialWidth=width;

   ((window.tutorialWidth == undefined) ? tutorialWidth=550 : tutorialWidth=window.tutorialWidth);

   // operate on current window - may be restricted by browser security
   window.moveTo(0,0);
   window.resizeTo(tutorialWidth, screen.availHeight);
   return;

   // old window control logic...
   var winOptions = "resizable=1,status=1,location=0,toolbar=0,menus=0";

   // establish handle to already opened window named tutorial
   var mywindow = window.open('','tutorial',winOptions);
   mywindow.moveTo(0,0);
   mywindow.resizeTo(tutorialWidth, screen.availHeight);

} // end of layoutWindow

function makeDropMenu(id) {
   var itemString;
   for (var i=0; i <= topics.length-1; i++) {
      itemString="<li><a id=topic_" + topics[i].id + " href=" + topics[i].src + ">" + topics[i].title + "</a></li>";
      document.getElementById(id).innerHTML += itemString;
   }
} // end of makeDropMenu

function dropMenu(name, state) {
var obj = document.getElementById(name);
if (state == 'show')
   obj.style.display='block';

if (state == 'hide')
   obj.style.display='none';

if (state == 'toggle') {
   if (obj.style.display == 'block')
      obj.style.display='none';
   else
      obj.style.display='block'
}
} // end of dropMenu

function pageUpdate() {
// dynamic elements must be conditionally controlled until TB editor supports course / theme includes

// localizable variables stored in HTML - update global variables
   pageTitle = document.getElementById('pageTitle').innerHTML;
   tutorialTitle = document.getElementById('tutorialTitle').innerHTML;

// developer info
   versionInfo  = "Course Title:\t" + courseTitle + "\n";
   versionInfo += "Tutorial Title:\t" + tutorialTitle + "\n";
   versionInfo += "Page Title:\t" + pageTitle + "\n";
   versionInfo += "Tutorial Author:\t" + tutorialAuthor + "\n";
   versionInfo += "Publish Date:\t" + publishDate + "\n";

document.title = (matchString) ? tutorialTitle + " " + matchString : tutorialTitle;
document.getElementById('mainTitle').innerHTML = (mainTitle) ? mainTitle : courseTitle;
document.getElementById('subTitle').innerHTML = (subTitle) ? subTitle : " ";

if (topics) makeDropMenu('dropMenu1');
if (!showTopics) {
   document.getElementById('menu').style.display = "none";
   document.getElementById('menuspace').style.display = "none";
   document.getElementById('menutopic').style.left = 0;
   document.getElementById('footer_links').style.display = "none";
}
if (showPrintable) {
   document.getElementById('printView').style.display = "inline";
}
if (showEmail) {
   var emailString = (toName) ? "mailto:" + toName + "@" + toDomain + "?subject=" + subjPrefix + " - " + pageTitle : " ";
   document.getElementById('aEmail').href = emailString;
   document.getElementById('sendEmail').style.display = "inline";
}
if (showForum) {
   document.getElementById('aForum').href = (forumURL) ? forumURL : "http://www.ptc.com/forums/index.php?c=8";
   document.getElementById('aForum').target = "_blank";
   document.getElementById('postForum').style.display = "inline";
}

} // end of pageUpdate

/*
 * End of functions.js
 */