// Add a field to the Pane form
function AddFieldToForm(sFieldName, sFieldValue){
	var bFieldExists = false;
	var iIndex=0;
	// See if the field already exists in the form
	for(var i=0;i<document.forms[0].length;i++){
		if(document.forms[0][i].name == sFieldName){
			// Field exists
			bFieldExists = true;
			// save field index
			iIndex = i;
			break;
		}
	}

//	debug("adding to form: '"+sFieldName+"', '"+sFieldValue+"' [exists: "+bFieldExists+"]");
	
	if(bFieldExists){
		// Change value of existing field
		document.forms[0][iIndex].value = sFieldValue;
//		debug("new field value: '"+ document.forms[0][iIndex].value+"'");
	}
	else{
		// Create new hidden field
		oHiddenField = document.createElement("input");
		oHiddenField.type = "hidden";
		oHiddenField.name = sFieldName;
		oHiddenField.id = sFieldName;
		oHiddenField.value = sFieldValue;
		// Append the new hidden field to the form
		document.forms[0].appendChild(oHiddenField);		
	}

}

function ToggleDetails(divID, linkObj) {
	var obj = document.getElementById(divID);
	if (obj.style.display == "block") {
		obj.style.display = "none";
		if(linkObj!=null) {
			linkObj.className = "ToggleLink";
		}
	} 
	else {
		obj.style.display = "block";	
		if(linkObj!=null) {
			linkObj.className = "ToggleLinkExpanded";
		}
	}
}

function SortNodesByPlacement(nodeA, nodeB) {
	return (nodeA.offsetTop - nodeB.offsetTop);
}

function ClearDebug() {
	if(parent.document.getElementById("debug")!=null) {
		parent.document.getElementById("debug").innerHTML = "";
	}
	else if(document.getElementById("debug")!=null) {
		document.getElementById("debug").innerHTML = "";
	}
}

function debug(sMessage) {
	if(parent.document.getElementById("debug")!=null) {
		parent.document.getElementById("debug").innerHTML += sMessage+"<br>";
	}
	else if(document.getElementById("debug")!=null) {
		document.getElementById("debug").innerHTML += sMessage+"<br>";
	}
}

// changes tab in the pane
function ChangeTab(sSource) {
	//debug("ChangeTab: "+sSource);
//    debug(QueryString("nodeid2", document.location.toString())=="");
//    return;
	sSource = sSource.replace('&amp;','&'); // HACK!!
	
	var sNodeId = QueryString("nodeid", document.location.toString())
	var sTypeId = QueryString("typeid", document.location.toString())
	sSource = AppendParameterToUrl(sSource, "iPaneId", iPaneId);
	if(iParentId!=null) {
		sSource = AppendParameterToUrl(sSource, "iParentId", iParentId);
	}
	SubmittedByApplyButton();
	if(Validate(arrValidations)) {
		AddFieldToForm("swPaneMenuRedirectUrl", sSource);
		if(sNodeId!="" && sTypeId!="") {
			AddFieldToForm("swTypeId", sTypeId);
			AddFieldToForm("swNodeId", sNodeId);
		}
		DoSubmit();
	}
	else {
		debug("ERROR: cannot validate...");
	}
//	ValidateSubmit();
}

// CORE-1524
function SetTabHighlight(tab, highlight) {
	var baseClass = "PaneMenuButton";
	if ( tab.iconbutton == "0" ) {
		baseClass = "PaneMenuTextButton";
	}
	
	// CORE-824
	var tipBar = document.getElementById("PaneMenuTipBar");
	
	if ( highlight ) {
		if ( tab.activebutton != "1" ) {
			tab.className += " " + baseClass + "Highlight";
			
			// CORE-824
			if ( tipBar != null ) {
				tipBar.className="PaneMenuTipBar PaneMenuTipBarHighlight";
				var tip = document.getElementById("PaneMenuTip");
				tip.innerText = tab.TipText;
			}
		}
	}
	else {
		if ( tab.activebutton == "1" ) {
			tab.className = baseClass + " " + baseClass + "Active";
		}
		else {
			tab.className = baseClass;
			
			// CORE-824
			if ( tipBar != null ) {
				tipBar.className="PaneMenuTipBar";
				var tip = document.getElementById("PaneMenuTip");
				tip.innerText = ""; // TipText of active button perhaps?
			}
		}
	}
}

RoundButtonHover = function(button, hover) {
	if ( button.disabled != "1" ) {
		var classprefix = "";
		if ( button.className.indexOf("selectorbutton") != -1 ) {
			classprefix = "selectorbutton ";
		}
		
		if ( hover ) {
			button.className = classprefix + "roundbutton butsel";
		}
		else {
			button.className = classprefix + "roundbutton";
		}
	}
}

// changes tab in the pane
function ChangeContentTab(iRequestedTabId) {
    debug("ChangeContentTab: "+iRequestedTabId);

	SubmittedByApplyButton();
	if(Validate(arrValidations)) {
		AddFieldToForm("swRequestedTabId", iRequestedTabId);
		DoSubmit();
	}
//	ValidateSubmit();
}

function Preview() {
	if(typeof(previewUrl)!="undefined") {
		// preview in new window
		window.open(previewUrl);
	}
	else {
		// TODO: remove (or localize?)
		GetPane().Alert("Preview error", "No URL to preview...");
	}
}

// this methos returns the value of a query string variable (or "" if the variable does not exist)
function QueryString(sKey, sUrl){
//	sQueryString = document.location.search.substring(1);
	sQueryString = sUrl.substring(sUrl.indexOf('?')+1, sUrl.length);
	aQueryArray = sQueryString.split("&");
	for (i=0; i < aQueryArray.length; i++) {
		iPairSplit = aQueryArray[i].indexOf("=");
		if (iPairSplit != -1) {
			sPairKey = aQueryArray[i].substring(0,iPairSplit);
			sPairValue = aQueryArray[i].substring(iPairSplit+1);
			if(sPairKey==sKey){
				return sPairValue;
			}			
		}
	}
	return "";
}

//this function opens a window in fullscreen with toolbar etc disabled
function OpenFull(sPageName){
	var features = "scrollbars=no,resizable=yes,width="+(screen.width-11)+",height="+(screen.height-58)+",top=0,left=0,status=no,toolbar=no,menubar=no,location=no";
	window.open(sPageName,"", features);
	//window.open(sPageName,"", "");
}
function OpenWindowUsingFeatures(sPageName, features){
	window.open(sPageName, "", features);
}
//this function opens a window
function OpenWindow(sUrl, iWidth, iHeight){
		window.open(sUrl,"","height=" + iHeight + ",width=" + iWidth);
		//var a = window.open(sUrl,"","scrollbars=0, Resizable=yes");
	
}

function BaseUrl(sUrl) {
	if(sUrl.indexOf('?')<0) {
		return sUrl;
	}
	return sUrl.substring(0, sUrl.indexOf('?'));
}

function ContainingUrl(sUrl) {
	// return from start to last '/'
	return sUrl.substring(0,sUrl.lastIndexOf('/')+1);
}

function GetScrollPosX(){
	var iScrollX = 0;
	if (document.body.scrollLeft) {
		//DOM compliant
		iScrollX = document.body.scrollLeft;
	} 
	else {
		//IE6 standards compliant mode
		iScrollX = document.documentElement.scrollLeft;
   	}
   	if(!iScrollX){iScrollX=0};
   	return iScrollX;
}

function GetScrollPosY(){
	var iScrollY = 0;
	if(document.body.scrollTop) {
			//DOM compliant
			iScrollY = document.body.scrollTop;	
    	} 
    	else {
		  	//IE6 standards compliant mode
        	iScrollY = document.documentElement.scrollTop;
		}
	if(!iScrollY){iScrollY=0};
	return iScrollY;
}

function GetWindowWidth() {
	var iBodyWidth = bBrowserIsIE ? document.documentElement.clientWidth : window.innerWidth;
	return iBodyWidth;
}

function GetWindowHeight() {
	var iBodyHeight = bBrowserIsIE ? document.documentElement.clientHeight : window.innerHeight;
	return iBodyHeight;
}

function AppendParameterToUrl(sUrl, sParam, sValue){
	if(sUrl.indexOf("?" + sParam + "=")>-1 || sUrl.indexOf("&" + sParam + "=")>-1) {
		// don't append twice
		return sUrl;
	}
	if(sUrl.indexOf("?") > -1){
		sUrl += "&" + sParam + "=" + sValue;
	}else{
		sUrl += "?" + sParam + "=" + sValue;
	}
	return sUrl;
}

// returns the styleSheet object holding the requested style sheet (requested by path/name)
// - returns null if no style sheet can be found
function GetStyleSheet(sStyleSheetPath) {
	debug('GetStyleSheet: '+sStyleSheetPath);

	var searchstring = sStyleSheetPath;
	if ( !bBrowserIsIE ) {
		// mozilla returns URLencoded strings from the DOM
		searchstring = escape(sStyleSheetPath);
	}

	// traverse the styleSheets collection to find the requested styleSheet object
	for(var i=0; i<document.styleSheets.length; i++) {
		// must use indexOf, as the "href" property returns the relative path to the style sheet in IE,
		// while mozilla returns the absolute path
		// debug('Match against: '+document.styleSheets[i].href);
		if(document.styleSheets[i].href.indexOf(searchstring)>=0) {
			return document.styleSheets[i];
		}
	}
	return null;
}

// returns the style object of a named class in a styleSheet object
// - returns null if the class does not exist in the styleSheet class
function GetStyleSheetClass(oStyleSheet, sClassName) {
	// append "." to the start of the class name if it is not there already
	if(sClassName.indexOf(".")!=0)
		sClassName = "."+sClassName;
	var oRules;
	// dual browser code - IE calls the styles collection "rules", while mozilla calls it "cssRules"
	if(bBrowserIsIE) {
		oRules = oStyleSheet.rules;
	}
	else {
		oRules = oStyleSheet.cssRules;
	}
	// traverse the rules to find the named class
	for(var i=0; i<oRules.length; i++) {
		if(oRules[i].selectorText==sClassName) {
			return oRules[i].style;
		}
	}
	return null;
}

function GetTotalStyleWidth(oStyle) {
	var iWidth = 0;

	iWidth  += (oStyle.width == "") ? 0 : parseInt(oStyle.width);
	iWidth  += (oStyle.borderLeftWidth == "") ? 0 : parseInt(oStyle.borderLeftWidth);
	iWidth  += (oStyle.borderRightWidth == "") ? 0 : parseInt(oStyle.borderRightWidth);
	iWidth  += (oStyle.paddingLeft == "") ? 0 : parseInt(oStyle.paddingLeft);
	iWidth  += (oStyle.paddingRight == "") ? 0 : parseInt(oStyle.paddingRight);
	iWidth += (oStyle.marginLeft == "") ? 0 : parseInt(oStyle.marginLeft);
	iWidth += (oStyle.marginRight == "") ? 0 : parseInt(oStyle.marginRight);
	
	return iWidth;	
}

function GetTotalStyleHeight(oStyle) {
	var iHeight = 0;
	
	iHeight += (oStyle.height == "") ? 0 : parseInt(oStyle.height);
	iHeight += (oStyle.borderTopWidth == "") ? 0 : parseInt(oStyle.borderTopWidth);
	iHeight += (oStyle.borderBottomWidth == "") ? 0 : parseInt(oStyle.borderBottomWidth);
	iHeight += (oStyle.paddingTop == "") ? 0 : parseInt(oStyle.paddingTop);
	iHeight += (oStyle.paddingBottom == "") ? 0 : parseInt(oStyle.paddingBottom);
	iHeight += (oStyle.marginTop == "") ? 0 : parseInt(oStyle.marginTop);
	iHeight += (oStyle.marginBottom == "") ? 0 : parseInt(oStyle.marginBottom);
	
	return iHeight;
}

function TotalOffsetLeft(element) {
	var safeCount = 100;
	var parentElement = element;
	var totalOffset = 0;
	while(parentElement!=null && parentElement.id != "FormContainer" && safeCount-->0) {
		if(parentElement.offsetLeft!=null) {
			totalOffset += parentElement.offsetLeft;
			parentElement = parentElement.parentNode;		
		}
	}
//	debug("TotalOffsetLeft="+totalOffset+" (safecount="+safeCount+")");
	return totalOffset;
}
function TotalOffsetTop(element) {
	var safeCount = 100;
	var parentElement = element;
	var totalOffset = 0;
	while(parentElement!=null && parentElement.id != "FormContainer" && safeCount-->0) {
		//debug("TotalOffsetTop " + parentElement.className + ": " + parentElement.offsetTop);
		if(parentElement.offsetTop!=null) {
			totalOffset += parentElement.offsetTop;
			parentElement = parentElement.parentNode;		
		}
	}
//	debug("TotalOffsetTop="+totalOffset+" (safecount="+safeCount+")");
	return totalOffset;
}

function TranslateTypeIdForFileTree (iTypeId) {
	var iReturnTypeId = parseInt(iTypeId);
	// generic file type?
	if(iReturnTypeId>=10000) {
    	iReturnTypeId = TypeIdFile;
    }
	return iReturnTypeId;
	/*
	switch(iReturnTypeId) {
		case TypeIdFileFolder:
			break;
		case TypeIdFileFolderNetworkShare:
			break;
		case TypeIdFileTreeSolution:
			break;
		default:
			// generic file type?
			if(iReturnTypeId>=10000) {
    			iReturnTypeId = TypeIdFile;
    		}
			break;
	}
	return iReturnTypeId;
	*/
}

function IsModuleType(typeId) {
	// Synkron module? (100000 - 199999)
	if(typeId >= 100000 && typeId <= 199999) {
		return true;
	}
	// 3rd party module? (200000, 999999)
	if(typeId >= 200000 && typeId <= 999999) {
		return true;
	}
	return false;
}

function LogOut() {
	if(confirm(TextLogOutConfirmation)) {
		if(window.opener!=null) {
			window.opener.navigate("default.aspx");
		}
		AddFieldToForm("Action", "Logout");
		document.forms[0].submit();
	}
}

// for QA!
function GetTreeElementInfo(paneId, nodename) {
//	alert(ArrPanes[paneId].ChildPane.document);

	var links = ArrPanes[paneId].ChildPane.document.getElementById("formcontainer").getElementsByTagName("A");
	for(var i=0; i<links.length; i++) {
		if(links[i].parentNode.className=="TreeNode") {
			debug("'"+links[i].innerText+"'");
			if(links[i].innerText==nodename) {
				alert(links[i].parentNode.NodeId+" "+links[i].parentNode.TypeId);
			}
		}
	}
}

InArray = function(arrHaystack, needle) {
	var i = arrHaystack.length;
	if ( i > 0 ) {
		do {
			if ( arrHaystack[i] === needle ) {
				return true;
			}
		} while (i--);
	}
	return false;
}
