function setTimedCookie(c_name, value, exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function readCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
          x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
          y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
          x=x.replace(/^\s+|\s+$/g,"");
          if (x==c_name)
          {
            return unescape(y);
          }
    }
}

function countrySelectedChanged(countryIndex)
{
    setTimedCookie('nnhf_country', countryIndex, 365*4);

	var url = window.location.pathname;
	var filename = url.substring(url.lastIndexOf('/')+1);
	var splitArr = url.split('.');
	
	if(countryIndex == 'en') {
	    location.href = splitArr[0] + '.' + splitArr[1] + location.search;
	}
	else {
	    location.href = splitArr[0] + '__' + countryIndex + '.' + splitArr[1] + location.search;
	}
}

function languageInit()
{
    var cookieValue = readCookie('nnhf_country');
    if(cookieValue == null)
    {
        // If no cookie is set and the page indicates being in another language 
        // than english set the cookie based on the url
        if(window.location.pathname.indexOf('__cn') != -1)
        {
            setTimedCookie('nnhf_country', 'cn', 365*4);
        }
        else if(window.location.pathname.indexOf('__fr') != -1)
        {
            setTimedCookie('nnhf_country', 'fr', 365*4);
        }
        else if(window.location.pathname.indexOf('__de') != -1)
        {
            setTimedCookie('nnhf_country', 'de', 365*4);
        }
        else if(window.location.pathname.indexOf('__es') != -1)
        {
            setTimedCookie('nnhf_country', 'es', 365*4);
        }
        else if(window.location.pathname.indexOf('__pt') != -1)
        {
            setTimedCookie('nnhf_country', 'pt', 365*4);
        }
        else 
        {
            setTimedCookie('nnhf_country', 'en', 365*4);
        }
        
        cookieValue = readCookie('nnhf_country');
        
        for (var i = 0; i <= document.getElementById('language-selector').options.length - 1; i++)
        {
            if(document.getElementById('language-selector').options[i].value == cookieValue)
            {
                document.getElementById('language-selector').options[i].selected = true;
            }
        }
    }
}
