$.fn.baseedit = function(data) {
      
      $.fn.baseedit.settings = {
         pageid: '0',
         allowbr: 1,
         maxwidth: 300,
         editbtn: '#admin_editbtn',
         savebtn: '#admin_savebtn',
         cancelbtn: '#admin_cancel',
         barselector: '#admin_menu',
         addpagebtn: '#admin_create',
         addimage: '#add_image',
         maxheight: 300,
         showicons: {},
         embed: {},
         nobar: 0
      };
      var options = $.extend($.fn.baseedit.settings, data);
      var obj=$(this);
      var openmenu=0;
      var embed = new Array();
      var contenteditable=true;
      
            //obj.find(".embed").each(function(){
            //      if ($(this).html()){
            //            
            //          var randomnumber=Math.floor(Math.random()*100001);
            //          //embed[randomnumber]=$(this).html();
            //          options.embed[randomnumber]=$(this).html();
            //          $(this).attr('id','emb'+randomnumber);
            //          alert($(this).html());
            //      } else {
            //          $(this).remove(); 
            //      }
            //});            
      //for(key in embed){  }
      
      obj.find("h2").each(function(){
            if ($(this).hasClass("header2")){} else {
                $(this).addClass("header2");
            }
      });
     
      obj.keydown(function(e) {
           $(".BE_image_overlay").hide();
           var shk= e.shiftKey;
           var kc=e.keyCode;           
           var pn= findpn($(this));                                 
           if ((kc==0)&&(e.charCode>0)) kc=e.charCode;   
           var l=$(this).text().length;
           var max= $(this).attr("maxchar");
           var checkforlength=1;
           if (($(this).attr("inputclass")=="line") && (kc==13))  return false;
           if ($(this).attr("inputclass")=="float"){               
               var doit=0;
               if (((kc>=96)&&(kc<=105))||((kc>=48)&&(kc<=57))||(kc==46)||(kc==8)||((kc>=37)&&(kc<=40))||(kc==35)||(kc==36))   doit=1;             
               if (doit==0) return false;               
               if (doit==1) return true;
               checkforlength=0;
           }           
           
           if ($(this).attr("inputclass")=="int"){            
               var doit=0;
               if (((kc>=96)&&(kc<=105))||((kc>=48)&&(kc<=57))||(kc==46)||(kc==8)||((kc>=37)&&(kc<=40))||(kc==35)||(kc==36))   doit=1;             
               if (doit==0) return false;               
               if (doit==1) return true;
               checkforlength=0;
           }
                      
           if ((checkforlength==1)&&(kc>=32)&&(l>max)) { return false; }           
           
           if (options.allowbr==0 && kc == 13) return false;
           
           if (kc == 13) {            
              var t=rangy.getSelection().focusOffset;              
              var u=rangy.getSelection().anchorNode
              while (!u.tagName){ u=u.parentNode; }
              ut=u;              
              contenteditable=u.getAttribute('contenteditable');              
              u=u.tagName;              
              if ((u!='LI') && (contenteditable!="false")) {                  
                  if (document.all) {
                      range = document.selection.createRange();              
			          if (range.htmlText.length == 0){
				          range.pasteHTML('<br>'+range.htmlText);				          
				         range.select();
			          }
                  } else {                        
                      if (window.getSelection) {                                                        
                        var t=$(ut).closest("h2");                        
                        if (t.size()==1){
                           return true;      
                        } else{                              
                              var selection = window.getSelection(),
                              range = selection.getRangeAt(0),
                              br = document.createElement("br");
                              range.deleteContents();
                              range.insertNode(br);
                              range.setStartAfter(br);
                              range.setEndAfter(br);
                              range.collapse(false);
                              selection.removeAllRanges();
                              selection.addRange(range);
                        }                        
                        return false;                        
                      }                          
                  }                       
                 return false;
               }
           }
           return true;      
        });
        
      $(options.cancelbtn).unbind('click').click(function() {            
        in_editmode=0;
        obj.find("img").fadeTo(300,1);        
        $(".BE_image_overlay").remove();
        $("#themechooser").show();         
        var loc=window.location.href;        
        loc=loc.replace(/\#/g,'');
        loc=loc.replace(/true/g,'');                
        window.location.href=loc;
      });
      
      $("#themechooser").change(function(){         
        var theme = $(this).find("option:selected");        
        jQuery.get('/manage/savetheme/'+theme.val(), function(){ window.location.reload(); return false;  });
      });
      
      $(options.editbtn).unbind('click').click(function() {         
         openmenu=1;
         in_editmode=1;       
         enable_editmode(obj);
     
         $("#themechooser").hide();         
         var actions='<a style="cursor:hand; cursor:pointer" onmousedown="deleteimg();" ><img src="/static/images/admin/admin_delete.png" alt="Delete Image" title="Delete Image"></a>';
             actions+='<a onmousedown="changeimage_be(\'/mediagallery/be_imagechange\');return false;" class="BE_change_content_image"><img src="/static/images/admin/admin_img_change.png" alt="Change Image" title="Change Image"></a>';
             actions+='<a style="cursor:hand; cursor:pointer" onmousedown="addleft();"><img src="/static/images/admin/admin_img_left.png" alt="Align Image Left" title="Align Image Left"></a>';
             actions+='<a style="cursor:hand; cursor:pointer" onmousedown="center();"><img src="/static/images/admin/admin_img_center.png" alt="Align Image Center" title="Align Image Center"></a>';
             actions+='<a style="cursor:hand; cursor:pointer" onmousedown="addright();"><img src="/static/images/admin/admin_img_right.png" alt="Align Image Right" title="Align Image Right"></a>';
             actions+='<a style="cursor:hand; cursor:pointer" onmousedown="dolink(\'picture\');" id="BE_piclink"><img src="/static/images/admin/admin_img_link.png" alt="Add Link" title="Add Link"></a>';
             actions+='<a style="cursor:hand; cursor:pointer" onmousedown="dopicunlink();" id="BE_picunlink"><img src="/static/images/admin/admin_img_unlink.png" alt="Remove Link" title="Remove Link"></a>';             
         $("#BE_current_image").removeAttr("id");
         
         if ($(".BE_embed_overlay").length==0) {
            var actionse='<a style="cursor:hand; cursor:pointer" onmousedown="deleteembed();" ><img src="/static/images/admin/admin_delete.png" alt="Delete Embed" title="Delete Embed"></a>';
            //actionse+='<a style="cursor:hand; cursor:pointer" onmousedown="embed_alignleft();" ><img src="/static/images/admin/admin_img_left.png" alt="Align Left" title="Align Left"></a>';
            //actionse+='<a style="cursor:hand; cursor:pointer" onmousedown="embed_center();" ><img src="/static/images/admin/admin_img_center.png" alt="Align Left" title="Align Center"></a>';
            //actionse+='<a style="cursor:hand; cursor:pointer" onmousedown="embed_alignright();" ><img src="/static/images/admin/admin_img_right.png" alt="Align right" title="Align right"></a>';
            //$("body").append('<div class="BE_embed_overlay">'+actionse+'</div>');
            $("body").append('<div style="margin-left: -15000px;" class="BE_embed_overlay">'+actionse+'</div>');
         }         
         
         if ($(".BE_image_overlay").length==0) {
            $("body").append('<div class="BE_image_overlay">'+actions+'</div>');
            $(".BE_image_overlay").mousedown(function(){ $("#BE_current_image").parentsUntil('.editable').parent().addClass("edited"); });
            $(".BE_image_overlay").resizable({ aspectRatio: true });
            $(".BE_image_overlay").resize(function(){
                findpn($("#BE_current_image"));                        
                var w=$(".BE_image_overlay").width();
                var h=$(".BE_image_overlay").height();
                $("#BE_current_image").css({width: w+'px', height: h+'px'});
                var p=$("#BE_current_image").offset();
                if (p != null){                
                    $(".BE_image_overlay").offset({top: p.top, left: p.left});                   
                }                
            });         
         }
         
         $(".BE_image_overlay").css({top: '-100px', left: '-5000px'});
         
         var inimageoverlay=0;
         obj.find("img").fadeTo(300,0.7);
         imagehover();
         embedhover();
          
         $(".BE_image_overlay").mouseover(function(){            
            var image= $("#BE_current_image").parent().attr("href");
            if (image) {               
               $("#BE_piclink").hide();
               $("#BE_picunlink").show();
            } else {               
               $("#BE_piclink").show();
               $("#BE_picunlink").hide();
            }      
         });
         $(".BE_image_overlay").mouseout(function(){ $(".BE_image_overlay").css({left: '-5000px'}); });
         
         obj.addClass('marked');
         $("#changeform").show();
         $(options.editbtn).hide();
         $(options.savebtn).show();
         $(options.addimage).show();
         $(options.cancelbtn).show();
         $(options.addpagebtn).hide();
         mode='edit';         
         $(".imageedit").each(function(){
            var self=$(this);
            set_image_placeholder_functions(self);
         });         
      });
      
      var image_mode='disabled';       
      $("#BE_image_placeholder_toggle").toggle(function(){         
         $(".imageedit").show();
         $(this).html("Hide Image Positions");
      }, function(){         
         $(this).html("Show Image Positions");
         $(".imageedit").each(function(){
            var url=$(this).attr("src");
            $(this).fadeTo(100,1);
            if (url == '/static/media/placeholder.jpg') $(this).hide();            
         });
         $("#BE_image_overlay").remove();
      });
                             
      this.each(function() {
         $(this).unbind('select').select(function() {            
            if (openmenu==1) {               
               open(obj,$(this));
               return false;
            } else return true;            
         });
                  
         //$(window).scroll(function() { $("#admin_wrapper").offset({top: $(window).scrollTop() });  });
         
         $(this).unbind('mousedown').mousedown(function() { open(obj,$(this)); });
            
         
         function exitimagemode(){
             $(".imageedit").each(function(){
                 var url=$(this).attr("src");             
                 if ($("#BE_image_overlay").length!=0){
                     var self=$(this);
                     $("#BE_image_overlay").fadeOut("fast", function(){                  
                        self.fadeTo(300,1);
                        $("#BE_image_overlay").remove();                        
                        if (url=='/static/media/placeholder.jpg') {                           
                           self.hide();
                        }
                     });
                 }      
             });
             obj.find("img").css({opacity: 1});
         }
         
         function onsave(){
            $(".admin_notice").show();
            $("#themechooser").show();
           $('#caret').remove;
            in_editmode=0;         
           $(".BE_image_overlay").remove();
           $("#changeform").hide();
           $("#media_icon").hide();
           
           $(".BE_current_embed").removeClass("BE_current_embed");
           
           //for(key in options.embed){   
           //    var item=$("#emb"+key);               
           //    item.html(embed[key]);               
           //    item.removeAttr('id');
           //}
           
            exitimagemode();
            disable_editmode(obj);
            $(options.barselector).fadeOut(1, function(){            
               obj.removeClass('marked');         
               $(options.savebtn).hide();
               $(options.cancelbtn).hide();
               $(options.addpagebtn).show();             
               $(options.editbtn).show();
               mode='view';
               openmenu=0;
            });
            
            var items = $(".edited");
             var data_arr = {};
             var data_arr2 = {};
             var dataarr= new Array();
      
             $(".edited").each(function(){
                
                var call='';
                call=$(this).attr("call");                
                var html = $(this).html();                
                html=cleanup(html);                 
                var id = $(this).attr("id");                
                
                 if (id.match(/^BE_/)){
                   id=id.replace(/^BE_/,'');
                   id=id.replace(/_[0-9]+$/,'');                     
                 }                
                if (call == undefined) {
                     if (id) eval('$.extend(data_arr, {'+ id+': html});');
                }
                else {                  
                   if(typeof(id)!='undefined'){                           
                      txt='';
                      if(!dataarr[call]) {                              
                         dataarr[call]='';
                      }
                      
                      dataarr[call]+='"'+id+'":"'+html+'",';                        
                   }                 
                }
             });
             if (dataarr){                  
               var storarr= new Array();
               var counter=0;
               for (i in dataarr){
                 storarr[counter]=i;
                 counter++;    
               }               
               max=counter;               
               docalls(dataarr, storarr, 0, max);
             }
             
             if (data_arr) jQuery.post( '/manage/staticpages/save', { page: options.pageid,data: data_arr }, function(msg){});             
         }
         
         $(options.savebtn).unbind('click').click(function() {            
            onsave();
            return false;
         });
                  
         function docalls(data, urldata, counter, max){                    
            if (counter<=max){               
               if (urldata[counter]) {                                          
                  jQuery.post( urldata[counter], { data: data[urldata[counter]] }, function(msg){                     
                     docalls(data, urldata, (counter+1), max);               
                  });
               }
            }          
         }
       
         function open(obj,self){
            findpn(obj);
            var baroptions = self.attr("toolbar");
            var icons = new Array('h2','h3','h1','bold','media','list','underline','italic','link','ar','al','ac');
            var doit=0;
            if (baroptions){               
               if (baroptions !='none') icons=baroptions.split(',');
               if (baroptions =='none') icons='';
            }
            
            self.addClass("edited");
            $(options.barselector).hide();
            var text='<a id="BE_close" style="display:none;">close editor</a>';                                                                    
            text+='<div id="BE_editor" style="display:none;">';
            text+='<div id="savechanges">save changes</div></div>';
            
            var tbefore=text;
            
            if ('h3' in oc(icons)) text+='<button class="BE_icons" id="BE_h3" title="Heading">&nbsp</button>';            
            if ('bold' in oc(icons)) text+='<button class="BE_icons" id="BE_bold" title="Bold">&nbsp</button>';
            if ('underline' in oc(icons)) text+='<button class="BE_icons" id="BE_underline" title="Underline">&nbsp;</button>';
            if ('italic' in oc(icons)) text+='<button class="BE_icons" id="BE_italic" title="Italic">&nbsp</button>';
         
            if ('link' in oc(icons)) {
               text+='<button class="BE_icons" id="BE_link" title="Link">&nbsp</button>';
               text+='<button class="BE_icons" id="BE_unlink" title="Un-link">&nbsp</button>';
            }
            if ('h2' in oc(icons)) text+='<button class="BE_icons" id="BE_h2" title="Heading" >&nbsp</button>';     
            if ('ol' in oc(icons)) text+='<button class="BE_icons" id="BE_ol" title="Numbered List">&nbsp</button>';
            if ('ul' in oc(icons)) text+='<button class="BE_icons" id="BE_ul" title="Bulleted List">&nbsp</button>';    
            if ('ar' in oc(icons)) text+='<button class="BE_icons" id="BE_ar" title="Align Right">right</button>';
            if ('al' in oc(icons)) text+='<button class="BE_icons" id="BE_al" title="Align Left">left</button>';
            if ('ac' in oc(icons)) text+='<button class="BE_icons" id="BE_ac" title="Align Center">center</button>';
            if ('media' in oc(icons)) { $("#media_icon").show(); } else { $("#media_icon").hide(); }
            if ('options' in oc(icons)) { $("#optionsdialog").show(); } else { $("#optionsdialog").hide(); }
            
            if ('embed' in oc(icons)) text+='<button class="BE_icons" id="BE_embed" title="Embed (Video, Widget, etc.)">&nbsp</button>';
            
            text+='<button class="BE_icons" onmousedown="saveSelection();openpastedialog();" id="BE_paste" title="Paste Content">&nbsp</button>';
            if (baroptions=='none') text='';                        
            $("#admin_toolbar_btns #dynamic").html(text);
            
            if ($("#admin_savebtn").is(':visible')){
                if (text!=tbefore) $("#admin_toolbar_btns").show();
            }
            if (text==tbefore) $("#admin_toolbar_btns").hide();
            
            //$(this).unbind('mouseleave').mouseleave(function() { saveSelection();  });
            
            $(options.barselector).fadeIn(1, function(){
               //$("#BE_h2").unbind('mousedown').mousedown(function() { wrapHtml('<h2>','</h2>'); });
               $("#BE_h2").unbind('mousedown').mousedown(function() {                
                toggleHeader2();
                //obj.find("[contenteditable=true].header2").each(function(){                     
                //     $(this).replaceWith('<h2 class="header2">'+$(this).html()+'</h2>');
                //});                
                //obj.find("[contenteditable=true]h2").each(function(){                     
                //     if (!$(this).hasClass('header2')) $(this).replaceWith($(this).html());                                          
                //});                
               });
               
               $("#BE_h3").unbind('mousedown').mousedown(function() {wrapHtml('<h3>','</h3>'); });
               $("#BE_italic").unbind('mousedown').mousedown(function() {   toggleitalic(); });
               $("#BE_bold").unbind('mousedown').mousedown(function() { togglebold(); });               
               $("#BE_underline").unbind('mousedown').mousedown(function() {     toggleunderline(); });
               
               $("#BE_ol").unbind('mousedown').mousedown(function() { doFormat('insertorderedlist'); });
               $("#BE_ul").unbind('mousedown').mousedown(function() {   doFormat('insertunorderedlist');});               
               $("#BE_ar").unbind('mousedown').mousedown(function() {    wrapHtml('<span style="float: right;">','</span>'); });
               $("#BE_ac").unbind('mousedown').mousedown(function() {     wrapHtml('',''); });
               $("#BE_al").unbind('mousedown').mousedown(function() {     wrapHtml('<span style="float: left;">','</span>'); });
               $("#BE_addhtml").unbind('mousedown').mousedown(function() { wrapHtml('<b>before -> ',' <- after</b>'); });
               
               $("#BE_embed").unbind('mousedown').mousedown(function() {                  
                  var u=rangy.getSelection().anchorNode;                  
                  var t=$(u).closest("h2");
                  var openbox=1;
                  if (contenteditable=='false'){
                        alert('Sorry, you are trying to embed something inside an embeddable, please insert a few empty lines and try again by clicking into those.');
                        openbox=0;
                  }                  
                  if (t.size()==1){
                        openbox=0;
                        alert('Sorry, you cannot embed Code inside a Header');
                  }
                  if(openbox==1){
                        saveSelection();
                        call_box_url('/manage/addembed');                        
                  }
               });
               $("#BE_link").mousedown(function(){   saveSelection();  dolink(''); });
               $("#BE_unlink").mousedown(function(){   doFormat('unlink'); });
            });
            return true;
         }
      });      
   }   
   
function triggertag(tag){      
      var t=getSelectionContainerElement();                  
      var nname= t.nodeName;
      if (nname==tag.toUpperCase()){
            var ct='';
            if  (t.innerText) {
                ct=t.innerText;
            } else {
                ct=node.textContent;
            }
         var text = document.createTextNode(ct);
         t.parentNode.replaceChild(text, t);                     
      } else { wrapHtml('<'+tag+'>','</'+tag+'>'); }                  
}   

function cleanup(text){
   var result='';
   result=text;   
   /*
    $(result).find("[class]").each(function(){
      alert($(this).attr('class'));
      });
   */    
   return result;
}

function disable_editmode(obj){
    obj.each(function(){
    $(this).removeClass('editable');
       if (document.all){ $(this).get(0).contentEditable='false'; } else {	$(this).attr('contenteditable','false'); }
       in_editmode=0;
    });
}

function embedhover(){
      $(".embed").unbind('hover').live('hover',function(){
            $(".BE_current_embed").removeClass('BE_current_embed');
            $(this).addClass("BE_current_embed");
            if ($(".BE_embed_overlay").length > 0){
                  var p=$(this).offset();            
                  $(".BE_embed_overlay").offset({top: p.top, left: p.left});
                  var w=$(this).width();
                  var h=$(this).height();                   
                  $(".BE_embed_overlay").css({ width: 'auto'});
            }
      });
}

function imagehover(){      
   if ($(".BE_image_overlay").length > 0){
     $(".embed img").addClass("inembed");
     $(".editable img").unbind('mouseover').live('mouseover',function(){
         if (!$(this).hasClass('inembed')) {
         findpn($(this));                  
         $("#BE_current_image").removeAttr('id');
         $(this).attr("id","BE_current_image");         
         var p=$(this).offset();            
         $(".BE_image_overlay").offset({top: p.top, left: p.left});
         var w=$(this).width();
         var h=$(this).height();                   
         $(".BE_image_overlay").css({width: w+'px', border: '1px solid yellow',height: h+'px'});
         $(".BE_image_overlay").show();
         }
      });   
   }
   $(".BE_image_overlay").hover(function(){         
         $(this).css({cursor: 'pointer'});         
   }, function(){         
         var p=$(".BE_image_overlay").offset();         
         var out=0;
   });
}

function enable_editmode(obj){
   obj.each(function(){
       if (document.all){ $(this).get(0).contentEditable='true'; } else { $(this).attr('contenteditable','true'); }
       
       $(this).addClass('editable');
   });
   
   obj.find("img").each(function(){ $(this).find("img").attr('contentEditable','false'); });
      
   $("td .editable").keypress(function (e) {
      var p=getpos;
      if (p==0) return false;
      return true;
   });           
   
   obj.keypress(function (e) {            
      if (( e.keyCode == 46 )||( e.keyCode == 8 )){                   
          var selection=getHtml();          
          if (selection!=null){ addHtml(''); } else return true;
      }   
      return true;
   });   
}



function doFormat(cmd, value) {
    if (!value) value=null;
    document.execCommand(cmd, false, value);
}

function dolink(state){      
      if (state) state='/'+state;
      call_box_url('/manage/show_link_box'+state);      
      
      var image= $("#BE_current_image").parent().attr("href");
      if (image) {               
         $("#BE_piclink").hide();
         $("#BE_picunlink").show();
      } else {               
         $("#BE_piclink").show();
         $("#BE_picunlink").hide();
      }         
}

function dowidget(){
      if (pageid){
            call_box_url('/manage/show_widget_box/'+pageid );          
      }
}

function dopicunlink(){
   var image=$("#BE_current_image").parent().attr("href");
   if (image) {
      $("#BE_current_image").unwrap();
      findpn($("#BE_current_image"));   
   }
   
     var image= $("#BE_current_image").parent().attr("href");
      if (image) {               
         $("#BE_piclink").hide();
         $("#BE_picunlink").show();
      } else {               
         $("#BE_piclink").show();
         $("#BE_picunlink").hide();
      }         
}

function oc(a){
  var o = {};
  for(var i=0;i<a.length;i++) o[a[i]]='';  
  return o;
}

function addleft(){
    findpn($("#BE_current_image"));           
    $("#BE_current_image").removeClass();
    $("#BE_current_image").addClass('img_left');
    var p=$("#BE_current_image").offset();
    $(".BE_image_overlay").offset({left: p.left, top: p.top});    
}

function deleteimg(){
   findpn($("#BE_current_image"));      
   $("#BE_current_image").remove();   
   $(".BE_image_overlay").offset({ left: -5000});
}

function deleteembed(){
   findpn($(".BE_current_embed"));      
   $(".BE_current_embed").remove();   
   $(".BE_embed_overlay").offset({ left: -5000});
}     


function center(){    
    findpn($("#BE_current_image"));       
    $("#BE_current_image").removeClass();
    $("#BE_current_image").addClass('img_center');
    var p=$("#BE_current_image").offset();
    $(".BE_image_overlay").offset({left: p.left, top: p.top});
}     

function addright(){   
    findpn($("#BE_current_image"));
    $("#BE_current_image").removeClass();        
    $("#BE_current_image").addClass('img_right');
    var p=$("#BE_current_image").offset();
    $(".BE_image_overlay").offset({left: p.left, top: p.top});
}

function embed_alignright(){
    findpn($(".BE_current_embed"));
    var node=$(".BE_current_embed");
    node.removeClass('img_left');
    node.removeClass('img_center');
    node.addClass('img_right');        
    var p=node.offset();
    $(".BE_embed_overlay").offset({left: p.left, top: p.top});
}
function embed_center(){
    findpn($(".BE_current_embed"));
    var node=$(".BE_current_embed");
    node.removeClass('img_left');
    node.removeClass('img_right');
    node.addClass('img_center');    
    var p=node.offset();
    $(".BE_embed_overlay").offset({left: p.left, top: p.top});         
    var p=$(".BE_current_embed").offset();
    $(".BE_embed_overlay").offset({left: p.left, top: p.top});
}

function embed_alignleft(){
    findpn($(".BE_current_embed"));
    var node=$(".BE_current_embed");
    node.removeClass('img_right');
    node.removeClass('img_center');
    node.addClass('img_left');  
    var p=node.offset();
    $(".BE_embed_overlay").offset({left: p.left, top: p.top});
}

function findpn(node){
   var pn=node.closest(".editable");
   pn.addClass("edited");
   return pn;
}

function strip(html, result){   
   var t=$('<div>'+html+'</div>');
   t.children().each(function(){     
      if ($(this).children().size() >0){
          //alert('tag:  '+$(this).tagName());
          result=result+strip($(this).html(), result);          
      } else {
          result=result+$(this).text();
      }     
   });      
   return result;   
}

function openpastedialog(){
      call_box_url('/manage/pastetext/');
      return false;
}; 

