/* -*- mode: C;-*--------------------------------------------------------------
 * (C)2001-2010 Copyright InfoStreet, Inc.
 * Use without the permission of InfoStreet Inc. is strictly prohibited.
 * Contact InfoStreet for more details (http://www.infostreet.com)
 *
 * Name:           $RCSfile: main.js,v $
 * Author:         L.C. (Laurentiu Badea) <lc@infostreet.com>
 * Created On:     Oct 11, 2001
 *
 * Modified:       $Date: 2010/06/22 23:38:01 $
 * Version:        $Revision: 1.65 $
 *
 *-----------------------------------------------------------------------------*/

/*
 * Set security context to the current domain for cross-domain access
 * http://msdn.microsoft.com/workshop/author/om/xframe_scripting_security.asp
 */
/*
 * Commented out as it causes problems with new frame/window elements.
 * I believe this attribute should be inherited to make them work, but is not.
if (document.domain){
  // remove everything that looks like something.my. before the domain.
  document.domain = document.domain.replace( /([-\w]+\.)?my\./i, "" );
}
*/

/*
 * Object hilighting - use with ID attribute names.
 */

function browserType(){
  if (document.layers){ return "NS4"; }
  if (document.all){ return "IE4"; }
  return "IE4"
}

// Reserve storage for 4 different hilighted items
var oldObj = new Array(5)
oldStyleName = "";

// Hilight selected area
function hilite(name, styleName){
  try {

    obj0 = document.getElementById( name );
    obj1 = document.getElementById( name + 1 );
    obj2 = document.getElementById( name + 2 );
    obj3 = document.getElementById( name + 3 );
    obj4 = document.getElementById( name + 4 );
    if ( oldStyleName ) {
      if ( oldObj[0] ) oldObj[0].className = oldStyleName + "BG";
      if ( oldObj[1] ) oldObj[1].className = oldStyleName + "Border";
      if ( oldObj[2] ) oldObj[2].className = oldStyleName + "Reflex";
      if ( oldObj[3] ) oldObj[3].className = oldStyleName + "Shadow";
      if ( oldObj[4] ) oldObj[4].className = oldStyleName ;
    }
    oldStyleName = styleName;
    if ( obj0 ) obj0.className = "FeatureBG_h";
    if ( obj1 ) obj1.className = styleName + "Border_h";
    if ( obj2 ) obj2.className = "FeatureReflex_h";
    if ( obj3 ) obj3.className = "FeatureShadow_h";
    if ( obj4 ) obj4.className = "Feature_h";

    for (i=0; i<5; i++) {
      oldObj[i] = eval( "obj" + i );
    }

  } catch (e){}
}

function hiliteNS4(name, color, block){
  obj = document.ids[name]
  if (oldObj[block]){
    oldObj[block].bgColor = ''
  }
  if (obj){
    obj.bgColor = color
    oldObj[block] = obj
  } else {
    alert("ID " + name + " not found in " + document.location);
  }
}

/*
 * Store the loggedIn status from the last isLoggedIn call
 * (to figure when we changed status)
 */
var lastActive = isLoggedIn();



/*
 * Returns 1 if user is logged in, 0 if not
 * Not foolproof but works most of the time.
 */
function isLoggedIn() {
  if (document.cookie.indexOf('==') == -1) { 
    return 0;
  } else {
    s = document.cookie.split("Basic_Hosting=");
    s2 = s[1].split("==");
    
    if (s2[0] != "") {
      return 1;
    } else {
      return 0;
    }
  }
}

/*
 * Reload menu bar (header frame) if status has changed
 * This should be called from the header frame that is persistent. 
 * It does not make much sense for the others.
 * Returns false if status did not change or we're not in the right frame
 */
function checkLoggedIn() {
  active = isLoggedIn();
  inactive = 1-active;

  if (window.name != "header"){
    return false;
  }

  if (lastActive != active){
    // status has changed, reload menu bar to possibly update buttons
    document.location.reload(true);
    if( parent.menu ) {
      parent.menu.location.reload(true);
    }  
    return true;
  }

  return false;
}

/*
 * Require that document shows inside the given frame of the main frameset
 * We are assuming the root (/) document is a frameset and knows about the #tag
 * Returns true if it already is there.
 */
function requireFrame(frame){
  current = document.location.href.split("#")[0]; // remove previous #tag
  ary = current.split( "/" );
  newURL = location.protocol + "//" + location.hostname + "/";
  if (frame == 'body'){
    newURL += "#" + location.pathname + location.search;
  }

  // set title and location URL from body document
  if (document.title && frame == 'body'){
    if (browserType() == "NS4"){
      top.document.title = document.title;
    } else {
      try {
    top.document.title = document.title;
    // IE5 on Mac reloads the page each time location is updated so we skip it
    // for a Mac.
    if (top.location.href != newURL && 
        navigator.appVersion.lastIndexOf("Mac") == -1){
      // top.location.href = newURL;
    }
      } catch (e){};
    }
  }

  if(top.frames[frame] != this.window) {
    top.location.replace( newURL );
    return false;
  }

  return true;
}

/*
 * Attempt to get at the menu frame. 
 * Returns false if the frame does not exist or is inaccessible, otherwise
 * returns the corresponding Window object
 */
function getMenuFrame(){

  var header;

  try {
    header = parent && (parent.header || parent.parent.header);
    // attempt to access something in the header frame to ensure we have access
    header.checkLoggedIn;
  } catch (e){
    return false;
  }

  return header;
}

function isInIFrame(){
  try {
    if (window.location == window.parent.location) {
      return false;
    } else {
      return true;
    }
  } catch(e) {
    return true;
  }
}



/*
 * Show help and logout if Require Navigation is set in page template.
 */

function requireNavigation( ) {
  header = getMenuFrame();

  noRedirect = 0;

  if (header) {
    //we are in frames.
    noRedirect = 1;
  }

  if (isInIFrame()) {
    noRedirect = 1;
  }

  /*
   * getMenuFrame can return false in two reasons:
   * 1- header frame doesn't exist and we need to reload the page and put the page on frame.
   * 2- there has been a "permission denied" error when trying to get header's properties.
   *     In this case we are definitely in frame and we don't need to reload the page.
   *     the following function checks to see  if we have permission or not.
   */
  try {
    var test = parent.location.href;
    // we have permission
  } catch(e) {
    // we don't have permission, so we are in frame with different domains.
     return;
  }

  //if this is a popup window from another page return
  if (window.opener) {
    return;
  }

  if (noRedirect == 1) {
    return
  }

  var topPageLogin = document.getElementById("TopPageLogin");
  var searchBox = document.getElementById("SearchBox");
  var searchImg = document.getElementById("SearchImg");
  var searchFieldSelector = document.getElementById("SearchFieldSelector");
  topPageLogin.style.display = "block";
  var displayOptionsSpan = document.getElementById("DisplayOptionsSpan");
  var filterOptions = document.getElementById("FilterOptions");
  var topPageLoginOffset = Number(topPageLogin.offsetHeight);
  if (searchBox) {
    var newH = topPageLoginOffset + Number(removePX(searchBox.style.top));
    searchBox.style.top = newH;
    searchImg.style.top = newH;
  }
  if (displayOptionsSpan) {
    displayOptionsSpan.style.top = topPageLoginOffset + Number(removePX(displayOptionsSpan.style.top)); 
  }
  if (searchFieldSelector) {
    searchFieldSelector.style.top = topPageLoginOffset + Number(removePX(searchFieldSelector.style.top)); 
  }

  for (menu in menuRegistry.menus) {
    var pulldown = document.getElementById(menu + "_pulldown");
    var pulldownBoundary = document.getElementById(menu + "_pulldownBoundary");
    var pulldownBoundaryBuffer = document.getElementById(menu + "_pulldownBoundaryBuffer");
    var pulldownFrame = document.getElementById(menu + "_pulldownFrame");
    var pulldownShadow = document.getElementById(menu + "_pulldownShadow");
    pulldown.style.top = topPageLoginOffset + Number(removePX(pulldown.style.top));
    pulldownBoundary.style.top = topPageLoginOffset + Number(removePX(pulldownBoundary.style.top)); 
    pulldownBoundaryBuffer.style.top = topPageLoginOffset + Number(removePX(pulldownBoundaryBuffer.style.top));
    pulldownFrame.style.top = topPageLoginOffset + Number(removePX(pulldownFrame.style.top));
    pulldownShadow.style.top = topPageLoginOffset + Number(removePX(pulldownShadow.style.top));
  }
}



/*
 * Require that the document always be in the "body" frame (not any more!)
 * It will also refresh the "menu" (header frame) if login status changed.
 */
function requireBody( noCookie ){

  header = getMenuFrame();
  if (!header){
    return;
  }

  // don't execute the rest if this document is already in the header frame
  if (header.name == window.name){
    return;
  }

  // Set the cookie that remembers last page visited in this frame.
  lastPage = location.href;

  try {
    if (header && header.location && header.location.hostname == location.hostname){
      lastPage = location.pathname + location.search;
    }
  } catch (e){}

//  if (!noCookie){
//    expires = new Date();
//    expires.setFullYear( expires.getFullYear() + 1 );
//    document.cookie = "lastVisitedPageBody=" + lastPage + 
//      "; expires=" + expires.toGMTString() + "; path=/";
//  }

  // update menu bar if login status has changed.
  // NOTE: if the header was reloaded, its contents is inaccessible for a while
  header.checkLoggedIn()

}
function showMainMenu( destination ) {
  expires = new Date(); 
  expires.setFullYear( expires.getFullYear() + 1 );

  if (!destination) {
    destination = document.location.href;
  }
  //store the current page as the lastVisitied page.
  document.cookie = "lastVisitedPageBody="  + uName + "*|*" + destination + 
                     "; expires=" + expires.toGMTString() + 
                     "; path=/";
  
  if ( document.cookie.indexOf("OpenMenus=") != -1 ) {
    var myCookie = ( document.cookie.split("OpenMenus=")[1] ).split( ";" )[0];
    var leftSideCookie = myCookie.substr( 0, myCookie.lastIndexOf( "|" ) ) + "|";
  } else {
    var leftSideCookie = "|||||";
  }
  document.cookie = "OpenMenus=" + leftSideCookie + "open" +
                    ";expires=" + expires.toGMTString() +
                    ";path=/nav/";
  document.location.href = "/";  
}

/*
 * same as above but without setting the cookie 
 */
function requireBodyNoCookie(){
  requireBody(1);
}

/*
 * Require that document be always in the top window (not in a frame)
 * Returns true if it already is.
 */
function requireTop(){
  if (window.self != window.top){
    top.location.replace( document.location );
    return false;
  }
  return true;
}

/*
 * Extract location from #tag in url
 */
function getLocation(){
  url = document.location.href.split('#')[1];
  return url;
}

/* 
 * update the selected option in a SELECT pull-down
 */
function updateSelected( select, option ){
  for (i=0; select.length > i; i++){
    if (select.options[i].value == option){
       select.selectedIndex = i;
       break;
    }
  }
  if (i==select.length){
    select.selectedIndex = 0;
  }
}

/* 
 * toggle between select all and un-select all for type=checkbox
 */
function checkAll(name, fname){
    var frm = document.forms[name];
    for (var i=0;i<frm.elements.length;i++) {
      var e = frm.elements[i];
      if (fname) {
        if ((e.name != 'selectAll') && (e.name==fname) && (e.type=='checkbox')) {
          e.checked = frm.selectAll.checked;
        }
      } else {
        if ((e.name != 'selectAll') && (e.type=='checkbox')) {
          e.checked = frm.selectAll.checked;
        }
      }

    }
}

/* 
 * checks to see if a checkbox is selected for delete, add, ....
 */
function checkField(formName, fieldName, formAction,numberPermited,popWidth,popHeight,message,type) {
    
   var  count = 0; 
   var  count2 =0;
   var  len  = eval('document.'+formName+'.'+fieldName+'.length');
   var  doc = eval('document.'+formName+'.'+fieldName);
   if(document.layers) {  
  
      if(eval(' (doc) && (doc != "'+formName+'")')) { 
         count2++;       
         if(eval('(doc'+'[0]) && (doc'+'[0] !=" '+formName+'.substr(0,1)")')){
           for (i=0; i<len; i++) {
             if(!type) {
               if(doc[i].checked) count++ ;
             } else {
               if(doc[i].value) count++ ;
             }
           }
         }else {
            if(!type) {
              if(doc.checked) count++;
            } else {
              if(doc.value) count++;
            }
         }
      } 
   }else{ 
      if(  (doc == "[object HTMLCollection]") || 
           (doc == "[object HTMLInputElement]") ||
           (doc == "[object]") ||
           (doc == "[object INPUT]") || 
           (doc == "[object NodeList]") || 
           (doc == "[object Collection]")
         ) {
         count2++;
         if(doc[0]){
           for(i=0; i<len; i++) {
             if(!type) {
               if(doc[i].checked) count++ ;
             } else {
                if(doc[i].value) count++ ;
             }
           }
         }else {
            if(!type) {
              if(doc.checked) count++;
            } else {
              if(doc.value) count++;
            }
         }
      }
   }
   if(numberPermited == "single") {
      if(count==1){
        eval('document.'+formName+'.action = "'+formAction+'"');
        if(message) conf = confirm(message);
        else conf=1;
        if(conf){ 
          if((popWidth) && (popHeight)) {
             popLeft = (screen.width -  popWidth)/2;
             popTop = (screen.height - popHeight)/2;
             if(popLeft<0) popLeft =0;
             if(popTop<0) popTop =0;  
             eval('newWin = window.open("","newWin","toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width='+popWidth+',height='+popHeight+',top='+popTop+',left='+popLeft+'")');
             newWin.focus();
             eval('document.'+formName+'.target="newWin"');
          }else {
            eval('document.'+formName+'.target="_self"');
          }
          eval('document.'+formName+'.submit()');
        }  
      }else {
        if(count2>0) alert('Please Select One Item');
      } 
   }else if(numberPermited == "multiple") {
      if(count > 0){
        eval('document.'+formName+'.action = "'+formAction+'"');
        if(message) conf = confirm(message);
        else conf=1;
        if(conf){ 
          if((popWidth) && (popHeight)) {
            popLeft = (screen.width -  popWidth)/2;
            popTop = (screen.height - popHeight)/2;
            if(popLeft<0) popLeft =0;
            if(popTop<0) popTop =0;  
            eval('newWin = window.open("","newWin","toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width='+popWidth+',height='+popHeight+',top='+popTop+',left='+popLeft+'")');
            newWin.focus();
            eval('document.'+formName+'.target="newWin"');
          }else {
            eval('document.'+formName+'.target="_self"');
          }
         eval('document.'+formName+'.submit()');
        } 
      }else {
        if(count2>0) alert("You Must Select at Least one Item");
      }
   }
}

/*
 * function openWindow
 * Opens a new popup window in four sizes(Small, Medium, Large, full size) at the center of screen
*/ 

function openWindow(size, URL, winName){
    if (size) {
        size = size.toLowerCase();
        if (size == 'small'){
            width = 350;
            height = 300;
        } else if (size == 'medium'){
            width = 550;
            height = 500;
        } else if (size == 'large') {
            width = 700;
            height = 600;
        } else if ( size == 'x-large' ) {
            width = 780;
            height = 500;
        } else if (size == 'xx-large') {
            width = 800;
            height = 600;
        }
    } else {
        width = screen.width-2;
        height = screen.height-2;
    }
    if (!winName){
        winName = "win" + Math.round(100000*Math.random());
    }
    if (!URL){
        URL = '';
    }

    newWin =  eval("window.open(URL,winName,'width=" + width + ",height=" + height +
                   ",resizable,scrollbars," + 
                   "left=" + ((screen.width-width)/2) + 
                   ",top=" + ((screen.height-height)/2) + "')");

    newWin.focus();

    return newWin;
}

function autoSize(passedWt, fixedPosition, extraHight) {
   if (!document.getElementById("windowAdjuster")) {
     document.write('<center><a id="windowAdjuster" ><font size="1">&nbsp;</font></a></center>');
   }  
   winAdjuster = document.getElementById("windowAdjuster");
   otherFrameHeight = 0;
   isFrame = parent.document.getElementsByTagName("frameset")[0];
   if(isFrame) {
     row = isFrame.rows;
     if(row){
       rowAr = row.split(",");
       for(i=0; i<rowAr.length; i++) {
         if( rowAr[i] != "*") {
           otherFrameHeight += Number(rowAr[i]);
         } 
       }
     }
   }   
   if (document.all) {
       Wt = 2*getLeft(winAdjuster) + 32;
       Ht = getTop(winAdjuster) + 50 + otherFrameHeight;
   } else {
       Wt = 2*getLeft(winAdjuster) + 12;
       Ht = getTop(winAdjuster) + 48 + otherFrameHeight;
   }

   if (passedWt) {

      if(!isNaN( passedWt )) {
          Wt = passedWt;
      } else {
          passedWt = passedWt.toLowerCase();
          if (passedWt == 'small'){
              Wt = 350;
          } else if (passedWt == 'medium'){
              Wt = 550;
          } else if (passedWt == 'large') {
              Wt = 700;
          }  
      }
   }
   if (extraHight && !isNaN(extraHight)) {
     Ht += extraHight;
   }
   if ( Wt>(screen.width - 40) ){
       Wt = screen.width - 40;
   }
   if ( Ht>(screen.height - 60) ){
       Ht = screen.height - 60;
   }


   parent.window.resizeTo(Wt,Ht);
   if (!fixedPosition ) {
       parent.window.moveTo( ((screen.width-Wt)/2), ((screen.height-Ht)/2) );
   }
}

function getTop(winAdjuster) {
    if (winAdjuster.offsetParent) {
        return (winAdjuster.offsetTop + getTop(winAdjuster.offsetParent));
    } else {
        return (winAdjuster.offsetTop);
    }
}

function getLeft(winAdjuster) {
    if (winAdjuster.offsetParent) {
        return (winAdjuster.offsetLeft + getLeft(winAdjuster.offsetParent));
    } else { 
        return (winAdjuster.offsetLeft);
    }
}

/*
 * This function is called from admin page for access contorl.
 * path is set on the pages.
 */
function adminAccessFunc() {
  url = "/access/admin/browse.pyt";
  url = url + "?feature=navigation&amp;showPath=1&amp;path=" + path;
  openWindow( "large/small",url );
}

/*
 * This function is called form admin navigation pages to open tree folder
 */
function openAdminTree(path) {
  if ( !path ) return;
  if ( parent.adminTree && parent.adminTree.openTreeFolder ) {
    setTimeout( "parent.adminTree.openTreeFolder(path, true)", 100 );
  }
}

/*
 * This function is called from login page to detect if Caps keys is locked
 */
var capsLockAlerted;
function checkCapsLock(event) {
  if (!capsLockAlerted) {
    var keyCode = event.which ? event.which : ( event.keyCode ? event.keyCode : ( event.charCode ? event.charCode : 0 ) );
    var shift   = (((window.Event) ? event.modifiers & Event.SHIFT_MASK : 0 ) || 
         event.shiftKey );
 
    if  (keyCode > 64 && keyCode < 91 && !shift) {
      alert("Your password is case sensitive and the Caps Lock key on your computer's keyboard has been turned on.\nPlease be sure to enter your password exactly as you created it. You may need to turn off Caps Lock for this.");
    }  
    capsLockAlerted = true;
  }
}
