var request;
var isFloateeMenuWidthSet=false;

//This function creates an XMLHttpRequest object based on the appropriate browser type.
function createRequest() {
    try {
        request = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                request = false;
            }
        }
    }
}

//This function invokes the action copyManagedObject.do which copies the VCM id of the object being copied into memory.
function copyManagedObject(vcmid) {
     var url = "/vgn-ext-templating-cma/secure/copyManagedObject.do?spfAId=" + vcmid;

     if(!request) {
         createRequest();
     }

     //Send a synchronous request to copyManagedObject.do to copy the managed object id into buffer. The page will
     //get blocked until this request is fulfilled.
     request.open("GET", url, false);
     request.send(null);

     if(request.status == 200) {
        var responseText=trimString(request.responseText);
        if(responseText.substr(0,5) == "<?xml") {
	    var xmldoc=getXMLDocumentRoot(responseText);
	    var resultnode=xmldoc.getElementsByTagName("result")[0];
            if(resultnode.childNodes[0].nodeValue == "ERROR") {
       	        var messagenode=xmldoc.getElementsByTagName("message")[0];
                if(messagenode.childNodes.length > 0) {
	            alert(messagenode.childNodes[0].nodeValue);
	        } else {
	    	    alert(messagenode.nodeValue);
	        }
	    }
        } else {
            url = url + "&loginPage=true";
            SimplePopwin(url, 'Copy','','800','600');
        }
     } else {
        alert("Copy failed with status code " + request.status);
     }
}

//Get a cross browser xml root document for the passed-in xml string
function getXMLDocumentRoot(xmltext) {
	// code for IE
	if (window.ActiveXObject) {
	    var doc=new ActiveXObject("Microsoft.XMLDOM");
	    doc.async="false";
	    doc.loadXML(xmltext);
	}
	// code for Mozilla, Firefox, Opera, etc.
	else {
	    var parser=new DOMParser();
	    var doc=parser.parseFromString(xmltext,"text/xml");
	}// documentElement always represents the root node

	return doc.documentElement;
}

function MM_findObj(n, d) {
//alert("in findObj");
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_changeProp(objName,x,theProp,theValue) {
//alert("in change prop");
  var obj = MM_findObj(objName);
//alert("after findObj");
  if (obj && (theProp.indexOf("style.")==-1 || obj.style)){
    if (theValue == true || theValue == false)
      eval("obj."+theProp+"="+theValue);
    else eval("obj."+theProp+"='"+theValue+"'");
  }
}

function getScrollLeft(){
	if(typeof window.pageXOffset=="number")
		return window.pageXOffset;
	if(document.documentElement.scrollLeft)
		return Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);
	else if(document.body.scrollLeft!=null)
		return document.body.scrollLeft;
	return 0;
}

function getScrollTop(){
	if(typeof window.pageYOffset=="number")
		return window.pageYOffset;
	if(document.documentElement.scrollTop)
		return Math.max(document.documentElement.scrollTop,document.body.scrollTop);
	else if(document.body.scrollTop!=null)
		return document.body.scrollTop;
	return 0;
}

function getAbsX(elt) { return (elt.x) ? elt.x : getAbsPos(elt,"Left"); }
function getAbsY(elt) { return (elt.y) ? elt.y : getAbsPos(elt,"Top"); }
function getAbsPos(elt,which) {
 iPos = 0;
 while (elt != null) {
  iPos += elt["offset" + which];
  elt = elt.offsetParent;
 }
 return iPos;
}

function MM_moveRelative(objName,event) {

  	var obj = MM_findObj(objName);
	if (! (obj.style.visibility == 'visible')) {
		x=event.clientX+getScrollLeft() - getAbsX(obj.offsetParent) - 10;
		y=event.clientY+getScrollTop() - getAbsY(obj.offsetParent) - 10;
		MM_changeProp(objName,x,"style.left",x + "px");
		MM_changeProp(objName,x,"style.top",y + "px");
	}
}
// Vicket 143143: This function changes the zIndex of 'epi-modDrg'(CPS portlet) to 9000 so that the edit menu
// within this portlet gets precedence and does not hide behind the next portlet
// Pre-condition to use this function:  origZIndex script variable must be declared within the function caller
function changeZIndex(objName) {
	var obj = MM_findObj(objName);
	var parentObj;
	while (obj != null) {
		if (obj.className == 'epi-modDrg') {
			parentObj=obj;
			break;
		}
		obj = obj.offsetParent;
	}
	if (parentObj!=null)
	{
		origZIndex=parentObj.style.zIndex;
		parentObj.style.zIndex=9000;
	}

}

// This function reverts the epi-modDrg(CPS portlet)'s zIndex to it's original value by taking from origZIndex variable
// Pre-condition to use this function: origZIndex script variable must be declared within the function caller
function resetZIndex(objName) {
	var obj = MM_findObj(objName);
	var parentObj;
	while (obj != null) {
		if (obj.className == 'epi-modDrg') {
			parentObj=obj;
			break;
		}
		obj = obj.offsetParent;
	}
	if (parentObj!=null)
	{
		parentObj.style.zIndex=origZIndex;
	}
}

//This function dynamically sets the zIndex for the region menu edit bug
function setRegionMenuZIndex(div,zIndexValue) {
	if (isIE()) {
		var divObj = MM_findObj(div);
		divObj.style.zIndex = zIndexValue;
	}
}

//This functions sets the src attribute of a specified image
function setImagePath(imgId, imgPath) {
    var imgObj = MM_findObj(imgId);
    imgObj.src = imgPath;
}

//Show the Edit Menus
function showEditMenu(topMenuId, regionBugId, topId) {
	MM_changeProp(topMenuId,'','style.visibility','visible');
	setRegionMenuZIndex(topId,1);
}

//Hide the Edit Menus
function hideEditMenu(topMenuId, regionBugId, topId) {
	MM_changeProp(topMenuId,'','style.visibility','hidden');
	setRegionMenuZIndex(topId,0);
}

//Show the Floatee Menus
function showFloateeMenu(menu, topPixel) {

	// To fix the issue where the region menu options were hidden by the floatie in non-IE browsers.
	// Vicket #145739.
	if (!isIE()) {
		MM_changeProp(menu,'','style.top', topPixel);
	}

	MM_changeProp(menu,'','style.visibility','visible');
	cancelEvent();
}

//Hide the Floatee Menus
function hideFloateeMenu(menu, topPixel) {
	MM_changeProp(menu,'','style.visibility','hidden');

	// To fix the issue where the region menu options were hidden by the floatie in non-IE browsers.
	// Vicket #145739.
	if (!isIE()) {
		MM_changeProp(menu,'','style.top',topPixel);
	}

	cancelEvent();
}

//Stop event propogation in IE
function cancelEvent() {
	//Vicket: 145737: Stop event propogation in IE to fix the menu flickering which was caused by the
	//mouse over handler (added inside portal/vuit.js) for the document object
	if(window.event) {
		window.event.cancelBubble=true;
	}
}

//This function dynamically sets the width of the floatee header (header that displays either
//Page View, Template View or Content View) and also sets the width of the floatee menu separtors.
function resetFloateeMenuSize() {

    //NOTE: Background selection when the user hovers the mouse pointer on the menu item doesn't
    //work correctly without the logic in this function.

	if(isFloateeMenuWidthSet == false) {
		var floateetable=document.getElementById("floateetable");
		if(floateetable) {
			var floateetablewidth=floateetable.offsetWidth;

			//var floateeheadertab=document.getElementById("floateeheadertab");
			// if(floateeheadertab) {
			//     floateeheadertab.style.width=floateetablewidth-87;
			// }

			var floateemenuseparator=document.getElementsByName("floateemenuseparator");
			if(floateemenuseparator) {
				if(floateemenuseparator.length) {
					for(i=0; i<floateemenuseparator.length; i++) {
						floateemenuseparator[i].style.width=floateetablewidth-6;
					}
				} else {
					floateemenuseparator.style.width=floateetablewidth-6;
				}
			}
		}
		isFloateeMenuWidthSet=true;
	}
}