// Additional JS for EKORNES ASA by Sebastian Brage Hansen

/*------------------- GLOBAL VARS ---------------------------------*/
var d = document;
var u = undefined;

var agnt = navigator.userAgent.toLowerCase();
var isOpera = agnt.indexOf('opera') >= 0? true: false;
var isIE = agnt.indexOf('msie') >= 0 && !isOpera? true: false;
var isSafari = agnt.indexOf('safari') >= 0 || agnt.indexOf('khtml') >= 0? true: false;
var isFF = agnt.indexOf('firefox') >= 0 ? true: false;

/*------------------- GLOBAL FUNCTIONS ---------------------------------*/
function isString(o) { return (typeof(o) == "string"); }
/* ///////////////////////////////////////////////////////////
ADDEVENT
Sets event

VARIABLES:
e: element to set event on
meth: trigger
funct: function to set

RETURNS:
Nothing
///////////////////////////////////////////////////////////*/
function ek_addEvent(e, meth, func, cap) {
	if (isString(e))	e = document.getElementById(e);

	if (e.addEventListener){
		e.addEventListener(meth, func, cap);
    	return true;
	}	else if (e.attachEvent)
		return e.attachEvent("on"+ meth, func);
	return false;
}
/* ///////////////////////////////////////////////////////////
TABSWITCH/SelectTab
Higlight tabs from selection. Works with template.

VARIABLES:
tab: name/value of tab
id: kmpid of template

RETURNS:
nothing
///////////////////////////////////////////////////////////*/
function selectTab(obj){
	// SWITCH HEADING
	var temp = obj.parentNode.childNodes;
	var sibl = new Array();
	for(i=0;i<temp.length;i++){
		if(temp[i].nodeType == 1)
			sibl.push(temp[i]);
	}
	for(i=0;i<sibl.length;i++){
		sibl[i].className = 'xx';
	}
	obj.className = 'selected';
	
	// SWITCH CONTENT
	var title = obj.title;
	var obj2 = $('t'+title);
	var temp = obj2.parentNode.childNodes;
	var sibl2 = new Array();
	for(i=0;i<temp.length;i++){
		if(temp[i].nodeType == 1)
			sibl2.push(temp[i]);
	}
	for(i=0;i<sibl2.length;i++){
		sibl2[i].style.display = 'none';
	}
	obj2.style.display = 'block';
	var tFx = new Fx.Style(obj2,'opacity').start(0,1);
}
function preselect(id,num){

console.log('id: ' + id + ', num: ' + num);
	if(num > 0) num--;
console.log('id: ' + id + ', num: ' + num);
	if(!num) var num = 0;
	var sel = false;
	var obj = $(id).childNodes;
	var temp = new Array();
	for(i=0;i<obj.length;i++){
		if(obj[i].title){
			temp.push(obj[i]);
		}
		if(obj[i].selected){
			obj[i].selected = false;
			sel = true;
		}
	}
	if(sel)
		temp[num].selected = true;
console.log(temp);
	selectTab(temp[num]);
}

function tabSwitch(tab,id){
/*------ Highlight selector tab -------*/
	var temp = $('tabList-tabs-'+id);
	if(isset(temp)){
		var temp1 = temp.childNodes;
		for(i=0;i<temp1.length;i++){
			if(temp1[i].nodeType == 1){
				if(temp1[i].id == 'sel-'+tab+'-'+id)
					temp1[i].className = 'selected';
				else
					temp1[i].className = '';
			}
		}	
	}
		
/*------ Show hide info -------*/
	var temp1 = $('tabList-'+id);
	var temp = temp1.childNodes;
	for(i=0;i<temp.length;i++){
		if(temp[i].nodeType == 1){
			temp[i].style.display = 'none';
		}
	}
	$('tab-' + tab + '-' + id).setStyle('opacity',0);
	$('tab-' + tab + '-' + id).setStyle('display','block');
	var myFx = new Fx.Style($('tab-' + tab + '-' + id), 'opacity').start(0,1);
}
/* ///////////////////////////////////////////////////////////
UPDATESAPFRAME
Load trigger for SAP IFRAME. 

VARIABLES:
optn: What case is used. 0 when null.

RETURNS:
Nothing but manipulates #SAP_iframeContainer
///////////////////////////////////////////////////////////*/
function updateSapFrame(optn){
if(!optn) var optn = 0;
switch (optn){
	case 0:
		var oldFrame = document.getElementById('sap-dealer');
		var container = oldFrame.parentNode;
		container.removeChild(oldFrame);
		
		var newFrame = oldFrame.cloneNode(true);
		newFrame.src=newFrame.src.replace(/portal\.ekornes\.[\.\w]+/, "portal.ekornes.com");
		oldFrame=null;
		
		container.appendChild(newFrame);
		optn++;
		window.checkState = setTimeout("updateSapFrame("+optn+")", 2000);
	break;
	
	case 1:
		var oldFrame = document.getElementById('sap-dealer');
		var container = oldFrame.parentNode;
		container.removeChild(oldFrame);
		
		var newFrame = oldFrame.cloneNode(true);
		newFrame.src=newFrame.src.replace(/portal\.ekornes\.[\.\w]+/, "isa.ekornes.com:50000");
		oldFrame=null;
		
		container.appendChild(newFrame);
		optn++;
		window.checkState = setTimeout("updateSapFrame("+optn+")", 2000);
	break;
	
	case 2:
		clearTimeout(window.checkState);
		document.getElementById('SAP_iframeContainer').className += ' complete';
	break;
	
	default:
		document.getElementById('SAP_iframeContainer').className += ' error';
	break;
	}
}
/* ///////////////////////////////////////////////////////////
ISSET (redundant)
Checks if the passed variable contains data

VARIABLES:
*a: variables to check

RETURNS:
Boolen (true/false)
///////////////////////////////////////////////////////////*/

function isset(a){
if(a === u || a === '' || a === null){ return false;}
else{ return true;}
}

/* ///////////////////////////////////////////////////////////
GETID
Gets the DOM element with ID passed ID.
Short version of document.getElementById()
Does not use isset() for speed issues

VARIABLES:
*id: What ID to find
doc: Where to look for the ID (document, body, head, other)

RETURNS:
HTML Element
///////////////////////////////////////////////////////////*/
function getId(id, doc){
	if(u === doc || doc === ''){doc = d;}
	return doc.getElementById(id);
}

/* ///////////////////////////////////////////////////////////
GETTAGS
Gets the DOM elements with TAGNAME = passed TAGNAME.
Short version of document.getElementsByTagName()
Does not use isset() for speed issues

VARIABLES:
tag: What tag to find (img, a, p, h1, other) (optional, returns all tags)
doc: Where to look for the ID (document, body, head, other) (optional, search in document)

RETURNS:
Array with HTML Elements
///////////////////////////////////////////////////////////*/
function getTags(tag, doc){
	if(u === doc || doc === ''){doc = d;}
	if(u === tag || tag === ''){tag = '*';}
	return doc.getElementsByTagName(tag);
}
/* ///////////////////////////////////////////////////////////
GETTAGCLASS
Gets the DOM elements with CLASS = passed CLASS and optional TAGNAME.
Does not use isset() for speed issues

VARIABLES:
iClass: what class to find (suports one class within many: getTagClass('hookme') will match class="bignumber hookme left")
tag: What tag to find (img, a, p, h1, other) (optional, returns all tags)
doc: Where to look for the ID (document, body, head, other) (optional, search in document)

RETURNS:
Array with HTML Elements
///////////////////////////////////////////////////////////*/
function getTagClass(tClass, tag, doc) {

	if(u === doc || doc === ''){doc = d;}
	if(u === tag || tag === ''){tag = '*'};
	
	temp = getTags(tag,doc);
	var classTags = new Array();
	for(i=0;i<temp.length;i++){
		ttClass = temp[i].className;
		tempArr = ttClass.split(' ');
		
		for(ii=0;ii<tempArr.length;ii++){
			if(tempArr[ii] == tClass){
				classTags.push(temp[i]);
				break;
			}
		}
		
	}
return classTags;
}
/* ///////////////////////////////////////////////////////////
NEWTABLE
Creates a table HTML Element with Y rows and X cells in each row.

VARIABLES:
y: Number of Rows in table
x: Number of cells in ewach row
id: ID of the created Table (optional)

RETURNS:
HTML TABLE Element
///////////////////////////////////////////////////////////*/
function newTable(y, x, id){

if(!isset(y)){y = 1;}
if(!isset(x)){x = 1;}
if(!isset(id)){id = false;}

var tr = new Array();
var td = new Array();

//create TABLE-element
var table = d.createElement('table');
var tbody = d.createElement('tbody');
if(id){table.setAttribute('id', id);}

for(var i=0; i<y; i++){ //Create #n TR
	tr[i] = d.createElement('tr');
	tr[i].setAttribute('id', 'row'+i);

	for(var j=0; j<x; j++){ //Create #n TD
		td[j] = d.createElement('td');
		td[j].setAttribute('id', i + '' + j);
		tr[i].appendChild(td[j]); //Put TD in TR
	}
	tbody.appendChild(tr[i]);
}
table.appendChild(tbody);
return table;
}

/*------------------- CUSTOM FUNCTIONS ---------------------------------*/
/* ///////////////////////////////////////////////////////////
WRITE301URL		
Gathers and shortens URL according to the 301 Error page fix.

VARIABLES:
None

RETURNS:
Nothing
///////////////////////////////////////////////////////////*/
function write301URL() {
URL = window.location.href;
if(URL.length > 64){
URL = URL.substr(0, 60) + '&nbsp;...';
}
document.write('"'+URL+'"');
}
/* ///////////////////////////////////////////////////////////
SHOW/HIDETOOLTIP
Shows or hides a tooltip

VARIABLES:
id: the ID to be shown/hidden

RETURNS:
Nothing
///////////////////////////////////////////////////////////*/
function showToolTip(id){
var tip = document.getElementById(id);
tip.style.display = 'block';
}
function hideToolTip(id){
var tip = document.getElementById(id);
tip.style.display = 'none';
}
/* ///////////////////////////////////////////////////////////
OSCILLATETABLE	
Alternet style on every second row of the table.

VARIABLES:
tableId = Id of the table that is going to be changed,
color = new bg-color of every other row.

RETURNS:
String with domain from top levle and down to spesified
///////////////////////////////////////////////////////////*/
function oscillateTable(tableId, color) {

if(!isset(color)){color = '#EFEFEF';}

container = getId(tableId);
tr = getTags('tr', container);
trigger = false;
for(i=0; i<tr.length; i++){
if(trigger){tr[i].style.background = color;}
trigger = !trigger;
}
}
/* ///////////////////////////////////////////////////////////
WRITECLIENTDOMAIN	
Extracts domain name with parents and returns it as a sting.

VARIABLES:
domainName = which domain to return with parents,

RETURNS:
String with domain from top levle and down to specified
///////////////////////////////////////////////////////////*/
function getDomain(domainName){
	clientURL = window.location.href;
	urlArr = clientURL.split('/');
	allDomains = urlArr[2];
	return allDomains.substring(allDomains.lastIndexOf(domainName));
}
/* ///////////////////////////////////////////////////////////
SETCAPTION
v.3.1 of MakeImgText. Fixed issue with table expanding indefenatly in IE.
Fixed IE7 bug. Fixed onload event. Changed so it sorts document, not just ID.

Crates a container Div, enters caption from alt and title

VARIABLES:
Call with no argument: Runs on 'document.body'

RETURNS:
Nothing
///////////////////////////////////////////////////////////*/
function makeImgCaption() {
	var offset = isIE?20:0;
	var expandOffset = 5;
	var allTags = getTags('*');
	var imgs = new Array;
	
	for(i=0;i<allTags.length;i++){
		if(allTags[i].tagName == 'IMG'){
			if(allTags[i].className.indexOf('setCaption')>-1 && allTags[i].className.indexOf('noCaption')==-1)
				imgs.push(allTags[i]);
		}
		else {
			if(allTags[i].className.indexOf('setCaption')>-1 && allTags[i].className.indexOf('noCaption')==-1){
				var ttemp = getTags('img', allTags[i]);
				for(ii=0;ii<ttemp.length;ii++){
					imgs.push(ttemp[ii]);
				}
			}
		}
	}
    for (i = 0; i < imgs.length; i++) {
        
		var img = imgs[i];
		
		var text = img.title + " " + img.alt;
		var height = img.height; 
		var width = img.width; // - offset; //The offset only occurs on some pages. Removing since the most prominent are not effected. Correction for 20px offset in IE where margin is added to width.
		
		//cssFloat is FF only. Set in if in case of updates to FF3.
		var align = isset(img.style.cssFloat) ? img.style.cssFloat : (isset(img.style.styleFloat) ? img.style.styleFloat : img.align);
        if (align != "left" && align != "right") {
            align = "center";
        }
        
		var pos = img.parentNode;
        if (pos.nodeName == "A") {
			pos.appendChild(img);
			img = pos;
            pos = pos.parentNode;
			a = true;
        }
		
		var container = d.createElement("div");
        container.setAttribute(isIE ? "className" : "class", "imgCaption" + " img" + align);
        container.style.width = width + 'px';
		
		pos.insertBefore(container, img);
		container.appendChild(img);
		
		var textContainer = d.createElement("div");
		var textNode = d.createTextNode(text);
		textContainer.innerHTML = text; //.appendChild(textNode);//
		container.appendChild(textContainer);
    }
}
/*
/* ///////////////////////////////////////////////////////////
SETDOWNLOAD
Crawl links and sett download Headers for files that should be sent as DL rather than link.
Use on PDF and similar files that tend to crash browser.

VARIABLES:
none

RETURNS:
nothing
///////////////////////////////////////////////////////////*/
function setDownload(){
	var allTags = getTags('*');
	var a = new Array();
	
	for(i=0;i<allTags.length;i++){
		if(allTags[i].tagName == 'A'){
			if(allTags[i].className.indexOf('setDownload')>-1 && allTags[i].className.indexOf('noDownload')==-1)
				a.push(allTags[i]);
		}
		else {
			if(allTags[i].className.indexOf('setDownload')>-1 && allTags[i].className.indexOf('noDownload')==-1){
				var ttemp = getTags('A', allTags[i]);
				for(ii=0;ii<ttemp.length;ii++){
					a.push(ttemp[ii]);
				}
			}
		}
	}
	
	for(i=0;i<a.length;i++){
		a.href = 'index.php?c_=EkornesImageGallery&m_=showPicture&filelocation=' + a.href;
	}
}

/* ///////////////////////////////////////////////////////////
SHORTEN TEXT
Cut text at last space after x char,
if there is no space within the x chars, the text is cut at x.

VARIABLES:
*str: string to operate on.
strln: Max length for returned string. 350 by default.
cutchar: What kind of char(s) should be put after the cut. Uses default if not set.

RETURNS:
String
///////////////////////////////////////////////////////////*/
function shortenText(str, strln, cutchar) {

	if(!isset(strln)){strln = 350;}
	if(!isset(cutchar)){cutchar = ' ...';}

	if(str.length > strln) {
		tempStr = str.substring(0, strln);
	 
		var temp = tempStr.substring(0, tempStr.lastIndexOf(' '));
		if (temp.length > 1){
			tempStr = temp;
		}
		str = tempStr + '<span class="textCut">'+ cutchar +'</span>';
	}
	document.write(str);
}

/* ///////////////////////////////////////////////////////////
FIX_CLASS_WIDTH_DIV
Set with of object with specified ID
For fixing problem with content menu not aligning in Fire Fox.
Sets new with for DIV's of given class.
Function not used any more, solved with overflow:hidden;

VARIABLES:
*the_class = Which ID attribute to search within,
*width: Width to put on object.

RETURNS:
Nothing
///////////////////////////////////////////////////////////*/
function fix_class_width_div(the_class, width) {

	var arr;
	var alltags=document.getElementsByTagName('div');
	
	for (i=0; i<alltags.length; i++){
		if (alltags[i].className==the_class){
			var thewidth = alltags[i].style.width;
			alltags[i].style.width = width+'px';
			}
	}
	
}

/* ///////////////////////////////////////////////////////////
WIDTH_FIX
Set with of object with spesified ID
Made to fixe problem with content av menu not aligning in Fire Fox.
Function not used any more, solved with overflow:hidden;

VARIABLES:
*id = Which ID attribute to search within,
*width: Width to put on object.

RETURNS:
Nothing
///////////////////////////////////////////////////////////*/
function width_fix(id, width) {
	document.getElementById(id).width = width;
}
/* ///////////////////////////////////////////////////////////
FLOATFIXHACKAUTO
For fixing glitches with objects not floating in Fire Fox.
Phases documents for all DIV elements, checks if they float and resets
the float if they do.

VARIABLES:
none

RETURNS:
nothing
///////////////////////////////////////////////////////////*/
function floatFixHackAuto(){
tags = document.getElementsByTagName('div');
	for(i=0;i<tags.length;i++){
		if(tags[i].style.cssFloat == 'left'){
		tags[i].style.cssFloat = 'left';
	}
		if(tags[i].style.cssFloat == 'right'){
		tags[i].style.cssFloat = 'right';
	}
	}
}
/* ///////////////////////////////////////////////////////////
FLOATFIXHACK
For fixing glitches with objects not floating in Fire Fox.
Phases documents for all DIV elements, checks if they float and resets
the float if they do.

VARIABLES:
none

RETURNS:
nothing
///////////////////////////////////////////////////////////*/
function floatFixHack(trigger) {
if(isset(trigger)){
	if(!isIE){
		tags = document.getElementsByTagName('div');
			for(i=0;i<tags.length;i++){
			tag = tags[i];
			if(tag.className == 'sidemenu'){
				tag.className == '';
				tag.className == 'sidemenu'
				tag.style.cssFloat = 'left';
				//tag.style.width = '190px';
				tag.style.overflow = 'hidden';
			}
			if(tag.className == 'content'){
				tag.className == '';
				tag.className == 'content'
				tag.style.cssFloat = 'right';
				//tag.style.width = '550px';
				tag.style.overflow = 'hidden';
			}
			}
		}
	}else {
		setTimeout("floatFixHack('true')",10);
	}
}/*
function floatFixHack(trigger) {
if(isset(trigger)){
	if(!isIE){
		tags = document.getElementsByTagName('div');
			for(i=0;i<tags.length;i++){
			tag = tags[i];
			if(tag.className == 'content'){
				tag.style.position = 'relative';
				tag.style.top = '0px';
			}
			}
		}
	}else {
		setTimeout("floatFixHack('true')",10);
	}
}

*/
/* ///////////////////////////////////////////////////////////
FIREFOXLOATFIX
For fixing a glitch with menu and content not aligning in Fire Fox.
Gets objects, adds style, rearranges them to force drop of menu.

VARIABLES:
none

RETURNS:
nothing
///////////////////////////////////////////////////////////*/
function firefoxfloatfixhack(){
	if(document.getElementById('fixTheMenu')){
		//Get DOM's
		var tMenu=document.getElementById('fixTheMenu');
		var container=tMenu.parentNode;
		var offset = document.getElementById('kqbar')?'218px':'132px';

		//Add position to align to top
		tMenu.style.position='absolute';
		tMenu.style.top=offset;

		//Rearrange order to get menu to drop rather than content
		container.removeChild(tMenu);
		container.appendChild(tMenu);
	}
}
/* ///////////////////////////////////////////////////////////
EMAILCLEANER
Cleans HTML markup in e-mails to fool spambots.
Sets (dot) and (at) to . and @ then removes anything within parentheses if @ is part of an anchor or anchor text.
Users can this way set proffered flag (remove), (delete) etc.
Brackets validate though W3C as part of anchors but are not supported in e-mails.

VARIABLES:
none

RETURNS:
nothing
///////////////////////////////////////////////////////////*/
function cleanEmail(){
	var a = document.getElementsByTagName('a');
	
	for(var i=0, aLen = a.length; i<aLen; i++){
		//Working with copys to reduse calculation (working directly on DOM takes more rescources)
		var eHTML = a[i].innerHTML;
		var eHref = a[i].href;
		
		//(dot) -> . && (at) -> @
		eHTML = eHTML.replace(/(\(at\))/g,'@');
		eHTML = eHTML.replace(/(\(dot\))/g,'.');		
		eHref = eHref.replace(/(\(at\))/g,'@');
		eHref = eHref.replace(/(\(dot\))/g,'.');
		
		//Remove whatever text is inside parantheses first.(remove)last(delete) -> first.last
		if(eHref.indexOf('@') >= 0)
			eHref = eHref.replace(/\(([^\(|^\)])*\)/g, '');
		if(eHTML.indexOf('@') >= 0)
			eHTML = eHTML.replace(/\(([^\(|^\)])*\)/g, '');
	
	//Put string back in DOM
	a[i].href = eHref;
	a[i].innerHTML = eHTML;
	}
}
/*------------------- Initialize ---------------------------------*/
ek_addEvent(window, 'load', makeImgCaption)
ek_addEvent(window, 'load', cleanEmail)
ek_addEvent(window, 'load', setDownload)
if(isFF) ek_addEvent(window, 'load', firefoxfloatfixhack)
