
if (document.images)
{
  preload_image_object = new Image();
  // set image url
  image_src = new Array();
  image_src[0] = "images/indicator.gif";
  image_src[1] = "images/ajax-loader.gif";
  image_src[2] = "images/ajax-loader2.gif";

   var i = 0;
   for(i=0; i<=3; i++) 
   {
     preload_image_object.src = image_src[i];
   }
} 

//Hide status bar msg II script- by javascriptkit.com
//Visit JavaScript Kit (http://javascriptkit.com) for script
//Credit must stay intact for use    
function hidestatus()
{
  window.status='';
  return true;
}

if (document.layers)
{
  document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);
}

document.onmouseover=hidestatus;
document.onmouseout=hidestatus;


var XHTMLNS = "http://www.w3.org/1999/xhtml";
// add namespace methods to HTML DOM; this makes the script work in both
// HTML and XML contexts.
if(!document.createElementNS)
{
  document.createElementNS = function(ns,elt)
  {
    return document.createElement(elt);
  }
}

function highlight_tr(tr)
{
  tr.className = 'highlight';
}
function set_class_name(obj, class_name)
{
  obj.className = class_name;
}

function datagrid_mouseout_tr (tr, closed_class, open_class, sub_id)
{
  var sub_tr = $(sub_id);
  if (sub_tr)
  {
    var isOpen = sub_tr.style.display != 'none';
    tr.className = isOpen ? open_class : closed_class;
  }
  else
  {
    tr.className = closed_class;
  }
}

//var last_sub_id = '';
function toggle_datagrid_sub (sub_id)
{
  /*
  if (last_sub_id != '')
  {
    toggle_div(last_sub_id);
    toggle_div(last_sub_id+'_plus');
    toggle_div(last_sub_id+'_minus');
  }
  */
  last_sub_id = sub_id;
  toggle_div(sub_id);
  toggle_div(sub_id+'_plus');
  toggle_div(sub_id+'_minus');
}

function show_confirm (msg, confirm_action, cancel_action)
{
  var popup = $('msg_popup');
  var popup_title = $('msg_popup_title'); 
  var popup_msg = $('confirm_text');
  var close_btn = $('cancel_action_1');
  var cancel_btn = $('cancel_action_2');
  var ok_btn = $('confirm_action'); 
  
  popup_title.innerHTML = 'Confirmation Required';
  popup_msg.innerHTML = msg;
  
  cancel_action = cancel_action == '' ? 'hide_popup_form(\'msg_popup\');' : cancel_action;
  
  close_btn.innerHTML = '<img class="close" src="images/framework_closebox.gif" title="Close" onclick="'+cancel_action+'"/>';
  
  cancel_btn.style.display = '';
  ok_btn.style.display = '';
  cancel_btn.innerHTML = '<button onclick="'+cancel_action+'">&nbsp;&nbsp;Cancel&nbsp;&nbsp;</button>';  
  ok_btn.innerHTML = '<button onclick="'+confirm_action+'">&nbsp;&nbsp;Continue&nbsp;&nbsp;</button>';    
  
  show_popup_form('msg_popup');
}

function center_obj (obj)
{
  obj.style.display = "";
  var windowHeight = 0;
  var windowWidth = 0;
  if (navigator.appName == "Microsoft Internet Explorer")
  {
    windowHeight = document.body.clientHeight;
    windowWidth = document.body.clientWidth;
  }
  else
  {
    windowHeight = window.innerHeight;
    windowWidth = window.innerWidth;
  }
  // watch for the window having been scrolled
  var scrl_coords = get_scroll_coords (window);  
  
  var x = (windowWidth / 2) - (obj.offsetWidth / 2) + scrl_coords['left'];
  var y = (windowHeight / 2) - (obj.offsetHeight / 2) + scrl_coords['top'];
           
  obj.style.top = y + 'px';
  obj.style.left = x + 'px';
}

function is_IE ()
{
  return navigator.appName == "Microsoft Internet Explorer";
}
function getSelect(obj, label)
{
    index = document.forms["main"].elements[label].selectedIndex;
    value = document.forms["main"].elements[label].options[index].value;
    if (value != '') {
        $(label).value = value;
        goServ();
    }
}

function goServ()
{
    document.main.submit();
}

function highlight (obj, color)
{
  obj.style.background = color;  
}

function toggle_tab(tabID, tabName, divID, divName, moduleCount)
{
  //alert('tabID=' + tabID + '\ntabName=' + tabName +'\ndivID=' + divID +'\ndivName=' + divName +'\nmoduleCount=' + moduleCount)
  for (i = 1; i <= moduleCount; i++) {
    modID = i;    
    if (divName + modID == divID) {
      show_div(divID)
      set_class_active(tabID);      
    }
    else {
      hide_div(divName + modID);
      unset_class_active(tabName + modID);
    }
  }
}
function set_class_active(foo){
  $(foo).className = 'tab_active';
}

function unset_class_active(foo) {
  $(foo).className = '';
}

function openDiv(divID, divName, moduleCount)
{
  for (i = 0; i <= moduleCount; i++) {
    modID = i;    
    if (divName + modID == divID) {
      show_div(divID);      
    }
    else {
      hide_div(divName + modID);
    }
  }
}


function toggle_div(foo){
  var curr_display = $(foo).style.display;
  if (curr_display != 'none')
  {
    $(foo).style.display = "none";
  } 
  else 
  {
    $(foo).style.display = "block";
  }
}

function toggle_sub_item(parent, item){
  var curr_display = $(item).style.display;
  if (curr_display == 'block')
  {
    $(item).style.display = "none";
    $(parent).src = "images/arrow_up.gif";
  } 
  else 
  {
    $(item).style.display = "block";
    $(parent).src = "images/arrow_down.gif";
  }
}

function show_div(foo){
  var elem = $(foo);
  if (elem != null) 
  {
    elem.style.display = "";
  }
}

function hide_div(foo) {
  var elem = $(foo);
  if (elem != null) 
  {
    elem.style.display = "none";
  }
}

function toggle_div2(foo, style) {
  var elem = $(foo);
  if (elem.style.display == "none")
  {
    elem.style.display = style;
  }
  else
  {
    elem.style.display = "none";
  }
}

function time_date (stamp)
{
  if (stamp == 0 || stamp == '')
  {
    return_date = 'N/A';
  }
  else
  {
    var time_date = new Date();
    return_date = new Date (stamp * 1000);
    return_date = date_ddmmyy(return_date)
  }
  return return_date;
}

function date_date (stamp)
{
  if (stamp == 0 || stamp == '')
  {
    return_date = 'N/A';
  }
  else
  {
    var time_date = new Date();
    return_date = new Date (stamp * 1000);
    return_date = date_ddmmyy(return_date)
  }
  return return_date;
}

function date_ddmmyy(stamp)
{
    date = new Date(stamp);
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    
    return "" + (m<10?"0"+m:m) + "/" + (d<10?"0"+d:d) + "/" + (y);
}

function confirm_popup(message)
{
    return window.confirm(message);
}

function disp_alert(message)
{
    return window.alert(message)
}

function add_day(fieldName)
{    
    var date = $(fieldName).value;    
    date = Date.parse(date);
    var setDate = new Date(date+(24*60*60*1000));
    $(fieldName).value = date_ddmmyy(setDate);
}

function remove_day(fieldName)
{
    var date = $(fieldName).value;    
    date = Date.parse(date);
    var setDate = new Date(date-(24*60*60*1000));
    $(fieldName).value = date_ddmmyy(setDate);
}

function getOffset(what, offsettype) 
{
  var totaloffset = (offsettype == "left") ? what.offsetLeft : what.offsetTop;
  var parentEl = what.offsetParent;
  
  while (parentEl != null)
  {
    totaloffset=(offsettype == "left")? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
    parentEl = parentEl.offsetParent;
  }
  
  return totaloffset;
}

function autoComplete (field, select, property, forcematch)
{
  var found = false;
  for (var i = 0; i < select.options.length; i++)
  {
    if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) >= 0 && select.options[i][property].indexOf('--Select One--') != 0) {
      found=true;
      break;
    }
  }
  
  if (found) {
    select.selectedIndex = i;
  }
  else
  {
    select.selectedIndex = -1;
  }
}

function add_option(value, text, index, formName, selectName)
{
    text = remove_html_entities(text);
    var select = eval("document.forms[formName]." + selectName);
    select.options[index] = new Option(text, value);
}

function remove_options(selectName)
{
    var select = $(selectName);
    var selectLength = select.length;
    for (var i = 0; i < selectLength; i++) {
        select.remove(select[i]);
    }
}

function set_selected (select, value)
{
  for (var i = 0; i < select.options.length; i++) 
  {
    if (select.options[i].value == value)
    {
      select.options[i].selected = true;
    }
  }
}

function IsNumeric(passedVal)
{
  var ValidChars = "0123456789.";
  var IsNumber=true;
  var Char;
  
  if(passedVal == "")
  {
    return false;
  }
  for (i = 0; i < passedVal.length && IsNumber == true; i++)
  {
    Char = passedVal.charAt(i);
    if (ValidChars.indexOf(Char) == -1)
    {
      IsNumber = false;
    }
  }
  return IsNumber;
}

function IsWholeNumber(passedVal)
{
  var ValidChars = "0123456789";
  var IsNumber=true;
  var Char;
  
  if(passedVal == "")
  {
    return false;
  }
  for (i = 0; i < passedVal.length && IsNumber == true; i++)
  {
    Char = passedVal.charAt(i);
    if (ValidChars.indexOf(Char) == -1)
    {
      IsNumber = false;
    }
  }
  return IsNumber;
}


function isAlphanumeric(alphane)
{
  var numaric = alphane;
  for(var j=0; j<numaric.length; j++)
  {
    var alphaa = numaric.charAt(j);
    var hh = alphaa.charCodeAt(0);
    if((hh > 47 && hh<59) || (hh > 64 && hh<91) || (hh > 96 && hh<123) || (hh == 95))
    {
      //chars 48 - 58 = 0 - 9
      //chars 65 - 90 = A - Z
      //chars 97 - 123 = a - z
      //char 95 = _
    }
    else  
    {
      return false;
    }
  }
  return true;
}


//Rounds the given number up or down (depending if it needs to)
//And formats the price to 2 decimal spots
function format_price (price)
{
  price = Math.round(price*100)/100;
  price = price.toFixed(2);
  
  return price;
}

//Validate a price field
function validate_price(id)
{
  var price_elem      = $(id);
  var last_price_elem = $('last_' + id);
  
  var price      = price_elem.value;
  var last_price = last_price_elem.value;
  
  if (price == ''|| price <= 0 || !IsNumeric(price))
  {    
    alert("'" + price + "'" + " is an invalid price");
    price_elem.value = last_price;
  }
  else
  {//Format the price and set the last valid price
    price = format_price(price);
    price_elem.value      = price;
    last_price_elem.value = price;
  }
}


/* Description: Validate that the extention of an uploaded image is that of an image
* @params: fld - image field
* @returns: n/a
*/
function validate_image_file_extension(fld) {
  if(!/(\.gif|\.jpg|\.jpeg|\.png)$/i.test(fld.value)) {
    //alert("Invalid image file type.");
    fld.value = '';
    fld.focus();
    return false;
  }
  return true;
}

/* Description: Validate that the extention of an uploaded file is .zip
* @params: fld - upload field
* @returns: n/a
*/
function validate_zip_extension(fld) {
  if(!/(\.zip)$/i.test(fld.value)) {
    alert("File must be .zip");
    fld.value = '';
    fld.focus();
    return false;
  }
  return true;
}


function findPosX(obj)
{
  var curleft = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curleft += obj.offsetLeft;
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curtop += obj.offsetTop;
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}

function findRelPosY(obj)
{
  return findPosY(obj) - findPosY(obj.offsetParent);
}

function findH(obj)
{
  var curheight = 0;
  if (obj.offsetHeight)
  {
    curheight = obj.offsetHeight;
  }
  else if (obj.h)
    curheight += obj.h;
  return curheight;
}

function findW(obj)
{
  var curwidth = 0;
  if (obj.offsetWidth)
  {
    curwidth = obj.offsetWidth;
  }
  else if (obj.w)
    curwidth += obj.w;
  return curwidth;
}

function getAllCoords (elem)
{
  var arr = new Array();
  arr['yCoord'] = findPosY(elem);
  arr['xCoord'] = findPosX(elem);
  arr['height'] = findH(elem);
  arr['width']  = findW(elem);
  
  return arr;
}

function get_scroll_coords (win)
{
  var x,y;
  if (win.pageYOffset) // all except Explorer
  {
    x = win.pageXOffset;
    y = win.pageYOffset;
  }
  else if (win.document.documentElement && win.document.documentElement.scrollTop)
    // Explorer 6 Strict
  {
    x = win.document.documentElement.scrollLeft;
    y = win.document.documentElement.scrollTop;
  }
  else if (win.document.body) // all other Explorers
  {
    x = win.document.body.scrollLeft;
    y = win.document.body.scrollTop;
  }
  /*
  var top, left;
  if (navigator.appName == "Microsoft Internet Explorer" && document.documentElement)
  {
    top = win.document.documentElement.scrollTop;
    left = win.document.documentElement.scrollLeft;
  }  
  else
  {
    top = win.document.body.scrollTop;
    left = win.document.body.scrollLeft;
  }
  */
  var arr = new Array();
  arr['top'] = y;
  arr['left'] = x;
  
  return arr;
}

function press_enter(funcName)
{
    if (event && event.which == 13)
    {
        eval(funcName);
    }
    else
    {
        return true;
    }
}

function remove_html_entities(value)
{
    value = value.replace(/&amp;/g, "\&");
    value = value.replace(/&quot;/g, "\"");
    value = value.replace(/&lt;/g, "\<");
    value = value.replace(/&gt;/g, "\>");
    return value;
}

function set_focused_element(elementID)
{
  var el = $(elementID);
  if(el)
  {
    el.focus();
    return true;
  }
  return false;
}

// the attrs and style arguments are given using JavaScript literal objects
function create_element(name, attrs, style, text)
{
  var e = document.createElement(name);
  if (attrs)
  {
    for (key in attrs)
    {
      if (key == 'class')
      {
        e.className = attrs[key];
      }
      else if (key == 'id')
      {
        e.id = attrs[key];
      }
      else
      {
        e.setAttribute(key, attrs[key]);
      }
    }
  }
  if (style)
  {
    for (key in style)
    {
      e.style[key] = style[key];
    }
  }
  if (text)
  {
    e.appendChild(document.createTextNode(text));
  }
  return e;
}

function create_calendar(event, field, img)
{
    var position = new Array(event.clientX, event.clientY);
    Calendar.setup({
        inputField     :    field,
        button         :    img,
        singleClick    :    true,
        position       :    position
    });
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
  if(!radioObj)
    return "";
  var radioLength = radioObj.length;
  if(radioLength == undefined)
    if(radioObj.checked)
      return radioObj.value;
    else
      return "";
  for(var i = 0; i < radioLength; i++) {
    if(radioObj[i].checked) {
      return radioObj[i].value;
    }
  }
  return "";
}

/*
Manage the page links that appear under a specific site.  A cookie is set
to remember what site is selected and what pages should be shown.
*/
function show_site_pages()
{
  var site_id = $('ddl_sites').value;
  var hide_site_id = $('previous_site_shown').value;

  if (site_id != 0)
  {
    if (hide_site_id != 0)
    {
      //$(hide_site_id).style.display = 'none';
      if($('pages_'+hide_site_id))
      {
        hide('pages_'+hide_site_id,1);
      }
    }
    // located in menu.js, shows the div and sets a cookie
    show('pages_'+site_id,1);
    $('previous_site_shown').value = site_id;
    setCookie('previous_site_shown', site_id);     
  }
  else if (hide_site_id != 0)
  {
    hide('pages_'+hide_site_id,1);
    //$(hide_site_id).style.display = 'none';
  }
}

function show_index ()
{
  var site_id = $('ddl_sites').value;
  window.location = $('index_'+site_id).href; 
}

/*
Shows the a transparent layer over top of the page, rendering the site disabled
*/
function show_disabled_layer ()
{
  var d_layer = $("disable_layer");  
  var scroll_coords = get_scroll_coords (window);
  //alert('top:'+ scroll_coords['top'] + ' left:' + scroll_coords['left']);
  d_layer.style.top = document.documentElement.scrollTop +'px';
  d_layer.style.left = document.documentElement.scrollLeft +'px';
  
  d_layer.style.display = "block";
  window.onscroll=function()
  {
    var dv = $("disable_layer");
    dv.style.top=document.documentElement.scrollTop +'px';
    dv.style.left=document.documentElement.scrollLeft +'px';
    //alert('top:'+document.documentElement.scrollTop + ' Left:' + document.documentElement.scrollLeft)
  }
}

/*
Shows the disabled layer, rendering the site disabled
*/
function hide_disabled_layer ()
{
  $("disable_layer").style.display = "none";
}


// Cross-browser implementation of element.addEventListener()
// Useage:
// addListener(window, 'load', myFunction);
function addListener(element, type, expression, bubbling)
{
  bubbling = bubbling || false;
  
  if(window.addEventListener) { // Standard
    element.addEventListener(type, expression, bubbling);
    return true;
  } else if(window.attachEvent) { // IE
    element.attachEvent('on' + type, expression);
    return true;
  } else return false;
}


function popupPage(page) 
{
  windowprops = "height=600,width=800,location=no,"
  + "scrollbars=1,menubars=no,toolbars=no,resizable=yes";
  
  window.open(page, "Preview", windowprops);
}

function addslashes(str) 
{
  str=str.replace(/\'/g,'\\\'');
  str=str.replace(/\"/g,'\\"');
  //str=str.replace(/\\/g,'\\\\');
  str=str.replace(/\0/g,'\\0');
  return str;
}
function stripslashes(str) 
{
  str=str.replace(/\\'/g,'\'');
  str=str.replace(/\\"/g,'"');
  str=str.replace(/\\\\/g,'\\');
  str=str.replace(/\\0/g,'\0');
  return str;
}

function contains_quotes (str)
{
  //var pattern = /["']+/g;
  //return pattern.test(str);
  return str.indexOf('"') > -1 || str.indexOf("'") > -1;
}

// Show the loading gif inside the given field
function show_loading (fld)
{
  fld.innerHTML = '<center><img src="'+LOADING_IMG+'" /></center>';
}

/*
disables the page and shows an element
*/
function show_popup_form(id) {
  var obj = $(id);
  toggle_all_videos ('hidden');
  show_disabled_layer ();
  center_obj(obj);
  //obj.style.display = "";
  //new Effect.BlindDown($(id));  
}

function show_loading_div (msg)
{
  var obj = $('loading_div');
  show_disabled_layer ();
  obj.innerHTML = msg + '&nbsp;&nbsp;<img src="'+LOADING_IMG+'" />';
  center_obj(obj);
}

function hide_loading_div ()
{
  hide_disabled_layer ();
  $('loading_div').style.display = "none";  
}

/*
enables the page and hides an given element
*/
function hide_popup_form(id) {
  toggle_all_videos ('visible');
  hide_disabled_layer ();
  //Effect.DropOut(id);
  $(id).style.display = "none";
}

function set_tab_active(tab_id)
{  
  $(tab_id).className = 'tab_active';  
  show_div(tab_id+'_div');
}

/*********
Parse out an id from a string in this format: name_{id}
ie. menu_link_1 would return 1
**********/
function parse_id (str)
{
  return str.substring(str.lastIndexOf("_")+1, str.length);
}

function resize_body()
{
  resize_elem_height('content_tr', 40);
}

function resize_elem_height(elem, bottom_pad)
{
  var height=window.innerWidth;//Firefox
  if (document.body.clientHeight)
  {
    height=document.body.clientHeight;//IE
  }
  $(elem).style.height= parseInt(height-$(elem).offsetTop-bottom_pad)+"px";
}

function toggle_all_videos (visibility)
{
  var iframe_obj = $(SITE_EDIT_IFRAME);
  if (iframe_obj != null)
  {
    var iframe_window = iframe_obj.contentWindow;
    var videos = iframe_window.document.getElementsByClassName('embedded_video');
    for (var i in videos)
    {
      var video = videos[i];
      if (typeof video == 'object')
      {
        video.style.visibility = visibility;
      }
    }
  }
}

function refresh_page ()
{
  window.location = window.location;
}

function close_window ()
{
  win = window;
  win.opener = window;
  win.close ();
}

function ScrollToElement(theElement){

  var selectedPosX = 0;
  var selectedPosY = 0;
              
  while(theElement != null){
    selectedPosX += theElement.offsetLeft;
    selectedPosY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }
                                  
 window.scrollTo(selectedPosX,selectedPosY);

}

function live_only(page)
{
  // only able to navigate to page if not in demo mode
  // or this is the admin
  if (_m == 0 || (_m == 1 && _a == 1))
  {
    window.location = page;
  }
  else
  {
    show_live_only_msg (); 
  }
}

function show_live_only_msg ()
{  
  show_error_msg ('Demo', 'This feature is not included in this Demo version', '');
}

function show_ds_exceeded_msg ()
{  
  show_error_msg ('Disk Space Exceeded', 'Your current disk space amount has been exceeded.\nPlease delete some files to make room', '');
}

function show_error_msg (title, msg, cancel_action)
{
  var popup = $('msg_popup');
  var popup_title = $('msg_popup_title');  
  var popup_msg = $('confirm_text');
  var close_btn = $('cancel_action_1');
  var cancel_btn = $('cancel_action_2');
  var ok_btn = $('confirm_action'); 
  
  popup_title.innerHTML = title;
  popup_msg.innerHTML = msg;
  
  cancel_action = 'hide_popup_form(\'msg_popup\');'+cancel_action;
  
  close_btn.innerHTML = '<img class="close" src="images/framework_closebox.gif" title="Close" onclick="'+cancel_action+'"/>';
  cancel_btn.style.display = 'none';
  ok_btn.innerHTML = '<button onclick="'+cancel_action+'">&nbsp;&nbsp;OK&nbsp;&nbsp;</button>';    
  
  show_popup_form('msg_popup');
}

function url_encode (params)
{
  return '?p='+encode64(params);
}

// This code was written by Tyler Akins and has been placed in the
// public domain.  It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}
function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}

function comment_script(str)
{
  str = str.replace(/\s/g, " ");
  return str.replace (/(<script(.*?)>)(.*?)(<\/script>)/gi, comment_script_helper);   
}

function comment_script_helper (str, script_begin, te, script_cnt, script_end, offset, s)
{
  script_begin = script_begin.replace(/script/i, 'sr_script ');
  script_cnt = script_cnt.replace('<!--', '');
  script_cnt = script_cnt.replace('//-->', '');
  script_cnt = "<!--" + script_cnt + "-->";
  script_end = script_end.replace(/script/i, 'sr_script');
  
  return script_begin+script_cnt+script_end;
}

function uncomment_script(str)
{
  return str.replace (/(<sr_script\b[^>]*>)(.*?)(<\/sr_script>)/gi, uncomment_script_helper);  
}

function uncomment_script_helper (str, script_begin, script_cnt, script_end, offset, s)
{
  script_begin = script_begin.replace(/sr_script/i, 'script');
  script_cnt = script_cnt.replace('<!--', '');
  script_cnt = script_cnt.replace('-->', '');
  script_end = script_end.replace(/sr_script/i, 'script');
  
  return script_begin+script_cnt+script_end;
}

// HACK: <script></script> tags get removed/modified if there is no element
// previous to the script.  We add a nbsp; char to trick the document body to 
// correctly add in the script tags
function pad_html_block (html)
{
  //var pad = "<span style=\"display: none\">&nbsp;</span>";  
  var pad = "&nbsp;";
  // Only add this padding if it is not there already and there are script tags
  if (contains_script (html) && !contains_padding(html, pad))
  {
    html = pad + html;
  }
  return html;
}
function unpad_html_block (html)
{
  //var pad = "<span style=\"display: none\">&nbsp;</span>"; 
  var pad = "&nbsp;";
  // Only remove this padding if it there are script tags and its at the begining
  if (contains_script (html) && contains_padding(html, pad))
  {
    html = html.substr(pad.length, html.length);
  }
  return html;
}
function contains_padding (html, pad)
{
  html = html.toUpperCase();
  pad = pad.toUpperCase();
  var pos = html.indexOf(pad);

  return pos == 0;
}
function contains_script (html)
{
  html = html.toUpperCase();
  var sr_pos = html.indexOf("<SR_SCRIPT");
  var pos = html.indexOf("<SCRIPT");

  return pos != -1 || sr_pos != -1;
}

function handle_page_links(str)
{
  //strip_href(str);
  return str.replace (/<a[^>]*id="([^"]*)"[^>]*>/gi, handle_page_links_helper);  
}

function handle_page_links_helper (str, id, offset, s)
{
  var target = '';
  if (str.indexOf('target=') != -1)
  {
    target = 'target="_blank"';
  }
  
  if (str.indexOf('javascript:void(0);') != -1)
  {// this a source code view
    var page_name = '';
    for(var i = 0; i < _pages.length; i++)
    {
      if (id == _pages[i].page_id)
      {
        page_name = _pages[i].page_name;
        break;
      }
    }
    
    if (page_name)
    {
      return '<a id="'+id+'" href="'+sanitize_filename(page_name)+'.html" '+target+'>';  
    }
    else
    {
      return str;
    }
  }
  else
  {// View text
    return '<a id="'+id+'" href="javascript:void(0);" '+target+'>'; 
  }
}

function strip_href(html) 
{
  //return html.replace('href=', 'href="javascript:void(0);" title=');
  return html.replace (/<a[^>]*href="([^"]*)"[^>]*>/gi, strip_href_helper);
}

function strip_href_helper(str, href, offset, s)
{
  if (href.indexOf('javascript:void(1);') == -1)
  {
    str = str.replace('href=', 'href="javascript:void(1);" tmp=');
    str = str.replace('target=', 'tar=');
  }
  return str;
}

function sanitize_filename(str) 
{
  str = str.replace(/\s/gi,'_'); // replace spaces with _
  str = str.replace(/[\W]*/gi, "");  // remove special characters    
 
  return str.toLowerCase();    
}