

// Add a field to the Pane form (or change the value of the existing field)
function AddFieldToForm(sFieldName, sFieldValue){
	// See if the field already exists in the form
	var theForm = document.forms[0];
	var theField = theForm[sFieldName];
	
	if (theField) {
		// Change value of existing field
		theField.value = sFieldValue;
	} else {
		// Create new hidden field
		var oHiddenField = document.createElement("input");
		oHiddenField.type = "hidden";
		oHiddenField.name = sFieldName;
		oHiddenField.id = sFieldName;
		oHiddenField.value = sFieldValue;
		// Append the new hidden field to the form
		theForm.appendChild(oHiddenField);
	}

}

function ToggleDetails(divID, linkObj) {
	var obj = document.getElementById(divID);
	var stateObj = document.forms[0][divID + "_HiddenState"];
	
	if (obj.style.display == "block") {
		obj.style.display = "none";
		if(linkObj!=null) {
			linkObj.className = "ToggleLink";
		}
		if (stateObj) {
			stateObj.value = "collapsed";	
		}
	} 
	else {
		obj.style.display = "block";	
		if(linkObj!=null) {
			linkObj.className = "ToggleLinkExpanded";
		}
		if (stateObj) {
			stateObj.value = "expanded";
		}
	}
	
	
}

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) {
	try {
		if( parent.debugMode ) {
			parent.document.getElementById("debug").innerHTML += sMessage+"<br>";
		}
		else if( debugMode ) {
			document.getElementById("debug").innerHTML += sMessage+"<br>";
		}
	}
	catch (ex) { } // empty catch
}

function timer(name) {
	try {
		if ( parent.debugMode && parent.debugExtension ) {
			parent.DP_Debug.timer(name);
		}
		else {
			if ( debugMode && debugExtension ) {
				DP_Debug.timer(name);
			}
		}
	}
	catch (ex) { } // empty catch
}

// changes tab in the pane
function ChangeTab(sSource) {
//    debug(QueryString("nodeid2", document.location.toString())=="");
//    return;
	
	// debug("---------- ChangeTab ----------");
	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 = "IconTab";
	if ( tab.icontab == "0" ) {
		baseClass = "Tab";
	}
	
	// CORE-824
	var tipBar = document.getElementById("PaneMenuTipBar");
	
	if ( highlight ) {
		if ( tab.activetab != "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.activetab == "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?
			}
		}
	}
}

function SetSubmitButtonHighlight(button, highlight) {
	if ( highlight ) {
		button.className = "SBButton SBButton"+button.buttonName+" ButtonHighlight";
	}
	else {
		button.className = "SBButton SBButton"+button.buttonName;
	}
}

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;
}

function GetTotalStyle(oStyleSheet, sClassName, sProperty) {
	// append "." to the start of the class name if it is not there already
	if(sClassName.indexOf(".")!=0)
		sClassName = "."+sClassName;
 	// dual browser code - IE calls the styles collection "rules", while mozilla calls it "cssRules"
	var oRules = (bBrowserIsIE) ? oStyleSheet.rules : oStyleSheet.cssRules;
	var value;
	// traverse the rules to find the named class
	for(var i = 0; i < oRules.length; i++) {
		if(oRules[i].selectorText == sClassName) {
			value = oRules[i].style[sProperty];
			if (value != null && value != "") {
				return parseInt(value);
			}
		}
	}	

	if (bBrowserIsIE) {
		for(var i = 0; i < oStyleSheet.imports.length; i++)	{
			value = GetTotalStyle(oStyleSheet.imports[i], sClassName, sProperty);
			if (value != 0)
				return value;
		}
	}
	else { 
		// TODO: Mozilla-> document.styleSheets[i].cssRules[j].styleSheet, or use prototype solution '$A(document.styleSheets)'
	}								

	return 0;
}

function GetTotalStyleWidth(oStyleSheet, sClassName) {
	var iWidth = 0;
		
	$w('width borderLeftWidth borderRightWidth paddingleft paddingRight marginLeft marginRight').each( function(prop) {
		iWidth += GetTotalStyle(oStyleSheet, sClassName, prop);
	});
	return iWidth;	
}

function GetTotalStyleHeight(oStyleSheet, sClassName) {
	var iHeight = 0;
	 				
	$w('height borderTopWidth borderBottomWidth paddingTop paddingBottom marginTop marginBottom').each( function(prop) {
			iHeight += GetTotalStyle(oStyleSheet, sClassName, prop);
		});
	
	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+")");
	// debug("cumulativeOffset().left = " + $(element).cumulativeOffset().left);
	return totalOffset;
}
function TotalOffsetTop(element) {
	var safeCount = 100;
	var parentElement = element;
	var totalOffset = 0;
	while (parentElement != null && parentElement.id != "FormContainer" && safeCount-->0) {
		if (parentElement.offsetTop != null) {
			totalOffset += parentElement.offsetTop;
			parentElement = parentElement.parentNode;		
		}
	}
	// debug("TotalOffsetTop = " + totalOffset + " (safecount="+safeCount+")");
	// debug("cumulativeOffset().top = " + $(element).cumulativeOffset().top);
	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.closed /*CORE-2101*/) {
			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;
}

swFindPaneIdFromElement = function(srcElement) {
	while ( srcElement.className.search(/\bPane\b/) == -1 && srcElement.parentElement != null ) {
		srcElement = srcElement.parentElement;
	}
	var match = /pane(\d+)/.exec(srcElement.id);
	if ( match.length > 1 ) {
		return match[1];
	}
	return null;
}

swFindParentWithClassFromElement = function(srcElement, classname) {
	var rexp = new RegExp("\\b"+classname+"\\b");
	while ( srcElement.className.search(rexp) == -1 && srcElement.parentElement != null ) {
		srcElement = srcElement.parentElement;
	}
	return srcElement;
}

swFindParentMatchingClassFromElement = function(srcElement, classname) {
	var rexp = new RegExp(classname);
	while ( srcElement.className.search(rexp) == -1 && srcElement.parentElement != null ) {
		srcElement = srcElement.parentElement;
	}
	return srcElement;
}

swFindActionFromElement = function(srcElement) {
	while ( srcElement.ActionId == null && srcElement.parentElement != null ) {
		srcElement = srcElement.parentElement;
	}
	return srcElement;
}

swFindParentWithTagNameFromElement = function(srcElement, tagname) {
	while ( srcElement.tagName.toLowerCase() != tagname.toLowerCase() && srcElement.parentElement != null ) {
		srcElement = srcElement.parentElement;
	}
	return srcElement;
}

AddClassToElement = function(element, addClass) {
	var rexp = new RegExp("\\b"+addClass+"\\b");
	if ( element.className.search(rexp) == -1 ) { // if not already present
		element.className = element.className + " " + addClass;
	}
}

RemoveClassFromElement = function(element, removeClass) {
	var rexp = new RegExp("\\b"+removeClass+"\\b");
	element.className = element.className.replace(rexp, "");
}

StripeTable = function(tableBody) {
	var rows = tableBody.getElementsByTagName("TR");
	
	var alternate = false;
	var rexp = new RegExp("\\b(Alternate)?Row(Selected)?\\b", "g");
	var newClass = "";
	
	for ( var i = 0; i < rows.length; i++ ) {
		newClass ="";
		
		if ( alternate ) { newClass = "Alternate"; }
		newClass += "Row";
		
		rows[i].className = rows[i].className.replace(rexp, newClass+"$2");
		alternate = !alternate;
	}
}

Utility = {
	/* Returns sum of widths of children */
	GetListSizeByChildren : function(list) {
		var retval = 0;
		
		if ( list != null ) {
			var children = Element.immediateDescendants(list);
			
			for ( var i = 0; i < children.length; i++ ) {
				var childWH = Element.getDimensions(children[i]);
				retval += childWH.width;
			}
		}
		
		return retval;
	},
	
	GetCookieValue : function(name) {
		var retval = "";
		var rexp = new RegExp(name+"=([^;]+);");
		var value = document.cookie.match(rexp);
		
		if ( value != null ) {
			retval = value[1];
		}
				
		return retval;
	},

	GetDimensions : function(element) {
		if ( typeof(element) == 'string' ) {
			element = document.getElementById(element);
		}
		
		var display = element.currentStyle.display;
		if ( display != 'none' && display != null ) {
			return {width: element.offsetWidth, height: element.offsetHeight};
		}
		
		var els = element.style;
		var originalVisibility = els.visibility;
		var originalPosition = els.position;
		var originalDisplay = els.display;
		els.visibility = 'hidden';
		els.position = 'absolute';
		els.display = 'block';
		var originalWidth = element.clientWidth;
		var originalHeight = element.clientHeight;
		els.display = originalDisplay;
		els.position = originalPosition;
		els.visibility = originalVisibility;
		return {width: originalWidth, height: originalHeight};
	},
	
	DumpDimensions : function(elm) {
		var ret = [];
		ret.push("Element dimensions:");
		ret.push("clientWidth: " + elm.clientWidth);
		ret.push("offsetWidth: " + elm.offsetWidth);
		ret.push(" ---- delta => " + Math.abs(elm.clientWidth - elm.offsetWidth));
		ret.push("clientHeight: " + elm.clientHeight);
		ret.push("offsetHeight: " + elm.offsetHeight);
		ret.push(" ---- delta => " + Math.abs(elm.clientHeight - elm.offsetHeight));
		return ret.join("<br/>");
	},

	HorizontalScrollbarVisible : function(element) {
		return (element.clientHeight != element.offsetHeight);
	},
	
	GetSitePreviewUrl: function(iSiteId) {
		var id = new String(iSiteId);
		if (gSiteUrls[id]) {
			return gSiteUrls[id].preview;
		}
	},
	
	GetSitePreviewUrlForQueryString: function(iSiteId, iElementId) {
		return encodeURIComponent(Utility.GetSitePreviewUrl(iSiteId).interpolate({"PageId": iElementId}));
	},
	
	ShowMediaSelectorPreview: function(sId) {
		var elem = $(sId);
		var container = elem.getOffsetParent();
		
		var myHeight	= elem.getHeight();
		var myPos		= elem.cumulativeOffset();
		var conPos		= container.cumulativeOffset();
		
		var myYpos		= myPos.top;
		var myXpos		= myPos.left;
		
		var conHeight	= container.getHeight();
		var conYpos		= conPos.top;
		var conXpos		= conPos.left;
		
		// Check if there's room for the preview layer 
		if (conHeight + conYpos < myYpos + myHeight) {
			// No? then pull it up by its height and position it next to the icon
			// Remember to calculate position within containing element ()
			elem.setStyle({
				'top': (myYpos - myHeight - conYpos) + "px",
				'left': (myXpos - conXpos + 18) + "px"
			});
		}
		
		// All OK, now show the preview
		elem.show();
		
	},
		
	HideMediaSelectorPreview: function(sId) {
		$(sId).hide();
	},
	
	ReloadCSS: function(file) {
		var sheet = $$("link[href*=" + file + "]")[0];
		if (sheet) {
			sheet.href += "?" + new Date().getTime();
		}
	},
	
	ReloadJS: function(file) {
		var script = $$("script[src*=" + file + "]")[0];
		if (script) {
			script.src += "?" + new Date().getTime();
		} else {
			debug('No script element with src="' + file + '" to reload.');
		}
	},
	
	LogMethodCall: function() {
		if (parent.debugMode) {
			var args = $A(arguments);
			var ins = {
				'name': args.shift(),
				'args': $A(args[0]).inspect().gsub(/[\[\]]/, "")
			};
			debug("<p>#{name}(#{args});</p>".interpolate(ins));
		}
	}
}

/*
	Translator class
	Handles translated texts
*/
if (typeof Translator == "undefined") { // Don't create a new Translator inside ChildPane
	var Translator = {
		texts: new Hash(),
		_overrides: new Hash(),
		
		AddText: function(alias, text) {
			Translator.texts.set(alias, text);
		},
		
		GetText: function(alias) {
			return (Translator._overrides.get(alias) || parent[alias] || Translator.texts.get(alias) || "¤" + alias);
		},
		
		GetCustomText: function(alias) {
			return (Translator._overrides.get(alias) || GetCustomText(alias) || "¤" + alias);
		}
	};
}

/* Profiler class */

ProfilerTimer = function() {
	this.start = null;
	this.accumulatedTime = 0;
}

ProfilerTimer.prototype.TriggerTimer = function() {
	if ( this.start == null ) {
		this.start = new Date();
	}
	else {
		var end = new Date();
		this.accumulatedTime += ( end.getTime() - this.start.getTime() );
		this.start = null;
	}
}

ProfilerTimer.prototype.GetAccumulatedTime = function() {
	return this.accumulatedTime;
}

Profiler = function() {
	this.timers = [];
}

Profiler.prototype.AddTimer = function(timerName) {
	this.timers[timerName] = new ProfilerTimer();
}

Profiler.prototype.Timer = function(timerName) {
	this.timers[timerName].TriggerTimer();
}

Profiler.prototype.GetAccumulatedTime = function(timerName) {
	return this.timers[timerName].GetAccumulatedTime();
}

/* FileConfCreator class */

FileConfCreator = Class.create();

FileConfCreator.prototype = {
	initialize: function(parentTypeId, parentElementId, editorName) {
		
		this.parentTypeId = parentTypeId;
		this.parentElementId = parentElementId;
		this.editorName = editorName;
	},
	
	CreateNew: function(fileId) {
		GetPane().ShowWaitLayer();		
		Synkron.Via.WebService.BackendFactory.CreateFileConfiguration(Utility.GetCookieValue("viaservicetoken"), this.parentTypeId, this.parentElementId, fileId, this.CreateNewCallback.bind(this));
	},
	
	CreateNewCallback: function(result) {		
		var editorFrame = document.getElementById(this.editorName);
		editorFrame.contentWindow.insertImageCallBack2(result.typeId, result.elementId, result.fileId);

		GetPane().HidePopupTool();
	},
	
	Clone: function(fileConfigId) {
		Synkron.Via.WebService.BackendFactory.CloneFileConfiguration(Utility.GetCookieValue("viaservicetoken"), this.parentTypeId, this.parentElementId, fileConfigId, this.CloneCallback.bind(this));
	},
	
	CloneCallback: function(result) {
		var editorFrame = document.getElementById(this.editorName);
		editorFrame.contentWindow.cloneImageCallBack(result.oldElementId, result.newElementId);
	}

};

function CreateFileConfiguration(parentTypeId, parentElementId, fileId, editorName) {
	var fcCreator = new FileConfCreator(parentTypeId, parentElementId, editorName);
	fcCreator.CreateNew(fileId);
}

function CloneFileConfigurations(parentTypeId, parentElementId, fileConfIds, editorName) {
	var i;
	for(i=0; i<fileConfIds.length; i++) {
		var fcCreator = new FileConfCreator(parentTypeId, parentElementId, editorName);
		fcCreator.Clone(fileConfIds[i]);
	}
}

function UpdateVisualEditorFileConf(editorName, fileConfId, args) {
	
	var parentPane = GetParentPane();
	if(parentPane == null) {
		// parent pane closed
		return;
	}

	var editorFrame = parentPane.ChildPane.document.getElementById(editorName);
	editorFrame.contentWindow.updateFileConfiguration(fileConfId, args);
}
