//See bottom for notes
function initYUIWindows() {
  var page_divs = document.getElementsByTagName('div');
  var yui_win, win_title;
  var page_panel_ids = {};
  if (page_divs && page_divs.length > 0) {
    for ( var i = 0 ; i < page_divs.length ; i++) {
      yui_win = page_divs[i].getAttribute('yui_win');
      if (page_divs[i].id && page_divs[i].id.length > 0 && page_divs[i].id.indexOf('help') == -1 && yui_win && yui_win.length > 0) {
        win_settings = eval("win_settings = " + yui_win + ";");
        if (!win_settings.constraintoviewport) {
          win_settings.constraintoviewport = true;
        }
        page_panel_ids[page_divs[i].id] = win_settings;
      }
    }
  }
  for (i in page_panel_ids) {
    win_title = '';
    if (page_panel_ids[i].title && page_panel_ids[i].title.length > 0) {
      win_title = page_panel_ids[i].title;
    }
    page_panels[i + '_win'] = {
      'window' : addYUIWin(i, win_title, page_panel_ids[i]),
      'settings' : page_panel_ids[i]
    };
  }
  allHiddenCheck();
  // Make window layering match settings
  var window_layers = [];
  for ( var i in current_iwp) {
    if (parseInt(current_iwp[i].initial_layer_level) > 0 && page_panels[i]) {
      window_layers[parseInt(current_iwp[i].initial_layer_level)] = i;
    }
  }
  for (i = window_layers.length - 1 ; i > 0 ; i--) {
    if (typeof current_iwp[window_layers[i]] != "undefined" && (!current_iwp[window_layers[i]].visible || current_iwp[window_layers[i]].visible == "true")) {
      page_panels[window_layers[i]].window.bringToTop();
    }
  }
  initTinyMCEWins();
}
function addYUIWin(window_id, header_text, settings) {
  var window_id_window = window_id + '_win';
  if (!$(window_id_window)) {
    var new_win = document.createElement("DIV");
    new_win.id = window_id_window;
    new_win.className = 'panel_window';
    document.body.appendChild(new_win);
  }
  if (typeof current_iwp[window_id_window] == 'object') {
    // Window settings exist
    if (current_iwp[window_id_window].x) {
      settings.x = parseInt(current_iwp[window_id_window].x);
    }
    if (current_iwp[window_id_window].y) {
      settings.y = parseInt(current_iwp[window_id_window].y);
    }
    if (current_iwp[window_id_window].height) {
      settings.height = current_iwp[window_id_window].height + "px";
    }
    if (current_iwp[window_id_window].width) {
      settings.width = current_iwp[window_id_window].width + "px";
    }
    if (current_iwp[window_id_window].visible) {
      settings.visible = current_iwp[window_id_window].visible == "true";
    }
  } else {
    // Need to enter default settings
    if (typeof settings != 'object') {
      settings = {};
    }
    if (typeof settings.close == 'undefined') {
      settings.close = true;
    }
    if (typeof settings.fixedcenter == 'undefined' && typeof settings.x == 'undefined' && typeof settings.xy == 'undefined') {
      settings.x = 10;
    }
    if (typeof settings.fixedcenter == 'undefined' && typeof settings.y == 'undefined' && typeof settings.xy == 'undefined') {
      settings.y = 40;
    }
    if (typeof settings.height == 'undefined') {
      settings.height = "300px";
    }
    if (typeof settings.width == 'undefined') {
      settings.width = "600px";
    }
    if (typeof settings.autofillheight == 'undefined') {
      settings.autofillheight = "body";
    }
  }
  var oPanel = new YAHOO.widget.Panel(window_id_window, settings);

  oPanel.setHeader(header_text);
  try {
    oPanel.setBody($(window_id).innerHTML);
    if (typeof settings.footer == 'undefined') {
      settings.footer = '';
    }
    oPanel.setFooter(settings.footer);
  
    oPanel.render();
  } catch (e) {
    return;
  }

  if (typeof settings.x != 'undefined') {
    oPanel.cfg.setProperty("x", settings.x);
  }
  if (typeof settings.y != 'undefined') {
    oPanel.cfg.setProperty("y", settings.y);
  }

  oPanel.bringToTop();

  if (!panelOverlayManager) {
    panelOverlayManager = new YAHOO.widget.OverlayManager();
  }

  panelOverlayManager.register(oPanel);
  if ((!settings.draggable || settings.draggable == true) && oPanel.dd) {
    oPanel.dd.on('startDragEvent', function() {
      constrainPanel(oPanel, {
        top : 30
      });
    });

    oPanel.dd.subscribe('endDragEvent', function(args) {
      if (!current_iwp[this.id]) {
        current_iwp[this.id] = {};
      }
      current_iwp[this.id].x = this.cfg.config.x.value;
      current_iwp[this.id].y = this.cfg.config.y.value;
      saveAsCookie();
    }, oPanel, true);
  }

  oPanel.beforeShowEvent.subscribe(function(args) {
    // Update cookie
    if (!current_iwp[this.id]) {
      current_iwp[this.id] = {};
    }
    current_iwp[this.id].visible = true;
    this.focus();
    // Need to check fo the dialogs_closed_help_win and remove
    var dialog_closed_win = panelOverlayManager.find('dialogs_closed_help_win');

    if (dialog_closed_win != null) {
      dialog_closed_win.hide();
    }
  });
  oPanel.beforeHideEvent.subscribe(function(args) {
    // Update cookie
    if (!current_iwp[this.id]) {
      current_iwp[this.id] = {};
    }
    current_iwp[this.id].visible = false;
    saveAsCookie();
    allHiddenCheck();
  });
  oPanel.focusEvent.subscribe(panelFocused);

  var resize = new YAHOO.util.Resize(window_id_window, {
    handles : [ "br" ],
    autoRatio : false,
    minWidth : (parseInt(settings.minWidth) > 0 ? settings.minWidth : 300),
    minHeight : (parseInt(settings.minHeight) > 0 ? settings.minHeight : 200),
    status : false
  });

  resize.on("startResize", function(args) {
    if (this.cfg.getProperty("constraintoviewport")) {
      var D = YAHOO.util.Dom;

      var clientRegion = D.getClientRegion();
      var elRegion = D.getRegion(this.element);

      resize.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
      resize.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
    } else {
      resize.set("maxWidth", null);
      resize.set("maxHeight", null);
    }
  }, oPanel, true);

  resize.on("resize", function(args) {
    var panelHeight = args.height;
    this.cfg.setProperty("height", panelHeight + "px");
  }, oPanel, true);

  resize.on("endResize", function(args) {
    if (!current_iwp[this.id]) {
      current_iwp[this.id] = {};
    }
    current_iwp[this.id].height = args.height;
    current_iwp[this.id].width = args.width;
    saveAsCookie();
    if (page_panels[this.id].settings.onResize && window[page_panels[this.id].settings.onResize]) {
      window[page_panels[this.id].settings.onResize](this);
    }
  }, oPanel, true);

  // Now, delete the original window DIV $(window_id)

  if ($(window_id) && $('page_windows')) {
    $('page_windows').removeChild($(window_id));
  }

  if (settings.onRender && window[settings.onRender]) {
    window[settings.onRender](oPanel);
  }

  return oPanel;
}
function $(id) {
  return document.getElementById(id);
}
function objectToString(obj) {
  var asString = '';

  if (typeof obj == 'object') {
    var obj_prefix = '';
    for ( var i in obj) {
      if (typeof obj[i] == 'object') {
        asString += obj_prefix + i + ':{' + objectToString(obj[i]) + '}';
      } else {
        asString += obj_prefix + i + ':"' + obj[i] + '"';
      }
      obj_prefix = ',';
    }
  } else {
    asString = obj;
  }

  return asString;
}
function saveAsCookie() {
  var cookie_expires = new Date();
  cookie_expires = new Date(cookie_expires.valueOf() + 60 * 60 * 24 * 180 * 1000); // Expires in 180 days

  YAHOO.util.Cookie.set("win_settings", '{' + objectToString(current_iwp) + '}', {
    expires : cookie_expires
  });
}
function allHiddenCheck() {
  // Check for all panels hidden
  var all_hidden = true;
  for ( var i in page_panels) {
    if (page_panels[i].window.cfg.getProperty("visible") == true) {
      all_hidden = false;
      break;
    }
  }
  if (all_hidden) {
    // First, check to see if this has already been shown
    var dialog_closed_win = panelOverlayManager.find('dialogs_closed_help_win');

    if (dialog_closed_win != null) {
      dialog_closed_win.show();
      return;
    }
    // Create a dialog showing the windows
    if ($('page_windows') && !$('dialogs_closed_help')) {
      var new_win = document.createElement("DIV");
      new_win.id = 'dialogs_closed_help';
      new_win.className = 'window_text';
      new_win.innerHTML = '<p>All windows have been closed!  If you need to get them back, click the <img src="../images/favicon.png" height="16"/> icon in the upper-left hand corner.</p>';
      $('page_windows').appendChild(new_win);
    }
    addYUIWin('dialogs_closed_help', 'All Windows Closed :: Help', {
      fixedcenter : true,
      draggable : false,
      close : false
    });
  }
}
function panelFocused() {
  if (!current_iwp[this.id]) {
    current_iwp[this.id] = {};
  }
  var window_layers = [];
  for ( var i in current_iwp) {
    if (page_panels[i]) {
      if (i != this.id) {
        if (window_layers[parseInt(current_iwp[i].initial_layer_level)] || parseInt(current_iwp[i].initial_layer_level) < 1) {
          window_layers[parseInt(window_layers.length) * -1] = i;
        } else {
          window_layers[parseInt(current_iwp[i].initial_layer_level)] = i;
        }
      }
    }
  }
  var active_layer = 2;
  for (i in window_layers) {
    current_iwp[window_layers[i]].initial_layer_level = active_layer;
    active_layer++;
  }
  current_iwp[this.id].initial_layer_level = 1;
  saveAsCookie();
}
function initTinyMCEWins() {
  tinyMCE
      .init({
        mode : "specific_textareas",
        editor_selector : "textarea_editable",
        theme : "advanced",
        theme_advanced_buttons1 : "cut,copy,paste,pastetext,pasteword,|,outdent,indent,blockquote,|,undo,redo,|,code,|,forecolor,backcolor",
        theme_advanced_buttons2 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink,|,formatselect,fontselect,fontsizeselect,|,charmap,emotions",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom"
      });
}
/*
 * var win_settings = { close:true, draggable:true, dragOnly:false, keylisteners:null, modal:false, underlay:"shadow", //shadow, matte, none effect:null, //
 * effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration: 1} // effect:{effect:YAHOO.widget.ContainerEffect.SLIDE, duration: 1} monitorresize:true,
 * visible:true, autofillheight:null, //header, body, footer constraintoviewport: true, context:null, /* context - Array
 * 
 * The array of context arguments for context-sensitive positioning.
 * 
 * The format of the array is: [contextElementOrId, overlayCorner, contextCorner, arrayOfTriggerEvents (optional), xyOffset (optional)], the the 5 array
 * elements described in detail below:
 * 
 * contextElementOrId <String|HTMLElement> A reference to the context element to which the overlay should be aligned (or it's id). overlayCorner <String> The
 * corner of the overlay which is to be used for alignment. This corner will be aligned to the corner of the context element defined by the "contextCorner"
 * entry which follows. Supported string values are: "tr" (top right), "tl" (top left), "br" (bottom right), or "bl" (bottom left). contextCorner <String> The
 * corner of the context element which is to be used for alignment. Supported string values are the same ones listed for the "overlayCorner" entry above.
 * arrayOfTriggerEvents (optional) <Array[String|CustomEvent]>
 * 
 * By default, context alignment is a one time operation, aligning the Overlay to the context element when context configuration property is set, or when the
 * align method is invoked. However, you can use the optional "arrayOfTriggerEvents" entry to define the list of events which should force the overlay to
 * re-align itself with the context element. This is useful in situations where the layout of the document may change, resulting in the context element's
 * position being modified.
 * 
 * The array can contain either event type strings for events the instance publishes (e.g. "beforeShow") or CustomEvent instances. Additionally the following 3
 * static container event types are also currently supported : "windowResize", "windowScroll", "textResize" (defined in _TRIGGER_MAP private property). xyOffset
 * <Number[]> A 2 element Array specifying the X and Y pixel amounts by which the Overlay should be offset from the aligned corner. e.g. [5,0] offsets the
 * Overlay 5 pixels to the left, after aligning the given context corners. NOTE: If using this property and no triggers need to be defined, the
 * arrayOfTriggerEvents property should be set to null to maintain correct array positions for the arguments.
 * 
 * For example, setting this property to ["img1", "tl", "bl"] will align the Overlay's top left corner to the bottom left corner of the context element with id
 * "img1".
 * 
 * Setting this property to ["img1", "tl", "bl", null, [0,5] will align the Overlay's top left corner to the bottom left corner of the context element with id
 * "img1", and then offset it by 5 pixels on the Y axis (providing a 5 pixel gap between the bottom of the context element and top of the overlay).
 * 
 * Adding the optional trigger values: ["img1", "tl", "bl", ["beforeShow", "windowResize"], [0,5]], will re-align the overlay position, whenever the
 * "beforeShow" or "windowResize" events are fired. Default Value: null
 */
/*
 * fixedcenter: false, //true, false, "contained"=>not get automatically centered when the user scrolls or resizes the window height:null,
 * preventcontextoverlap:false, width: null, x:null, xy:null, // null, [] y:null, zIndex: null };
 */
