/*
 *  $Id: dipity.js 7570 2009-08-07 20:19:26Z bag $
 *
 *  Copyright (c) 2008 Underlying Inc. All rights reserved.
 */

PopupDialog = function(args)
{
  var hash = args.hash;
  var width = args.width;
  var height = args.height;
  var url = args.url;
  var top_offset = args.top_offset;
  var popup_align = args.popup_align;
  var onclose = args.onclose;
  var onopen = args.onopen;
  var wc = ' ' + args.windowclass;
  var shade_id = 'modal_dialog_shade' + hash;
  var container_id = 'modal_dialog_container' + hash;
  var container_class = 'modal_dialog_container' + wc;
  var container_style = args.windowstyle;
  var receiver_url = args.receiverurl;
  var is_modal = args.ismodal;
  var content_scrolling = 0;
  var anchor_left_offset = args.left_offset;
  var anchor_top_offset = args.top_offset;

  var this_obj = this; // for closures
  var elems = {};
  var default_width = 575;
  var default_height = 455;
  var default_top_offset = 24;
  var client_state = null;
  var first = 1;
  var popup_open = 0;
  var popup_prepared = 0;
  var max_shade_opacity = 0.5;
  var show_loading = args.showloading;

  this.setUrl = function(arg_url) {
    url = arg_url;
  }

  this.prepareOpen = function() {
    if (show_loading) {
      elems.container.style.visibility = "visible";
      var doc = elems.iframe.contentDocument;
      if (doc == undefined || doc == null) {
        doc = elems.iframe.contentWindow.document;
      }
      doc.open();
      var html = [
        '<html xmlns="http://www.w3.org/1999/xhtml">',
        '  <body style="background:white;margin:0; padding:0;">',
        '    <div style="text-align:center; margin-top:48px; font-size:24px; color:#999; font-family:Arial;">',
        '      Loading...',
        '    </div>',
        '  </body>',
        '</html>'
      ].join('');
      doc.write(html);
      doc.close();

      this.resize(0);
      popup_prepared = 1;
      this.open();
    } else {
      elems.container.style.visibility = "hidden";
    }
    elems.container.style.display = "block";
    elems.iframe.src = url;

    if (is_modal) {
      var shade_attributes = { opacity: { 'from':0, 'to':max_shade_opacity } };
      var shadeAnim = new YAHOO.util.Anim(elems.shade, shade_attributes, 0.05);
      elems.shade.style.display = 'block';
      shadeAnim.animate();
    }
    
    popup_prepared = 1;
  };

  this.open = function() {
    if (popup_open === 1) { return; }
    popup_open = 1;

    if (!popup_prepared) {
      this.prepareOpen();
    }

    YAHOO.util.Dom.setStyle(elems.container, 'visibility', 'visible');
    YAHOO.util.Dom.setStyle(elems.iframe, 'opacity', 1);

    this.doFadeAnimation(elems.container, true);

    if (typeof onopen == "string" && onopen.length) {
      eval(onopen);
    } else if (typeof onopen == "function") {
      onopen();
    }
  };

  this.close = function() {
    if (is_modal) {
      var shade_attributes = { opacity: { 'from':max_shade_opacity, 'to':0 } };
      var shadeAnim = new YAHOO.util.Anim(elems.shade, shade_attributes, 0.25, YAHOO.util.Easing.easeOut);
      shadeAnim.onComplete.subscribe( function() { elems.shade.style.display = 'none'; } );
      shadeAnim.animate();
    }
    this.doFadeAnimation(elems.container, false, function() { this_obj.really_close() });
  };

  this.really_close = function() { 
    elems.iframe.src = "about:blank";
    elems.container.style.display = "none";
    popup_prepared = 0;
    YAHOO.util.Event.removeListener(elems.close, "click");

//     console.log("client_state[" + client_state + "] client_state.numValues[" + (client_state ? client_state.numValues() : "") + "]");
    var callback = function() {
      if (typeof onclose == "string" && onclose.length) {
        eval(onclose);
      } else if (typeof onclose == "function") {
        onclose();
      }
    }

    if (client_state && client_state.numValues()) {
      if (!receiver_url) {
        console.log("ERROR client state with no receiver set!");
      }
      else {
        client_state.send(receiver_url, callback);
      }
    }
    else {
      callback();
    }

    popup_open = 0;
  };

  this.doFadeAnimation = function(elem, fadeIn, callback) {
    // fade animation on IE breaks the user content div which
    // carries the tooth for bubble popups. only fade for the
    // standard popup, which makes the "standard" css class
    // selector special.  yuck!
    if (container_class.indexOf("standard") >= 0) {
      var attributes = fadeIn ? { opacity: { 'from':0, 'to':1.0 } } : { opacity: { 'from':1.0, 'to':0 } };

      var anim = new YAHOO.util.Anim(elem, attributes, 0.25, YAHOO.util.Easing.easeOut); 
      if (typeof callback == "function") {
        anim.onComplete.subscribe(callback);
      }
      anim.animate();
    }
    else {
      YAHOO.util.Dom.setStyle(elem, 'opacity', 1.0);
      if (typeof callback == "function") {
        callback();
      }
    }
  };

  this.resize = function(animate) {
    // resize elements
    if (animate && !first) {
      var container_attributes = { 
        width:  { 'to':this.getWidth() },
        height: { 'to':this.getHeight() }
        }; 
      var content_attributes = { 
        width:  { 'to':this.getWidth() },
        height: { 'to':this.getHeight() }
        }; 
      var containerAnim = new YAHOO.util.Anim(elems.container, container_attributes, 0.1, YAHOO.util.Easing.easeOut); 
      containerAnim.animate(); 
      var contentAnim = new YAHOO.util.Anim(elems.content, content_attributes, 0.1, YAHOO.util.Easing.easeOut); 
      contentAnim.animate(); 
      var iframeAnim = new YAHOO.util.Anim(elems.iframe, content_attributes, 0.1, YAHOO.util.Easing.easeOut); 
      iframeAnim.animate(); 
    } else {
      elems.container.style.width  = this.getWidth() + "px";
      elems.container.style.height = this.getHeight() + "px";
      elems.content.style.width    = this.getWidth() + "px";
      elems.content.style.height   = this.getHeight() + "px";
      elems.iframe.style.width     = this.getWidth() + "px";
      elems.iframe.style.height    = this.getHeight() + "px";
    }

    // XXX: the declarations (or lack of) popup_left and popup_top
    // are significant to the positioning behavior of dialogs when
    // containerObj.do_layout() is called.  DO NOT define either
    // unless that axis should be positioned, which is NOT the case
    // in general.
    var popup_left = 0;
    var popup_top = 0;
    if (!args.anchor) {
      // position elements if we're centering on page
      popup_left = -1 * Math.round(this.getWidth() / 2);
      popup_top = YAHOO.util.Dom.getDocumentScrollTop() + top_offset;
    } else {
      var region = YAHOO.util.Dom.getRegion(args.anchor);
      popup_left = region.left;
      popup_top = region.top;
      if (popup_align) {
        if (popup_align.vertical) {
          if (popup_align.vertical == 'middle') {
            popup_top -= parseInt(this.getHeight() / 2);
          } else if (popup_align.vertical == 'bottom') {
            popup_top -= this.getHeight();
          }
        }
        if (popup_align.horizontal) {
          if (popup_align.horizontal == "center") {
            popup_left -= parseInt(this.getWidth() / 2);
          } else if (popup_align.horizontal == 'right') { 
            popup_left -= this.getWidth();
          }
        }
      }
      else {
        if (args.anchor) {
          if (typeof(anchor_left_offset) != "undefined") { popup_left += anchor_left_offset; }
          if (typeof(anchor_top_offset) != "undefined")  { popup_top += anchor_top_offset;   }
          // alert("popup_left[" + popup_left + "] popup_top[" + popup_top + "]");
        }
      }
    }

    containerObj.do_layout({ left: popup_left, top: popup_top }, animate);
 
    first = 0;
  };

  this.setOnOpen = function(script) {
    onopen = script;
  }

  this.setOnClose = function(script) {
    onclose = script;
  }

  this.getWidth = function() {
    if (width) {
      return width;
    }
    return default_width;
  };

  this.setWidth = function(val) {
    width = val;
  };
  
  this.setTopOffset = function(val) {
    top_offset = val;
  }
  
  this.getTopOffset = function() {
    if (top_offset) {
      return top_offset;
    }
    return default_top_offset;
  }

  this.getHeight = function() {
    if (height) {
      return height;
    }
    return default_height;
  };

  this.setHeight = function(val) {
    var max_height = null;
    if (document.body.style.overflow == "hidden" || document.body.style.overflowY == "hidden")
    {
      var window_height = null;
      if (window.innerHeight) {
        window_height = window.innerHeight;
      } else if (document.body.offsetHeight) {
        window_height = document.body.offsetHeight;
      }

      if (window_height) {
        max_height = window_height - (window_height > 475 ? 20 : 0);
        if (elems.anchor) {
          var anchorRegion = YAHOO.util.Dom.getRegion(args.anchor);
          if (popup_align && popup_align.vertical == "middle") {
            max_height = Math.min(anchorRegion.top, max_height - anchorRegion.top) * 2;
          } else {
            max_height -= anchorRegion.top;
          }
        }
      }
    }

    if (max_height && val > max_height) {
      val = max_height;
      content_scrolling = 1;
    } else {
      content_scrolling = 0;
    }
    height = val;
  }

  this.isContentScrolling = function() {
    return (content_scrolling == 1);
  }

  this.getClientState = function() {
    if (!client_state) {
      client_state = new ClientState();
    }
    return client_state;
  }

  elems.anchor = null;
  if (false && args.anchor) {
    elems.anchor = document.getElementById(args.anchor);
  }
  else {
    var div = document.createElement("div");
    div.id = 'modal_dialog_anchor' + hash;
    div.className = 'modal_dialog_anchor' + wc + (args.anchor ? " modal_dialog_anchor_anchored" : "");

    var body = document.getElementsByTagName("body")[0];
    body.insertBefore(div, body.firstChild);
    elems.anchor = document.getElementById('modal_dialog_anchor' + hash);
  }

  var contentMarkup = [
    '<div id="modal_dialog', hash, '" class="modal_dialog' + wc + '">',
    '  <iframe id="modal_dialog_iframe', hash, '" name="', hash, '" ',
    '    class="modal_dialog_iframe', wc, '" frameborder="0" scrolling="no"></iframe>',
    '</div>'
  ].join("");

  var containerObj = new Container(shade_id, container_id, container_class, wc, container_style, contentMarkup, elems.anchor);

  elems.content = document.getElementById('modal_dialog' + hash);
  elems.iframe = document.getElementById('modal_dialog_iframe' + hash);
  elems.shade = containerObj.getShadeElem();
  elems.container = containerObj.getContainerElem();

  dipity.dialogs[hash] = this;
};

Container = function(shade_id, container_id, container_class, selectors, container_style, html, parent_elem)
{
  var this_obj = this;
  var first = 1;
  var attribs = {};

  this.do_layout = function(offset_obj, animate)
  {
    if (typeof(offset_obj.left) != "undefined") {
      if (animate && !first) {
        attribs.left = { 'to':offset_obj.left }; 
      } else {
        container_elem.style.left = parseInt(offset_obj.left) + "px";
      }
    }
      
    if (typeof(offset_obj.top)  != "undefined") {
      if (animate && !first) {
        attribs.top = { 'to':offset_obj.top }; 
      } else {
        container_elem.style.top = parseInt(offset_obj.top) + "px";
      }
    }

    if (animate && !first && (attribs.left || attribs.top)) {
      var posAnim = new YAHOO.util.Anim(container_elem, attribs, 0.25, YAHOO.util.Easing.easeOut); 
      posAnim.animate(); 
    }

    first = 0; // we don't want the first layout to get animated
  };

  this.getContainerElem = function() {
    return container_elem;
  };

  this.getShadeElem = function() {
    return shade_elem;
  };

  //var divForIE = document.createElement("DIV");
  //divForIE.style.width = "0px";
  //divForIE.style.height = "0px";

  var class_sel = container_class + ' ' + selectors;
  parent_elem.innerHTML = [
    '<div class="modal_dialog_shade" id="', shade_id, '"></div>',
    '<div id="', container_id, '" class="', class_sel, '" style="', container_style, '">',
    ' <div class="modal_dialog_user_div', selectors, '"></div>',
      html,
    '</div>'
  ].join("");

  //if (parent_elem.firstChild) {
  //  parent_elem.insertBefore(divForIE, parent_elem.firstChild);
  //}
  //else {
  //  parent_elem.appendChild(divForIE);
  //}
  var container_elem = document.getElementById(container_id);
  var shade_elem = document.getElementById(shade_id);

  YAHOO.util.Dom.setStyle(container_elem, 'opacity', 0);
  YAHOO.util.Dom.setStyle(shade_elem, 'opacity', 0);
};

ClientState = function()
{
  this.setValue = function(name, val)
  {
    if (typeof(form.elements[name]) != "undefined" && name.indexOf("[]") < 0) {
      form.elements[name].value = val;
    }
    else {
      var input = document.createElement("INPUT");
      input.type = "hidden";
      input.name = name;
      input.value = val;
      form.appendChild(input);
    }
  };

  this.unsetValue = function(name, val)
  {
    if (typeof(form.elements[name]) != "undefined") {
      if (form.elements[name] instanceof NodeList) {
        var list = form.elements[name];
        for (i = 0; i < list.length; i++) {
          if (list.item(i).value == val) {
            form.removeChild(list.item(i));
          }
        }
      }
      else {
        form.removeChild(form.elements[name]);
      }
    }
  };

  this.hasValue = function(name, val)
  {
    if (typeof(form.elements[name]) != "undefined") {
      if (form.elements[name] instanceof NodeList) {
        var list = form.elements[name];
        for (i = 0; i < list.length; i++) {
          if (list.item(i).value == val) {
            return true;
          }
        }
      }
      else {
        if (form.elements[name].value == val) {
          return true;
        }
      }
    }
    return false;
  };

  this.getValue = function(name)
  {
    if (typeof(form.elements[name]) == "undefined") {
      return false;
    }
    return form.elements[name].value;
  };

  this.numValues = function()
  {
    return form.elements.length;
  };

  this.send = function(receiverUrl, completedCallback)
  {
    this.completedCallback = completedCallback;
    YAHOO.util.Connect.setForm(form); 
    var callback = {
      success: function(o) { this_obj.processResponse(o); },
      failure: function(o) { this_obj.processError(o); }
    };
    YAHOO.util.Connect.asyncRequest('POST', receiverUrl, callback);
  };

  this.processError = function(o)
  {
    console.error("ClientState HTTP Error", o);
    this.clear();
    this.doCompletedCallback();
  };

  this.processResponse = function(o)
  {
    if (o.responseText) {
      var response = eval('(' + o.responseText + ')');
      if (response.status == 'success') {
        if (typeof response['eval'] != "undefined") {
          eval(response['eval']);
        }
      }
      else {
        console.error("ClientState Form Error", o);
      }
    }
    this.clear();
    this.doCompletedCallback();
  };

  this.doCompletedCallback = function()
  {
    if (typeof this.completedCallback == "function") {
      this.completedCallback();
    }
  }

  this.clear = function()
  {
    var body = document.getElementsByTagName("body")[0];
    if (form) {
      body.removeChild(form);
    }
    form = document.createElement("FORM");
    body.appendChild(form);
  };

  var form = null;
  var this_obj = this; // for closures

  // initialize
  this.clear();
};

if (dipity.curr_login !== "" && 
    window.opener && 
    typeof(window.opener.dipity) != "undefined" && 
    window.opener.dipity.curr_login === "") 
{
  window.opener.location.reload(false);
}

// queued update stuffff
function pollQueuedUpdate()
{
  var callback = { 
    success:checkQueuedUpdate,
    failure:function() {}
  };
  YAHOO.util.Connect.asyncRequest('GET', dipity.base_url + "/check_timeline_update_time?tidarr=" + dipity.tid + "&from_ts=" + dipity.request_time, callback);
}
function checkQueuedUpdate(d)
{
  var o = eval("(" + d.responseText + ")");
  if (typeof(o.status) != 'undefined') {
    if (o.status === 0) {
      setTimeout(pollQueuedUpdate, 5000);
      return;
    } 
    var spinner_elem = document.getElementById('queued_update_spinner');
    if (spinner_elem) {
      spinner_elem.style.display = 'none';
    }
    tl.refresh();
  }
}
