
/*===========================================================
   Helpers
============================================================= */


 function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; 
    for(i=0; i<a.length; i++)
      if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; 
  for(i=0;i<(a.length-2);i+=3)
    if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function clickclear(thisfield, defaulttext) {
  if (thisfield.value == defaulttext) {
    thisfield.value = "";
  }
}

function clickrecall(thisfield, defaulttext) {
  if (thisfield.value == "") {
    thisfield.value = defaulttext;
  }
}


/*===========================================================
   Tiny MCE extensions
============================================================= */

function cmsFileBrowser (field_name, url, type, win) {
    var cmsURL = window.location.pathname;      // script URL

    var imageSplit = window.location.pathname.split ('/');
    if (imageSplit) {

       if (field_name == 'href') {
             var imageURL = "/cms/content_types/list/";
       } else {
             var imageURL = "/cms/ims/choose/";
       }

    } else {
        return false;
    }
    var fileBrowserWindow = new Array();

    /* If you work with sessions in PHP and your client doesn't accept cookies you might need to carry
       the session name and session ID in the request string (can look like this: "?PHPSESSID=88p0n70s9dsknra96qhuk6etm5").
       These lines of code extract the necessary parameters and add them back to the filebrowser URL again. */

    // var searchString = window.location.search;  // possible parameters
    // if (searchString.length < 1) {
        // add "?" to the URL to include parameters (in other words: create a search string because there wasn't one before)
    //    searchString = "?";
    //}

    // fileBrowserWindow["file"] = cmsURL + searchString + "&type=" + type; // PHP session ID is now included if there is one at all

    fileBrowserWindow["file"] = imageURL;

    fileBrowserWindow["title"] = "File Browser";
    fileBrowserWindow["width"] = "640";
    fileBrowserWindow["height"] = "400";
    fileBrowserWindow["close_previous"] = "no";

    tinyMCE.openWindow(fileBrowserWindow, {
      window : win,
      input : field_name,
      resizable : "yes",
      inline : "yes",
      scrollbars: "1"
    });
    return false;
}


function cmsSubmit(URL) {
  //call this function only after page has loaded
  //otherwise tinyMCEPopup.close will close the
  //"Insert/Edit Image" or "Insert/Edit Link" window instead

  //var URL = this.src.value;
  var win = tinyMCE.getWindowArg("window");

  // insert information now
  win.document.getElementById(tinyMCE.getWindowArg("input")).value = URL;

  // for image browsers: update image dimensions
  if (win.getImageData) win.getImageData();

  // close popup window
  tinyMCEPopup.close();
}


function init_tiny_mce_editor() {
    tinyMCE.init({
        // General options
        mode : "textareas",
        theme : "advanced",
        height : "450",
        width: "650",
        convert_urls : false,
        plugins : "safari,table,save,advimage,preview,searchreplace,print,contextmenu,paste,fullscreen,noneditable,inlinepopups",

        // Theme options
        theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,|,print,|,fullscreen",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_resizing : true,

        // Example word content CSS (should be your site CSS) this one removes paragraph margins
        //content_css : "/static_media/css/tiny_mce_editor_area.css",
        file_browser_callback : 'cmsFileBrowser'
    }); 
}


/*===========================================================
   CMS
============================================================= */


function init_drag_drop() {
    $(".drag_nav").draggable({helper: 'clone',
                              scroll: true});

    $(".drop_nav").droppable({
        accept: ".drag_nav",
        activeClass: 'droppable-active',
        hoverClass: 'droppable-hover',
        drop: function(ev, ui) {
            move_left_nav_items($(ui.draggable).attr('id'), this.id);
         }
     });
}

function move_left_nav_items(origin_id, destination_id) {
      if ( origin_id == destination_id ) {
            return false;
      }

      /*var element = document.getElementById(todo_id + '_status_area');
      element.style.display = "block";*/

      jQuery.ajax({
            type: "GET",
            url: "/cms/ajax/left_nav/" + origin_id + "/" + destination_id + "/",
            datatype: "html",

            // using a smaller timeout here can cause broken pipe errors
            // in django - be careful
            timeout: 3000000,

            error: function(req, textstatus, another) {
              alert(textstatus);
            },

            success: function(r) {
                $('#left_nodes_holder').empty();
                $('#left_nodes_holder').append(r);
                init_drag_drop();
            }
       })
};


