/* 

common.js  


*/

var DNA = {};

function init() {

	//createTableStripe();
	linkActions();
	formTooltips();
	showHideFieldset();
	salespointList();
	
}
	
function DNA_init() {
    //DNA.SetEqualHeightColumns.Init({id:'reference', tag:'div', css:'column'})
}

/*

function for even and odd table row backgrounds

*/

function createTableStripe() {	
	var tables = document.getElementsByTagName("table");  

	for(var x=0;x!=tables.length;x++){
		var table = tables[x];
		if (! table) { return; } 

		var tbodies = table.getElementsByTagName("tbody");

		for (var h = 0; h < tbodies.length; h++) {
			var even = true;
			var trs = tbodies[h].getElementsByTagName("tr");

			for (var i = 0; i < trs.length; i++) {
				trs[i].onmouseover=function(){
					this.className += " ruled"; return false
				}
				trs[i].onmouseout=function(){
					this.className = this.className.replace("ruled", ""); return false
				}

				if(even)
				  trs[i].className += " even";

				even = !even;
			}
		}
	}
}


/* create new windows from css-class="new-window" */

// Create the new window
function openInNewWindow() {
    // Change "_blank" to something like "newWindow" to load all links in the same new window
    var newWindow = window.open(this.getAttribute('href'), 'newWindow',',resizable=1,width=450,height=458');
    newWindow.focus();
    return false;
}

// Close window
function closeWindow() {
    window.close();
}


// Close layer
function removeNodes(id) {
	var elem = document.getElementById(id);
	if (!elem)
		return;
	while (elem.firstChild) {
		elem.removeChild(elem.firstChild);
	}
	elem.parentNode.removeChild(elem);
}

// Form tooltips
function formTooltips() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		// find all inputs
		var inputs = document.getElementsByTagName('input');
		var elemInput;
		for (var i = 0; i < inputs.length; i++) {
			elemInput = inputs[i];
			if (/\btooltip\b/.exec(elemInput.className)) {
				elemInput.onfocus = function() {
					var tmpElm = this.nextSibling;
					
					while (tmpElm.nodeType != 1) {
						tmpElm = tmpElm.nextSibling;
					}
					tmpElm.className = 'form-tooltip-show'
				};
				
				elemInput.onblur = function() {
					var tmpElm = this.nextSibling;
					
					while (tmpElm.nodeType != 1) {
						tmpElm = tmpElm.nextSibling;
					}
					tmpElm.className = 'form-tooltip'
				};
				
			}
			
		}
	}
}

// Form required tooltips
function formRequiredTooltips() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		// find all inputs
		var inputs = document.getElementsByTagName('input');
		var elemInput;
		for (var i = 0; i < inputs.length; i++) {
			elemInput = inputs[i];
			if (/\brequired\b/.exec(elemInput.className)) {
				elemInput.onfocus = function() {
					var tmpElm = this.parentNode;
					var tooltip = document.createElement('span');
					tooltip.setAttribute('id','tooltip-required');
					tooltip.className = 'form-tooltip-required';
					var tooltipWrap = document.createElement('span');
					tooltipWrap.className = 'form-tooltip-required-wrap';
					tooltipWrap.innerHTML = 'Täydennä pakollinnen tieto';
					
					tooltip.appendChild(tooltipWrap);
					tmpElm.appendChild(tooltip);
				};
				
				elemInput.onblur = function() {
					var oNodeToRemove = document.getElementById('tooltip-required');
    					oNodeToRemove.parentNode.removeChild(oNodeToRemove);
				};
				
			}
			
		}
	}
}

// Show hide fieldset via checkbox
function showHideFieldset() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		// find all inputs
		var inputs = document.getElementsByTagName('input');
		var elemInput;
		for (var i = 0; i < inputs.length; i++) {
			elemInput = inputs[i];
			if (/\bopen\-fieldset\b/.exec(elemInput.className)) {
				if (elemInput.checked) {
					toggleFieldset('visible');
				} else {
					toggleFieldset('hidden');
				}
					
				elemInput.onclick = function() {
					if (this.checked) {
						toggleFieldset('visible');
					} else {
						toggleFieldset('hidden');
					}
				};				
			}
			
		}
	}
}

function toggleFieldset(type) {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		// find all fieldsets
		var fieldsets = document.getElementsByTagName('fieldset');
		var elemFieldset;
		for (var i = 0; i < fieldsets.length; i++) {
			elemFieldset = fieldsets[i];
			if (/\bfieldset\-hidden\b/.exec(elemFieldset.className) || /\bfieldset\-visible\b/.exec(elemFieldset.className) ) {
				if (type == 'visible') {
					elemFieldset.className = 'fieldset-visible';
				} else {
					elemFieldset.className = 'fieldset-hidden';
				}
			}
			
		}
	}
}


// Add the linkActions function to the onclick event of links with a class name of "new-window"
function linkActions() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		// Change this to the text you want to use to alert the user that a new window will be opened
		var strNewWindowAlert = " ";
		// Find all links
		var links = document.getElementsByTagName('a');
		var objWarningText;
		var strWarningText;
		var link;
		for (var i = 0; i < links.length; i++) {
			link = links[i];
			// Find all links with a class name of "new-window"
			if (/\bnew\-window\b/.exec(link.className)) {
				// Create an em element containing the new window warning text and insert it after the link text
				objWarningText = document.createElement("em");
				strWarningText = document.createTextNode(strNewWindowAlert);
				objWarningText.appendChild(strWarningText);
				link.appendChild(objWarningText);
				link.onclick = openInNewWindow;
			}
			
			// Find all links with a class name of "close-window"
			if (/\bclose\-window\b/.exec(link.className)) {
				// Create an em element containing the new window warning text and insert it after the link text
				objWarningText = document.createElement("em");
				strWarningText = document.createTextNode(strNewWindowAlert);
				objWarningText.appendChild(strWarningText);
				link.appendChild(objWarningText);
				link.onclick = closeWindow;
			}
			
			// Find all links with a class name of "close-layer"
			if (/\bclose\-layer\b/.exec(link.className)) {
				// Create an em element containing the new window warning text and insert it after the link text
				objWarningText = document.createElement("em");
				strWarningText = document.createTextNode(strNewWindowAlert);
				objWarningText.appendChild(strWarningText);
				link.appendChild(objWarningText);
				link.onclick = function() {
					removeNodes('dna_alert');
				};
			}
		}
		objWarningText = null;
	}
}

function salespointList() {
	if (document.all&&document.getElementById) {
		navRoot = document.getElementById("salespoint-selector");
		
		if(!navRoot)
			return
		
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
  		}
 	}
}

/*

Sets Equal height to columns

Initialize by calling DNA.SetEqualHeightColumns.Init which accepts a JavaScript object or an array of Javascript objects as a parameter

Objects passed as parameters must contain attributes:
	id: columns element parent id in HTML (str)
	tag: column tagnames (str)
	css: CSS classes (str) from which columns are identified

Example: DNA.SetEqualHeightColumns.Init({id:'reference', tag:'div', css:'column'});

*/
DNA.SetEqualHeightColumns = function () {
	
	var ELEMENTS = {},
		BROWSER_LT_IE7 = false,
		MONITOR_FONT_SIZE = true, 			// Font size change monitoring on/off
		MONITOR_FONT_SIZE_INTERVAL = 500, 	// How often font-size change is monitored
		ENABLE_DISPLAY_TABLE = true, 		// enable display:table when users browser supports it
		UA = navigator.userAgent;
	
	// Returns true if browser is IE and version is < 7
	function ieCheck() {
		
		return (UA.indexOf('MSIE') > -1 && UA.indexOf('Opera') === -1) ? ((parseFloat(navigator.appVersion.split('MSIE')[1]) < 7) ? true : false) : false;
		
	}
	
	// Set height or minHeight. Height if browser < IE 7
	function setHeight(el, h) {
		
		return (BROWSER_LT_IE7) ? el.style.height = h : el.style.minHeight = h;
		
	}
	
	// Set equal height elements according to the highest element
	function setEqualHeight() {

		var	refHeight = 0,
			height, 
			columns, 
			i, j;
		
		for (i in ELEMENTS) {

			if (ELEMENTS.hasOwnProperty(i)) {
				
				columns = ELEMENTS[i];
				
				for (j = 0; j < columns.length; j++) {
					
					// Reset height
					setHeight(columns[j], '1%');
					
					// Get element heights
					height = columns[j].clientHeight;
					
					// Get highest element
					if (height > refHeight) {
						refHeight = height;
					}

				}
				
				// set column heights to highest
				for (j = 0; j < columns.length; j++) {
					setHeight(columns[j], refHeight + 'px');
				}
			
			}
		
		}
			
		return null;
		
	}
	
	// Monitor if font size has changed using a refenence element height
	function monitorFontSizeChange() {
		
		var ref = document.getElementById('ref'), 
			refElement = document.createElement('div'),
			refHeight = 0,
			newHeight = 0;

		// Create refernce element if none exists
		if (!ref) {
			refElement.id = 'ref';
			document.getElementsByTagName('body')[0].appendChild(refElement);
		}
		else {
			refElement = ref;
		}
		
		// Get element height
		refHeight = refElement.clientHeight;
		
		// Periodiacally check for reference element size changes
		window.setInterval(function () {
			
			// Check if reference element height has changed
			newHeight = refElement.clientHeight;
			if (newHeight !== refHeight) {
				refHeight = newHeight;
				setEqualHeight();
			}
		
		}, MONITOR_FONT_SIZE_INTERVAL);
		
		return null;
	
	}
			
	// Initialize
	//  @param obj : JavaScript object or an array oy objects 
	//	obj.id	: columns parent element id
	//	obj.tag: column tags inside columns element
	//	obj.css :  CSS classname of the column element
	function init(obj) {
	
		var arr,
			cols_parent,
			cols,
			matches = false,
			css_display_table_support = false,
			i, j;

		// If obj is not an array make one
		if (typeof obj[0] === 'undefined') {
			obj = [obj];
		}

		// Browser check
		BROWSER_LT_IE7 = ieCheck();

		// Loop through objects
		for (i = 0; i < obj.length; i++) {
			
			// Check if element can be found
			cols_parent = document.getElementById(obj[i].id);
		
			if (!cols_parent) {
				return;
			}
			
			// Check if display:table support is enabled
			if (ENABLE_DISPLAY_TABLE) {
			
				// See if display:table is supported
				try {
					cols_parent.style.display = 'table';
					cols_parent.className += ' table-row';
					css_display_table_support = true;
				}
				catch (e) {}
			
			}
			
			arr = [];
			cols = cols_parent.getElementsByTagName(obj[i].tag);
			
			// CSS classes must match
			for (j = 0; j < cols.length; j++) {
				if (cols[j].className.match(obj[i].css)) {
					
					if (!css_display_table_support) {
						arr.push(cols[j]); 
					}
					else {	
						cols[j].className += ' table-cell';
					}
					matches = true;
				}			
			}
			
			// No matching elements found
			if (!matches) {
				return;
			}
			
			if (!css_display_table_support) {
			
				// Add to list of elements to be updated
				ELEMENTS[cols_parent.id] = arr;
			
			}
		
		}
		
		// Use display table  instead of JavaScript if user's browser supports it
		if (!css_display_table_support) {
		
			// Set equal height columns
			setEqualHeight();

			// Monitor font size changes if enabled
			if (MONITOR_FONT_SIZE) {
				monitorFontSizeChange();
			}
		
		}
		
		return null;
		
	}
	
	return {
		
		Init: function (obj) {
			return init(obj);
		}
	
	};
	

}();


_spBodyOnLoadFunctionNames.push('DNA_init');
Initializers.add(function(){init()});
