var socs_cssFile = '';
var socsSavingChanges = false;

function socsPreviewTP(articleText) {
  var $ = jQuery;
  $("#ed_preview input[name='cssFile']").val(socs_cssFile);
  socsPreview(articleText);
}

function socsPreview(articleText) {
  var $ = jQuery;

  $("#ed_preview input[name='article_id']").val($('#article_id').val());
  $("#ed_preview input[name='artHeadline']").val($('#eipHeadline').val());
  $("#ed_preview input[name='artTagline']").val($('#eipTagline').val());
  $("#ed_preview input[name='artByline']").val($('#eipByline').val());
  $("#ed_preview input[name='artText']").val(articleText);
  $("#ed_preview input[name='artRelatedURLs']").val($('#artRelatedURLs').val());
  $("#ed_preview input[name='artSection']").val($('#artSection').val());
  $("#ed_preview input[name='artPublishDate']").val($('#artPublishDate').val());
  $("#ed_preview input[name='numimages']").val($('#numimages').val());
  $("#ed_preview input[name='image_1_on']").val($('#image_1_on').val());
  $("#ed_preview input[name='image_2_on']").val($('#image_2_on').val());
  $("#ed_preview input[name='image_3_on']").val($('#image_3_on').val());
  if ($('#feedbackBox').length) $("#ed_preview input[name='vfeedback']").val('vfeedback');

  window.open('', 'preview', 'resizable=1,toolbar=0,scrollbars=1');

  $('#ed_preview').submit();

  socs_cssFile = '';
  $("#ed_preview input[name='cssFile']").val('');
}

function socsSaveChanges(articleText) {
  var $ = jQuery;
  var errMsg = '', $ajaxLoading = $('#ajaxLoadingEIP'), $ajaxDialog = $('#ajaxDialog'), artHeadline = $.trim($('#eipHeadline').val());

  // Let the jQuery-namespaced code know that we're trying to save changes through a global variable
  socsSavingChanges = true;

  // Validation - Headline and article text must exist
  if (artHeadline.length === 0 || articleText.length === 0) {
    $ajaxLoading.jqmHide();
    if (artHeadline.length === 0) {
      errMsg = '<strong>Please provide a headline for the article.</strong>';
    } else {
      errMsg = '<strong>Please provide text for the article.</strong>';
    }
    $ajaxDialog.find('p').html(errMsg).end().jqmShow();
    return false;
  }

  $.ajax({
    url: '/vnews/libs/ajax_edit_in_place_save_changes.php',
    type: 'POST',
    data: {
      article_id: $('#article_id').val(),
      artHeadline: artHeadline,
      artTagline: $.trim($('#eipTagline').val()),
      artByline: $.trim($('#eipByline').val()),
      artText: articleText,
      artSection: $('#artSection').val(),
      socsPageType: socsPageType
    },
    beforeSend: function() {
      $ajaxLoading.jqmShow();
    },
    error: function(xhr, textStatus, errorThrown) {
      $ajaxLoading.jqmHide();
      $('#ajaxDialog').find('p').html('<strong>Unexpected Ajax Error<br /><br />' + xhr.responseText).end().jqmShow();
    },
    success: function(data) {
      // May get PHP errors that won't trigger the ajaxError event
      if (data.indexOf('error') != -1) {
        $ajaxLoading.jqmHide();
        $ajaxDialog.find('p').html('<strong>Unexpected Ajax Error<br /><br />Error Text:</strong><br />' + data).end().jqmShow();
        return false;
      }

      data = $.parseJSON(data);

      if (data.errMsg.length) {
        $ajaxLoading.jqmHide();
        $ajaxDialog.find('p').html(data.errMsg).end().jqmShow();
        return false;
      }

      if (data.saved) window.location.reload();
    }
  });

}

(function($){
  $(function() {
    function addIconsToPage(type, $container, ezeDesign) {
      switch(type) {
        case 'article': // Edit article, Edit Images, Delete article
          $container.prepend(
            '<div id="ezEdit">' +
              '<a href="#"><img src="/vimages/backend/shared/editArticle.gif" title="Edit Article in Place" alt="Edit Article in Place Icon" \/><\/a>' +
              '<a href="/vnews/editor.v?TARGET=editArticle&Lid=' + socsArticleID + '&from_target=ezeArticle">' +
                '<img src="/vimages/backend/shared/editArticleCS.gif" title="Edit Article in Central Services" alt="Edit Article in CS Icon" \/><\/a>' +
              '<a href="/vnews/editor.v?TARGET=editGallry&numimages=0&Lid=' + socsArticleID + '&from_target=ezeArticle">' +
                '<img src="/vimages/backend/shared/editImages.gif" title="Edit Images" alt="Edit Images Icon" \/><\/a>' +
              '<a href="#"><img src="/vimages/backend/shared/deleteArticle.gif" title="Delete Article" alt="Delete Article Icon" \/><\/a>' +
            '<\/div>'
          );
          break;
        case 'section': // Create new article
          $container.prepend(
            '<div id="ezEdit">' +
              '<a href="/vnews/editor.v?TARGET=menuRoute&submit=newGallry&ezeSectionName=' + escape(socsSectionName) + '&from_target=ezeNewArticle">' +
                '<img src="/vimages/backend/shared/addArticle.gif" title="Create New Article in Central Services" alt="Create Article Icon" \/><\/a>' +
            '<\/div>'
          );
          break;
        case 'teacherblog': // Create new blog article
          $container.prepend(
            '<div id="ezEdit">' +
              '<a href="/vnews/editor.v?TARGET=menuRoute&submit=newGallry&ezeSectionName=' + escape(socsSectionName) + '&from_target=ezeNewTBlog&ezeDesign=' + ezeDesign + '">' +
                '<img src="/vimages/backend/shared/addArticle.gif" title="Create New Blog Article in Central Services" alt="Create Article Icon" \/><\/a>' +
            '<\/div>'
          );
          break;
        case 'teacherpage': // Edit staff page, Edit Images, Delete staff page
          $container.prepend(
            '<div id="ezEdit">' +
              '<a href="#"><img src="/vimages/backend/shared/editArticle.gif" title="Edit Teacher Page in Place" alt="Edit Teacher Page in Place Icon" \/><\/a>' +
              '<a href="/vnews/editor.v?TARGET=editArticle&Lid=' + socsArticleID + '&from_target=ezeTPage&ezeDesign=' + ezeDesign + '">' +
                '<img src="/vimages/backend/shared/editArticleCS.gif" title="Edit Teacher Page in Central Services" alt="Edit Teacher Page in CS Icon" \/><\/a>' +
              '<a href="/vnews/editor.v?TARGET=editGallry&numimages=0&Lid=' + socsArticleID + '&from_target=ezeTPage&ezeDesign=' + ezeDesign + '">' +
                '<img src="/vimages/backend/shared/editImages.gif" title="Edit Images" alt="Edit Images Icon" \/><\/a>' +
              '<a href="#"><img src="/vimages/backend/shared/deleteArticle.gif" title="Delete Teacher Page" alt="Delete Article Icon" \/><\/a>' +
            '<\/div>'
          );
          break;
      }
    }

    function buildEditorMenu(data) {

      var html = '<div id="js-editor-menu" class="clearfix"><ul><li class="top"><a href="#">Insert</a><div class="js-sub"><ul>';

      $.each(data.jsEditorMenu.Insert, function(idx, val) {
        html += '<li><a href="#" class="' + idx + '">' + val + '</a></li>';
      });
      html += '</ul></div></li>';

      // Bit of a hack to find out if there are articles for the "Articles" menu
      var cnt = 0;
      try {
        $.each(data.jsEditorMenu.Articles, function(i, v) {
          cnt++;
          return false;
        });
      } catch (e) {}

      if (cnt) {
        html += '<li class="top"><a href="#">Articles</a><div class="js-sub"><ul class="js-articles">';
        $.each(data.jsEditorMenu.Articles, function(idx, val) {
          html += '<li><a href="#" class="' + idx + '" rel="' + escape(val[1]) + '" title="' + val[0] + '">' + val[0] + '</a></li>';
        });
        html += '</ul></div></li>';
      }

      cnt = 0;
      try {
        $.each(data.jsEditorMenu.MyArticles, function(i, v) {
          cnt++;
          return false;
        });
      } catch (e) {}

      if (cnt) {
        html += '<li class="top"><a href="#">My Articles</a><div class="js-sub"><ul class="js-articles">';
        $.each(data.jsEditorMenu.MyArticles, function(idx, val) {
          html += '<li><a href="#" class="' + idx + '" rel="' + escape(val[1]) + '" title="' + val[0] + '">' + val[0] + '</a></li>';
        });
        html += '</ul></div></li>';
      }

      cnt = 0;
      try {
        $.each(data.jsEditorMenu.Slideshows, function(i, v) {
          cnt++;
          return false;
        });
      } catch (e) {}

      if (cnt) {
        html += '<li class="top"><a href="#">Slideshows</a><div class="js-sub">' +
'<input type="hidden" id="js-slideshow-height" name="js-slideshow-height" value="' + data.jsEditorMenu.SlideshowHeight + '" />' +
'<input type="hidden" id="js-slideshow-width" name="js-slideshow-width" value="' + data.jsEditorMenu.SlideshowWidth + '" /><ul class="js-slideshows">';
        $.each(data.jsEditorMenu.Slideshows, function(idx, val) {
          html += '<li><a href="#" class="' + idx + '" rel="' + escape(val[1]) + '" title="' + val[0] + '">' + val[0] + '</a></li>';
        });
        html += '</ul></div></li>';
      }

      html += '</ul></div>';
      $(html).insertBefore('#js-editor');

      // Top-level menu will display/hide the drop-down menu
      $('#js-editor-menu .top').hover(function() {
        var winH = $(window).height(), winST = $(window).scrollTop();
        var $div = $(this).children('div:first');
        var divAdjTop = $div.offset().top - winST;

        // If the menu is too tall for the available space, resize it to fit in the available space
        // (plus a little padding to keep it off the chrome) and set a fixed width to account for the scrollbar.
        if ($div.height() > (winH - divAdjTop)) {
          $div.css({
            'height': winH - (divAdjTop + 10),
            'width': '300px'
          });
        }
        $div.css('left', 'auto');
      }, function() {
        // Hide the menu and reset the height and width.
        $(this).children('div:first').css({
          'left': '-999em',
          'height': '',
          'width': ''
        });
      });

      // Don't do anything if the top-level menu is clicked.
      $('#js-editor-menu').delegate('.top > a', 'click', function(e) {
        e.preventDefault();
      });

      // Insert Menu - Article Redirect
      $('#js-editor-menu a.iar').click(function(e) {
        e.preventDefault();
        // Emulate normal menu behavior by hiding the drop-down menu that we just "clicked" on
        closeMenu($(this));
        socs_insertArticleRedirect();
      });

      // Insert Menu - Local File
      $('#js-editor-menu a.ilf').click(function(e) {
        e.preventDefault();
        closeMenu($(this));
        insertLocalFile();
      });

      // Insert Menu - Local Image
      $('#js-editor-menu a.ili').click(function(e) {
        e.preventDefault();
        closeMenu($(this));
        insertLocalImage();
      });

      // Insert Menu - Teacher Page Link
      $('#js-editor-menu a.tpl').click(function(e) {
        e.preventDefault();
        closeMenu($(this));
        socs_insertTeacherPageLink();
      });

      // Insert Menu - Teacher Page Template
      $('#js-editor-menu a.tpt').click(function(e) {
        e.preventDefault();
        closeMenu($(this));
        socs_insertTeacherPageTemplate();
      });

      // Insert Menu - Image 2/Image 3
      $('#js-editor-menu a.js-img2, #js-editor-menu a.js-img3').click(function(e) {
        e.preventDefault();
        closeMenu($(this));
        if ($(this).hasClass('js-img2')) {
          tinyMCE.execCommand('mceInsertContent', false, '<img src="http://socshelp.fes.org/sharedimages/image2tag.gif" />');
        } else {
          tinyMCE.execCommand('mceInsertContent', false, '<img src="http://socshelp.fes.org/sharedimages/image3tag.gif" />');
        }
      });

      // Articles & My Articles Menu
      $('#js-editor-menu .js-articles').delegate('a', 'click', function(e) {
        e.preventDefault();
        var $this = $(this);

        // Build and insert the HTML for the article link
        var html = '<a href="/vnews/display.v/ART/' + $this.attr('class') + '">' +  unescape($this.attr('rel')) + '</a>';
        tinyMCE.execCommand('mceInsertContent', false, html);

        closeMenu($this);
      });

      // Slideshows Menu
      $('#js-editor-menu .js-slideshows').delegate('a', 'click', function(e) {
        e.preventDefault();
        var $this = $(this);

        // Build and insert the HTML for the slideshow image and link
        var html = '<img src="/vimages/shared/slide_show_icon.gif" alt="Slideshow Icon" />&nbsp;<a href="#" '
          + 'onclick="window.open(\'/vslideshow/viewer.v?&slideshow_id=' + $this.attr('class') + '\', \'vss_view\', \'width='
          + $('#js-slideshow-width').val() + ',height=' + $('#js-slideshow-height').val() + ',left=20,screenX=20,top=20,screenY=20,location=0,toolbar=0,status=0,scrollbars=1\'); return false;">'
          + unescape($this.attr('rel')) + '</a>';
        tinyMCE.execCommand('mceInsertContent', false, html);

        closeMenu($this);
      });

    }

    function buildTeacherPageContent(data) {
      var $x = null;

      // The following are drop-down select boxes on the "Insert Teacher Page Link" dialog
      // accessed through the EditLive menu: Insert -> Teacher Page Link...
      //
      // insertTeacherPageLink.html, insertTeacherPageLink.js

      // Article to be displayed
      if (typeof data.teacherSections !== 'undefined') {
        if (data.teacherSections.tblogArticlesExist) {
          $('#tpa select').append('<option value="' + data.teacherSections.tblogSectionName + '">&mdash; My Blog &mdash;</option>');
        }
      }
      if (typeof data.teacherPages !== 'undefined') {
        if (data.teacherPages.id[0]) {
          $x = $('#tpa select');
          $.each(data.teacherPages.id, function(index, value) {
            $x.append('<option value="' + value + '">' + data.teacherPages.artHeadline[index] + '</option>');
          });
        }
      }

      // Template design
      if (typeof data.teacherSections !== 'undefined') {
        if (data.teacherSections.tpSectionName) {
          var customFlag = false;

          // Custom designs
          if (data.tpCustomTemplates) {
            $('#tpt select').append('<optgroup label="Custom" />');
            $x = $('#tpt optgroup:first');
            $.each(data.tpCustomTemplates, function(key, value) {
              $x.append('<option value="' + key + '">' + value + '</option>');
            });
            customFlag = true;
          }

          // Stock designs
          if (data.tpStockTemplates) {
            if (customFlag) {
              $('#tpt select').append('<optgroup label="Standard" />');
              $x = $('#tpt optgroup:last');
            } else {
              $x = $('#tpt select');
            }
            $.each(data.tpStockTemplates, function(key, value) {
              $x.append('<option value="' + key + '">' + value + '</option>');
            });
          }
        }
      }

      // The following is the drop-down select box on the "Insert Teacher Page Template" dialog
      // accessed through the EditLive menu: Insert -> Teacher Page Template...
      //
      // insertTeacherPageTemplate.html
      if (typeof data.tpTemplates !== 'undefined') {
        if (data.tpTemplates.id[0]) {
          $x = $('#tpTpl select');
          $.each(data.tpTemplates.id, function(index, value) {
            $x.append('<option value="' + value + '">' + data.tpTemplates.artHeadline[index] + '</option>');
          });
        }
      }

    }

    function closeMenu($this) {
      $this.parents('div.js-sub').css({
        'left': '-999em',
        'height': '',
        'width': ''
      });
    }

    function customImageTags(replaceTags) {
      var txt = '';
      if (replaceTags) {
        // Replace embedded custom <image2> and <image3> tags with HTML <img> tags pointing to images
        // that use the EditLive "custom tag" graphic.
        txt = unescape($('#articleText').val());
        txt = txt.replace(/<image([23])>/g,'<img src="http://socshelp.fes.org/sharedimages/image$1tag.gif" />');
      } else {
        // Restore the custom <image2> and <image3> tags
        txt = tinyMCE.activeEditor.getContent();
        txt = txt.replace(/<img.*socshelp\.fes\.org\/sharedimages\/image([23])tag\.gif.*\/>/g, '<image$1>');
      }
      return txt;
    }

    function deletePage(type, from, e, $this) {
      if (confirm('Are you sure you want to delete this ' + type + '?')) {
        window.location = '/vnews/editor.v?TARGET=dispRoute&submit=Delete+Article&article_id=' + socsArticleID + '&from_target=' + from;
      } else {
        $this.blur(); // Get rid of outline around link
        e.preventDefault();
      }
    }

    function displayEditor(data) {

      if (socsPageType === 'article') {
        // Load the "header" fields - Headline, Tagline, Byline
        $('#eipHeadline').val($.trim($('#artHead').html()));
        $('#eipTagline').val($.trim($('#artTag').html()));
        $('#eipByline').val($.trim($('#byline').text()));
      } else {
        // Teacher Page
        $('#eipHeadline').val($.trim($('#title3 h1 span').html()));
        $('#eipTagline').val($.trim($('#title3 h2 span').html()));
        $('#eipByline').val($.trim($('#title3 h3 span').text()));
      }

      // Initialize and load the article editor
      if (data.TextEditorType === 'HTML') {
        htmlEditor = true;
        $('#sessionTimer').css('display', 'none');
        $('#HTMLEditor').css('display', '');
        $('#eipHTMLArtText').val(data.artText);
      } else {
        if (data.TextEditorType === 'jseditor') {
          jsEditor = true;
          $('#java-editor').css('display', 'none');
          $('#js-editor').parent().css('display', '');
        } else {
          editLiveEditor = true;
        }

        buildTeacherPageContent(data);

        $('#sessionTime').html(data.sessionTime);

        // Size the editor to fit the container
        var h = $('#ezEdit').parent().height();
        if (h < 400) h = 400; // min-height will be 400 pixels

        if (jsEditor) {
          $('#articleText').val(data.artText);

          buildEditorMenu(data);

          // This needs to be loaded BEFORE TinyMCE has been instantiated.
          $('head').append('<script type="text/javascript" src="/javascripts/cs/elsession.js"></script>');

          initTinyMCE(data, h);

        } else {
          // NOTE: The variable name for the EditLive object HAS TO MATCH the name given
          // in the "backend" articleRecForm.tpl file. Code in "insertTeacherPageLink.js"
          // uses the "editlivejava1" variable name.
          // Also note that this variable is declared globally (see top of file).
          try {
            editlivejava1 = new EditLiveJava("articleText", '100%', h);
            editlivejava1.setConfigurationText(data.xml_data);
            editlivejava1.setBody(data.artText);
            editlivejava1.setDownloadDirectory('/java/' + data.TextEditorType);
            editlivejava1.setLocalDeployment(false);
            if (editlivejava1.setExperimentalBrowserSupport) editlivejava1.setExperimentalBrowserSupport(true);
            editlivejava1.showInElement('java-editor');

            // This needs to be loaded AFTER EditLive has been instantiated.
            $('head').append('<script type="text/javascript" src="/javascripts/cs/elsession.js"></script>');

          } catch (err) {
            $ajaxLoading.jqmHide();
            errFlag = true;
            $('#ajaxDialog').find('p').html('<strong>Error:</strong><br /><br />There was a problem loading the EditLive editor. The most likely reason is that this version of EditLive is not compatible with the "Edit in Place" feature.<br /><br />You can use the "Edit in Central Services" icon or change your editor version from the Editor menu in Central Services.').end().jqmShow();
            return false;
          }

        }

        // Do some cleanup work on the buttons
        $('#eipWrap .actionButtons input').removeAttr('disabled');
      }

      $('#artPublishDate').val(data.artPublishDate);

      // Hide the #articleBody div and show the #eipContent div.
      $('#eipContent').css('display', '');
      if (socsPageType === 'article') {
        $('#articleBody').css('display', 'none');
      } else {
        $('#content3').css('display', 'none');
      }

      $ajaxLoading.jqmHide();
    }

    function editInPlace(e, savingChanges) {
      e.preventDefault();

      // Make sure user is still logged in and still has rights to edit this article.
      // If so, get all the stuff needed to load the article into the editor.
      errFlag = false;
      $.ajax({
        url: '/vnews/libs/ajax_edit_in_place.php',
        type: 'GET',
        data: {
          article_id: $('#article_id').val(),
          artSection: $('#artSection').val(),
          artEditor: $('#artEditor').val(),
          numimages: $('#numimages').val(),
          savingChanges: savingChanges
        },
        beforeSend: function() {
          $ajaxLoading.jqmShow();
        },
        error: function(xhr, textStatus, errorThrown) {
          $ajaxLoading.jqmHide();
          $('#ajaxDialog').find('p').html('<strong>Unexpected Ajax Error<br /><br />' + xhr.responseText).end().jqmShow();
        },
        success: function(data) {
          data = $.parseJSON(data);

          if (data.errMsg.length) {
            $ajaxLoading.jqmHide();
            errFlag = true;
            $('#ajaxDialog').find('p').html(data.errMsg).end().jqmShow();
            return false;
          }

          if (!data.access) return false;

          if (savingChanges) {
            if (htmlEditor) {
              socsSaveChanges($('#eipHTMLArtText').val());
            } else if (jsEditor) {
              // Suppress the "Are you sure you want to navigate away from this page" dialog that TinyMCE
              // will display--if the editor content has changed--when the page is reloaded after the save.
              tinyMCE.activeEditor.isNotDirty = 1;
              socsSaveChanges(customImageTags(false));
            } else {
              // IE can't get the contents of the EditLive editor if it's hidden, so unhide it before calling GetBody
              if (editLiveEditor) $('#java-editor').css('visibility', '');
              editlivejava1.GetBody('socsSaveChanges', true);
            }
          } else {
            displayEditor(data);
          }
        }
      });

    }

    function initTinyMCE(data, height) {

      tinyMCE.init({
        mode: 'exact',
        elements: 'js-editor',
        theme: 'advanced',
        skin: 'o2k7',
        skin_variant: 'silver',

        file_browser_callback : 'tinyBrowser',

        custom_undo_redo_levels: 10,
        convert_urls : false,

        setup: function(ed) {
          ed.onInit.add(function(ed) {
            ed.setContent(customImageTags(true));
            ed.isNotDirty = 1; // Force not dirty state
          });
          ed.onPostRender.add(function(ed, cm) {
            // Setup the session timer with the initial length of the editor's content
            socsInitEditorLength(customImageTags(true));
          });
        },

        plugins: "spellchecker,table,advhr,advimage,advlist,advlink,iespell,inlinepopups,insertdatetime,searchreplace,contextmenu,paste,fullscreen,noneditable,wordcount,media",

        theme_advanced_buttons1: "fullscreen,spellchecker,|,bold,italic,underline,strikethrough,|,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,blockquote",
        theme_advanced_buttons3: "forecolor,backcolor,|,sub,sup,|,link,unlink,anchor,image,code,|,insertdate,inserttime,charmap,iespell,advhr",
        theme_advanced_buttons4: "tablecontrols,visualaid,|,removeformat",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true,

        theme_advanced_source_editor_width: $(window).width() * 0.75,
        theme_advanced_source_editor_height: $(window).height() * 0.75,
        theme_advanced_resizing_min_width: $('#eipWrap').parent().width(),
        theme_advanced_resizing_min_height: 400,
        theme_advanced_resizing_use_cookie: false,

        plugin_insertdate_dateFormat: '%m-%d-%Y',
        plugin_insertdate_timeFormat: '%I:%M %p',

        height: height + 'px',
        width: '100%',

        content_css: '/css/' + $('#template').val() + '/editor.css',

        // Drop lists for link/image/media/template dialogs
        external_image_list_url : '/javascripts/vnews/external_image_list_url.js'
      });

    }

    // If the global JS variable created and set by the Smarty "signedin" insert function
    // doesn't exist or is false, leave without doing anymore work.
    if (typeof socsUserAccess === 'undefined' || !socsUserAccess) return false;

    // Cached DOM elements and globals
    var $ajaxLoading = $('#ajaxLoadingEIP');
    var $wrap = $('#eipWrap');
    var errFlag = false;
    var htmlEditor = false;
    var editLiveEditor = false;
    var jsEditor = false;

    // Will work as a flag to let preview code know if viewing a teacher page article/blog
    var ezeDesign = '';

    // Ajax dialog boxes - jQModal --------------------------------------------
    $('#ajaxDialog, #ajaxLoadingEIP').jqm({
      modal: true,
      overlay: 30,
      onShow: function(h) {
        h.w.fadeIn();
      },
      onHide: function(h) {
        h.w.stop().fadeOut();
        h.o.remove();
      }
    });
    // IE needs the dialogs to be at the same level in the DOM as the overlay - direct children of the body tag
    $('body').append($('.jqmWindow'));

    // OK button on Ajax dialog box
    $('#ajaxDialog input').click(function() {
      if (errFlag) {
        location.reload();
      } else if (socsSavingChanges) {
        // Choked while saving so unhide the EditLive applet
        if (editLiveEditor) $('#java-editor').css('visibility', '');
      }
    });

    // Adding icons to page and setting up event handlers for the icons -------

    // If viewing an article, the articleBody div will exist
    var $container = $('#articleBody');
    if ($container.length) {
      // Add the "EZ Edit" container and links to the div that was found.
      addIconsToPage('article', $container);

      // Edit in Place link
      $('#ezEdit a:first').click(function(e) {
        // Pass zero in the savingChanges argument - PHP code treats JavaScript FALSE as TRUE
        // JavaScript: editInPlace(e, false);
        // PHP: if ($savingChanges)
        // In PHP, the IF statement above is resolved as TRUE even though a JavaScript false was passed.
        // So, resort to zero = false, and non-zero = true
        editInPlace(e, 0);
      });

      // Delete link
      $('#ezEdit a:last').click(function(e) {
        deletePage('article', 'ezeArticle', e, $(this));
      });

    } else if (socsPageType === 'section') {
      $container = $('#mainContentBox .otherArt:first').parent();
      if ($container.length) addIconsToPage(socsPageType, $container);

    } else if (socsPageType === 'teacherpage' || socsPageType === 'teacherblog') {
      $container = $('#wrap9 #content3');
      if ($container.length) {
        // Extract the Teacher Page design from the URL - pass it along on the querystring for the link
        ezeDesign = window.location.href.match(/.*\/teacherpages\/(.*)\/default.css/)[1];

        addIconsToPage(socsPageType, $container, ezeDesign);

        if (socsPageType === 'teacherpage') {
          // Edit in Place link
          $('#ezEdit a:first').click(function(e) {
            editInPlace(e, 0);
          });

          // Delete link
          $('#ezEdit a:last').click(function(e) {
            deletePage('teacher page', 'ezeTPage', e, $(this));
          });
        }
      }
    }

    // Edit in Place button event handlers ------------------------------------

    // Submit buttons
    $('#eipSubmit, #eipSubmit2').click(function(e) {
      // Hide the EditLive applet - because the Ajax overlay and dialogs display "behind" it - not good.
      if (editLiveEditor) $('#java-editor').css('visibility', 'hidden');
      editInPlace(e, 1);
    });

    // Cancel buttons
    $('#eipCancel, #eipCancel2').click(function() {
      location.reload();
    });

    // Preview buttons
    $('#eipPreview, #eipPreview2').click(function() {
      if (ezeDesign) {
        // Preview teacher page article/blog
        socs_cssFile = '/teacherpages/' + ezeDesign + '/default.css';
        if (htmlEditor) {
          socsPreviewTP($('#eipHTMLArtText').val());
        } else if (jsEditor) {
          var txt = tinyMCE.activeEditor.getContent();
          txt = txt.replace(/<img.*socshelp\.fes\.org\/sharedimages\/image([23])tag\.gif.*\/>/g, '<image$1>');
          socsPreviewTP(txt);
        } else {
          editlivejava1.GetBody('socsPreviewTP', true);
        }
      } else {
        // Preview regular article
        if (htmlEditor) {
          socsPreview($('#eipHTMLArtText').val());
        } else if (jsEditor) {
          var txt = tinyMCE.activeEditor.getContent();
          txt = txt.replace(/<img.*socshelp\.fes\.org\/sharedimages\/image([23])tag\.gif.*\/>/g, '<image$1>');
          socsPreview(txt);
        } else {
          editlivejava1.GetBody('socsPreview', true);
        }
      }
    });

  });
})(jQuery);


