var _ezPopup_tracker = null;
var _PopupDiv;
var _PopupDivID;
var _IncludeCloseButton;
var _IAmClosing = false;

function ezPopupShowURL(URL, IncludeCloseButton) {

    // We are  not passing in any div to use as the Popup.
    // However, we need SOMETHING to be the Popup, so we are using MainMaster_ezPopupShowURL - which is a div on the master page.

    _PopupDivID = "MainMaster_ezPopupShowURL";
    _PopupDiv = document.getElementById(_PopupDivID);
    _IncludeCloseButton = IncludeCloseButton;

    top.Communicator.AddRequest("item", "HandleModalResponse", URL, null);

}

function ezPopupShowiFrame(URL, IncludeCloseButton) {

    // We are  not passing in any div to use as the Popup.
    // However, we need SOMETHING to be the Popup, so we are using MainMaster_ezPopupShowiFrame - which is a div on the master page.
    _PopupDivID = "MainMaster_ezPopupShowiFrame";
    _PopupDiv = document.getElementById(_PopupDivID);

    _IncludeCloseButton = IncludeCloseButton;

    var sGuid = NewGuid();
    //_PopupDiv.innerHTML = "<iframe ezPopupType='iframe' src='" + URL + "' width='100%' height='100%' scrolling='yes' frameborder='0' onload='ezPopupResizeiFrame(this)' />"
    _PopupDiv.innerHTML = "<iframe ezPopupType='iframe' id='" + sGuid + "' src='" + URL + "' width='100%' height='100%' scrolling='yes' frameborder='0' onload='ezPopupResizeiFrame(this)' />"

    Prepare_PopupDiv();

}

function ezPopupShowDiv(PopupDivID, IncludeCloseButton) {

    _PopupDivID = PopupDivID;
    _PopupDiv = document.getElementById(_PopupDivID);
    _IncludeCloseButton = IncludeCloseButton;

    Prepare_PopupDiv();
    CenterTheDiv(_PopupDiv)
}

function ezPopupShowDivWithURL(PopupDivID, URL, IncludeCloseButton) {

    _PopupDivID = PopupDivID;
    _PopupDiv = document.getElementById(_PopupDivID);
    _IncludeCloseButton = IncludeCloseButton;

    top.Communicator.AddRequest("item", "HandleModalResponse", URL, null);

}

function Prepare_PopupDiv() {

    var zIndexToUse = 2000;

    var arr = new Array();
    arr = document.getElementsByTagName("div");
    for (var i = 0; i < arr.length; i++) {
        var obj = arr[i];
        if (obj.id.indexOf('_ezPopupBackground') > -1) {
            if (obj.style.zIndex >= zIndexToUse) zIndexToUse = obj.style.zIndex + 2;
        }
    }

    _PopupDiv.style.display = "block";
    _PopupDiv.style.zIndex = zIndexToUse + 1;


    ////////////////////////////////////////////////////////////
    // Put close button on div - it should not already be there
    ////////////////////////////////////////////////////////////

    if (_IncludeCloseButton) {

        // Can't use getElementById on _PopupDiv
        var foundCloseButton = false;
        arr = _PopupDiv.getElementsByTagName("a");
        for (var i = 0; i < arr.length; i++) {
            var obj = arr[i];
            if (obj.id == 'ezPopupCloseButton') foundCloseButton = true;
        }

        if (!foundCloseButton) {

            var btn = document.createElement('a');

            btn.id = 'ezPopupCloseButton';
            btn.className = 'ezPopupCloseButton';
            btn.setAttribute('href', '#');
            btn.setAttribute('onclick', 'javascript:ezPopupHideDiv("' + _PopupDivID + '")');
            btn.style.zIndex = zIndexToUse + 1;

            _PopupDiv.appendChild(btn);

        }
    }

    ////////////////////////////////////////////////////////////////////////////
    // Put the background div in the document - it should not already be there
    ////////////////////////////////////////////////////////////////////////////
    ezPopupKillBackgroundDiv(_PopupDivID);  // do this just in case

    var bgDiv = document.createElement('div');

    bgDiv.id = _PopupDivID + '_ezPopupBackground';
    bgDiv.className = 'ezPopupBackground';
    bgDiv.style.zIndex = zIndexToUse;
    bgDiv.style.display = "block";

    _PopupDiv.parentNode.appendChild(bgDiv);


    /////////////////////////////////////////////////////////
    // Make the popup draggable
    /////////////////////////////////////////////////////////
    _PopupDiv.handlerobj = new ezPopupMakeMoveable(_PopupDiv);
    
}

function ezPopupResizeiFrame(iframe) {
    // This function resizes an iFrame object
    // to fit its content.
    // The iFrame tag must have a unique ID attribute.

    if (window.frames.length == 0) {
        return;
    }

    if (BrowserDetect.browser == 'Firefox' || BrowserDetect.browser == 'Opera') {
        iframe.width = document.getElementById(iframe.id).contentDocument.body.scrollWidth * 3 + 75;
        iframe.height = document.getElementById(iframe.id).contentDocument.body.scrollHeight + 75;
    }
    else {
        iframe.width = document.getElementById(iframe.id).contentDocument.body.scrollWidth + 25;
        iframe.height = document.getElementById(iframe.id).contentDocument.body.scrollHeight + 25;
    }

    if (window.document.location != window.parent.document.location) {

        AdjustMyParent(window.parent.window, iframe);

    }

    if (_PopupDiv) {
        CenterTheDiv(_PopupDiv);
    }

}

function GetTopDocument(wndw) {
    if (wndw.document.location != wndw.parent.document.location) {
        var x = wndw.document.location;
        return GetTopDocument(wndw.parent.window);
    } else {
        var y = wndw.document.location;
        return wndw.document;
    }
}

function AdjustMyParent(parentWindow, iframe) {

    var arrFrames = parentWindow.document.getElementsByTagName("iframe");
    for (var i = 0; i < arrFrames.length; i++) {

        if (arrFrames[i].width < parseInt(iframe.width) + 100) {
            arrFrames[i].width = parseInt(iframe.width) + 100;
        }
        if (arrFrames[i].height < parseInt(iframe.height) + 100) {
            arrFrames[i].height = parseInt(iframe.height) + 100;
        }
        if (parentWindow.document.location != parentWindow.parent.document.location) {
            AdjustMyParent(parentWindow.parent.window, arrFrames[i]);
        }

    }

}

function CenterTheDiv(obj) {

    obj.style.display = "block";
    obj.style.position = "absolute";

    var scrolledX, scrolledY;
    if (self.pageYOffset) {
        scrolledX = self.pageXOffset;
        scrolledY = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        scrolledX = document.documentElement.scrollLeft;
        scrolledY = document.documentElement.scrollTop;
    } else if (document.body) {
        scrolledX = document.body.scrollLeft;
        scrolledY = document.body.scrollTop;
    }

    //

    var viewportWidth, viewportHeight;
    if (self.innerHeight) {
        // all except explorer
        viewportWidth = self.innerWidth;
        viewportHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        // explorer 6 strict mode
        viewportWidth = document.documentElement.clientWidth;
        viewportHeight = document.documentElement.clientHeight;
    } else if (document.body) {
        // other explorers
        viewportWidth = document.body.clientWidth;
        viewportHeight = document.body.clientHeight;
    };

    //get dialog's width and height
    dialogWidth = obj.offsetWidth;
    dialogHeight = obj.offsetHeight;

    //calculate position
    dialogTop = scrolledY + (viewportHeight / 2) - (dialogHeight / 2);
    dialogLeft = scrolledX + (viewportWidth / 2) - (dialogWidth / 2);

    if (findFirstRelativelyPositionedParent(obj)) {
        dialogTop = dialogTop - findYPos(findFirstRelativelyPositionedParent(obj));
        dialogLeft = dialogLeft - findXPos(findFirstRelativelyPositionedParent(obj));
    }

    //Position the Dialog
    obj.style.top = dialogTop + "px";
    obj.style.left = dialogLeft + "px";

}


function findYPos(obj) {
	
    var curtop = 0;

    if (obj.offsetParent) {
        do {
			curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
        return curtop;
    }
}

function findXPos(obj) {

    var curtop = 0;

    if (obj.offsetParent) {
        do {
            curtop += obj.offsetLeft;
        } while (obj = obj.offsetParent);
        return curtop;
    }
}


function findFirstRelativelyPositionedParent(obj) {

    if (obj.offsetParent && obj.offsetParent != null) {
        do {
            if (obj.offsetParent.style) {
                if (obj.offsetParent.style.position) {
                    if (obj.offsetParent.style.position == 'relative') {
                        return obj.offsetParent;
                    }
                }
            }
        } while (obj = obj.offsetParent);
    }

}


function findOffsetParentOffsetTop(obj) {

    var curtop = obj.offsetTop;
    var found = 0;

    if (obj.offsetParent) {
        do {
            if (obj.offsetParent.style.position) {
                if (obj.offsetParent.style.position == 'relative') {
                    return obj.offsetParent.offsetTop;
                }
            }
            curtop = obj.offsetTop;
        } while (obj = obj.offsetParent);
        return curtop;
    }
}



function CenterTheDiv_____OLD(DivToCenter) {

    //////////////////////////////////////////////////////////////////////
    // To center, do this 
    //////////////////////////////////////////////////////////////////////
    var pt = window.center({ width: DivToCenter.offsetWidth, height: DivToCenter.offsetHeight });

    if (pt.y < 15) {
        DivToCenter.style.top = "15px";
    } else {
        DivToCenter.style.top = pt.y + "px";
    }

    if (pt.x < 15) {
        DivToCenter.style.left = "15px";
    } else {
        DivToCenter.style.left = pt.x + "px";
    }

    //////////////////////////////////////////////////////////////////////
    // To NOT center, do this instead
    //////////////////////////////////////////////////////////////////////
    //var top = DivToCenter.offsetTop - DivToCenter.scrollTop
    //var left = DivToCenter.offsetLeft - DivToCenter.scrollLeft

    //DivToCenter.style.top = top + "px";
    //DivToCenter.style.left = left + "px";

}

function ezPopupHideDiv(PopupDivID) {

    var _PopupDiv = document.getElementById(PopupDivID);
    _PopupDiv.style.display="none";

    ezPopupKillBackgroundDiv(PopupDivID);

}

function ezPopupHideDivOnParent(PopupDivID) {

    var _PopupDiv = window.parent.document.getElementById(PopupDivID);
    _PopupDiv.style.display = "none";

    ezPopupKillBackgroundDivOnParent(PopupDivID);

}


function ezPopupKillBackgroundDiv(PopupDivID) {

    if (document.getElementById(PopupDivID + "_ezPopupBackground")) {
        document.getElementById(PopupDivID + "_ezPopupBackground").parentNode.removeChild(document.getElementById(PopupDivID + "_ezPopupBackground"));
    }
}

function ezPopupKillBackgroundDivOnParent(PopupDivID) {

    if (window.parent.document.getElementById(PopupDivID + "_ezPopupBackground")) {
        window.parent.document.getElementById(PopupDivID + "_ezPopupBackground").parentNode.removeChild(window.parent.document.getElementById(PopupDivID + "_ezPopupBackground"));
    }
}





// code from: http://www.geekdaily.net/2007/07/04/javascript-cross-browser-window-size-and-centering/
window.size = function()
{
   var w = 0;
   var h = 0;

   //IE
   if(!window.innerWidth)
   {
      //strict mode
      if(!(document.documentElement.clientWidth == 0))
      {
         w = document.documentElement.clientWidth;
         h = document.documentElement.clientHeight;
      }
      //quirks mode
      else
      {
         w = document.body.clientWidth;
         h = document.body.clientHeight;
      }
   }
   //w3c
   else
   {
      w = window.innerWidth;
      h = window.innerHeight;
   }
   return {width:w,height:h};
}

window.center = function()
{
   var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};

   var _x = 0;
   var _y = 0;
   var offsetX = 0;
   var offsetY = 0;

   //IE
   if(!window.pageYOffset)
   {
      //strict mode
      if(!(document.documentElement.scrollTop == 0))
      {
         offsetY = document.documentElement.scrollTop;
         offsetX = document.documentElement.scrollLeft;
      }
      //quirks mode
      else
      {
         offsetY = document.body.scrollTop;
         offsetX = document.body.scrollLeft;
      }
   }
   //w3c
   else
   {
      offsetX = window.pageXOffset;
      offsetY = window.pageYOffset;
   }

   _x = ((this.size().width-hWnd.width)/2)+offsetX;
   _y = ((this.size().height-hWnd.height)/2)+offsetY;

   return{x:_x,y:_y};
}


//******************
//******************
//******************

top.Communicator = new AjaxCommunicator();

function HandleModalResponse(RequestID) {

    var request = top.Communicator.GetRequest(RequestID);

    _PopupDiv.innerHTML = request["Response"];

    Prepare_PopupDiv()





    if (window.parent.document) {

        arr = window.parent.document.getElementsByTagName("iframe");
        for (var i = 0; i < arr.length; i++) {
            var obj = arr[i];

            // this is checking to see if the iframe is from ezPopup
            if (obj.ezPopupType) {


                alert("in HandleModalResponse");



                obj.width = _PopupDiv.offsetWidth + 200;
                obj.height = _PopupDiv.offsetHeight + 200;
            }

        }

        _PopupDiv.style.top = "30px";
        _PopupDiv.style.left = "30px";

    } else {
        CenterTheDiv(_PopupDiv);
    }







    // is this return statement necessary?  I don't think so ...
    // is this return statement necessary?  I don't think so ...
    // is this return statement necessary?  I don't think so ...
    return;

}

function AjaxCommunicator() {

    var objhttp = null;
    var activerequests = new Object();

    //Initialize the HTTP object

    if (window.XMLHttpRequest) {
        objhttp = new XMLHttpRequest();
    }

    else if (window.ActiveXObject) {
        objhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    this.CreateRequestParameters = function (Parameter, ParameterValue, ParameterObject) {
        var paramobject = ParameterObject;
        if (typeof (paramobject) == "undefined") {
            paramobject = new Object();
        }

        paramobject[Parameter] = ParameterValue;

        return paramobject;

    }


    //Handles the incoming requests
    /*
    RequestID = Unique ID for the request
    Callback = The function to call when the request completed
    */
    this.AddRequest = function (RequestID, CallBack, URI, Parameters) {

        activerequests[RequestID] = new Object();
        activerequests[RequestID]["URI"] = URI;
        activerequests[RequestID]["Callback"] = CallBack;
        activerequests[RequestID]["Parameters"] = Parameters;
        this.SendRequest(RequestID);

        return activerequests[RequestID];
    }

    this.GetRequest = function (RequestID) {
        return activerequests[RequestID];
    }

    this.SendRequest = function (RequestID) {

        var request = this.GetRequest(RequestID);
        var params = request["Parameters"];

        //Send the request to the server
        objhttp.onreadystatechange = function () { top.Communicator.RequestComplete(RequestID); };
        objhttp.open("GET", request["URI"], true);
        objhttp.send();

    }

    this.RequestComplete = function (RequestID) {

        if (objhttp.readyState == 4) {

            if (objhttp.status != 200) {
                activerequests[RequestID]["Response"] = objhttp.statusText + RequestID + objhttp.responseText;
            }

            else {
                activerequests[RequestID]["Response"] = objhttp.responseText;
                this.PerformCallback(RequestID);
            }

            objhttp.abort();

        }

    }

    this.PerformCallback = function (RequestID) {

        var callback = activerequests[RequestID]["Callback"];

        if (callback != null) {
            eval("try{" + callback + "('" + RequestID + "');}catch(err){alert(err.message)}");
        }

    }

}


function ezPopupMakeMoveable(div_obj) {
    var _div_obj = div_obj;
    //div_obj.handlerobj = this;

    var downposX = 0;
    var downposY = 0;
    var dragging = false;

    this.isIE = false;
    this.isNS = false;


    this.Init = function () {
        if (navigator.userAgent.indexOf("MSIE") >= 0 ||
            navigator.userAgent.indexOf("Opera") >= 0) {
            this.isIE = true;
        }
        else {
            this.isNS = true;
        }
    }


    _div_obj.onmousedown = function (event) {
        var x = 0;
        var y = 0;

        _this = this.handlerobj;

        if (_this.isIE) {
            x = window.event.clientX +
                document.documentElement.scrollLeft +
                document.body.scrollLeft;

            y = window.event.clientY +
                document.documentElement.scrollTop +
                document.body.scrollTop;
        }
        else {
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
        }

        var top = parseInt(this.style.top, 10);

        var client_y = y - top;
        if (!(client_y > 0 && client_y < 30)) {
            return;
        }

        _this.cursorStartX = x;
        _this.cursorStartY = y;
        _this.divStartX = parseInt(this.style.left, 10);
        _this.divStartY = top;

        if (this.handlerobj.isIE) {
            document.attachEvent("onmousemove", _this.onmousemove);
            document.attachEvent("onmouseup", _this.onmouseup);
            window.event.cancelBubble = true;
            window.event.returnValue = false;
        }
        else {
            document.addEventListener("mousemove", _this.onmousemove, true);
            document.addEventListener("mouseup", _this.onmouseup, true);
            event.preventDefault();
        }

        _ezPopup_tracker = _this;
        _this._div_obj = this;

    }

    this.onmousemove = function (event) {
        _this = _ezPopup_tracker;

        var x = 0;
        var y = 0;


        if (_this.isIE) {
            x = window.event.clientX + document.documentElement.scrollLeft
              + document.body.scrollLeft;
            y = window.event.clientY + document.documentElement.scrollTop
              + document.body.scrollTop;
        }
        else {
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
        }

        _this._div_obj.style.left = (_this.divStartX + x - _this.cursorStartX) + "px";
        _this._div_obj.style.top = (_this.divStartY + y - _this.cursorStartY) + "px";

        if (_this.isIE) {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
        }
        else {
            event.preventDefault();
        }
    }

    this.onmouseup = function () {
        _this = _ezPopup_tracker;
        if (_this.isIE) {
            document.detachEvent("onmousemove", _this.onmousemove);
            document.detachEvent("onmouseup", _this.onmouseup);
        }
        else {
            document.removeEventListener("mousemove", _this.onmousemove, true);
            document.removeEventListener("mouseup", _this.onmouseup, true);
        }
        _ezPopup_tracker = null;

    }

    this.Init();
}



var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{
		    string: navigator.userAgent,
		    subString: "Chrome",
		    identity: "Chrome"
		},
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari",
		    versionSearch: "Version"
		},
		{
		    prop: window.opera,
		    identity: "Opera",
		    versionSearch: "Version"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.userAgent,
		    subString: "iPhone",
		    identity: "iPhone/iPod"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};
BrowserDetect.init();
