/**
 * This script is intended to handle the page title for ajax or 
 * any page action that wishes to change the title on the client 
 * at runtime. 
 * 
 * Also, this will handle Portlet layers that need to overlay on 
 * the page.
 * 
 * This also contains a library of very useful functions, 
 * such as positioning, string trim, etc.
 * 
 */
var PAGE_CONTROL_VERSION="1.4.3";
var contextRoot="";
var width = 350;
var page_x = 0;
var page_y = 100;
var isCSS, isW3C, isIE4, isIE6, isNN4, isMAC;
var ie = (navigator.appName.indexOf('Microsoft')+1);
var POP_LAYER = "PopQueue";
var BG_LAYER = "BGDisplay";
var isSet=false;
var activeLayer=BG_LAYER;
var runLocal=false;
var PAGE_LABEL="";

function loadCheckBase(){
  if (isSet==false) {
    ie = (navigator.appName.indexOf('Microsoft')+1);
    isIE6=false;
    isCSS = (document.body && document.body.style) ? true : false;
    isW3C = (isCSS && document.getElementById) ? true : false;
    isIE4 = (isCSS && document.all) ? true : false;
    if(ie==true){
      if(navigator.appVersion.indexOf("MSIE 6")!=-1){
        isIE6=true;
      }
    }
    isNN4 = (document.layers) ? true : false;
    isMAC = (navigator.userAgent.indexOf("Mac") > -1) ? true : false;
    setPageX();
    isSet=true;
  }
}
function setPageX(){
  page_x = parseFloat((getInsideWindowWidth()/2)-(width/2));
}
var bgLayerVisible=false;
var page;
/**
 * This is the Primary Page method for pages and Portlets within Portal.
 */
function Page(){
  var page = this;
  try{
    loadCheckBase();
    log.info("PAGE_CONTROL_VERSION","\n****************************\nPage Control Version: "+PAGE_CONTROL_VERSION);
    log.info("BROWSER","Browser: "+navigator.appName);
    log.info("userAgent","userAgent: "+navigator.userAgent+"\n");
  } catch(efs){}
  this.previousSubTitle="";
  this.layers = new Array();
  this.queue = new Array();
  this.errors = new Array();
  this.setPageTitle = function(string){
    if(document.getElementById("pageTitle")){
      document.getElementById("pageTitle").innerHTML = string;
    }
  }
  this.setSubTitle = function(string){
    if(document.getElementById("pageSubTitle")){
      document.getElementById("pageSubTitle").innerHTML = string;
    }
  }
  this.setTitle = function(pageTitle, subTitle){
    if(document.getElementById("pageTitle")){
      document.getElementById("pageTitle").innerHTML = pageTitle;
    }
    if(document.getElementById("pageSubTitle")){
      document.getElementById("pageSubTitle").innerHTML = subTitle;
    }
  }
  this.setVar = function(varE, string){
    eval(varE = string);
  }
  this.displayPopLayer = function(elemId){
    //page.hidePopLayer();
    //window.scroll(0,0);
    //page_scrollWithPage(0);
    $("#footerBase").append("<div id='TB_overlay'></div>");
    try{log.info(elemId+"_vDis","displaying "+elemId);}catch(exeption){}
    try{
      loadCheckBase();
      setPageX();
      if(document.getElementById){
        activeLayer=elemId;
          var obj = document.getElementById(elemId);
          var queueObj = document.getElementById(POP_LAYER);
          if(obj) {
          try{
            if(obj.getAttribute("width")){
              width = parseInt(obj.getAttribute("width"))+60;
            }
          } catch(wE){try{log.error(wE,"Trying to set width. "+wE.message);}catch(exeption){}}
          //setOverlaySize(BG_LAYER);
          
          
          
          bgLayerVisible=true;
          obj.style.display="block";
          queueObj.innerHTML = obj.innerHTML;
          obj.innerHTML=""; // Prevents duplicate forms and JS errors
          
          show(POP_LAYER);
          
          setFlashObjectsVisibility("hidden");
          TB_overlaySize();
          var y = (TB_getPageScrollTop()[1]!=0) ? TB_getPageScrollTop()[1]:100;
          shiftTo(queueObj, parseFloat((getInsideWindowWidth()/2)-(width/2)), y);
          $(window).scroll(TB_position);
          $(window).resize(TB_position);
        }
      }
    }catch(e){try{log.error(e,e.message);}catch(exeption){}}
  }
  this.hidePopLayer = function(){
    loadCheckBase();
    //window.scroll(0,0);
    try{log.info("hideLayer"+POP_LAYER,"Hidding the current pop layer");}catch(exeption){}
    try{
      hide(POP_LAYER);
      //hide(BG_LAYER);
      $('#TB_overlay').remove();
      var obj = document.getElementById(activeLayer);
      obj.style.display="none";
      var queueObj = page.get(POP_LAYER);
      obj.innerHTML = queueObj.innerHTML;
      queueObj.innerHTML="";
      bgLayerVisible=false;
      
      setFlashObjectsVisibility("visible");
      
    } catch(e){try{log.error(e+"_hideError",e.message);}catch(exeption){}}
  }
  this.addToFavorites = function() {
    if(document.images) {
      window.external.AddFavorite(location.href, document.title);
    } else {
      alert("Press Ctrl+D to bookmark this site!");
    }
  }
  this.get = function(id){
    try{
      log.info("get"+id,"get document.getElementById("+id+")");
        return document.getElementById(id);
    } catch(eG){try{
      log.warn("ObjectIdError"+id,"Could not find: "+id+". Obj: "+eG);
    } catch(exeption){}}
  }
  this.display = function(elemId, displayE){
    try{
      if(document.getElementById){
          var obj = document.getElementById(elemId);
          if(obj) {
          obj.style.display = displayE;
          //setTimeout("ajaxDisplayFix('"+elemId+"','"+displayE+"')",100);
        } else {
          try{
            log.warn("NoStyle"+elemId,"Could not change display for id: "+elemId+" to "+ displayE);
          } catch(exeption){}
        }
      }
    } catch(e){try{log.error(e,e.message);} catch(exeption){}}
  }
  this.toggle = function(elemId){
    try{if(document.getElementById){
        var obj = document.getElementById(elemId);
        if(obj) {
          if(obj.style.display=="none"){
            display(elemId, "inline");
          } else {
            display(elemId, "none");
          }
        }
      }
    }catch(eG){try{log.error(eG,eG.message);}catch(exeption){}}
   }
 }
 function ajaxDisplayFix(elemId,display){
  try{
    var obj = document.getElementById(elemId);
    obj.style.display = display;
  } catch (e) {}
 }
 
 /**
  * id
  * title
  * pop-layer
  * display-on-load
  * Example of usage.
  * <div id="MyAccountPortlet_1.2" 
  *   pop-layer="true" 
  *   display-on-load="false" 
  *   title="My Account" 
  *   priority="1">
  *   ...
  * </div>
  * 
  * Problem: Must determine which portlet takes priority. 
  * Not first in load order! So, a portlet priority must be set.
  * 
  */
  var element;
  var firstLoadObjects = true;
function loadPageObjects(){
  if(!firstLoadObjects)
    return;
  firstLoadObjects = false;
  var firstInQueSet=true;
  try{
    var obj = document.getElementsByTagName("div");
    for(var i=0; i<obj.length; i++){
      if(obj[i].getAttribute("pop-layer")){
        //page.layers.push(obj[i]);
        try{
          if(obj[i].getAttribute("display-on-load")=="true"){
            //page.display(obj[i].id,"none");
            if(firstInQueSet){
              element = obj[i].getAttribute("id");
              try
              {
                setOmnitureVarsOnPageLayerLoad(eval("element"));
              }
              catch (e)
              {
              }                                       
              page.displayPopLayer(element);
              try{log.info(element+"_loading","Loading... "+element);}catch(exe){}
              firstInQueSet=false;
              break;
            } else {
              // Add to queue
              //page.queue.push(obj[i].getAttribute("id"));
            }
          }
        }catch(g){try{log.error(g,g.message);}catch(exeption){}}
      }else if(obj[i].getAttribute("display-on-load") == "true"){       
        element = obj[i].getAttribute("id");              
        try
              {
                setOmnitureVarsOnPageLayerLoad(eval("element"));
              }
              catch (e)
              {
              }
      }
    }
  } catch (E){try{log.error(E,E.message);}catch(exeption){}}
}

function showHere(objectHere, objectOverlayId){
  var obj = document.getElementById(objectOverlayId);
  page.display(objectOverlayId,'inline');
  log.info("overLayObjectLeft"+objectOverlayId,objectOverlayId+": Left: "+getX(objectHere));
  log.info("overLayObjectTop"+objectOverlayId,objectOverlayId+": Top: "+getY(objectHere));
  shiftTo(document.getElementById(objectOverlayId),getX(objectHere), getY(objectHere));
}
function getX(element){
  var x=0;
  for(var e= element; e; e=e.offsetParent){
    x += e.offsetLeft;
  }
  for(e=element.parentNode; e && e != document.body; e = e.parentNode){
    if(e.scrollTop){
      // Subtract for scollbar
      x -= e.scrollLeft;
    }
  }
  return x;
}
function getY(element){
  var y=0;
  for(var e= element; e; e=e.offsetParent){
    y += e.offsetTop;
  }
  for(e=element.parentNode; e && e != document.body; e = e.parentNode){
    if(e.scrollTop){
      // Subtract for scollbar
      y -= e.scrollTop;
    }
  }
  return y;
}

/**
 * Errors Management
 */
function setError(id,message){
    var valObj = page.get("validate_"+id);    
    if(valObj ){
        displayHeaderError(true);
        try{
          var valMsgObj = page.get("validate_"+id+"_message");
          valMsgObj.innerHTML = message;
          $("#validate_"+id).fadeIn();
          page.errors.push(id);
          log.info("setError:validate_"+id,
            "SetError: validate_"+id+", Set Message: "+ message);
        }catch(e){
          log.error("setError:validate_"+id,
            "SetError: validate_"+id+", Error found: "+e);
        }
    }
}
function resetErrors(){
  try{
    log.info("ResetErrors:Check_","Number Of Errors: "+page.errors.length);
    displayHeaderError(false);
    for(var er=0; er<page.errors.length; er++){
      try{
        resetError(page.errors[er]);
      } catch(eE){
          log.error("Error found: "+eE);
        }
    }
    page.errors = new Array();
  } catch(e){
      log.error("Error found: "+e);
    }
}
function resetError(id){
  var valObj = page.get("validate_"+id);    
    if(valObj){
        try{
          page.display("validate_"+id,"none");
          page.errors.slice(id);
          log.info("resetError:validate_"+id,
            "ResetError: validate_"+id);
        } catch(e){
          log.error("Error: ResetError: Error found: "+e);
        }
    }
}
function getErrorSize(){
  return page.errors.length;
}
function hasErrors(){
  if(page.errors.length==0){
    return false;
  }
  return true;
}

function gotoFirstError(){
  try{
    if(hasErrors()){
      if(document.getElementById("validate_topHeaderError")){
        location.hash = "topHeaderError";
      } else {
        location.hash = page.errors[0];
      }
    }
  } catch (e){
    window.scroll(0,0);
    log.error("gotoFirstError_"+e,
      "Error: gotoFirstError ["+ page.errors[0] +"]: "+e);
  }
}

function gotoError(id){
  try{
    if(hasErrors()){
      location.hash = page.errors[findError(id)];
    }
  } catch (e){
    window.scroll(0,0);
    log.error("gotoFirstError_"+e,
      "Error: gotoFirstError ["+ id +"]: "+e);
  }
  
}
function findError(id){
  for(var er=0; er<page.errors.length; er++){
    if(page.errors[er]==id){
      return er;
    }
  }
  return null;
}
function displayHeaderError(display){
  try{
    if(display==true){
      page.display("validate_topHeaderError","block");
    } else {
      page.display("validate_topHeaderError","none");
    }
  } catch (e){
    log.error("displayHeaderError_"+e,
      "Error: Display Top Error Message [validate_topHeaderError]: \n > "+e);
  }
}
var niceScrollId="";
var niceScrollPos=0;
 function doScroll() {
    if(bgLayerVisible){
      //window.scroll(0,0);
      page_scrollWithPage(getPageScrollTop());
      
    }
  }
function niceScroll(){
  var active;
  niceScrollPos = parseInt(niceScrollPos/100);
  if(niceScrollPos==0){
    window.clearInterval(niceScrollId);
    setTimeout(resetId,1200);
    window.scroll(0,0);
  } else {
    window.scroll(0,niceScrollPos);
  }
}



function resetId(){
  niceScrollId='';
}
 function lockParentElements(obj, lock){
    var formElems = obj.getElementsByTagName("input");
    for(var i=0; i<formElems.length; i++){
      try{
        formElems[i].disabled=lock;
      }catch(e){errorLog+=e.message+"\n";}
    }
 }
 /**
  * display("elementId","none"); hides node
  * display("elementId","inline"); displays node
  */

/**
 * Seek nested NN4 layer from string name
 */
function seekLayer(doc, name) {
    var theObj;
    for (var i = 0; i < doc.layers.length; i++) {
        if (doc.layers[i].name == name) {
            theObj = doc.layers[i];
            break;
        }
        // dive into nested layers if necessary
        if (doc.layers[i].document.layers.length > 0) {
            theObj = seekLayer(document.layers[i].document, name);
        }
    }
    return theObj;
}
/**
 * Convert object name string or object reference into a 
 * valid element object reference
 */
function getRawObject(obj) {
    var theObj;
    if (typeof obj == "string") {
        if (isW3C) {
            theObj = document.getElementById(obj);
        } else if (isIE4) {
            theObj = document.all(obj);
        } else if (isNN4) {
            theObj = seekLayer(document, obj);
        }
    } else {
        // pass through object reference
        theObj = obj;
    }
    return theObj;
}
/**
 * Convert object name string or object reference into a 
 * valid style (or NN4 layer) reference
 */
function getObject(obj) {
    var theObj = getRawObject(obj);
    if (theObj && isCSS) {
        theObj = theObj.style;
    }
    return theObj;
}
/**
 * Position an object at a specific pixel coordinate
 * shift([Object] or id, x pixel, y pixel);
 */
function shiftTo(obj, x, y) {
    var theObj = getObject(obj);
    if (theObj) {
        if (isCSS) {
            var units = (typeof theObj.left == "string") ? "px" : 0 
            theObj.left = x + units;
            theObj.top = y + units;
        } else if (isNN4) {
            theObj.moveTo(x,y)
        }
    }
}
/**
 * Move an object by x and/or y pixels
 */
function shiftBy(obj, deltaX, deltaY) {
    var theObj = getObject(obj);
    if (theObj) {
        if (isCSS) {
            // equalize incorrect numeric value type
            var units = (typeof theObj.left == "string") ? "px" : 0 
            theObj.left = getObjectLeft(obj) + deltaX + units;
            theObj.top = getObjectTop(obj) + deltaY + units;
        } else if (isNN4) {
            theObj.moveBy(deltaX, deltaY);
        }
    }
}
/**
 * Set the z-order of an object
 */
function setZIndex(obj, zOrder) {
    var theObj = getObject(obj);
    if (theObj) {
        theObj.zIndex = zOrder;
    }
}
/**
 * Set the background color of an object
 */
function setBGColor(obj, color) {
    var theObj = getObject(obj);
    if (theObj) {
        if (isNN4) {
            theObj.bgColor = color;
        } else if (isCSS) {
            theObj.backgroundColor = color;
        }
    }
}
/**
 * Set the visibility of an object to visible
 */
function show(obj) {
    var theObj = getObject(obj);
    if (theObj) {
        try{$("#"+theObj.id).fadeIn();}catch(e){alert(e)}
        theObj.visibility = "visible";
    }
}
/**
 * Set the visibility of an object to hidden
 */
function hide(obj) {
    var theObj = getObject(obj);
    if (theObj) {
        try{$("#"+theObj.id).fadeOut();}catch(e){}
        theObj.visibility = "hidden";
    }
}
/**
 * Retrieve the x coordinate of a positionable object
 */
function getObjectLeft(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (document.defaultView) {
        var style = document.defaultView;
        var cssDecl = style.getComputedStyle(elem, "");
        result = cssDecl.getPropertyValue("left");
    } else if (elem.currentStyle) {
        result = elem.currentStyle.left;
    } else if (elem.style) {
        result = elem.style.left;
    } else if (isNN4) {
        result = elem.left;
    }
    return parseInt(result);
}
/**
 * Retrieve the y coordinate of a positionable object
 */
function getObjectTop(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (document.defaultView) {
        var style = document.defaultView;
        var cssDecl = style.getComputedStyle(elem, "");
        result = cssDecl.getPropertyValue("top");
    } else if (elem.currentStyle) {
        result = elem.currentStyle.top;
    } else if (elem.style) {
        result = elem.style.top;
    } else if (isNN4) {
        result = elem.top;
    }
    return parseInt(result);
}
/**
 * Retrieve the rendered width of an element
 */
function getObjectWidth(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetWidth) {
        if (elem.scrollWidth && (elem.offsetWidth != elem.scrollWidth)) {
            result = elem.scrollWidth;
        } else {
            result = elem.offsetWidth;
        }
    } else if (elem.clip && elem.clip.width) {
        result = elem.clip.width;
    } else if (elem.style && elem.style.pixelWidth) {
        result = elem.style.pixelWidth;
    }
    return parseInt(result);
}
/** 
 * Retrieve the rendered height of an element
 */
function getObjectHeight(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetHeight) {
        result = elem.offsetHeight;
    } else if (elem.clip && elem.clip.height) {
        result = elem.clip.height;
    } else if (elem.style && elem.style.pixelHeight) {
        result = elem.style.pixelHeight;
    }
    return parseInt(result);
}
/** 
 * Return the available content width space in browser window
 */
function getInsideWindowWidth() {
    if (window.innerWidth) {
        return window.innerWidth;
    } else if (document.body && document.body.clientWidth) {
        return document.body.clientWidth;
    }
}
/**
 * Return the available content height space in browser window
 */
function getInsideWindowHeight() {
    if (window.innerHeight) {
        return window.innerHeight;
    } else if (document.body && document.body.clientHeight) {
        return document.body.clientHeight;
    }
}
function getLayerCss(id){
  var lyr, lyrcss;
  lyr = (document.getElementById)? document.getElementById(id): 
    (document.all)? document.all[id]: (document.layers)? getLyrRef(id,document): null;
  if (lyr) lyrcss = (lyr.style)? lyr.style: lyr;
  return lyrcss;
}
function trim(strng){
  try{
    var start=false; var end=false; var i=0; var e=0;
    for(i=0; i<strng.length; i++){
      if(!start){
        if(strng.substring(i,i+1)==" "){
          break;
        } else { start=true; }
      }
    }
    for(e=strng.length; e<i; e--){
      if(!end){
        if(strng.substring(e-1,e)==" "){
          break;
        } else { end=true; }
      }
    }
    return strng.substring(i,e);
  } catch(eX){}
  return strng;
}


// ADDED 7/8/2008 - axambro
function LTrim(str) {
 for (var i=0; ((str.charAt(i)<=" ")&&(str.charAt(i)!="")); i++);
 return str.substring(i,str.length);
}
function RTrim(str) {
 for (var i=str.length-1; ((str.charAt(i)<=" ")&&(str.charAt(i)!="")); i--);
 return str.substring(0,i+1);
}

function Trim(str) {
 return LTrim(RTrim(str));
}


function wrapClass(innerHTML, title, classE, display){
  return innerHTML;
}
function buildClassWrapper(obj){
  if(!obj.getAttribute("wrapped")){
    var title = (obj.getAttribute("title")!=null)?obj.getAttribute("title"):"";
    obj.innerHTML=wrapClass(obj.innerHTML, title, "opacity2", false);
    obj.setAttribute("wrapped","true");
  }
  return obj.innerHTML; // not a copy
}
function bgOverlay(){
  setOverlaySize(BG_LAYER)
}
function setOverlaySize(div){
  
  // This just sets the layer width and height
  var yScroll=0;
  var xScroll=0;
  try{
    if(document.documentElement && document.documentElement.clientHeight){
      document.getElementById(div).style.height=document.documentElement.clientHeight;
      document.getElementById(div).style.width=document.documentElement.clientWidth;
    } else {
      try{
        yScroll = window.innerHeight + window.scrollMaxY;
        xScroll = window.innerWidth + window.scrollMaxX;
        var deff = document.documentElement;
        var wff = (deff&&deff.clientWidth) || document.body.clientWidth || window.innerWidth || self.innerWidth;
        var hff = (deff&&deff.clientHeight) || document.body.clientHeight || window.innerHeight || self.innerHeight;
        xScroll -= (window.innerWidth - wff);
        yScroll -= (window.innerHeight - hff);
        
      } catch (e){}
      try{
        yScroll = document.body.scrollHeight;
        xScroll = document.body.scrollWidth;
      } catch (e){}
      try{
        yScroll = document.body.offsetHeight;
        xScroll = document.body.offsetWidth;
      } catch (e){}
      document.getElementById(div).style.height=yScroll;
      document.getElementById(div).style.width=xScroll;
      $(div).css({"height": yScroll, "width": xScroll});
    }
  } catch (ed){}
}
function getPageScrollTop(){
  var yScrolltop;
  if (self.pageYOffset || self.pageXOffset) {
    yScrolltop = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){  // Explorer 6 Strict
    yScrolltop = document.documentElement.scrollTop;
  } else if (document.body) {// all other Explorers
    yScrolltop = document.body.scrollTop;
  }
  return yScrolltop;
}
function page_scrollWithPage(y){
  var pop = page.get(POP_LAYER);
  var bg = page.get(BG_LAYER);
  shiftTo(pop, getObjectLeft(pop), y+100);
  shiftTo(bg, getObjectLeft(bg), y);
}


var page_select_list = new Array();
function page_hideSelectLists(){
  log.info("page_hideSelectLists()","page_hideSelectLists() called");
  if(isIE6==true){
    page_select_list = new Array();
    var fln = document.forms.length;
    for(f=0; f<fln; f++){
        var form = document.forms[f];
        var eln = form.elements.length;
      log.info("page_hideSelectLists() # of elements in forms to search"," > Elements in forms to search: "+ eln);
        for(e=0; e<eln; e++){
          var element = form.elements[e];
          try{          
            if(element.type=="select-one" || element.type=="select-multiple"){
            //alert("element.type===="+element.type);
            //alert("page_hideSelectLists() Item found"," > Item Found: "+ (element.name || element.id));
            log.info("page_hideSelectLists() Item found"," > Item Found: "+ (element.name || element.id));
              page_select_list.push(element);
              element.style.display="none";
            }
          } catch(ex){log.warn("page_hideSelectLists()","page_hideSelectLists() - Could not hide select list");}
        }
    }
  }
}

function page_showSelectLists(){
  log.info("page_showSelectLists()","page_showSelectLists() called");
  try{
    var len = page_select_list.length;
    log.info("page_showSelectLists() # of lists"," > Number of lists on page: "+len);
    for(var i=0; i<len; i++){
      var element = page_select_list[i];
      log.info("page_showSelectLists() Element name"," > > : "+(element.name || element.id));
      element.style.display="inline";
    }
  } catch(ex){log.error("page_showSelectLists()E","page_showSelectLists()\n > Warning: \n > "+ex);}
}

var page_flash_objects = new Array();

function setFlashObjectsVisibility(arg){
  log.info("setFlashObjectsVisibility"," > setFlashObjectsVisibility("+arg+") item found");
  var objType =(ie) ? "object":"embed";
  var objects = document.getElementsByTagName(objType);
  var len = objects.length;
  for(var i=0; i<len; i++){
    try{
      log.info("setFlashObjectsVisibility"," > setFlashObjectsVisibility("+arg+") item found");
      objects[i].style.visibility=arg;
    } catch(e){log.error("setFlashObjectsVisibility()","setFlashObjectsVisibility()\n > Error: \n > "+e);}
  }
}
function addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be attached");
  }
}
var page;
/*
$(document).ready(
  function(){
    page = new Page();
    loadPageObjects();
  }
);
*/


$(window).load(
  function(){$(window).scroll(doScroll);}
);
