/**
 * Miscellaneous JavaScript functions for the KONE.com Business Site.
 *
 * Requires: cookies.js
 */

function alertNotSupported( reqObj )
{
    var msg;
    if (requiredFeature) {
        msg = "Unfortunately, this feature requires support for '" + reqObj
            + "',\n which is not provided by your browser.";
    } else {
        msg = "Unfortunately, this feature is not supported by your browser.";
    }
    msg += "\n\nThis service has been successfully tested with the latest\n"
        + "versions of Internet Explorer, Netscape and Mozilla. Please\n"
        + "upgrade your browser, and sorry for the inconvenience.";
    alert(msg);
}

/**
 * Front-end for session handling.
 */
var Session = {

    sessionCookie: "SMSESSION",
    localeCookie: "country",
    textSizeCookie: "preferredTextSize",
    virtualSiteCookie: "virtualSite",
    corporateLocales: ["en","fi"],
    localePrefixRegExp: /\/([a-z]{2}_[a-zA-Z]{2,3}|[a-z]{2}|master)\//,
    cookieAge: 365 * Cookies.ONE_DAY,
    cookieDomain: "kone.com",
    cookiePath: "/",
    
    isLoggedIn: function ()
    {
        var c = Cookies.get(this.sessionCookie);
        return ( c != null && c != "LOGGEDOFF" );
    },
    getPreferredLocale: function ()
    {
        return Cookies.get(this.localeCookie);
    },
    setPreferredLocale: function (loc)
    {
        Cookies.set( this.localeCookie, loc, this.cookieAge, this.cookieDomain, this.cookiePath);
    },
    getCurrentLocale: function ()
    {
        var a = this.localePrefixRegExp.exec(document.URL);
        return (a != null) ? a[1] : null;
    },
    getPreferredTextSize: function ()
    {
        return parseInt( Cookies.get(this.textSizeCookie) ) || 11;
    },
    setPreferredTextSize: function (size)
    {
        Cookies.set( this.textSizeCookie, size, this.cookieAge, this.cookieDomain, this.cookiePath);
    },
    getVirtualSite: function ()
    {
        return parseInt( Cookies.get(this.virtualSiteCookie) );
    },
    setVirtualSite: function (size)
    {
        Cookies.set( this.virtualSiteCookie, size, this.cookieAge, this.cookieDomain, this.cookiePath );
    },
    isMyKonePage: function()
    {
        return ( document.URL.indexOf("/MyKone/") != -1 );
    },
    isMyKoneContentPage: function()
    {
        return ( document.URL.indexOf("cmknavielem_id=") != -1 );
    },
    isCorporateSite: function()
    {
        var loc = this.getCurrentLocale();
        for (var i = 0; i < this.corporateLocales.length; i++) {
            if (this.corporateLocales[i] == loc) {
                return true;
            }
        }
        return false;
    },
    getUserCountry: function ()
    {
    	var lang = navigator.systemLanguage || navigator.language;
    	if (lang.length == 5)
    		return lang.substring(3, 5);
    	return null;
    }
}

/**
 * Holds attributes of a single "virtual site".
 */
function VirtualSite(id, prefix, name, topLeftImg, topLeftFlash, topRightImg)
{
	this.id = id || null;
	this.prefix = prefix || null;
	this.name = name || null;
	this.countryCode = null;
	this.topLeftImg = topLeftImg || null;
	this.topLeftFlash = topLeftFlash || null;
	this.topRightImg = topRightImg || null;
}
VirtualSite.instances = [];
VirtualSite.selectedSite = null;
VirtualSite.defaultCountryCode = null;
VirtualSite.getById = function (id)
{
	for (var i = 0; i < this.instances.length; i++) {
		var site = this.instances[i];
		if (site.id == id) {
			return site;
		}
	}
	return null;
}
VirtualSite.getSiteNameRegExp = function(siteName)
{
	return new RegExp('^\\s*(KONE)?\\s*' + siteName + '\\s*$');
}
VirtualSite.getBySiteName = function (name)
{
	var re = this.getSiteNameRegExp(name);
	for (var i = 0; i < this.instances.length; i++) {
		var site = this.instances[i];
		if (re.test(site.name)) {
			return site;
		}
	}
	return null;
}
VirtualSite.getByCountryCode = function (code)
{
	for (var i = 0; i < this.instances.length; i++) {
		var site = this.instances[i];
		if (site.countryCode == code) {
			return site;
		}
	}
	return null;
}
VirtualSite.add = function (id, prefix, name, countryCode)
{
	var site = new VirtualSite(id, prefix, name);
	site.countryCode = countryCode;
	this.instances[this.instances.length] = site;
}
VirtualSite.getSelectedByCookie = function ()
{
	var siteId = Session.getVirtualSite();
	if (!siteId)
		return null;
	var site = this.getById(siteId);
	if (site && site.prefix == Session.getCurrentLocale())
		return site;
	return null;
}
VirtualSite.getSelectedByUserCountry = function ()
{
	var country = Session.getUserCountry();
	if (!country)
		return null;
	return this.getByCountryCode(country);
}
VirtualSite.getSelectedByDefaultCountry = function ()
{
	if (!this.defaultCountryCode)
		return null;
	return this.getByCountryCode(this.defaultCountryCode);
}
VirtualSite.getSelected = function ()
{
	if (!this.selectedSite) {
		this.selectedSite = this.getSelectedByCookie()
			|| this.getSelectedByUserCountry()
			|| this.getSelectedByDefaultCountry();
	}
	return this.selectedSite;
}
VirtualSite.writeIf = function (siteName, html)
{
	var currentSite = this.getSelected();
	var re = this.getSiteNameRegExp(siteName);
	if (!(currentSite && re.test(currentSite.name)))
		return;
	document.write(html);
}

/**
 * Front-end for changing the text size.
 */
var TextSize = {

    normal: 11,
    big: 13,
    current: 11,
    
    change: function (reportNotSupported)
    {
        var eHtml = document.documentElement, eBody = document.body;
        if (!(eHtml || eBody)) {
            if (reportNotSupported) {
                alertNotSupported();
            }
            return false;
        }
        var cssSize, imgSrc;
        if (this.current == this.normal) {
            this.current = this.big;
            imgSrc = "icon_magn_2.gif";
        } else {
            this.current = this.normal;
            imgSrc = "icon_magn_1.gif";
        }
        cssSize = this.current + "px";
        imgSrc = "/pics/bizsite/" + imgSrc;
        
        if (eHtml)
            eHtml.style.fontSize = cssSize;
        if (eBody)
            eBody.style.fontSize = cssSize;
        Session.setPreferredTextSize(this.current);
        
        var img;
        if (document.getElementById) {
            img = document.getElementById("textSizeIcon");
        } else if (document.all) {
            img = document.all["textSizeIcon"];
        }
        if (img) {
            img.src = imgSrc;
        }
        return false;
    },
    setPreferred: function ()
    {
        var prefSize = Session.getPreferredTextSize();
        if (prefSize != this.current) {
            this.change( false );
        }
    }
}

/**
 * Simple navigation related functions.
 */
var Navigation = {

    backToTop: function()
    {
        if (window.scrollTo) {
            window.scrollTo(0,0);
            return false;
        }
        return true;
    },
    
    backToPrevious: function()
    {
        history.go(-1);
        return false;
    },
    
    overLoginLink: function()
    {
        if (this.style)
            this.style.textDecoration = "underline";
        return true;
    },
    outLoginLink: function()
    {
        if (this.style)
            this.style.textDecoration = "none";
        return true;
    },
    overLoginIconLink: function()
    {
        if (document.getElementById) {
            var loginLink = document.getElementById("loginLink");
            if (loginLink) {
                loginLink.style.textDecoration = "underline";
            }
        }
        return true;
    },
    outLoginIconLink: function()
    {
        if (document.getElementById) {
            var loginLink = document.getElementById("loginLink");
            if (loginLink) {
                loginLink.style.textDecoration = "none";
            }
        }
        return true;
    }
}

/**
 * Allows several onload handlers to be defined cumulatively.
 */
var OnLoadHandler = {

    functions: [],

    add: function (f)
    {
        var funcs = OnLoadHandler.functions;
        funcs[funcs.length] = f;
    },
    
    doOnLoad: function()
    {
        var funcs = OnLoadHandler.functions;
        for (var i = 0; i < funcs.length; i++) {
            funcs[i]();
        }
    }
}
window.onload = OnLoadHandler.doOnLoad;

var initialSearchText = "";

OnLoadHandler.add( function () {

    if (document.getElementById) {
        var search = document.getElementById("search");
        if (search) {
            //search.value = "Search";
            initialSearchText = search.value;
            search.onfocus = function () {
                if (this.value == initialSearchText) {
                    this.value = "";
                }
            };
        }
        var loginLink = document.getElementById("loginLink");
        var loginIconLink = document.getElementById("loginIconLink");
        if (loginLink && loginIconLink) {
            loginIconLink.textLinkStyle = loginLink.style;
            loginLink.onmouseover = loginIconLink.onmouseover = function () {
                (this.textLinkStyle || this.style).textDecoration = "underline";
                return true;
            }
            loginLink.onmouseout = loginIconLink.onmouseout = function () {
                (this.textLinkStyle || this.style).textDecoration = "none";
                return true;
            }
        }
    }
    // Set PDF links to open in a new window
	if (document.getElementsByTagName) {
		var links = document.getElementsByTagName("A");
		for (var i = 0; i < links.length; i++) {
			var link = links[i];
			var url = link.href;
			if (url && url.toLowerCase().lastIndexOf('pdf') == (url.length - 3) && url.indexOf('/media/') != -1) {
				link.target = '_blank';
			}
		}
	}
} );
