/*----------------------------------------------------------------------
 * setFocus( [Object o] )
 *   Sets the focus on the specified object, by 
 *   default the first element of the first form on
 *   the page is selected. Ignores hidden fields.
 *
 */
function setFocus( o ) {
    
    if( o != undefined )
    {                                                    // If object has been specified.
        try {                                            // Try the function in case object cannot be focused
            o.focus();
            o.select();
        } catch(e) {}
    } 
    else if( document.forms.length > 0)                  // If at least 1 form is present.
    {
        var l = document.forms[0].elements.length;       // Store length for faster loop execution.
        for(var i=0; i < l; i++) {
            var element = document.forms[0].elements[i];
            if( element.type != "hidden" ) {             // If the element is of type hidden ignore.
                try {
                    element.focus();
                    element.select();
                } catch(e) {}
                break;                                   // Break if first focusable field is found.
            }
        }
    }
    
}
 
/* Tabs */
var activeTabID = new Object();
function switchTab( tabObject, tabSetID, tabID )
{
        if( activeTabID[tabSetID] == tabID )
            return;
        tabObject.className="tabactive";
        try {
            thisTab = document.getElementById( "tab-"+ tabSetID +"-"+ activeTabID[tabSetID] );
            if( thisTab != null )
                thisTab.className = "";        // default class name for tab li
            thisTabArea = document.getElementById( "tabarea-"+ tabSetID +"-"+ activeTabID[tabSetID] );
            if( thisTabArea != null )
                thisTabArea.style.display = "none";
            document.getElementById( "tabarea-"+ tabSetID +"-"+ tabID ).style.display = "block";
        } catch (e) { alert( e.description ); }
        activeTabID[tabSetID] = tabID;
}
/* Season scroll */
var scrollAreas = {};
var scrollAreaSections = {};
var scrollActiveIndex = {};
function initScrollArea( name )
{
    scrollAreas[name] = document.getElementById( name );
    var tmpArray = scrollAreas[name].getElementsByTagName("DIV");
    var addIndex = 0;
    scrollAreaSections[name] = new Array();
    for( var i = 0; i < tmpArray.length; i++ )
        if( tmpArray[i].className == "scroll_section" )
            scrollAreaSections[name][addIndex++] = tmpArray[i];
    var last = scrollAreaSections[name].length-1;
    if( scrollAreas[name].className == "showall_area" ) {
        scrollAreaSections[name][0].style.display = "none";
        scrollAreaSections[name][last].style.display = "none";
        scrollActiveIndex[name] = -1;
    } else {
        for( var i=0; i < 3 && i <= last; i++ )
        scrollAreaSections[name][i].style.display = "block";
        scrollActiveIndex[name] = 1;
    }
}
function scrollNext( name )
{
    var last = scrollAreaSections[name].length-1;
    var current = scrollActiveIndex[name];
    if( scrollActiveIndex[name] > (last-2) || scrollActiveIndex[name] < 0 )
        return;
    scrollAreaSections[name][current-1].style.display = "none";
    scrollAreas[name].style.marginLeft = "0";
    scrollAreaSections[name][current+2].style.display = "block";
    scrollActiveIndex[name] = current+1;
    setTimeout( "shiftNext( '"+ name +"', 1 )", 10 );
}
function shiftNext( name, index )
{
    scrollAreas[name].style.marginLeft = "-"+ index*10 +"px";
    if( index < 61 )
        setTimeout( "shiftNext( '"+ name +"', "+ (index+1) +" )", 10 );
}
function scrollPrevious( name )
{
    var current = scrollActiveIndex[name];
    if( scrollActiveIndex[name] < 2 )
        return;
    scrollAreaSections[name][current+1].style.display = "none";
    scrollAreas[name].style.marginLeft = "-1220px";
    scrollAreaSections[name][current-2].style.display = "block";
    scrollActiveIndex[name] = current-1;
    setTimeout( "shiftPrevious( '"+ name +"', 1 )", 10 );
}
function shiftPrevious( name, index )
{
    scrollAreas[name].style.marginLeft = "-"+ (1220-(index*10)) +"px";
    if( index < 61 )
        setTimeout( "shiftPrevious( '"+ name +"', "+ (index+1) +" )", 10 );
}
/* Browse Buttons */
function gotoLinkAD()
{
    window.location=document.getElementById("catalogad").value;
}
function gotoLinkCH()
{
    window.location=document.getElementById("catalogch").value;
}
function selectedOptionJumpTo()
{
    var jumpto = document.getElementById("jumpto").value;
    if (jumpto != "default") {
        window.location = jumpto;
    }
}
/* cookie functions from quirksmode.org: http://www.quirksmode.org/js/cookies.html */
function createCookie(name,value,hours) {
    if (hours) {
        var date = new Date();
        date.setTime(date.getTime()+(hours*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
   
    document.cookie = name+"="+value+expires+"; path=/";
}


function createCookiewSpace(name,value,hours) {
    if (hours) {
        var date = new Date();
        date.setTime(date.getTime()+(hours*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
   
    document.cookie = name+"="+escape(value)+expires+"; path=/";
}

function readCookie(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) {
    createCookie(name,"",-1);
}

/*
  unescape an URL encoded string, including '+' -> ' '
*/
function super_unescape(string) {
  string = unescape(string);
  return string.replace('+', ' ');
}
/*
  gets the text value from the DOM node
*/
function getNodeText(node) {
  for (j = 0; j < node.childNodes.length; j++) {
    if (node.childNodes[j].nodeType == 3) {
      return node.childNodes[j].nodeValue;
    }
  }
  return null;
}
/*
  quick parse of LiveServer XML results
*/
function parseLiveServerXML(data) {
  var xml = null;
  if (typeof(data) == 'string') {
    // strip the DOCTYPE, it confuses some parsers
    var stridx = data.indexOf("<dynaments");
    data = data.substr(stridx);
    try {
      xml = new ActiveXObject('Microsoft.XMLDOM');
      xml.async = false;
      xml.loadXML(data);
    }
    catch(e) {
      try {
        parser = new DOMParser();
        xml = parser.parseFromString(data, "text/xml");
      }
      catch(e) {
        window.alert(e.message);
      }
    }
  }
  else {
    xml = data;
  }
  return xml;
}
/*
  abstracts for session ID set/get, in case this changes
*/
function get_hc_session() {
  return readCookie('hc_login_session');
}
function get_hc_username() {
  return readCookie('hc_login_username');
}
function get_hc_loginname() {
  return readCookie('hc_login_loginname');
}
function get_hc_sharedaccount() {
  return readCookie('hc_login_shared');
}
function set_hc_session(newid) {
  createCookie('hc_login_session', newid, 0);
  return readCookie('hc_login_session');
}
function set_hc_username(newname) {
  createCookie('hc_login_username', newname, 0);
  return readCookie('hc_login_username');
}
function set_hc_loginname(newlogin) {
  createCookie('hc_login_loginname',newlogin, 0);
  return readCookie('hc_login_loginname');
}
function set_shared_account(sharedname)
{
  createCookie('hc_login_shared',sharedname, 0);
  createCookiewSpace('hc_login_sharedjs',sharedname, 0);
  return readCookie('hc_login_shared');
}
function unset_hc_session() {
  eraseCookie('hc_session');
  eraseCookie('hc_auth');
  eraseCookie('hc_login_username');
  eraseCookie('hc_login_loginname');
  eraseCookie('hc_login_shared');
  return eraseCookie('hc_login_session');
}
function is_logged_in() {
  var session = get_hc_session()
  return session !== null;
} 
function isHCuser()
{
 if (is_logged_in() )
  {
    if (get_hc_loginname().toLowerCase().indexOf('harpercollins')>-1)
     {
       return true;
     }
    return false;
  }
  return false;
}
/*
  handles namespaces on XML elements in a super-simple fashion
*/
function quickNS(doc, ns, node) {
  if (typeof(doc.getElementsByTagNameNS) == 'undefined') {
    return doc.getElementsByTagName(ns + ':' + node);
  }
  else {
    return doc.getElementsByTagNameNS('*', node);
  }
}
/*
  helper function for building AJAX URLs
*/
function getAjaxBase(with_session) {
  if (with_session === undefined) {
    with_session = true;
  }
  var url = 'liveserver_include.asp?includepath=http://65.17.199.179:8080/cps/rde/xchg';
  var session = get_hc_session();
  if (with_session && session !== null) {
    url += '/' + session;
  }
  url += '/harpercollins-ecatalog/';
  return url;
}
/*
  generic AJAX error callback
*/
function server_error(XMLHttpRequest, textStatus, thrownError) {
  document.body.style.cursor = 'auto';
  window.alert("I'm sorry, there was an error while performing this action. Please try again, or contact the webmaster if the problem persists.");
}
/*
  button click handler for logout link
*/
function logout_click(event) {
  event.stopPropagation();
  event.preventDefault();
  logout_start();
  //logout_start();
}
/*
  start the AJAX call for logout
*/
function logout_start() {
  document.body.style.cursor = 'wait';
  var sessionID = get_hc_session();
  $.ajax({
    type: 'GET',
    cache: false,
    url: getAjaxBase() + 'dynaments/logout.xml',
    success: logout_success,
    error: server_error
  });
}
/*
  logout AJAX success callback
*/
function logout_success(data, textStatus) {
  // parse the return data in case it was not already parsed
  var xml = parseLiveServerXML(data);
  
  // get the return code, check for empty results
  var sresult = xml.getElementsByTagName('login-return-code')[0];
  var return_code = getNodeText(sresult);
  if (return_code === null) {
    return server_error();
  }
  return_code = parseInt(return_code);
  
  // doesn't really matter what the return code was, kill the session ID anyway
  unset_hc_session();
  
  // finish up and reload the page
  document.body.style.cursor = 'auto';
  window.location.reload();
}
/*
   Log user out if LS session has expired.
 */
function checkExpiry_start( ) {
  var sessionID = get_hc_session();
  $.ajax({
    type: 'GET',
    cache: false,
    url: getAjaxBase() + 'dynaments/check_login.xml',
    success: checkLogin_success,
    error: server_error
  });
}
function checkLogin_success(data, textStatus)
{
   
    try {
      var elems = data.getElementsByTagName( "result" );
      if( elems.length == 0 ) {
          unset_hc_session();
          window.location.reload();    
      }
    } catch( e ) {
      try {
        if( data.search(/SUCCESS/) < 1 ) {
          unset_hc_session();
          window.location.reload(); 
        }
      } catch( e ) { alert( "Could not verify login." ); }
    }
}
/*
  add things to jQuery onLoad handler
*/
$(document).ready(function(){
  $('#logoutlink').click(logout_click);
  var username = get_hc_username();
  if (username) {
    $('#header-generic').css('display', 'none');
    $('#header-username').text(username);
    $('#header-personal').css('display', 'block');
    checkExpiry_start( );
  }
});