﻿// Nice, handy strprintf for javascript
function jstrprintf() {
    len = arguments.length;
    if (len == 0) { return; }
    if (len == 1) { return arguments[0]; }

    var result;
    var regexstr;
    var replstr;
    var formatstr;
    var re;

    result = "";
    regexstr = "";
    replstr = "";
    formatstr = arguments[0];

    for (var i=1; i<arguments.length; i++) {
        replstr += String(i+100) + arguments[i]  + String(i + 100);
        regexstr += String(i+100) + "(.*)" + String(i+100);
    }
    re = new RegExp(regexstr);
    var result;
    result = replstr.replace(re, formatstr);
    return result;
}

function AddPx(num) {
    return String(num) + "px";
}

function findParentDiv(obj) {
    while (obj) {
        if (obj.tagName.toUpperCase() == "DIV") return obj;
        if (obj.parentElement) obj = obj.parentElement;
        else return null;
    }
    return null;
}

function findParentTagById(obj, parentname) {
    while (obj) {
        if (obj.id.match(parentname)) return obj;
        if (obj.parentElement) obj = obj.parentElement;
        else return null;
    }
    return null;
}

function getXMLHttpRequest()
{
  var request = false;
    
  try {
    request = new XMLHttpRequest();
  }
  catch(err1) {
    try {
      request = new ActiveXObject('Msxml2.XMLHTTP');
    }
	catch(err2) {
      try {
        request = new ActiveXObject('Microsoft.XMLHTTP');                
      } catch(err3) {
        request = false;
      }
    }
  }

  return request;
}

var m_topZ = 1;

function Test()
{
	var newdiv;

	//var elem = parent.document.getElementById("wrapper");
	//alert(elem);

	newdiv = parent.document.createElement("div");
	newdiv.id = "testy";
	newdiv.style.position = 'absolute';
	newdiv.style.width = '200px';
	newdiv.style.height = '200px';
	newdiv.style.left = 0;
	newdiv.style.top = 0;
	newdiv.style.zIndex = 1;
	newdiv.style.backgroundColor = 'rgb(240, 240, 240)';
	newdiv.style.opacity = 0.95;
	newdiv.style.allowtransparency = 'true';

	//newdiv.innerHTML="<p>ala ma kota</p>";

	parent.document.body.appendChild(newdiv);
}

//doc = parent.document,  document etc.
//height - wysokość okienka, jezeli height=null to wysokosc nie jest ustawiana
function CreateFloatingWindow(id, doc, caption, x, y, width, height, canMove, url) {
    //Sprawdzam czy okno juz istnieje, jezeli tak to tylko odswiezam jego zawartosc
	//var checkdiv = doc.getElementById("dragTitle" + String(id));
	//if(checkdiv!=null)
	if(IsShowedFloatingWindow(id,doc)==true)
	{
		UpdateFloatingWindow(id,doc,url);
		return;
	}

    var newdiv = doc.createElement("div");
    newdiv.id = "dragTitle" + String(id);
    newdiv.className = "divDragTitle";

    newdiv.style.width = width;
    newdiv.style.left = AddPx(x);
    newdiv.style.top = AddPx(y);
    newdiv.style.zIndex = m_topZ;

    newdiv.innerHTML = jstrprintf(
        '<table><tr><td>$1</td>' + 
        '<td style="width:12px;margin:0px;padding:0px;">' +
        '<img src="../viewerfiles/button_expand.gif" class="divTitleButton" id="dragButton$2" ' + 
        'onmousedown="javascript:toggleContentWin($2)" /></td>' +
        '<td style="width:12px;margin:0px;padding:0px;">' +
        '<img src="../viewerfiles/button_close.gif" class="divTitleButton" id="closeButton$2" ' + 
        'onmousedown="javascript:closeContentWin($2)" /></td>' +
        '</tr></table>',
        caption, id);

    // If canMove is false, don't register event handlers
    if (canMove) {
        // IE doesn't support addEventListener, so check for its presence
        if (newdiv.addEventListener) {
            // firefox, etc.
            newdiv.addEventListener("mousemove", function(e) { return mouseMove(e) }, true);
            newdiv.addEventListener("mousedown", function(e) { return mouseDown(e) }, true);
            newdiv.addEventListener("mouseup", function(e) { return mouseUp(e) }, true);
			//newdiv.addEventListener("dblclick", function(e) { return mouseDblClick(e) }, true);
        }
        else {
            // IE
            newdiv.attachEvent("onmousemove", function(e) { return mouseMove(e) });
            newdiv.attachEvent("onmousedown", function(e) { return mouseDown(e) });
            newdiv.attachEvent("onmouseup", function(e) { return mouseUp(e) });
        }
    }
    doc.body.appendChild(newdiv);

    var newdiv2;
    newdiv2 = doc.createElement("div");
    newdiv2.id = "dragContent" + String(id);
    newdiv2.className = "divDragContent";
    newdiv.style.position = 'absolute';
    newdiv2.style.width = width;
    if(height!=null) newdiv2.style.height = height;
    newdiv2.style.left = AddPx(x + 0);
    newdiv2.style.top = AddPx(y + 20);
    newdiv2.style.zIndex = m_topZ;
    //if (contentSource) {
    //    newdiv2.innerHTML = document.getElementById(contentSource).innerHTML;
    //}

    if (canMove) {
        if (newdiv2.addEventListener) {
            // firefox, etc.
            newdiv2.addEventListener("mousemove", function(e) { return mouseMove(e) }, true);
            newdiv2.addEventListener("mousedown", function(e) { return contentMouseDown(e) }, true);
            newdiv2.addEventListener("mouseup", function(e) { return mouseUp(e) }, true);
        }
        else {
            // IE
            newdiv2.attachEvent("onmousemove", function(e) { return mouseMove(e) });
            newdiv2.attachEvent("onmousedown", function(e) { return contentMouseDown(e) });
            newdiv2.attachEvent("mouseup", function(e) { return mouseUp(e) }, true);
        }
    }
    doc.body.appendChild(newdiv2);

    // Save away the content DIV into the title DIV for 
    // later access, and vice versa
    newdiv.content = newdiv2;
    newdiv2.titlediv = newdiv;

    m_topZ += 1;

	UpdateFloatingWindow(id,doc,url);
}

var m_ajax_httpreq;
var m_ajax_id;
var m_doc;

function UpdateFloatingWindow_data()
{
  if (m_ajax_httpreq.readyState == 4) {
    if (m_ajax_httpreq.status == 200 || m_ajax_httpreq.status == 304) {
		var elem = m_doc.getElementById("dragContent" + String(m_ajax_id));
		if(elem!=null) elem.innerHTML = m_ajax_httpreq.responseText;
    }
  }
}

function UpdateFloatingWindow(id,doc,url) {
	m_ajax_id = id;
	m_doc = doc;
	if (m_ajax_httpreq = getXMLHttpRequest()) {
		e = document.getElementById("dragContent" + String(id));
		m_ajax_httpreq.open('GET', url);
		m_ajax_httpreq.onreadystatechange = UpdateFloatingWindow_data;
		m_ajax_httpreq.send(null);
	}
}

function IsShowedFloatingWindow(id,doc) {
	var checkdiv = doc.getElementById("dragTitle" + String(id));
	if(checkdiv!=null) return true;
	return false;
}

function FloatingWindowLoadingIconVisible(id,doc,visible) {
//	var elem = doc.getElementById("dragContent" + String(id));
//	if(elem==null) return;
//	if(visible==true) elem.style.backgroundImage = "url('FloatingWindows_loading.gif')";
//	else elem.style.backgroundImage = "none";
//	elem.style.backgroundImage = "c:\Program Files\MapGuideOpenSource2.0\WebServerExtensions\www\viewerfiles\FloatingWindows_loading.gif";
}

function toggleContentWin(id) {
    var elem = document.getElementById("dragContent" + String(id));
    var img = document.getElementById("dragButton" + String(id));

    if (elem.style.display == "none") {
        // hidden, so unhide
        elem.style.display = "block";
        
        // Change the button's image
        img.src = "../viewerfiles/button_expand.gif";
	}
    else {
        // showing, so hide
        elem.style.display = "none";

        // Change the button's image
        img.src = "../viewerfiles/button_collapse.gif";
    }
}

function closeContentWin(id) {
    var elem = document.getElementById("dragContent" + String(id));
	document.body.removeChild(elem);
    elem = document.getElementById("dragTitle" + String(id));
	document.body.removeChild(elem);
}

// Drag methods
var m_dragObjTitle = null;
var m_dragOffsetX = 0;
var m_dragOffsetY = 0;

function contentMouseDown(e) {
    // Move the window to the front
    // Use a handy trick for IE vs FF
    var dragContent = e.srcElement || e.currentTarget;
    if ( ! dragContent.id.match("dragContent")) {
        dragContent = findParentTagById(dragContent, "dragContent");
    }
    if (dragContent) {
        dragContent.style.zIndex = m_topZ;
        dragContent.titlediv.style.zIndex = m_topZ;
        m_topZ++;
    }
}

function mouseDown(e) {
    // These first two lines are written to handle both FF and IE
    var curElem = e.srcElement || e.target;
    var dragTitle = e.currentTarget || findParentDiv(curElem);
    if (dragTitle && dragTitle.className != 'divDragTitle') return;
    
    // Start the drag, but first make sure neither is null
    if (curElem && dragTitle) {
        // Attach the document handlers. We don't want these running all the time.
        addDocumentHandlers(true);
    
        // Move this window to the front.
        dragTitle.style.zIndex = m_topZ;
        dragTitle.content.style.zIndex = m_topZ;
        m_topZ++;
    
        // Check if it's the button. If so, don't drag.
        if (curElem.className != "divTitleButton") {
            
            // Save away the two objects
            m_dragObjTitle = dragTitle;
            
            // Calculate the offset
            m_dragOffsetX = e.clientX - 
                dragTitle.offsetLeft;
            m_dragOffsetY = e.clientY - 
                dragTitle.offsetTop;
                
            // Don't let the default actions take place
            if (e.preventDefault) {
                e.preventDefault();
            }
            else {
                document.onselectstart = function () { return false; };
                e.cancelBubble = true;
                return false;
            }
        }
    }
}

function mouseMove(e) {
//console.debug(e.clientX+" "+e.clientY);
    // If not null, then we're in a drag
    if (m_dragObjTitle) {
        if (!e.preventDefault) {
            // This is the IE version for handling a strange
            // problem when you quickly move the mouse
            // out of the window and let go of the button.
            if (e.button == 0) {
                finishDrag(e);
                return;
            }
        }

        m_dragObjTitle.style.left = AddPx(e.clientX - m_dragOffsetX);
        m_dragObjTitle.style.top = AddPx(e.clientY - m_dragOffsetY);
        m_dragObjTitle.content.style.left = AddPx(e.clientX - m_dragOffsetX);
        m_dragObjTitle.content.style.top = AddPx(e.clientY - m_dragOffsetY + 20);
        if (e.preventDefault) {
            e.preventDefault();
        }
        else {
            e.cancelBubble = true;
            return false;
        }
    }
}

function mouseUp(e) {
    if (m_dragObjTitle) finishDrag(e);
}

function mouseDblClick(e) {
}

function finishDrag(e) {
    var finalX = e.clientX - m_dragOffsetX;
    var finalY = e.clientY - m_dragOffsetY;
    if (finalX < 0) finalX = 0;
    if (finalY < 0) finalY = 0;

    m_dragObjTitle.style.left = AddPx(finalX);
    m_dragObjTitle.style.top = AddPx(finalY);
    m_dragObjTitle.content.style.left = AddPx(finalX);
    m_dragObjTitle.content.style.top = AddPx(finalY + 20);
    
    // Done, so reset to null
    m_dragObjTitle = null;
    addDocumentHandlers(false);
    if (e.preventDefault) e.preventDefault();
    else {
        document.onselectstart = null;
        e.cancelBubble = true;
        return false;
    }
}

function addDocumentHandlers(addOrRemove) {
    if (addOrRemove) {
        if (document.body.addEventListener) {
            // firefox, etc.
            document.addEventListener("mousedown", function(e) { return mouseDown(e) }, true);
            document.addEventListener("mousemove", function(e) { return mouseMove(e) }, true);
            document.addEventListener("mouseup", function(e) { return mouseUp(e) }, true);
        }
        else {
            // IE
            document.onmousedown = function() { mouseDown(window.event) } ;
            document.onmousemove = function() { mouseMove(window.event) } ;
            document.onmouseup = function() { mouseUp(window.event) } ;
        }
    }
    else {
        if (document.body.addEventListener) {
            // firefox, etc.
            //document.removeEventListener("mousedown", mouseDown, true);
            //document.removeEventListener("mousemove", mouseMove, true);
            //document.removeEventListener("mouseup", mouseUp, true);
        }
        else {
            // IE
            // Be careful here. If you have other code that sets these events,
            // you'll want this code here to restore the values to your other handlers,
            // rather than just clear them out.
            document.onmousedown = null;
            document.onmousemove = null;
            document.onmouseup = null;
        }
    }
}