// mollerutil.js

/*
 * Synopsis: Set the dispatch form variable and submit the form
 * Function: submitDispatch
 * Params:
 *   destination: value to set
*/
function submitDispatch(destination) {
	setDispatch(destination);
	submitFormExt(true);
	return 0;
}

/*
 * Synopsis: Set the dispatch form variable and submit the form to a new window
 * Function: submitDispatch
 * Params:
 *   destination: value to set
*/
function submitDispatchToNewWindow(destination) {
	document.forms[0].setAttribute('target', '_blank');
	setDispatch(destination);
	submitFormExt(false);
	return 0;
}

/* 
 * Synopsis: set the dispatch form variable
 * Function: setDispatch
 * Params:
 *   destination: value to set
*/
function setDispatch(destination) {
	document.forms[0].dispatch.value=destination;
	return 0;
}

/*
 * Synopsis: submit the form after removing target attribute
 * Function: submitForm
*/
function submitForm() {
	submitFormExt(true);
}

/*
 * Synopsis: submit the form
 * Function: submitFormExt
 * Params:
 *   removeTarget: true if target attribute should be removed before submitting
*/
function submitFormExt(removeTarget) {
	if(removeTarget == true) {
		document.forms[0].removeAttribute('target');
	}
	document.forms[0].submit();
}

/* 
 * Synopsis: set the dealerId form variable
 * Function: setDealerId
 * Params:
 *   dealerId: value to set
*/
function setDealerId(dealerId) {
	document.forms[0].dealerId.value=dealerId;
	return 0;
}

/* 
 * Synopsis: set the three form variable carlineId, modelYear and mainType 
 * Function: setCarlineVaraibles
 * Params:
 *   carlineId: value to set
 *	 modelYear: value to set
 *   mainType: value to set
 *   typeNumber: value to set
*/
function setCarlineVariables(carlineId, carlineGroup, modelYear, mainType, typeNumber) {
	setCarlineId(carlineId);
	setCarlineId(carlineGroup);
	setModelYear(modelYear);
	setMainType(mainType);
	setTypeNumber(typeNumber);
	return 0;
}

/* 
 * Synopsis: set the carlineId form variable
 * Function: setCarlineId
 * Params:
 *   carlineId: value to set
*/
function setCarlineId(carlineId) {
	document.forms[0].carlineId.value=carlineId;
	return 0;
}

/* 
 * Synopsis: set the carlineId form variable
 * Function: setCarlineId
 * Params:
 *   carlineId: value to set
*/
function setCarlineGroup(carlineGroup) {
	document.forms[0].carlineGroup.value=carlineGroup;
	return 0;
}

/* 
 * Synopsis: set the modelYear form variable
 * Function: setModelYearId
 * Params:
 *   modelYear: value to set
*/
function setModelYear(modelYear) {
	document.forms[0].modelYear.value=modelYear;
	return 0;
}

/* 
 * Synopsis: set the mainType form variable
 * Function: setMainType
 * Params:
 *   mainType: value to set
*/
function setMainType(mainType) {
	document.forms[0].mainType.value=mainType;
	return 0;
}

/* 
 * Synopsis: set the typeNumber form variable
 * Function: setTypeNumber
 * Params:
 *   typeNumber: value to set
*/
function setTypeNumber(typeNumber) {
	document.forms[0].typeNumber.value=typeNumber;
	return 0;
}

/* 
 * Synopsis: set the modelId form variable
 * Function: setModelId
 * Params:
 *   modelId: value to set
*/
function setModelId(modelId) {
	document.forms[0].modelId.value=modelId;
	return 0;
}

/* 
 * Synopsis: set the detailOption form variable
 * Function: setDetailOption
 * Params:
 *   optionId: option id
*/
function setDetailOption(optionId) {
	document.forms[0].detailOption.value=optionId;
	return 0;
}

/* 
 * Synopsis: set the extColor form variable
 * Function: setExtColor
 * Params:
 *   col      : color code
 *   ecOption : option code
*/
function setExtColor(col, ecOption) {
	document.forms[0].extColor.value=col;
	document.forms[0].extColorOption.value=ecOption;
	return 0;
}

/* 
 * Synopsis: set the intColor form variable
 * Function: setIntColor
 * Params:
 *   col      : color code
 *   icOption : option code
*/
function setIntColor(col, icOption) {
	document.forms[0].intColor.value=col;
	document.forms[0].intColorOption.value=icOption;
	return 0;
}

/* 
 * Synopsis: set the position form variable
 * Function: setPosition
 * Params:
 *   positionFieldName : the name of the position field 
 *   newValue : new position value
*/
function setPosition(positionFieldName, newValue) {
	positionFieldName.value=newValue;
	return 0;
}

/* 
 * Synopsis: set the filter form variable
 * Function: setFilter
 * Params:
 *   filterFieldName: The name to the filter form value
 *   newValue: new filter value
*/
function setFilter(filterFieldName, newValue) {
	if(filterFieldName.value != newValue) {
		filterFieldName.value=newValue;
		// sortDirection is reset when an other sort criteria is used
		document.forms[0].sortDirection.value = ''; 
	}
	return 0;
}

/* 
 * Synopsis: set the column form variable
 * Function: setSort
 * Params:
 *   column : the name of the column in list 
*/
function setSort(column) {
	document.forms[0].sortColumn.value = column;
	return 0;
}

/* 
 * Synopsis: set the dealersSelectedRowId form variable
 * Function: setDealersSelectedRow
 * Params:
 *   rowId: value to set
*/ 
function setDealersSelectedRow(rowId) {
  document.forms[0].dealersSelectedRowId.value = rowId;
  return 0;	
}

/* 
 * Synopsis: set the enginesSelectedRowId form variable
 * Function: setEnginesSelectedRow
 * Params:
 *   rowId: value to set
*/ 
function setEnginesSelectedRow(rowId) {
  document.forms[0].enginesSelectedRowId.value = rowId;
  return 0;	
}
/* 
 * Synopsis: get the enginesSelectedRowId form variable
 * Function: setEnginesSelectedRow
 * Params:
 *   rowId: value to set
*/ 
function getEnginesSelectedRow() {
  if (document.forms[0].enginesSelectedRowId)
  	return document.forms[0].enginesSelectedRowId.value;
  return null;
}

/* 
 * Synopsis: Open a popup window showing the image in the given url
 * Function: showImage
 * Params:
 *   url: image url
*/
var imgWin;
function showImage(imageURL, imageTitle){
	var PositionX = 100;
	var PositionY = 100;
	var defaultWidth  = 500;
	var defaultHeight = 300;
	var AutoClose = true;

	imageTitle = trim(imageTitle);
	
	imgWin=window.open('about:blank', '', 'scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY);
	with (imgWin.document){
		writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>');
		writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
		writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
		writeln('function reSizeToImage(){');writeln('if (isIE){');writeln('window.resizeTo(300,300);');
		writeln('width=300-(document.body.clientWidth-document.images[0].width);');
		writeln('height=300-(document.body.clientHeight-document.images[0].height);');
		writeln('window.resizeTo(width,height);}');writeln('if (isNN){');       
		writeln('window.innerWidth=document.images["George"].width;');writeln('window.innerHeight=document.images["George"].height;}}');
		writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>');
		if (!AutoClose) writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
		else writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
		writeln('<img name="George" src="'+imageURL+'" style="display:block" alt="'+imageTitle+'"></body></html>');
		close();		
	}
}

function resizeContainer() {
	resizeContainerById('resizableContainer');
	resizeContainerById('resizableContainerRight');
}

/*
 * Synopsis: resize the resizable container to make it fill its available height
 * Function: resizeContainer 
*/
function resizeContainerById(id) {
	var footer = document.getElementById('footerFrame');
	var mainFrame = document.getElementById('mainFrame');
	var container = document.getElementById(id);
	
	// The container will never be shrunk smaller than minHeight
	var minHeight = 150; 

	if (footer != null && mainFrame != null && container != null) {
		var bodyHeight = document.body.clientHeight; // the height of the html page in the browser window
		var footPos = getAbsolutePosition(footer); // the position of the upper left corner of footer
		var mainFramePos = getAbsolutePosition(mainFrame); // the position of the upper left corner of mainFrame
		var containerPos = getAbsolutePosition(container); // the position of the upper left corner of container
		
		// deltaY is the new available height for the container. 
		var deltaY = bodyHeight - (containerPos.y - mainFramePos.y) - calculateHeight(container);
				
		if (deltaY > minHeight) {
			container.style.height = deltaY + 'px'; // Sets the container height to deltaY
			mainFrame.style.height = bodyHeight + 'px'; // Sets the mainFrame height to bodyHeight
		}
	}	
};

/*
 * Synopsis: Recursive function which calculates the sum of the height of every element below 
 * 			 element el, outwards till it reach the mainFrame.
 * Function: calculateHeight
 * Param:
 *   el: the element
 * Returns: the height  
*/
function calculateHeight(el) {
	var height = nextSiblingsHeight(el);
	var parent = el.parentNode;
	
	// As long as the parent element exist and isn't the mainFrame, we will continue to add to the total height.
	if(parent != null && parent.id != 'mainFrame') { 
		height += calculateHeight(parent);
	}
	return height;
}

/*
 * Synopsis: Calculates the sum of the heights of every sibling below element el.
 * Function: nextSiblingsHeight
 * Param:
 *   el: the element 
 * Returns the height
*/
function nextSiblingsHeight(el) {
	var h = 0;
	
	// If the element is a TD, we don't add any extra height because the element is after the previous element instead of under it.
	if(el.nodeName == 'TD') {
		return 0; 
	}
	
	if(el.nodeName == 'TABLE') { // Workaround: Need to add some extra pixels if the element is a table because of the table border width.
		h += 3; 
	}
	
	var n = getNextElement(el);		
	while(n != null) {
		h += n.offsetHeight;
		n = getNextElement(n);
	}
	return h;
};

/*
 * Synopsis: finds the next HTML element after el
 * Function: getNextElement
 * Param:
 *   el: the element 
 * Returns the next HTML element
*/
function getNextElement(el) {
 	var n = el;
 	do n = n.nextSibling;
 	while (n && n.nodeType != 1);
 	return n;
};

/*
 * Synopsis: get the absolute position of an element. Not bulletproof, but is sufficient for our needs
 * Function: getAbsolutePosition(element)
 * Params:
 *     element: the DOM element to get the position for
 * Returns: an object with x and y attributes
*/
function getAbsolutePosition(element) {
	var r = { x: element.offsetLeft, y: element.offsetTop };
	if (element.offsetParent) {
		var tmp = getAbsolutePosition(element.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
};

function addLoadListener(fn) {
	if (typeof window.addEventListener != 'undefined') {
		window.addEventListener('load', fn, false);
	} else if (typeof document.addEventListener != 'undefined') {
		document.addEventListener('load', fn, false);
	} else if (typeof window.attachEvent != 'undefined') {
		window.attachEvent('onload', fn);
	} else {
		return false;
	}

	return true;
};

function attachEventListener(target, eventType, functionRef, capture) {
	if (typeof target.addEventListener != "undefined") {
		target.addEventListener(eventType, functionRef, capture);
	} else if (typeof target.attachEvent != "undefined") {
		target.attachEvent("on" + eventType, functionRef);
	} else {
		return false;
	}

	return true;
};

/*
 * Synopsis: Trim leading/trailing whitespace off string 
 * Function: trim(str)
 * Params:
 *     str: the string which we want to trim
 * Returns: the trimed string
 * Example: "     Hello    world    " => "Hello    world"
*/
function trim(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

/* 
 * Synopsis: Remove duplicated whitespace from a string 
 * Function: removeDuplicatedWhiteSpace
 * Params:
 *   str 	: The string containing whitespace  
 * Returns: A string without whitespace
 * Example: "     Hello    world    " => " Hello world "
*/
function removeDuplicatedWhiteSpace(str) {
	return str.replace(/\s\s+/g, ' ');
}

/* 
 * Synopsis: Gets the text inside an element
 * Function: getInnerText
 * Params:
 *   el : The element containing the text 
 * Returns: Returns the text 
*/
function getInnerText(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

/* 
 * Synopsis: Gets a spesific parent to an element 
 * Function: getParent
 * Params:
 *   el       : The element 
 *   pTagName : The name of the parent element
 * Returns: Returns the parent element if it exist
*/
function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}

/*
 * Synopsis: Toggle an elements visibility on and off. 
 * Function: toggleDisplay(elementId)
 * Params:
 *     elementId: the id to the element which we want to change the visibility to.
*/
function toggleDisplay(elementId)
{
	// this is the way the standards work
	var style2 = document.getElementById(elementId).style;
	style2.display = style2.display? "":"block";
}

/*
 * Synopsis: Sets a red border on a input element with errors.
 * Function: setInputError((element)
 * Params:
 *     element: input element to set a red border on
*/
function setInputError(element) {
	element.style.borderColor="red";
}

/*
 * Synopsis: Removes a red border on a input element with errors.
 * Function: removeInputError((element)
 * Params:
 *     element: input element to remove a red border from
*/
function removeInputError(element) {
	element.style.borderColor="";
}

/*
 * Synopsis: Saves the current position in a scrollable div or list. 
 * Function: keepDivPosition(div,position)
 * Params:
 *     div: The scrollable div containing the scrollbar we want to remember the current position to.
 *	   position: The current position 	
*/
function keepDivPosition(div, position) {
	div.scrollTop = position;   
} 

attachEventListener(window, "resize", resizeContainer, false);


