var popupWindow = null;

/* this allows toggling the overlay effect without having to create a WindowModal object tied to a modal popup */
var StaticOverlay = new Object();

StaticOverlay.activate = function() {
  if ( isIE )
  {
    this.prepareIE();
    this.hideSelects('hidden');
  }
  document.getElementById('overlay').style.display = 'block';
}.bind(StaticOverlay);

StaticOverlay.showPageDim = function() {
  if ( isIE )
  {
    this.prepareIE();
  }
  document.getElementById('overlay').style.display = 'block';
}.bind(StaticOverlay);

StaticOverlay.deactivate = function() {
  if ( isIE )
  {
    this.prepareIE();
    this.hideSelects('visible');
  }
  document.getElementById('overlay').style.display = 'none';
}.bind(StaticOverlay);

StaticOverlay.hidePageDim = function() {
  if ( isIE )
  {
    this.prepareIE();
  }
  document.getElementById('overlay').style.display = 'none';
}.bind(StaticOverlay);

	/*
	* This function fixes problem in IE with overlay layer height
	*/
StaticOverlay.prepareIE = function () {
  bod = document.getElementsByTagName('body')[0];
  document.getElementById('overlay').style.height = bod.scrollHeight+'px';
}.bind(StaticOverlay);

StaticOverlay.hideSelects = function ( visibility ) {
  if (isIE)
  {
    var selects = document.getElementsByTagName('select');
    for(i = 0; i < selects.length; i++)
    {
      if (!YAHOO.util.Dom.hasClass(selects[i], 'excludeFromIEHideSelects'))
      {
        selects[i].style.visibility = visibility;
      }
    }
  }
}.bind(StaticOverlay);

/*
* This simple Object is used for working of popup dialogs
* @param {mixed} HrefHTMLElement/null
*/
var WindowModal = function ( ctrl , isMovable, isModalPoupup)
{
  this.dimmer = new DynamicDimLayer();
  this.isDraggable = false;
  if ( ctrl )
	{
		this.ctrl		= ctrl;
		this.content 	= ctrl.href;
		ctrl.onclick 	= this.activate.bind(this);
		popupWindow		= this;
  }
    this.isMovable = (isMovable == undefined) ? false: isMovable;

  //after Load the Content to clear the dim Effect
    this.isModalPoupup = (isModalPoupup == undefined) ? true: isModalPoupup;
};

WindowModal.prototype = {

  setRefreshOnError: function(url)
  {
    this.refreshOnErrorUrl = url;
  },

  setDraggable: function(isDrag)
  {
    this.isDraggable = isDrag;
  },

  /*
	*	This method is used to get content for popup dialog and sets correct window position.
	*/
	getPage: function ()
	{
    //alert("about to send request to: "+ this.content);

    var popupCallback = {success:this.handlePopupSuccess.bind(this),failure:this.handlePopupFailure.bind(this)};
    vfAsyncRequest("GET",this.content, popupCallback);
	},

  handlePopupSuccess: function(response)
  {
    try
    {
      if (this.dimmer)
      {
        this.dimmer.clearPageDimEffect();
      }

      this.dimmer.hideMessage();
      
      document.getElementById('overlay').style.height = Math.max(document.body.clientHeight, document.documentElement.clientHeight)  + "px"
      document.getElementById('overlay').style.width =  Math.max(document.body.clientWidth, document.documentElement.clientWidth) + "px"
      var winObj = document.getElementById('window');
      // set the window dim effect to full document.
      if (this.isModalPoupup)
      {
        winObj.style.height = Math.max(document.body.clientHeight, document.documentElement.clientHeight) + "px"
        winObj.style.width = Math.max(document.body.clientWidth, document.documentElement.clientWidth) + "px"
      }
      
      winObj.innerHTML = "<div id='lbContent'>" + response.responseText + "</div>";
      winObj.className = "done";

      if(this.isMovable)
        winObj.style.position = "absolute";
      else
        winObj.style.position = "";

      var htmlContainer = document.getElementById('lbContent').getElementsByTagName('div');
      if (htmlContainer && htmlContainer[0])
      {
        var winWidth = htmlContainer[0].offsetWidth;
        var winHeight = htmlContainer[0].offsetHeight;
        // remove the dim effect and set the window object size fit to content loaded
        if (!this.isModalPoupup)
        {
          winObj.style.left = parseInt(Math.abs(document.body.clientWidth - winWidth) / 2) + 'px';
          winObj.style.top = parseInt(Math.abs(Math.min(document.body.clientHeight, document.documentElement.clientHeight) - winHeight) / 2) + this.docScrollTop() + 'px';
          htmlContainer[0].style.left = "0px";
          if(!this.isMovable)
          {
            winObj.style.width = winWidth + 'px';
            winObj.style.height = winHeight + 'px';
            this.dimmer.clearPageDimEffect();
          }
        }
        else
        {
          winObj.style.left = "0px";
          winObj.style.top = "0px";
          if (!htmlContainer[0].style.left)
          {
            htmlContainer[0].style.left = parseInt(Math.abs(document.body.clientWidth - winWidth) / 2) + 'px';
          }
          if (!htmlContainer[0].style.top)
          {
            if (isIE && (navigator.userAgent.toLowerCase().indexOf('msie 6') > -1))
            {
              htmlContainer[0].style.top = parseInt(Math.abs(Math.min(document.body.clientHeight, document.documentElement.clientHeight) - winHeight) / 2) + this.docScrollTop() + 'px';
            }
            else
            {
              htmlContainer[0].style.top = parseInt(Math.abs(Math.min(document.body.clientHeight, document.documentElement.clientHeight) - winHeight) / 2) + 'px';
            }
          }
          htmlContainer[0].style.visibility = 'visible';
          if (this.isDraggable)
          {
            dd = new YAHOO.util.DD(htmlContainer[0]);
          }
        }
      }
      
      shadow_configure(htmlContainer[0].id);


      var script = this.extractScripts(response.responseText);
      this.evalGlobally(script);
      this.actions();
    }
		catch (e)
    {
      if (this.refreshOnErrorUrl)
      {
        document.location.href=this.refreshOnErrorUrl;
      }
    }
  },

  handlePopupFailure: function()
  {

  },

  /*
	* This method is used to define scroll offset (used only in IE)
	*/
	docScrollTop: function()
	{
		if ( window.pageYOffset )
			return window.pageYOffset;
		else if ( document.documentElement && document.documentElement.scrollTop )
			return document.documentElement.scrollTop;
		else if ( document.body )
			return document.body.scrollTop;
		else
			return 0;
    },

	/*
	* Returns a String object containing all the <script /> blocks found in the text.
	* @param {String}	text
	* @return {String}
	*/
	extractScripts: function ( text )
	{
		var matchAll = new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'img');
		var matchOne = new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'im');
		if ( matchAll && text.match(matchAll) )
			return (text.match(matchAll)[0].match(matchOne)[1]);
		return '';
	},

	/*
	* Evaluates scripts
	* @param {String}	script
	*/
	evalGlobally: function ( script )
	{
		var ret;
		script = script.replace(/(^\s+)|(<!--)/gim, "");
		script = script.replace(/(\/\/-->)|(\s+$)/gim, "");
		if ( 0 < script.length )
		{
			try
			{
				ret = (window.execScript ? window.execScript(script) : (isSafari ? setTimeout(script, 0) : eval.apply(window, [script])));

			}
			catch(e)
			{
				alert(e);
			}
		}
		return ret;
	},

	/*
	* Shows popup dialog.
	*/
	activate: function()
	{
		if ( isIE )
		{
			this.hideSelects('hidden');
		}
		this.displayWindow("block");
		return false;
	},

	/*
	* This function is used for IE to hide selects HTML elements
	* @param {String}	hidden/visible
	*/
	hideSelects: function ( visibility )
	{
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++)
    {
      if (!YAHOO.util.Dom.hasClass(selects[i], 'excludeFromIEHideSelects'))
      {
        selects[i].style.visibility = visibility;
      }
    }
	},

	/*
	* Sets window visibility property
	* @param {String}	none/block
	*/
	displayWindow: function(display)
	{
		document.getElementById('overlay').style.display = display;
		document.getElementById('window').style.display = display;
		document.getElementById('window').innerHTML = '';
		if(display != 'none')
    {
      this.dimmer.showMessage();
      this.getPage();
    }
	},

	/*
	* Sets deactivate onclick events on HREF with REL=='deactivate'
	*/
	actions: function()
	{
		var closeActions = document.getElementsByTagName('A');
		for(i = 0; i < closeActions.length; i++) {
			if ( closeActions[i].rel == 'deactivate' )
			{
				closeActions[i].onclick = this.deactivate.bind(this);
			}
		}
	},

	/*
	* Hides popup dialog.
	*/
	deactivate: function()
	{
		if ( isIE )
		{
			this.hideSelects("visible");
		}
		this.displayWindow("none");
    WindowModal.closeCalendar();
    return false;
	}
};

WindowModal.closeCalendar = function()
{
  var calendar = document.getElementById("calContainer");
  if (calendar) {
    calendar.style.display = "none";
  }
}.bind(WindowModal);

/*
* Is used for quick initialization of HREF onclick events.
* If HREF has REL attribute and REL=='showWindow', popup dialog will be displayed
*/
function initializeWindow()
{
	addWindowModal();
	var w = document.getElementsByTagName('A');
	for ( i = 0; i < w.length; i++ ) {
		if ( w[i].rel == 'showWindow' )
		{
			new WindowModal(w[i]);
		}
    if ( w[i].rel == 'showMovableWindow' )
		{
      new WindowModal(w[i], true, false);     
    }
  }
}

/*
* Is used to create overlay HTML element in DOM
*/
function addWindowModal()
{
	var bod 				= document.getElementsByTagName('body')[0];
  // for every initialize window call, a overlay element and window element will be created.
  // This leads to duplication of overlay and window elements. This will happen when we have multiple handlers
  // when the overlay div element is already available in document, we do not need to create a duplicate
  if (!document.getElementById('overlay'))
  {
    var overlay 			= document.createElement('div');
    overlay.id			= 'overlay';
    bod.appendChild(overlay);
  }
  // when the window div element is already available in document, we do not need to create a duplicate
  if (!document.getElementById('window'))
  {
    var win				= document.createElement('div');
    win.id				= 'window';
    win.className 		= 'loading';
    bod.appendChild(win);
  }
}

function shadow_configure(elem_id){
        var elem = document.getElementById(elem_id);
        var ieWidthFix = 0;
        //if (isIE && (navigator.userAgent.toLowerCase().indexOf('msie 6') > -1)) ieWidthFix = 4;

        if (elem){

                // adjust width for child elements
                elems = elem.getElementsByTagName("div");

                if (elems) {
                        for (var i = 0; i < elems.length; i++) {
                                if ((elems[i].className == 'popup-tc') || (elems[i].className == 'popup-bc')) {
                                        elems[i].style.width = (elem.offsetWidth - 16) + 'px';
                                }

                                /* opera */
                                if (isOpera) {
                                        if ((elems[i].className == 'popup-bottom')) {
                                                elems[i].style.width = (elem.offsetWidth) + 'px';
                                        }
                                }
                                else{
                                        if ((elems[i].className == 'popup-top') || (elems[i].className == 'popup-bottom')) {
                                                elems[i].style.width = (elem.offsetWidth) + 'px';
                                        }
                                }

                                if ((elems[i].className == 'popup-bc')) {
                                        elems[i].style.width = (elem.offsetWidth-16) + 'px';
                                }




                        }
                }
        }
}