// standard library

(function( $ )
{
 
 

})( jQuery )





	
///// IMPORTANT!!!!! Many functions will rely on this variable in order to be able to tell
///// if the URL should point to DEV or PRODUCTION environment
///// value options are either 'dev' or 'production'

//function setEnvironmentVar(){
	//saalert('here');
	var url = new String(window.location);
	
	if( url.indexOf("admin.php") >0 ){
		var site_root = '/admin.php';
	}else if(url.indexOf("frontend_dev.php") >0){
		var site_root = '/frontend_dev.php';
	}else{
		var site_root = '';
	}
	
	
	
//}
///// END site root definition	
	
	

/**
 * print to console object params and values
 */
var pr = function( obj )
{
  if( typeof console == 'object' )
  {
    for( i in obj )
    {
      console.log( i + ' is: ' + obj[i] );	    
    }
  }
}

/**
 * short for console log - added benefit: checks for presence of console which prevents scripts from breaking
 */
var cl = function( msg )
{
  if( typeof console == 'object' )
  {
    console.log( msg );	    
  }
}

var id = function( el )
{
  return document.getElementById( el );
}
/**
 * usually just see if the object is there. some use cases for isset
 */
var isset = function( is_obj )
{
  if( typeof is_obj == 'undefined' )
  {
    return false;	  
  }
  else
  {
    return true;
  }
}

var findMouseByClick = function( ev, el )
{
  var obj = el;
  var mousePos = { x:0, y:0 };

  if (obj.offsetParent) 
  {
    do 
    {
      mousePos.x += obj.offsetLeft;
      mousePos.y += obj.offsetTop;
    } 
    while (obj = obj.offsetParent);
  }
  
  return mousePos;
} // end find mouse by click
/**
 * if in an iframe get the iframe posistion in the parent
 */
var getParentOffset = function ( el_id, mousePos )
{
  obj = parent.document.getElementById( el_id );
  if (obj.offsetParent) 
  {
    do 
    {
      mousePos.x += obj.offsetLeft;
      mousePos.y += obj.offsetTop;
    } 
      while (obj = obj.offsetParent);
  }
  return mousePos;
}
/**
 * cross browser, straight forward mouse position
 */
var mouseCoords = function( ev )
{
  ev = ev || window.event;
  if(ev.pageX || ev.pageY)
  {
    var mousePos =  { x:ev.pageX, y:ev.pageY };
  }
  else
  {
    var mousePos = {
      x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
      y:ev.clientY + document.body.scrollTop  - document.body.clientTop
    }
  }
  
  return mousePos;
} // end find mouse coords
/**
 * mouse position while in an iframe
 */
var iframeMouseCoords = function( ev, iframe_id )
{
  var mousePos = mouseCoords( ev );
  mousePos = getParentOffset( iframe_id, mousePos );
  return mousePos;
} // end find mouse coords

/**
 * fake out an event to fire on a different element
 * Caution - this is not truly cross browser
 */
var fireEvent = function (element,event)
{
  if( typeof element == 'string' )
  {
    element = id( 'element' );	  
  }
  if (document.createEventObject)
  {
    // dispatch for IE
    var evt = document.createEventObject();
    return element.fireEvent('on'+event,evt)
  }
  else
  {
    // dispatch for firefox + others
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(event, true, true ); // event type,bubbling,cancelable
    return !element.dispatchEvent(evt);
  }
}





var fadeBG = {
  // call this to use shadow in an iframe fadeBG.fadeInIframe( url, fields, height, width, iframe_scroll )
  fadeInIframe: function ( url, fields, height, width, iframe_scroll )
  {
    if( arguments.length < 3 ) // height and width were not supplied
    {
      var height = 600;
      var width = 800;
    }
    if( arguments.length < 5 )
    {
      var iframe_scroll = 'no';
    }
    if( typeof fields == 'object' )
    {
      // if using symfony create url get fields as part of url string
      var gets = '';
      for( i in fields )
      {
        gets += '/' + escape( i ) + '/' + escape( fields[i] );	    
      }
      url = url + gets;
    }
    // fade in background
    fadeBG.fadeInBg( function ()
    {
		

      var top = winDim.getScrollTop() + 100; // add 100 px to the scroll
      var margin_left = Math.round( (width / 2 ));
      var iframe = '\
  <iframe id="asset_iframe" scrolling="' + iframe_scroll + '" style="background-color: #ffffff; border: none; height: ' + height + 'px; width: ' + width + 'px; z-index: 150; position: absolute; top: '+top+'px; left: 50%; margin-left: -' + margin_left + 'px;" src="'+url+'"></iframe>\
      ';
      jQuery( 'body' ).prepend( iframe );
      jQuery( id( 'fade_bg' )).click( function() { fadeBG.closeshadowIframe() });
    });
    
  },
    // removes iframe
  closeshadowIframe: function ( cb )
  {
	 
    jQuery( '#asset_iframe' ).remove();
    fadeBG.fadeOutBg( cb );
  },
  
  
  // use this to shadow in a slide show - must also have shadowSlideShow object
  fadeInShadowSlideShow: function ( cb )
  {
    fadeBG.fadeInBg( function ()
    {
      shadowSlideShow.init( );
      
      jQuery( id('fade_bg' )).click( function ()
      {
         shadowSlideShow.closeshadowSlideShow();
      })
     
    });
  },
  // fades out the BG
  fadeOutBg: function ( cb )
  { 
 
    jQuery( id( 'fade_bg' )).fadeOut( 500, function (  ) 
    {
      jQuery( 'fade_bg' ).remove();

      if(typeof cb == 'function')
      {
        try{ cb(); } catch(e){ 
        //alert(e) 
        }
      }
    });
  },
  // fades in the bg. Change the opacity in the fadeTo func (second argument)
  fadeInBg: function ( cb )
  {
    if( id( 'fade_bg' ))
    {
      //fade background exists so remove it
      jQuery( id( 'fade_bg' )).remove();
    }
    jQuery( 'body' ).prepend(
      '<div id="fade_bg"></div>'
    )
    
    jQuery( '#fade_bg' ).css({ 
      'opacity': 0,
      'z-index': 100, 
      'width': '100%', 
      'height': winDim.getDocHeight(),
      'position': 'absolute', 
      'left': 0, 
      'top': 0,
      'backgroundColor': 'black',
      'display': 'block'
    })
    .fadeTo( 750, .5, function()
    {
		
		
      if( typeof cb == 'function' )
      {
        try{ cb(); } catch(e){ 
		//alert(e) 
		}
			
			
	
      }
    });  
  }
} // end fadeBG

/**
 *
 * Set up: You need to create the object called: imgObject below by supplying the root directory
 * for the images and then by filling in each of
 * the images you would like in the slide show. Each imgObject image should have a width height
 * filename and caption. Filenames must be unique - only one root allowed
 *
 * in the function shadowSlideShow.showContainer, change the next back images to your preference
 *
 * Then use the jQuery dom ready function: jQuery().ready(, and attach the the fadeBG function
 * fadeBG.fadeInShadowSlideShow() to an onclick of whatever element you choose.
 *
 * adjust containers is the fuction that initiates a change from one image to the next.
 * It chagnes the container size, then on completion calls the function that checks to
 * see if the image is loaded. If the image is loaded then the callback to fade that image.
 *
 * The function that sets up the callbacks is showImg - 
 *
 */
var shadowSlideShow = {
  count: 0,
  imgArr: [],
  imgCount: 0,
  autoPlayTimeout: {},
  // recursive test to make sure the image exists
  is_loaded: function ( img, cb )
  {
    if( img.height > 0  )
    {
      shadowSlideShow.count = 0;
      cb();
    }
    else
    {
      shadowSlideShow.count++;
      
      if( shadowSlideShow.count > 5 * 1000 )
      {
        return false; // silently die if there is something wrong with loading this image
      }
      setTimeout( function () { shadowSlideShow.is_loaded( img, cb ); }, 1 );
    }
    
  },
  // image preloader, called in the init function
  loadImages: function ()
  {
    // assumes image object is "imageObject" to modularize this, just need to pass as an argument
    for( i in imgObject.images )
    {
      img = new Image();
      img.src = '/' + imgObject.root + '/' + imgObject.images[i].src;
      shadowSlideShow.imgArr.push( img );
    }
  },
  // create the basic HTML for the slide show and prepend the body tag
  showContainer: function ()
  {
    var html = '\
      <div id="shadow-content-container" style="float:left; background-color: #000000; position: absolute; z-index: 15; overflow: visible !important;">\
        <div id="image-holder" style="height: 100%; overflow: hidden;"></div>\
        <div id="caption-holder" style="height: 20px;  padding: 8px 0px 0px 0px;  width: 100%; position: absolute; bottom: -20px; background-color: #FFCC00; color: #666; ">\
            <div id="ss-close-button" style="float:left; margin-right: 10PX; cursor: pointer;  height: 20px; background-color: #FFCC00; font-family: arial, helvetica, sans-serif; font-size:12px;">&nbsp;&nbsp;<img src="../images/adwords/close_ss.gif"></div>\
		  <div id="auto-play-button" style="float:right; margin-right: 10PX; cursor: pointer;  height: 20px; background-color: #FFCC00; font-family: arial, helvetica, sans-serif; font-size:12px;"><img src="../images/adwords/play.gif"></div>\
          <div id="auto-pause-button" style="display: none; float:right; margin-right: 10PX; cursor: pointer;  height: 20px; background-color: #FFCC00; font-family: arial, helvetica, sans-serif; font-size:12px; "><img src="../images/adwords/pause.gif"></div>\
          <div id="next-button" style="float:right; margin-right: 10PX; cursor: pointer;  height: 20px; background-color: #FFCC00; font-family: arial, helvetica, sans-serif; font-size:12px;"><img src="../images/adwords/next.gif"></div>\
          <div id="prev-button" style="float:right; cursor: pointer;  height: 20px; background-color: #FFCC00; font-family: arial, helvetica, sans-serif; font-size:12px;"><img src="../images/adwords/prev.gif">&nbsp;&nbsp;</div>\
          <p id="caption" style="float: left; color: #ffffff;"><!-- / --></p>\
        </div>\
      </div>';
    jQuery('body').prepend( html );
    var top = ( winDim.getScrollTop() + ( winDim.getHeight() / 2 ));   
    jQuery( '#shadow-content-container' ).css({
      'height': '0px',
      'width': '0px',
      'top': top + 'px',
      'left': '50%'
    });
  },
  // first in chain, changes the box to match the size of the next image
  adjustContainer: function ( im_obj, cb )
  {
    if( id( 'slide-image' ))
    {
      jQuery( '#slide-image' ).fadeOut();
    }
    jQuery( id('caption') ).fadeTo( 250, .01 );
    var marg = -1 * ( im_obj.width / 2 );
    var top = winDim.getScrollTop() + ( winDim.getHeight() / 2 ) - ( im_obj.height / 2 );
    jQuery( '#shadow-content-container' ).animate( { 
      'width': im_obj.width, 
      'height': im_obj.height, 
      'margin-left': marg, 
      'top': top 
    }, 550, function () { 
      if( typeof cb == 'function' )
      {
        cb();
      }
    });
  },
  // starts / controls the chain of actions to move from one image to the next
  autoPlay: function ()
  {
    shadowSlideShow.imgCount++;
    shadowSlideShow.showImg( );
    
    id( 'auto-play-button' ).style.display = 'none';
    id( 'auto-pause-button' ).style.display = 'block';
    
    
    shadowSlideShow.autoPlayTimeout = setTimeout( function ()
    {
      shadowSlideShow.autoPlay();
    }, 3 * 1000 );
  },
  killAutoPlay: function ()
  {
    clearTimeout( shadowSlideShow.autoPlayTimeout );
    id( 'auto-play-button' ).style.display = 'block';
    id( 'auto-pause-button' ).style.display = 'none';
  },  
  showImg: function ( )
  {
    shadowSlideShow.fixImgCount();
    var img = shadowSlideShow.imgArr[ shadowSlideShow.imgCount ];
    shadowSlideShow.adjustContainer( shadowSlideShow.getBySrcFromImgObject( img.src ), function ()
    {
      shadowSlideShow.is_loaded( img, function()
      {
        var im_obj = shadowSlideShow.getBySrcFromImgObject( img.src );
        id( 'image-holder' ).innerHTML = '<img style="display: none;" id="slide-image" src="' + img.src + '" />';
        jQuery( '#slide-image' ).fadeIn( 'fast', function()
        { 
          id('caption').innerHTML = im_obj.caption ? im_obj.caption : '<!-- / -->'; // prevents sporkage in IE
          jQuery( id('caption') ).fadeTo( 250, 1 ); // don't fade out to avoid the display: none and prevent the buttons from dissappering
        });
      })
    });
  },
  // if our current count is outside of the img array set it to beginning or end
  fixImgCount: function ()
  {
    /**
     * instead of using a modulo we're just going to force it to one end or the other
     * assuming if is it less than zero then a decrement was used
     * and if greater than the length than an increment was used
     */
    if( shadowSlideShow.imgCount >= shadowSlideShow.imgArr.length )
    {
      shadowSlideShow.imgCount = 0;
    }
    if( shadowSlideShow.imgCount < 0 )
    {
      shadowSlideShow.imgCount = ( shadowSlideShow.imgArr.length - 1 );
    }  
  },
  // used to relate images on array to imgObject
  getBySrcFromImgObject: function( my_src )
  {
    var src = my_src.split( '/' ).pop(); // just get the image filename
    for( i in imgObject.images )
    {
      if( imgObject.images[ i ].src == src )
      {
        return imgObject.images[i];
      }
    }
  },
  // removes both parts
  closeshadowSlideShow: function ()
  {
    jQuery( '#shadow-content-container' ).remove();
    fadeBG.fadeOutBg();
  },
  
  /**
   * init creates container, preloads images and attaches events
   * to the newly created next and back buttons
   */
  init: function ()
  {
    shadowSlideShow.showContainer();
    shadowSlideShow.loadImages();
    
    shadowSlideShow.showImg( );
    jQuery( '#auto-play-button' ).click( function (ev)
    {
      ev.preventDefault();
      shadowSlideShow.autoPlay();
    });
    jQuery( '#ss-close-button' ).click( function (ev)
    {
      ev.preventDefault();
      shadowSlideShow.closeshadowSlideShow();
    });
    jQuery( '#auto-pause-button' ).click( function (ev)
    {
      ev.preventDefault();
      shadowSlideShow.killAutoPlay();
    });
    jQuery( '#next-button' ).click( function (ev)
    {
      ev.preventDefault();
      shadowSlideShow.killAutoPlay( );
      shadowSlideShow.imgCount++;
      shadowSlideShow.showImg( );
    });
    jQuery( '#prev-button' ).click( function (ev)
    {
      ev.preventDefault();
      shadowSlideShow.killAutoPlay( );
      shadowSlideShow.imgCount--;
      shadowSlideShow.showImg( );
    });
  }
}


/**
 *
 * example imgObject
 *
 
var imgObject = {
  'root': 'slideshow',
  'images' : {
    'img1': {
      'src': '1.jpg',
      'width': 571,
      'height': 315,
      'caption': ''
    }
}
 */
 

 
function getScrollerWidth() 
{
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild(
        document.body.lastChild);

    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}
 
 
 

var winDim = {
  // uses jQuery to return the distance the window has been scrolled down.
  getScrollTop: function ()
  {
    return jQuery(window).scrollTop();
  },
  // gets the full height of the window, including parts not seen
  getDocHeight: function ()
  {
    var db = document.body;
    var de = document.documentElement
    return Math.max(
      Math.max(db.scrollHeight, de.scrollHeight),
      Math.max(db.offsetHeight, de.offsetHeight),
      Math.max(db.clientHeight, de.clientHeight)
    );
  },
  getDocHeightIframe: function ( iframe )
  { 
    var db = iframe.contentWindow.document.body;
    var de = iframe.contentWindow.document.documentElement
    return Math.max(
      Math.max(db.scrollHeight, de.scrollHeight),
      Math.max(db.offsetHeight, de.offsetHeight),
      Math.max(db.clientHeight, de.clientHeight)
    );	  
  },
  // may or may not include the scroll bar on the right
  getWidth: function ()
  {
    var x = 0;
    if (self.innerHeight) {
      x = self.innerWidth;
    } else if (document.documentElement && document.documentElement.clientHeight) {
      x = document.documentElement.clientWidth;
    } else if (document.body) {
      x = document.body.clientWidth;
    }
    return x;
  }, // end get wid
  // gets the window frame instead of the document height
  getHeight: function ()
  {
    var y = 0;
    if (self.innerHeight) {
      y = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
      y = document.documentElement.clientHeight;
    } else if (document.body) {
      y = document.body.clientHeight;
    }
    return y;
  } // end get ht
}; // end winDim










var SetCookie = function ( name, value, expires, path, domain, secure )
{
  var today = new Date();
  today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct expires time, the current script below will set it for x number of days, to make it for hours, delete * 24, for minutes, delete * 60 * 24 */
  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 set cookie


var Get_Cookie = function ( name ) 
{
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
  {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}





var pageIMGcontext = {};
var pageIMGsrc = '';
var pageIMGcaption = '';
var pageIMGurl = '';
var editImageContainer = {};
var current_toolbar_area = {};

var setRTEImage = function ()
{ 
//alert( 'node name: ' + pageIMGcontext.nodeName + ' edit image container node name: ' + editImageContainer.nodeName );
  var html = document.createElement( 'div' );
  html.setAttribute( 'class', 'img_r' );

  // add the content to be added
  var in_html = '<img src="/files/images/' + pageIMGsrc.replace( /.+?\/files\/images\//, '' ) + '" />'; // replace just for consistency
  
  if( pageIMGcaption != '' )
  {
    in_html = in_html + '<p class="img_caption">' + pageIMGcaption + '</p>';
  }
  if( pageIMGurl != '' )
  {
    in_html = '<a href="' + pageIMGurl + '">' + in_html + '</a>';
  }
  html.innerHTML = in_html;

  fadeBG.closeshadowIframe();
  
  //If we're in the situation where we are editing an image as opposed to a new image
  if( editImageContainer.innerHTML && editImageContainer.innerHTML.match( 'src' ))
  {
    jQuery( editImageContainer ).after( html );
    jQuery( editImageContainer ).remove();
    editImageContainer = {}; // reset the currently clicked image container
    
    jQuery( '.image_behaviors', current_toolbar_area ).hide(); // remove the image edit dropdown
    
    // add the click event back to the edited image
    jQuery( 'img', html ).click( function( ev )
    { 
      ev.preventDefault();
      current_image = this;
      jQuery( '.image_behaviors', current_toolbar_area ).show();
    });
  }
  else  // new image case
  {
    var insertion_el = {};
    if( pageIMGcontext.nodeName.match( /text/i ))  // if the node is text we need the parent (ie fix)
    {
      insertion_el = pageIMGcontext.parentNode;
    }
    else
    {
      insertion_el = pageIMGcontext;
    }
    jQuery( insertion_el ).before( html ).prev().mousedown( function (ev)
    {    
      jQuery( 'img', html ).click( function( ev )
      {  
        ev.preventDefault();
        current_image = this;
        jQuery( '.image_behaviors', current_toolbar_area ).show();
      });	    
    });
  }

  setTimeout( function () 
  {
    var width = html.getElementsByTagName( 'img' )[0].offsetWidth;
    html.style.width = width;
  }, 20 ); // short delay to make sure the image has time to get in there

}


 


jQuery.fn.rte = function(css_url, media_url, editable_object, toolbar_buttons) {
	
    if(document.designMode || document.contentEditable)
    {
        if( ! toolbar_buttons ) 
        { // default to all buttons

          toolbar_buttons = {
            'inputs': true,
            'bold': true,
            'italic': true,
            'bullets': true,
            'link': true,
            'removelink': true,
            'image': true,
            'disable': true
          }
        }
        
        jQuery(this).each( function(){         
            var textarea = jQuery( this );// this is the newly created ta
            try {
              enableDesignMode(textarea, toolbar_buttons);
            } catch( e ) {
              cl( 'error: ' + e );
            }
        });
    }
    
    current_image = {};
    var toolbar_area = {};
    
    function formatText(iframe, command, option) {
        iframe.contentWindow.focus();
        try{
            iframe.contentWindow.document.execCommand(command, false, option);
        }catch(e){ cl(e); }
        iframe.contentWindow.focus();
    }
    
    function tryEnableDesignMode(iframe, doc, callback) {
        try {
            iframe.contentWindow.document.open();
            iframe.contentWindow.document.write(doc);
            iframe.contentWindow.document.close();
			
        } catch(error) {
            cl(error);
        }
        if (document.contentEditable) {
            iframe.contentWindow.document.designMode = "On";
            callback();
            return true;
        }
        else if (document.designMode != null) {
            try {
                iframe.contentWindow.document.designMode = "on";
                iframe.spellcheck = true;
                callback();
                return true;
            } catch (error) {
                cl(error);
            }
        }
        // jQuery('iframe > div').live( 'mousedown', 
        setTimeout( function(){ tryEnableDesignMode(iframe, doc, callback) }, 250);
        return false;
    }
    function imageBehaviors( behavior ) 
    { 
      switch( behavior )
      {
        case 'edit':
          editImage( current_image );
          break;
        case 'left':
          alignImage( current_image, 'l' );
          break;
        case 'right':
          alignImage( current_image, 'r' );
          break;
        case 'delete':
          deleteImage( current_image );
          break;
      }
    }
    function editImage( image )
    {
      current_toolbar_area = toolbar_area;
      editImageContainer = getDivNode( image );
      var img_filename = image.src.split( '/' ).pop();
      pageIMGcontext = editImageContainer; //getSelectionElement(iframe);  // only if we can get the selection node
      fadeBG.fadeInIframe(  site_root + '/imageupload/edit', { type: 'rte', sitemap_id: page_info.sitemap_id, position: 'rte', 'rte_filename': img_filename } );
    }
    function getDivNode( start_node )
    {
      var div_node = start_node.parentNode;
      var count = 0;
      while( ! div_node.nodeName.match( /div/i ))
      {
        div_node = div_node.parentNode;
        count++;
        if( count > 50 ) return;
      }
      return div_node;
    }
    
    function alignImage( image, way )
    {
      div_node = getDivNode( image );
      div_node.className = 'img_' + way;
    }
    
    function deleteImage( image )
    {
      if( ! confirm( 'Are you sure you would like to remove this image?' ))
      {
        return false;
      }
      div_node = getDivNode( image );
      jQuery( div_node ).remove();
    }
    
    function enableDesignMode(textarea, toolbar_buttons) {
        // need to be created this way
        var iframe = document.createElement("iframe");
        iframe.frameBorder = 1;
        
        iframe.framePadding = 3;

        iframe.height = editable_object.offset_height;
        iframe.width =  editable_object.offset_width;
          
        if(textarea.attr('class'))
            iframe.className = textarea.attr('class');
        if(textarea.attr('id'))
            iframe.id = textarea.attr('id');
        if(textarea.attr('name'))
            iframe.title = textarea.attr('name');
        textarea.after(iframe);
        var css = "";
		
        if(css_url)
            var css = "<link type='text/css' rel='stylesheet' href='"+css_url+"' />"
        var content = textarea.val();
        
        // Mozilla needs this to display caret
        if(jQuery.trim(content)=='')
            content = '<p><br /></p>';
        var doc = "<html><head>"+css+"</head><body class='frameBody'>"+content+"</body></html>";
         
        tryEnableDesignMode(iframe, doc, function() { // this is the callback function - called when the iframe node is inserted
          jQuery( "#toolbar-" + iframe.title ).remove();
          jQuery( id( 'rte-toolbar-container' )).append( toolbar( iframe ));
          setTimeout( function () // ie fix. give the js time to registar the images as real html content / dom
          {
            jQuery( 'img', iframe.contentWindow.document ).click( function( ev )
            {
              ev.preventDefault();
              current_image = this;
              jQuery( '.image_behaviors', toolbar_area ).show()
          });
          }, 20 );
          textarea.remove();          
        }); // end try enable design mode
    }
    
    function traverseChildNodes(node) 
    {
      var next;
      if (node.nodeType === 1) 
      {
        if (node = node.firstChild) 
        {
            do 
            {
                // Recursively call traverseChildNodes
                // on each child node
                next = node.nextSibling;
                traverseChildNodes(node);
            } 
            while(node = next);
        }
      } 
      else if (node.nodeType === 3) 
      {
        node.data = node.data.replace( /([a-zA-Z]) - ([a-zA-Z])/g, '$1 &mdash; $2' );
        node.data = node.data.replace( /([0-9]) - ([0-9])/g, '$1 &ndash; $2' );
        node.data = node.data.replace( /(\w)'(.?)/g, '$1&rsquo;$2' );
//        node.data = node.data.replace( /(\w)'(\w)/g, '$1&rsquo;$2' );
        node.data = node.data.replace( /( |^)'(\w)/g, ' &lsquo;$1' );
        node.data = node.data.replace( /(\w)"(.?) /g, '$1&rdquo;$2' );
        node.data = node.data.replace( / "(\w)/g, ' &ldquo;$1' ); 
      }
 
    }
    
    function disableDesignMode(iframe, submit, ev) {
      if ( ! iframe.contentWindow ) {
        return;
      }
      traverseChildNodes( iframe.contentWindow.document.getElementsByTagName("body")[0] );
      
      var content = iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
      content = content.replace( '&amp;', '&' ); //fix the html entities put on there for no reason
      if( submit == true ) 
      {  //alert( 'submit true' );
      
        var myTa = document.createElement( 'textarea' );
        myTa.setAttribute( 'name', editable_object.opts.id + '_editablearea' );
        myTa.setAttribute( 'id', editable_object.opts.id + '_editablearea' );
        
        myTa.value = content;
        
        iframe.parentNode.insertBefore( myTa, iframe);
        
       
        //iframe.remove();		
        jQuery(iframe).remove();
        
        jQuery( iframe ).remove();
       
        editable_object.save()
        
        return;
      } 
      else 
      {
	 
	  
        var textarea = jQuery('<textarea style="width: ' + editable_object.offsetWidth + 'px; height: ' + editable_object.offsetHeight + 'px;"></textarea>');
		
        textarea.val(content);
        t = textarea.get(0);
        if(iframe.className)
          t.className = iframe.className;
        if(iframe.id)
          t.id = iframe.id;
        if(iframe.title)
          t.name = iframe.title;
        jQuery(iframe).before(textarea);
      }  // end if else submit
      
      if( submit != true )
          jQuery(iframe).remove();
      return textarea;
    }
    
    function removeToolbar( title )
    {
      jQuery( '#' + editable_object.opts.id + '-editablearea > div' ).remove();
      editable_object.cancel();
    }
    
    function toolbar(iframe) {
      var holdHTML = "<div class='rte-toolbar' id='toolbar-"+iframe.title+"'>\
        <table border='0' cellspacing='0' cellpadding='0' >\
          <tr>\
            <td class='rte-buttons'>";
       if( toolbar_buttons.inputs )
       {
         holdHTML += "\<label class='style'>Style:\
                    <select>\
                        <option value=''>-Choose-</option>\
                        <option value='h3'>Title</option>\
                        <option value='p'>Paragraph</option>\
                   </select></label>\
         ";
       }
	  
       if( toolbar_buttons.bold )
         holdHTML += "     <a href='#' class='bold'><img src='"+media_url+"RTE-ico-bold.gif' alt='bold' title='Bold' ></a>";//bold
       if( toolbar_buttons.italic ) //RTE-ico-image.gif
         holdHTML += "     <a href='#' class='italic'><img src='"+media_url+"RTE-ico-itals.gif' alt='italic' title='Italics' ></a>";//italic
       if( toolbar_buttons.image ) //
         holdHTML += "     <a href='#' class='image'><img src='"+media_url+"RTE-ico-image.gif' alt='image' title='Image' ></a>";//italic
       if( toolbar_buttons.bullets ) //
         holdHTML += "     <a href='#' class='bullets'><img src='"+media_url+"RTE-ico-ul.gif' alt='bullet-list' title='Bullet List' ></a>";//italic
       if( toolbar_buttons.link )
         holdHTML += "     <a href='#' class='link'><img src='"+media_url+"RTE-ico-link.gif' alt='link' title='Links' ></a>";//add link
       if( toolbar_buttons.removelink )
         holdHTML += "     <a href='#' class='rmv_link'><img src='"+media_url+"RTE-ico-break-link.gif' alt='remove link' title='Remove Link' ></a>";//remove link
       if( toolbar_buttons.disable )
         holdHTML += "     <a href='#' class='disable'><img src='"+media_url+"RTE-ico-html.gif' alt='close rte' title='Edit HTML' ></a>";//edit html

       holdHTML += "<div class='save_cancel'><div class='sml_btn sml_save_btn'><a href='#' class='save'>Save</a></div>\
              <div class='sml_btn sml_blank_btn'><a href='#' class='cancel-edit' alt='cancel edit' >Cancel</a></div></div>\
       ";
      
       if( toolbar_buttons.image )
       {
         holdHTML += '<div class="image_behaviors"><label>Image Options:&nbsp;</label><select><option value="">-Choose-</option>\
           <option value="left">Align Left</option>\
           <option value="right">Align Right</option>\
           <option value="delete">Remove Image</option>\
           <option value="edit">Edit Image</option>\
           </select>\
           </div>';
       }
       
       holdHTML += "</td></tr></table></div>";

      var tb = jQuery(holdHTML);
      setTimeout( function() {  toolbar_area = tb; }, 50 );
      //toolbar_area = tb; cl( typeof toolbar_area );
      jQuery( '.image_behaviors select', tb ).change( function ()
      {
        jQuery( this ).focus();
        imageBehaviors( this.value, this );
      });
      jQuery( '.image_behaviors', tb ).blur( function ()
      {
        jQuery( this ).hide();
      });
      jQuery( '.image_behaviors', tb ).hide();
      
      jQuery('.style select', tb).change(function(){ 
        var index = this.selectedIndex;
        if( index!=0 ) {
          var selected = this.options[index].value;
          formatText(iframe, "formatblock", '<'+selected+'>');
        }
      });
      
      jQuery('.image', tb).click(function(ev)
      { 
        ev.preventDefault();
        current_toolbar_area = tb;
        try{
          pageIMGcontext = getSelectionElement(iframe);  // only if we can get the selection node
          fadeBG.fadeInIframe(  site_root + '/imageupload/new', { type: 'rte', sitemap_id: page_info.sitemap_id, position: 'rte' } );
        } catch(e) {
          cl( 'img error: ' + e );
        }
      });
	  
	  
	  
      jQuery('.save', tb).click( function( ev ) { ev.preventDefault(); disableDesignMode( iframe, true, ev ); } );
      jQuery('.bold', tb).click(function( ev ){ ev.preventDefault(); formatText(iframe, 'bold');return false; });
      jQuery('.italic', tb).click( function( ev ){ ev.preventDefault(); formatText(iframe, 'italic'); return false; });
      jQuery('.bullets', tb).click( function( ev ){ ev.preventDefault(); formatText(iframe, 'InsertUnorderedList'); return false; });
      jQuery('.cancel-edit', tb).click( function ( ev ) { ev.preventDefault();disableDesignMode( iframe, false ); removeToolbar( iframe.title ); return false; })      
      jQuery('.rmv_link', tb).click( function ( ev ) {
        ev.preventDefault();
        var sel_element = getSelectionElement(iframe);
        // test for content
        var sel_range = getRTESelection(iframe);
        var alert_msg = 'Sorry, you did not select any text. You must highlight the text which you would like to remove a link from.';
        if ( sel_range.toString ) { // Mozilla
          if ( !sel_range.toString().match(/\S/) ) { // match non white space
            alert( alert_msg );
            return false;
          } // end if did not match a character
        } else { // IE
          if ( !sel_range.text.match(/\S/) ) { // match non white space
            alert( alert_msg );
            return false;
          } // end if text match
        } // end else if browsersniff toString()
        // should indeed have content now:
        // getSelectionElement is not returning the correct element so this is a 'best' solution
        if ( sel_element.nodeName.toString().match( /text/i ) ) {
          sel_element = sel_element.parentNode;
        }
        if ( !sel_element.nodeName.toString().match( /a/i )){
          alert( 'Sorry, that does not seem to be a link. I can not remove it. Do not select the first or last letter of the link.' );
          return false;
        }
        var answer = confirm( 'Would you like to remove this link?' );
        if ( answer ) {
          var txt = sel_element.innerHTML;
          jQuery(sel_element).before( txt ); // insert just the text
          jQuery(sel_element).remove(); // remove the anchor
        } // end if answer
      }); // end remove link
	  
	   
      jQuery('.link', tb).click(function( ev ){
        ev.preventDefault();
        
        //
        // test for content
        //
        var sel_range = getRTESelection(iframe);
        var alert_msg = 'Sorry, you did not select any text. You must highlight the text which you would like to add a link to.';
        if ( sel_range.toString ) { // Mozilla
          if ( !sel_range.toString().match(/\S/) ) { // match non white space
            alert( alert_msg );
            return false;
          } // end if did not match a character
        } else { // IE
          if ( !sel_range.text.match(/\S/) ) { // match non white space
            alert( alert_msg );
            return false;
          } // end if text match
        } // end else if browsersniff toString()
        // end test
        
	
	/*
	** ADDED BY TY 080610
	Pop up for adding link insead of prompt. uncomment  " var p=prompt("Copy and paste the URL:");  "   below to use propmt
	*/
	
	var paste_url_markup = ' <div id="paste_url"><h1>Paste a Link</h1>\
	<div style="text-align:right;"><div class="sml_btn sml_save_btn"><a class="add">Add Link</a></div>\
	<div class="sml_btn sml_blank_btn"><a class="cancel">Cancel</a></div></div>\
	<input name="paste_url_textarea" class="paste_url_textarea" id="link_inp" type= />\
	<p><strong>NOTE:</strong> To link to a page or document within your site, use the palette to the right and right-click on the item you wish to link to, and then right-click in the field above to paste it.</p>\
	</div>';
	
	jQuery('body').prepend(paste_url_markup);
// /* 
try{
  jQuery( '#link_inp' ).bind( 'contextmenu', function ( ev )
  {
    ///*
    ev.preventDefault();
    par_win = parent;
    i = 0;
    while( par_win.parent )
    { i++;
      par_win = par_win.parent;
      if( i > 50 ) { break; }
    }
    if( par_win )
    { var msg = 'parwin'
      this.value = par_win.current_clicked_slug;
    }
    else
    { var msg = 'righthere'
      this.value = current_clicked_slug;
    }
    //alert( this.value + ' and ' + msg );
    /* */
  });
/* */
}catch(e){
	//alert( 'could not put on context menu ' + e )
	}
	  jQuery('#paste_url').show();
	  //if user cancels
	  jQuery('#paste_url .cancel').click(function(){ jQuery('.paste_url_textarea').val('');   jQuery('#paste_url').hide();   })
	  //if user adds
	  jQuery('#paste_url .add').click(function(){
		p_link = jQuery('.paste_url_textarea').attr('value');
		
		if( p_link.match(/^http/)) // check if too much info
          {
            p_link = p_link.replace( /^http:\/\/(www\.)?saferfoundation\.org/, '' ); // if local then remove it
          }
          // create link
		  formatText( iframe, 'CreateLink', p_link );
          //
          //  need to set target="_blank"
          //  remove all instances of target="_blank" to avoid doubling up in the RTE
          //  add target="_blank" to all instances that match an external link
          //  external links denoted by containing 'http' in the href.
          //
          var with_targs = iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
          var no_targs = with_targs.replace( /target="_blank"/gi, '' );
          var content = no_targs.replace( /<a href="http([:\w\/\.]+)"/gi, '<a href="http$1" target="_blank" ' ); 
		  jQuery('.paste_url_textarea').val('');
		  jQuery('#paste_url').hide();
          return false; // try to kill a # link from moving the page
		
												 
		 })
	  

      });
      jQuery('.disable', tb).click(function( ev ) {
        ev.preventDefault();
        var txt = disableDesignMode(iframe);
        var edm = jQuery('<div class="sml_btn sml_back_btn"><a href="#">Back to design mode</a></div>');
        tb.empty().append(edm);
        edm.click(function(){
          enableDesignMode(txt);
          jQuery( edm ).remove();
          return false;
        });
        return false; 
      });
      var iframeDoc = jQuery(iframe.contentWindow.document);
      var select = jQuery('select', tb)[0];
      iframeDoc.mouseup(function(){ 
        setSelectedType(getSelectionElement(iframe), select);
        return true;
      });
      iframeDoc.keyup(function(){ // resize 
        setSelectedType(getSelectionElement(iframe), select);
        var body = jQuery('body', iframeDoc);
        if( body.scrollTop() > 0 )
          iframe.height = (parseInt(iframe.height)+body.scrollTop() + 20) + 'px';
          //iframe.height = Math.min(350, parseInt(iframe.height)+body.scrollTop());
        return true;
      });
        /* */
      return tb;
    }
        
    function setSelectedType(node, select) {
        while(node.parentNode) {
            var nName = node.nodeName.toLowerCase();
            node = node.parentNode;
        }
        //select.selectedIndex=0;
        return true;
    }
    
    function getSelectionElement(iframe) {
        if (iframe.contentWindow.document.selection) {
            // IE selections
            selection = iframe.contentWindow.document.selection;
            range = selection.createRange();
            try {
                node = range.parentElement();
            }
            catch (e) {
                return false;
            }
        } else {
            // Mozilla selections
            try {
                selection = iframe.contentWindow.getSelection();
                range = selection.getRangeAt(0);
            }
            catch(e){
                return false;
            }
            node = range.commonAncestorContainer;
        }
        return node;
    }
	
  function getRTESelection(iframe) {
    if (iframe.contentWindow.document.selection) {
      // IE selections
      try{
        selection = iframe.contentWindow.document.selection;
      } catch( e ) {
        cl( 'create selection error: ' + e )
      }
      try{
        range = selection.createRange();
    
      } catch( e ) {
        cl( 'createRange error: ' + e )
      }
            
    } else {
      // Mozilla selections
      try {
        selection = iframe.contentWindow.getSelection();
        range = selection.getRangeAt(0);
      }
      catch(e){
        return false;
      }
    } // end else if
    return range;
  } // end get rte selection
  
  //return function ( iframe ) { disableDesignMode( iframe ) };
};




// /*


var inplaceEditor = function ( opts )
{
  this.original_content = '';
  this.edit_html = {};
  this.offset_height = 0;
  this.offset_width = 0;
  this.type = {};
  this.opts = opts;
  
  // id suffix of the editable item - iframe or text area
  if( ! this.opts.editable_suffix )
  {
    this.opts.editable_suffix = '_editablearea'
  }
  
  if( this.opts.element )
  {
    this.el = this.opts.element;
  }
  else
  {
    this.el = id( this.opts.id )  
  }
  
  try{
    this.init(  );
  }
  catch( e )
  {
    alert( e );
  }
}


inplaceEditor.prototype.init = function ( )
{
  
  if( ! this.opts.fields ) // default to regular HTML on a page
  {
    if( ! this.opts.id )
    {
      // throw "You must provide an ID to apply the in place editor.";
    }
    if( ! this.opts.url )
    {
      throw "You must provide a URL to which we can ajax updates.";
    }
    if( ! this.opts.position )
    {
      throw "You must provide the 'postion' of the element.";
    }
    if( ! this.opts.toolbar )
    {
      this.opts.toolbar = null;	  
    }
	
  }
  
  if( ! this.opts.css_file )
  {
    this.opts.css_file = '/css/rte.css';
  }
  
  this.original_content = this.el.innerHTML;  // this.el.cloneNode( true );
  
  this.offset_height = jQuery( this.el ).outerHeight();
  this.offset_width = jQuery( this.el ).outerWidth();
  //ADDED BY TY 082610 Set a min-width on a text area if less than 150px wide.
  if (this.offset_width < 150) { this.offset_width = 150 };
  this.setEditButton( );
  
} // end init

inplaceEditor.prototype.initEditMode = function (  )
{
  if( window.is_active )
  { // if there is already an active inplace editor
    return false;
  }

  window.is_active = true;
  // pre edit call back
  if( typeof this.opts.preOnInitilizeEdit == 'function' )
  {
    this.opts.preOnInitilizeEdit();
  }
  jQuery( '#' + this.opts.id + '_edit_btn' ).remove();

  var ta = this.createTextarea();
  ta.value = id( this.opts.id ).innerHTML;
  
  id( this.opts.id ).innerHTML = '';
  id( this.opts.id ).appendChild( ta );
  
  if( this.opts.is_link )
  {
	  try{
    this.addRightClickUrl( ta );
	  }catch( e ) { alert( 'could not add right click url: ' + e ) }
  }
  if( this.opts.rte )
  {
    var ie = this;
    jQuery( id( this.opts.id + this.opts.editable_suffix )).rte( ie.opts.css_file, '/images/buttons/', ie, ie.opts.toolbar );
  }
  else
  {
    this.createControlButtons();
  }

}

inplaceEditor.prototype.addRightClickUrl = function ( el )
{
  jQuery( el ).bind( 'contextmenu', function ( ev )
  {
    ev.preventDefault();
    this.value = parent.parent.current_clicked_slug;
  });
}

inplaceEditor.prototype.removeEdit = function ()
{
  jQuery( id( this.opts.id + '_edit_btn' )).remove();
}

inplaceEditor.prototype.setEditButton = function ( )
{
  if( ! this.opts.edit_html )
  {
    var html = document.createElement( 'div' );
    //TC 092110 IE7 DOES NOT LIKE THIS. Use style.cssText to apply style attribute html.setAttribute( 'style', 'background-color: #3399FF; position: absolute; z-index: 50; display: none;' );
    html.setAttribute( 'className', 'edit_button' );//TC 092110 IE7 needs className instead of class
	html.setAttribute( 'class', 'edit_button' );
    html.setAttribute( 'id', this.opts.id + '_edit_btn' );
    html.innerHTML = 'EDIT';
    this.opts.edit_html = html;
  }
  else
  {
    var html = document.createElement( 'div' );
   //TC 092110 IE7 DOES NOT LIKE THIS. Use style.cssText to apply style attribute html.setAttribute( 'style', 'background-color: #3399FF; position: absolute; z-index: 50; display: none;' );
    html.setAttribute( 'className', 'edit_button' );//TC 092110 IE7 needs className instead of class
	html.setAttribute( 'class', 'edit_button' );
    html.setAttribute( 'id', this.opts.id + '_edit_btn' );
    html.innerHTML = 'EDIT';
    this.opts.edit_html = html;
    
  }

  this.el.insertBefore( html, this.el.childNodes[0] );
 
  
  var ie = this;
  jQuery( this.el ).hover( function ()
  {
    id( ie.opts.id + '_edit_btn' ).style.display = 'block'; 
    id( ie.opts.id).style.backgroundColor = '#efefef'; 
  }, function() {
    id( ie.opts.id + '_edit_btn' ).style.display = 'none'; 
    id( ie.opts.id).style.backgroundColor = 'transparent'; 
  });

  jQuery( '#' + this.opts.id + '_edit_btn' ).click( function ()
  {
    ie.initEditMode();
  });
}

inplaceEditor.prototype.setRTE = function ( )
{
  // create ta first
  this.setTextarea(); // make this a ta first so that the rte works as originally concepted
  var ie = this;

  jQuery( id( this.opts.id + this.opts.editable_suffix )).rte( ie.opts.css_file, '/images/buttons/', ie, ie.opts.toolbar )
} // end set rte    this.opts.css_file


inplaceEditor.prototype.createTextarea = function ()
{
	
  var ta = document.createElement( 'textarea' )
  ta.setAttribute( 'name', this.opts.id + this.opts.editable_suffix );
 // ta.setAttribute( 'style', 'height: ' + this.offset_height + 'px; width: ' + this.offset_width + 'px;' ); 
  ta.setAttribute( 'id', this.opts.id + this.opts.editable_suffix );
  jQuery(ta).css({'width' : this.offset_width,
				 'height' : this.offset_height });

  return ta;
}

inplaceEditor.prototype.setTextarea = function ( )
{ 
  var myTa = this.createTextarea(); // use the id and the name as the same thing - might need to add something to avoid css issues
  myTa.value = id( this.opts.id ).innerHTML;
 
  id( this.opts.id ).innerHTML = '';
  
//  this.el.parentNode.insertBefore( myTa, this.el);
//  this.el.parentNode.removeChild( this.el);
  if( ! this.opts.rte )
  { // if rte - let the rte set the controls
    this.createControlButtons();
  }
  
  
}
inplaceEditor.prototype.removeControlButtons = function ()
{
  id( 'rte-toolbar-container' ).innerHTML = '';
}

inplaceEditor.prototype.createControlButtons = function ( container )
{
  if( arguments.length === 0 )
  {
    container = id( 'rte-toolbar-container' );
  }
  if( typeof container == 'string' ) // allow for container ID to be passed as well as element
  {
    container = id( container );
  }
  
  container.innerHTML = '\
  <div class="rte-toolbar">\
    <div class="sml_btn sml_save_btn"><a href="#" id="inplace-edit-save" class="save">save</a></div>\
    <div class="sml_btn sml_blank_btn"><a href="#" id="inplace-edit-cancel" class="cancel-edit" >Cancel</a></div>\
  </div>';
  //<input type="button" id="inplace-edit-save" value="Save" />\
  //<input type="button" id="inplace-edit-cancel" value="Cancel" />';
  //id( 'rte-toolbar-container' ).innerHTML = container;
  var ie = this;
  jQuery( '#inplace-edit-cancel' ).click( function ( ev )
  {
    ev.preventDefault();
    ie.cancel( );
  });
  jQuery( '#inplace-edit-save' ).click( function ( ev )
  {
    ev.preventDefault();
    ie.save( );
  });
}

inplaceEditor.prototype.cancel = function ()
{
  this.setContent();
  this.setEditButton();
  this.removeControlButtons();
  id( this.opts.id ).style.backgroundColor = 'transparent';
  if( typeof this.opts.onLeaveEdit == 'function' )
  {
    this.opts.onLeaveEdit();
  }
  window.is_active = false;
    
}

inplaceEditor.prototype.save = function ( )
{ 
  var content = this.getContent();
  var save_note = document.createElement( 'a' );
  save_note.innerHTML = '<img src="/images/icons/small_saving.gif" />';
  if( ! this.opts.rte )
  {
    id( 'inplace-edit-save' ).parentNode.insertBefore( save_note, id( 'inplace-edit-save' ));
    id( 'inplace-edit-save' ).parentNode.removeChild( id( 'inplace-edit-save' ));
  }
  
  var ie = this;
  if( this.opts.fields )
  {
    var fields = this.opts.fields;
    fields.content = content;
  }
  else
  { // standard fields
    var fields = { 'content': content, 'html_id': this.opts.html_id, 'position': this.opts.position, 'sitemap_id': this.opts.sitemap_id };
  }

  jQuery.post( this.opts.url, fields, function ( resp )
  {
    ie.setContent();
    id( ie.opts.id ).innerHTML = resp;
    ie.removeControlButtons();
    
    ie.setEditButton();
   
    if( typeof ie.opts.onLeaveEdit == 'function' )
    {
      ie.opts.onLeaveEdit( resp );
    }
    window.is_active = false;
    if( ! ie.opts.html_id || ! ie.opts.imagefragment_id )
    {
      window.location.reload();
    }
    else
    {
      //alert( 'is not new: ' + ie.opts.html_id )
    }
  });

}

inplaceEditor.prototype.setContent = function ()
{
  // if textarea
  //id( this.opts.id + this.opts.editable_suffix ).parentNode.insertBefore( this.original_content, id( this.opts.id + this.opts.editable_suffix ) );
  //id( this.opts.id + this.opts.editable_suffix ).parentNode.removeChild( id( this.opts.id + this.opts.editable_suffix ) );	
  
  id( this.opts.id ).innerHTML = this.original_content;
  
}

inplaceEditor.prototype.getContent = function ()
{
  if( id( this.opts.id + this.opts.editable_suffix ))
  {
    var content = id( this.opts.id + this.opts.editable_suffix ).value;
  }
  else
  {
    var content = id( this.opts.id + '-editablearea' ).value;
  }
  return content;
}
   /* */
   
   


var listEditor = function ( opts )
{
	
	
  this.opts = opts;
  if( this.opts.element )
  {
    this.el = this.opts.element;
    this.opts.id = this.el.getAttribute( 'sitemap_id' );
  }
  else
  {
    this.el = id( this.opts.id )  
  }
  
  try{
    this.init();
  }
  catch( e )
  {
    //alert( 'There was a problem trying to initiate the list editor: ' + e );
  }
}

listEditor.prototype = {
  init: function ()
  { 
    this.setEditButton();
  },
  setEditButton: function ( )
  { //alert( 'got called' );
    var html = document.createElement( 'div' );
    //html.setAttribute( 'style', 'background-color: #0066FF; position: absolute; z-index: 50; display: none;' );
    if( this.opts.delete_btn )
    {
      html.setAttribute( 'className', 'edit_container' );
    }
    else
    {
      html.setAttribute( 'className', 'edit_container_only_edit' );
    }

	
    var edit = document.createElement( 'div' );
     edit.setAttribute( 'className', 'edit_button' );//TC 092110 IE7 needs className instead of class
	edit.setAttribute( 'class', 'edit_button' );
    edit.setAttribute( 'id', this.opts.id + '_edit_btn' );
    edit.setAttribute( 'style', 'float: left; display: block;' );
    edit.innerHTML = 'EDIT';
    html.appendChild( edit );
	
    if( this.opts.delete_btn )
    {
      var del = document.createElement( 'div' );
      del.setAttribute( 'className', 'delete_btn' );
	  del.setAttribute( 'class', 'delete_btn' );
      del.innerHTML = '<img src="/images/buttons/lt_remove_btn.png" alt="Delete" />';
      html.appendChild( del );
    }


    if( this.opts.drag_btn )
    {
		
      if( this.opts.delete_btn ) //if there is both a delte and a drag button, add a divider
      {
        var divider = document.createElement( 'div' );
        divider.setAttribute( 'className', 'del_divider' );
		divider.setAttribute( 'class', 'del_divider' );
        divider.innerHTML='<!-- divider -->';
        html.appendChild( divider );
      }

      var drag = document.createElement( 'div' );
      drag.setAttribute( 'className', 'drag_handle' );
	   drag.setAttribute( 'class', 'drag_handle' );
      drag.setAttribute( 'id', 'item_' + this.opts.id );
      drag.innerHTML = '<img src="/images/buttons/drag_btn_lt.gif" alt="Reorder" />';
      html.appendChild( drag );
      //this.opts.edit_html = html;
    }
        
    
    
    this.el.insertBefore( html, this.el.childNodes[0] );
    
    //if( ! id( this.opts.id + '_edit_btn' )) {  }
    //alert( this.opts.id + '_edit_btn' + ' no edit btn: ' + this.el.childNodes[0].innerHTML );
    html.style.display = 'none';
    
    jQuery( this.el ).hover( function ()
    {
      html.style.display = 'block'; 
      //html.style.backgroundColor = '#0066FF'; 
    }, function() {
      html.style.display = 'none';
      html.style.backgroundColor = 'transparent'; 
    });
    var ie = this;
    jQuery( edit ).click( function ()
    {
		
		
      if( ie.opts.pop_up )
      {
        fadeBG.fadeInIframe( ie.opts.url, ie.opts.fields )
      }
      else
      {
		  //alert(ie.opts.edit_url);
        window.location.href = ie.opts.edit_url; 
      }
    });
  }
  
} // end list editor prototype




///// BEGIN SLIDESHOW ////
function slideShowObject ( slidesArr, is_fullscreen ) {

  var slideShow = this;
  if ( is_fullscreen == true ) {
    this.thumb_shifter_id = '#shadow_thumbshifter';
    this.thumb_prefix = 'shadow';
  } else {
    this.thumb_shifter_id = '#thumbshifter';
    this.thumb_prefix = '';
  }
  this.slides = slidesArr;
  this.captions= [];
	this.allowClick= true;
	this.arrayLenth= 0;
	this.shifter= {};
	this.slide0= {};
	this.slide1= {};
	this.slide2= {};
	this.holder= {};
	this.rightArrow= {};
	this.leftArraow= {};
	this.aniTime= 1250;
	this.pauseTime= 7000;
	this.sectionWidth= 700;
	this.timer= 0;
	this.links= [];
	this.count= 0;
	this.arrLen= 0;
	this.getC= function () 
	{
		return this.count;
	};
	this.setC= function (num)
	{
		this.count = num;
	};
	this.addC= function ()
	{
		this.count = ( this.count + 1 );
	};
	this.subC= function () 
	{
		this.count = ( this.count - 1 );
	};
	this.getArrPrev= function ()
	{
		return ( (this.count - 1) % this.arrLen );
	};
	this.getArrNow= function ()
	{
		return ( this.count % this.arrLen );
	};
	this.getArrNext= function ()
	{
		return ( (this.count +1) % this.arrLen );
	};
	this.slideLeft= function ()
	{
		if ( this.allowClick == true ){
			// this is only for photo slide show
			if ( id( 'play_btn') ) {
				id( 'play_btn' ).style.display = 'none';
				id( 'pause_btn' ).style.display = 'block';
			}
			//stop users from clicking before animation has finished
			slideShow.addC(); // increment one to get to the next one
			this.allowClick = false;
			
			
			this.highlightThumb("add"); //highlight the thumbnail
			
			
			clearTimeout( slideShow.timer );
			
			jQuery('#photo_caption').fadeOut('fast', function () {
				id('photo_caption').innerHTML = slideShow.captions[slideShow.getArrNow()]
			});
	
			jQuery( this.shifter ).animate({left: ( -2 * this.sectionWidth ) }, this.aniTime, 'swing', function ()
			{ 
				var next = slideShow.getArrNext(); // next is the next in line after animating
	
				jQuery( slideShow.shifter.getElementsByTagName('img')[0] ).remove();
				slideShow.shifter.style.left = ( -1 * slideShow.sectionWidth ) + 'px'; //'-668px';
				slideShow.slide0 = slideShow.slide1;
				slideShow.slide1 = slideShow.slide2;
				slideShow.slide2 = slideShow.slides[next];
				jQuery(slideShow.shifter).append( slideShow.slide2 );
				slideShow.allowClick = true;
				slideShow.play();
				jQuery( '.shifter_link2 > a' ).attr( 'href', slideShow.links[ slideShow.getArrNow() ] );
				jQuery('#photo_caption').fadeIn('fast', function () {});
				return false;
			});
		}
 		return false;
	};
	this.slideRight = function ()
	{
		if (this.allowClick==true){
			// this is only for photo slide show
			if ( id( 'play_btn') ) {
				id( 'play_btn' ).style.display = 'none';
				id( 'pause_btn' ).style.display = 'block';
			}
			//stop users from clicking before animation has finished
			slideShow.subC(); // decrement one to get to the next one
			this.allowClick=false;
			
			
			slideShow.highlightThumb("sub"); //highlight the thumbnail
			
			
			clearTimeout( slideShow.timer );
			jQuery('#photo_caption').fadeOut('fast', function () {
				id('photo_caption').innerHTML = slideShow.captions[slideShow.getArrNow()]
			});
		
			jQuery(this.shifter).animate({left: 0}, this.aniTime, 'swing', function ()
			{ 
				slideShow.allowClick = true;
				
				var prev = slideShow.getArrPrev(); // prev will be the one that was just showing
			
				// fix the shifter child elements
				jQuery( id( slideShow.shifter.id.toString() ).getElementsByTagName('img')[2] ).remove();
				slideShow.shifter.style.left = ( -1 * slideShow.sectionWidth ) + 'px';
				slideShow.slide2 = slideShow.slide1;
				slideShow.slide1 = slideShow.slide0;
				slideShow.slide0 = slideShow.slides[prev];
				var test = slideShow.shifter.id.toString();
				//cl( 'shifter slideshow: ' + id( .src );
				jQuery( id( slideShow.shifter.id.toString() ).getElementsByTagName('img')[0] ).before( slideShow.slide0 );
				slideShow.allowClick = true;
				slideShow.play();
				jQuery( '.shifter_link2 > a' ).attr( 'href', slideShow.links[ slideShow.getArrNow() ] );
				jQuery('#photo_caption').fadeIn('fast', function () {});
				return false;
			}); 
			
		} // end if allow click wrapper
		return false; // kill the # link

	};
	
	this.play = function ()
	{
		
		this.timer = setTimeout( function () { slideShow.slideLeft(); }, slideShow.pauseTime );
	},
	
	this.pause = function ()
	{
		clearTimeout( this.timer  );
		// this is only for photo slide show
		if ( id( 'play_btn') ) {
			id( 'play_btn' ).style.display = 'block';
			id( 'pause_btn' ).style.display = 'none';
			jQuery('#play_btn').click( function (ev) {
				ev.preventDefault();
				id( 'play_btn' ).style.display = 'none';
				id( 'pause_btn' ).style.display = 'block';
				slideShow.slideLeft();			
			});
		}
	};
	
	
//////////	//////////	//////////	//////////	//////////	//////////
	//added by ty to reset the slides when a thumbnail is clicked
	
	this.slideNumber = 0; //added to keep track of the actual number of the current slide
	
	this.resetSlides = function(arr_id){
		if (this.allowClick==true){
			clearTimeout( this.timer  );
			
			//slideShow.setC(parseInt(arr_id));
			this.count = 100 * this.arrLen;
			this.count =  (parseInt(arr_id) + (100 * this.arrLen));
			var curr = (parseInt(arr_id));
			var prev = parseInt(arr_id) - 1;
			var next = parseInt(arr_id) + 1;
				
			//check to see if the the previous image will be at the end of the array
			if(prev < 0){ prev = this.arrLen -1 } ;
			//check to see if the the nxt image will be at the beginning of the array
			if(next > this.arrLen -1){ next = 0 } ;
			jQuery( slideShow.shifter.getElementsByTagName('img')).remove();
			this.slide0 = this.slides[prev];
			this.slide1 = this.slides[curr];
			this.slide2 = this.slides[next];
			jQuery(this.shifter).append( this.slide0 );  
			jQuery(this.shifter).append( this.slide1 ); 
			jQuery(this.shifter).append( this.slide2 ); 
			slideShow.highlightThumb(arr_id); //highlight the thumbnail
			
			var prev = slideShow.getArrPrev(); // prev will be the one that was just showing
			var next = slideShow.getArrNext(); // prev will be the one that was just showing
			
			this.timer = setTimeout( function () { slideShow.slideLeft(); }, slideShow.pauseTime );
		}
  };

	//end resetSlides
	//begin thumb highligh
	this.highlightThumb = function(add_sub_int){
		if(jQuery(slideShow.thumb_shifter_id)){
			
		if(add_sub_int=="add"){//if advancing
			(this.slideNumber==this.arrLen -1 ? this.slideNumber=0 : this.slideNumber++);
			
			}else if(add_sub_int=="sub"){//if rewinding
			(this.slideNumber==0 ? this.slideNumber=this.arrLen -1 : this.slideNumber--);
		
			}else{//if skipping directly
			this.slideNumber=add_sub_int;
		}
	
			
			
		jQuery(slideShow.thumb_shifter_id + " img").removeClass('current');
		jQuery(slideShow.thumb_shifter_id + " #" + slideShow.thumb_prefix + this.slideNumber).addClass('current');
			
		}//end if thumbshifter element exists
	};

	//end all additions
	
	//////////	//////////	//////////	//////////	//////////	//////////
	


	this.init = function (imgSize, containerElement, leftEl, rightEl )
	{
		if( id('shifter') ) {
			//$('#shifter').append('<div class="shifter_link1"><a href="#">LEARN MORE</a></div>');
			//$('#shifter').append('<div class="shifter_link2"><a href="#">LEARN MORE</a></div>');
			//$('#shifter').append('<div class="shifter_link3"><a href="#">LEARN MORE</a></div>');
		//	$( '.shifter_link2 > a', id('shifter') ).attr( 'href', slideShow.links[0] );
		} // shifter is on the home page

		//for ( i in slideShow.slides ) {

		for ( i=0; i<slideShow.slides.length; i++ ) {

			// these arrays have the entire <img> tag - so we need to parse the value to get the image URL	

			var srcHold = slideShow.slides[i].match( /src=["|'].+?["|']/).toString().replace(/src=["|']/, '').replace(/['|"]/, '');
			var image = new Image()
			image.src = srcHold;
		} // end FOR LOOP
		this.arrLen = this.slides.length;
		this.count = 100 * this.arrLen;
		this.rightArrow =  rightEl; // id('right_arrow');
		this.leftArraow =  leftEl;  // id('left_arrow');
		this.shifter = containerElement; 
		this.slide0 = this.slides[(this.arrLen - 1)];
		this.slide1 = this.slides[0];
		this.slide2 = this.slides[1];
		
		if ( imgSize ) {
			this.sectionWidth = imgSize;
		}
		
		// example jQuery( id( 'rte-toolbar-container' )).append( toolbar( iframe ));
		
		jQuery(this.shifter).append( this.slide0 );  // '<div id="slide0">'+slides[(arrLength - 1)]+'</div>'
		jQuery(this.shifter).append( this.slide1 ); //'<div id="slide1">'+slides[0]+'</div>'
		jQuery(this.shifter).append( this.slide2 ); //'<div id="slide2">'+slides[1]+'</div>'
		
		
		jQuery(this.rightArrow).click( function (ev) {

			ev.preventDefault();
			slideShow.slideLeft();
		});
		jQuery(this.leftArraow).click( function (ev) {
			
			ev.preventDefault();
			slideShow.slideRight();
		});
		if ( id('photo_caption') ) {
			jQuery('#photo_caption').fadeOut('fast', function () {
				id('photo_caption').innerHTML = slideShow.captions[slideShow.getArrNow()];
				jQuery('#photo_caption').fadeIn('fast', function () {});
			});
		} // end if id photo caption exists
		this.play();
		
	}; // end init function
	

} // end slide show object
//// END SLIDESHOW ///

