// JavaScript Document
/*global window: false, document: false, LG_sitekey: false, screen: false, navigator: false */

// jslint test: 31JAN2010

"use strict";
var contentColumns,
CssColNumber = 0;
var aryClassElements = [];
var IE = false; 
if (navigator.appName === "Microsoft Internet Explorer") {
    IE = true;
}

function getElementsByClassName(strClassName, obj) {
    // used by onclicklisten
    var ar,
    re,
    i;
    ar = arguments[2];
    re = new RegExp("b" + strClassName + "b", "g");

    if (re.test(obj.className)) {
        ar.push(obj);
    }
    for (i = 0; i < obj.childNodes.length; i = i + 1) {
        getElementsByClassName(strClassName, obj.childNodes[i], ar);
        return ar;
    }
}


function setRule(selector, currentStyleParam, currentStyleValue) {
    // Used by resize_css
    var i,
    x,
    sheet,
    currSelector,
    css_rules;
    
  //  sheet = document.styleSheets[0];

 //   for (x = document.styleSheets.length - 1; 0 <= x; x = x - 1) {

        sheet = document.styleSheets[0];
        css_rules = sheet.cssRules || sheet.rules;
        for (i = css_rules.length - 1; css_rules.length - 1 <= i; i = i - 1) {

			// Lower Case needed for IE / Firefox+WebKit compatibilty
            currSelector = encodeURIComponent(css_rules[i].selectorText).toLowerCase();

            if (currSelector === selector) {

                CssColNumber = i;
                if (currentStyleParam === "width") {
                    css_rules[CssColNumber].style.width = currentStyleValue;
                    return;
                }
                if (currentStyleParam === "height") {
                    css_rules[CssColNumber].style.height = currentStyleValue;
                    return;
                }
            }
        }
   // }

}


function liveGuideGetCookie(cookieName, name) {
	// used by NetOp Live Guide
    var cookieEnd,
    cookieStart;
    if (document.cookie.length > 0) {
        cookieStart = document.cookie.indexOf(cookieName + "=");
        if (cookieStart !== -1) {
            cookieStart = cookieStart + cookieName.length + 1;
            cookieEnd = document.cookie.indexOf(";", cookieStart);
            if (cookieEnd === -1) {
                cookieEnd = document.cookie.length;
            }
            return ('&' + name + '=' + encodeURIComponent(document.cookie.substring(cookieStart, cookieEnd)));
        }
    }
    return "";
}

function liveGuideActivate() {
	// Anvendes af LiveGuideIntialize til brug for onclick paa LiveGuide knap
    var  LG_clickUrl, 
     LG_winParams,
     LGWin;

    // Set cookies
    liveGuideGetCookie('LiveGuide_' + LG_sitekey +  '_duration', 'LiveGuideCIDuration'); 
    liveGuideGetCookie('LiveGuide_' + LG_sitekey +  '_ref', 'LiveGuideCIRef');
    liveGuideGetCookie('LiveGuide_' + LG_sitekey +  '_title', 'LiveGuideCITitle');
    liveGuideGetCookie('LiveGuide_' + LG_sitekey +  '_url', 'LiveGuideCIUrl');

    // Open window
    LG_clickUrl = "http://clients.liveguide01eu.netop.com/swf.php?LiveGuideUID=" + LG_sitekey + '&amp;myurl=' + encodeURIComponent(window.location) + '&amp;title=' + encodeURIComponent(document.title);
    LG_winParams = "width=250,height=640,status=yes,left=" + (screen.availWidth - 250) + ",top=0,resizable=1";
    
    // Open window and set focus to new window
    LGWin = window.open(LG_clickUrl, "NetopWebDesk", LG_winParams);
    if (!IE) {
        // IE doesn't accept .focus events
        LGWin.focus();
    }
}

function liveGuideInitialize() {
    var LG_pictUrl,
    LG_tag_parent,
    LG_tag_a,
    LG_tag_img;
    
    LG_pictUrl = "http://clients.liveguide01eu.netop.com/status.php?LiveGuideUID=" + LG_sitekey + '&amp;from=' + encodeURIComponent(window.location);
   
    // Create elements
    LG_tag_parent = document.getElementById("LiveGuide");
    LG_tag_a = document.createElement("A");
    LG_tag_img = document.createElement("IMG");
    
    // Set parameters
    LG_tag_img.setAttribute("src", LG_pictUrl);
    LG_tag_img.setAttribute("alt", "Trigono Support");
    LG_tag_a.setAttribute("style", "cursor:pointer;");

    // Set into DOM
    LG_tag_a.appendChild(LG_tag_img);
    LG_tag_parent.appendChild(LG_tag_a);
    
    // Start onclick watch
    if (LG_tag_a.addEventListener) {
        LG_tag_a.addEventListener('click', liveGuideActivate, true); 
    } else if (LG_tag_a.attachEvent) {
        LG_tag_a.attachEvent('onclick', liveGuideActivate);
    }
}


function googleAnalytics() {
   /* Google analytics start */
    var  _gaq,
    ga;
    _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-12516949-1']);
    _gaq.push(['_trackPageview']);

    (function () {
        ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' === document.location.protocol ? 'https://ssl': 'http://www') + '.google-analytics.com/ga.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
    }
   ());
}   

function resize_css_main(contentElement) {
    var columnWidth,
    list,
    listItems,
    listItemsCount,
    minimumColumnWidth,
    columnPadding,
    contentWidth,
    cssSelector,
    contentColumns,
    contentRows,
    widthPercentage,
    columnPaddingPct,
    currentStyle,
    imageSize,
    i;
    
    list = document.getElementById(contentElement);
    if (list === null) {
        return;
    }
    
    // Finds all elements (li), and counts them
    listItems = list.getElementsByTagName('li');
    listItemsCount = listItems.length;
    
    // Determines width of main content area
    contentWidth = document.getElementById(contentElement).offsetWidth;

    // Sets number of columns based on width of main content area
    minimumColumnWidth = 230;
    columnPadding = 10;
    columnPaddingPct = Math.ceil((columnPadding / contentWidth) * 100);
    contentColumns = Math.floor(contentWidth / (minimumColumnWidth + columnPadding));
    
    // Number of columns must be in the interval [1;5]
    if (contentColumns > 5) { 
        contentColumns = 5; 
    }
    if (contentColumns < 1) { 
        contentColumns = 1; 
    }
    
    // Calculate the width of every column, and adding padding in between
    columnWidth = Math.floor(contentWidth / contentColumns) - columnPadding;
    if ((columnWidth > minimumColumnWidth * 1.3) && (contentColumns > 1)) {
        imageSize = "120px";
    } else {
        imageSize = "90px";
    }
    
    contentRows = Math.ceil(listItemsCount / contentColumns);
    widthPercentage = Math.floor(100 / contentColumns) - columnPaddingPct;
    currentStyle = widthPercentage + "%";

    // uses the class (not id) fullcol. Has to been found at the bottom of the primary CSS file.
  
        cssSelector = "ul.fullcol%20li%20%3e%20a%20img";    
    
    setRule(cssSelector, "width", imageSize);
    setRule(cssSelector, "height", imageSize);
    
    // remove all clears in list
    for (i = 0; i < listItemsCount; i = i + 1) {
        listItems[i].style.clear = "none";
        listItems[i].style.width = currentStyle;

    }
    // then set left clear on leftmost object (except 1st row) and set no padding on rightmost object in every row - ensures correct wrapping
    for (i = contentColumns; i < listItemsCount; i = i + contentColumns) {
        listItems[i].style.clear = "left";
        listItems[i - 1].style.paddingRight = "0";
    }
    listItems[listItemsCount - 1].style.paddingRight = "0";

}

function MenuvToggleSub(obj) {
    // Expands the left side navigation
    var subId,
    objName;
    objName = obj.id;
    subId = objName.charAt(objName.length - 1);
    if (obj.innerHTML !== '+') {
        // Firefox doesn't understand innertext and text is not handled by IE7.
        obj.innerHTML = '+';
        document.getElementById('menuv_sub' + subId).style.display = 'none';
    } else {
        obj.innerHTML = '–';
        document.getElementById('menuv_sub' + subId).style.display = 'inline';
    }
    return false;
}

function SearchBoxReset(obj) {
    // removes the content of the "Search box"
    var localValue,
    objValue;
    objValue = obj.value;
    localValue = document.getElementById('searchlabellocal').value;

    if (objValue === localValue) {
        obj.value = '';
    }
}

function ToggleTab(obj) {
    // used on product pages
    var selectedTab,
    tabCount,
    i;
    selectedTab = obj.id;
    tabCount = 4;
    //document.getElementById('tabContent').childNodes[0].length;
    for (i = 0; i <= tabCount - 1; i = i + 1) {
        if (document.getElementById('tab' + i)) {
            document.getElementById('Contenttab' + i).style.display = 'none';
            document.getElementById('tab' + i).style.background = '#595959';
            document.getElementById('tab' + i).style.paddingBottom = '2px';
            document.getElementById('tab' + i).style.marginBottom = '1px';
        }
    }
    document.getElementById('Content' + selectedTab).style.display = 'block';
    document.getElementById(selectedTab).style.background = '#d85208';
    document.getElementById(selectedTab).style.paddingBottom = '3px';
    document.getElementById(selectedTab).style.marginBottom = '0';
    window.location.hash='#show'+selectedTab;
}

function highlight(id,color,seconds) {
	var element = document.getElementById(id)
	var origcolor = element.style.backgroundColor
	element.style.backgroundColor = color;
	var t = setTimeout(function(){
	   element.style.backgroundColor = origcolor;
	},(seconds*1000));
}

function highlightflash(id,color) {
	var element = document.getElementById(id)
	var origcolor = element.style.backgroundColor
	var t = setTimeout(function(){
		element.style.backgroundColor = color;
		var t = setTimeout(function(){
		   element.style.backgroundColor = origcolor;
			var t = setTimeout(function(){
			   element.style.backgroundColor = color;
				var t = setTimeout(function(){
				   element.style.backgroundColor = origcolor;
				},(500));
			},(500));
		},(500));
	},(1500));
}

function initPage() { 
	resize_css_main("fullcol");
	googleAnalytics();
	liveGuideInitialize();
	if (document.getElementById("fullcol2")) {
        resize_css_main("fullcol2");
    }
    if(document.location.hash.length) {
    	var tabHash=document.location.hash.substring(5);
    	ToggleTab(document.getElementById(tabHash));
    	
    }

}
// Loading google analytics, resizer, live guide
window.onload = initPage;
