function togglePreviewDetails(link, id)
{
    /*var detailsElem = $('#more'+id);
    detailsElem.toggle();

    var newLabel = (detailsElem.is(':visible')) ? labels['Less'] : labels['More'];
    $(link).text(newLabel);*/
    var detailsElem = $id('more'+id);

    if (detailsElem.style.display == 'block')
    {
		detailsElem.style.display = 'none';
        link.innerHTML = labels['More'];
	}
    else
    {
		detailsElem.style.display = 'block';
        link.innerHTML = labels['Less'];
	}
    
}
/* PRIVATE SECTION */
// using jQuery
function addAddress()
{
    var newAddress = $('#newaddress-template').clone();
    var newCount = $('table.address-table').length + 1;
    newAddress.attr('id', 'add-'+newCount);
    
    var elemsIDs = ['street', 'stateorprovince', 'city', 'postalcode', 'phone', 'fax', 'mobilephone', 'countryid', 'type', 'published'];
    var elemsCount = elemsIDs.length;
    var currentElem, currentID;

    for (var i=0; i<elemsCount; i++)
    {
        currentElem = $(newAddress).find('#'+elemsIDs[i]);
        currentID = 'info-native-'+elemsIDs[i]+'-'+newCount;
        currentElem.attr('id', currentID);
        currentElem.attr('name', currentID);
    }

    $(newAddress).find(':button').click(function(){
        removeAddress(newCount);
    });
    
    $('#addresses-form').append(newAddress.show());
}

function removeAddress(id)
{
    $('#addresses-form').find('#add-'+id).remove();
}

function deleteAddress(form, id)
{
    form.operation.value = 'delete';
    $id('current-address').value = id;
    $id('addresses-form').submit();
}

function showPubDetails(link, pubID)
{
    show(pubID);
    link.style.padding = '0 4px';
    link.innerHTML = '-';
    link.onclick = function(){hidePubDetails(link, pubID);}
}

function hidePubDetails(link, pubID)
{
    hide(pubID);
    link.style.padding = '0 2px';
    link.innerHTML = '+';
    link.onclick = function(){showPubDetails(link, pubID);}
}

function checkPubsInfos()
{
    var valid = true;

    if (checkTextInput('desc-shared-native-TITLE') == false)
    {
        valid = false;
    }
    if (checkTextInput('desc-shared-native-HEADER') == false)
    {
        valid = false;
    }

    if (valid == false)
    {
        alert(labels['EmptyFieldsErr']);
    }

    return valid;
}

function confidentialityCheck(checkID)
{
    if (!$id(checkID).checked)
    {
        alert(labels['ConfidentialMaterialErr']);
        return false;
    }

    return true;
}

function checkTextInput(inputID)
{
    var valid = true;
    var errorStyle = 'solid red 1px';

    var inputElem = $id(inputID);

    if (inputElem.value == '')
    {
        inputElem.style.border = errorStyle;
        valid = false;
    }
    else
    {
        inputElem.style.border = '';
    }

    return valid;
}

function checkSelectInput(inputID)
{
    var valid = true;
    var errorStyle = 'solid red 1px';

    var inputElem = $id(inputID);

    if (inputElem.selectedIndex == 0)
    {
        inputElem.style.border = errorStyle;
        valid = false;
    }
    else
    {
        inputElem.style.border = '';
    }

    return valid;
}

function checkPasswords()
{
    var valid = true;

    if (checkTextInput('password1') == false)
    {
        valid = false;
    }

    if (checkTextInput('password2') == false)
    {
        valid = false;
    }

    if (valid == false)
    {
        alert(labels['EmptyPasswordErr']);
    }
    else
    {
        if ($id('password1').value != $id('password2').value)
        {
            alert(labels['PasswordsDifferentsErr']);
            valid = false;
        }
    }

    return valid;
}

function checkDetailsInfos()
{
    var valid = true;

    if (checkTextInput('info-native-title') == false)
    {
        valid = false;
    }
    if (checkTextInput('info-native-firstname') == false)
    {
        valid = false;
    }

    if (checkTextInput('info-native-lastname') == false)
    {
        valid = false;
    }
     if (checkTextInput('info-native-email1') == false)
    {
        valid = false;
    }

    if (valid == false)
    {
        alert(labels['EmptyFieldsErr']);
    }

    return valid;
}

function addAltLanguage()
{
    var altLangSelect = $id('alternatelanguage');
    var langIDSelected = altLangSelect.options[altLangSelect.selectedIndex].value;
    if (langIDSelected == '') return;

    var langSelected = altLangSelect.options[altLangSelect.selectedIndex].innerHTML;

    var altLineIndex = $id('addlangline').rowIndex;

    var newRow = $id('detailstable').insertRow(altLineIndex);
    newRow.id = 'langline-'+langIDSelected;

    var newCell = newRow.insertCell(0);
    newCell.className = 'black-label';
    var inputID = 'dependency-altlang-'+langIDSelected;
    newCell.innerHTML = '<input type="text" name="'+inputID+'" id="'+inputID+'" value="'+langSelected+'" />';

    newCell = newRow.insertCell(1);
    newCell.className = 'txt-up';
    newCell.innerHTML = '<a href="#altlang-anchor" onclick="removeAltLanguage(\''+langIDSelected+'\');">'+labels['Remove']+'</a>';

    newCell = newRow.insertCell(2);
    newCell.innerHTML = '&#160;';
}

function removeAltLanguage(langID)
{
    var altLineIndex = $id('langline-'+langID).rowIndex;
    $id('detailstable').deleteRow(altLineIndex);
}

function isPublic(dataID)
{
    var visibilitySelector = $id(dataID);
    var value = visibilitySelector.options[visibilitySelector.selectedIndex].value;

    return (value == 'PUBLIC');
}

function displayValueIfVisible(dataID)
{
    var elem = $id('info-native-'+dataID);
    $id('visitor-preview-'+dataID).innerHTML = elem.value;

    if (!isPublic(dataID+'-visibility'))
    {
        hide('visitor-preview-'+dataID+'line');
    }
}

function setVisitorPreviewDetails()
{
    var title = $id('info-native-title').value;

    var fullName = $id('info-native-lastname').value + ', ' + $id('info-native-firstname').value + ' ' + $id('visitor-denomination').value + ' ('+ title +')';
    $id('visitor-preview-fullname').innerHTML = fullName;

    var city = $id('info-native-city');
    $id('visitor-preview-city').innerHTML = city.value;

    var countrySelect = $id('info-native-countryid');
    var countryID = countrySelect.options[countrySelect.selectedIndex].value;
    var country = countrySelect.options[countrySelect.selectedIndex].innerHTML;
    $id('visitor-preview-country-flag').src = flagsLocation + '16/' + countryID + '.png';

    var address = $id('info-native-address');
    $id('visitor-preview-address').innerHTML = address.value;

    displayValueIfVisible('address');

    var postalCode = $id('info-native-postalcode');
    $id('visitor-preview-postalcodecity').innerHTML = postalCode.value + ' ' + city.value;

    $id('visitor-preview-country').innerHTML = country;

    displayValueIfVisible('phone1');
    displayValueIfVisible('phone2');
    displayValueIfVisible('fax');
    displayValueIfVisible('email1');

    var motherTongueSelect = $id('info-native-languageid');
    var motherTongue = motherTongueSelect.options[motherTongueSelect.selectedIndex].innerHTML;
    $id('visitor-preview-mothertongue').innerHTML = motherTongue;

    var IPALanguageSelect = $id('info-native-IPA__MEMBER_IPALANGUAGEID');
    var IPALanguage = IPALanguageSelect.options[IPALanguageSelect.selectedIndex].innerHTML;
    $id('visitor-preview-ipalanguage').innerHTML = IPALanguage;

    var altLanguages = getElementsByClass('altlanguages');
    var langsCount = altLanguages.length;
    var altLangText = '';

    for (var i=0; i<langsCount;i++)
    {
        altLangText += altLanguages[i].value;
        if (i < (langsCount - 1)) altLangText += ', ';
    }
    $id('visitor-preview-altlanguages').innerHTML = altLangText;
}

function setMembersPreviewDetails()
{
    var title = $id('info-native-title').value;
    
    var fullName = $id('info-native-lastname').value + ', ' + $id('info-native-firstname').value + ' ' + $id('visitor-denomination').value + ' ('+ title +')';
    $id('members-preview-fullname').innerHTML = fullName;

    var city = $id('info-native-city');
    $id('members-preview-city').innerHTML = city.value;

    var countrySelect = $id('info-native-countryid');
    var countryID = countrySelect.options[countrySelect.selectedIndex].value;
    var country = countrySelect.options[countrySelect.selectedIndex].innerHTML;
    $id('members-preview-country-flag').src = flagsLocation + '16/' + countryID + '.png';

    var address = $id('info-native-address');
    $id('members-preview-address').innerHTML = address.value;

    var postalCode = $id('info-native-postalcode');
    $id('members-preview-postalcodecity').innerHTML = postalCode.value + ' ' + city.value;

    $id('members-preview-country').innerHTML = country;

    var workphone = $id('info-native-phone1');
    $id('members-preview-workphone').innerHTML = workphone.value;

    var homephone = $id('info-native-phone2');
    $id('members-preview-homephone').innerHTML = homephone.value;

    var fax = $id('info-native-fax');
    $id('members-preview-fax').innerHTML = fax.value;

    var email = $id('info-native-email1');
    $id('members-preview-email1').innerHTML = email.value;

    var motherTongueSelect = $id('info-native-languageid');
    var motherTongue = motherTongueSelect.options[motherTongueSelect.selectedIndex].innerHTML;
    $id('members-preview-mothertongue').innerHTML = motherTongue;

    var IPALanguageSelect = $id('info-native-IPA__MEMBER_IPALANGUAGEID');
    var IPALanguage = IPALanguageSelect.options[IPALanguageSelect.selectedIndex].innerHTML;
    $id('members-preview-ipalanguage').innerHTML = IPALanguage;

    var altLanguages = getElementsByClass('altlanguages');
    var langsCount = altLanguages.length;
    var altLangText = '';
    for (var i=0; i<langsCount;i++)
    {
        altLangText += altLanguages[i].value;
        if (i < (langsCount - 1)) altLangText += ', ';
    }
    $id('members-preview-altlanguages').innerHTML = altLangText;
}

function previewDetails()
{
    setVisitorPreviewDetails();
    setMembersPreviewDetails();

    hide('details');
    show('rosterpreview');
}

function hidePreviewDetails()
{
    hide('rosterpreview');
    show('details');
}

/* *** */
/*
function setDefaultTab(tab)
{
    this.currentTab = tab;

    show(this.currentTab);
    $id(this.currentTab+'-link').className = 'active';
}

function switchToTab(newTab)
{
    hide(this.currentTab);
    $id(this.currentTab+'-link').className = ''

    this.currentTab = newTab;

    show(this.currentTab);
    $id(this.currentTab+'-link').className = 'active';
}
*/
/* INDEX PAGE & GENERAL FUNCTIONS */

function adjustNewsCount() 
{
    //console.log('Adjusting news list...');

    var newsBlocks = getElementsByClass("blocknews");
    var newsBlocksCount = newsBlocks.length;

    //console.log(newsBlocksCount);

    if (newsBlocksCount > 0)
    {
        // padding : 20px, newslist margin : 10px, security : 20px
        var limitHeight = $id('newsaroundtheworld').clientHeight - 20 - 10 - 20;
        // IE specifics
        if ('\v'=='v') limitHeight -= 80;
        limitHeight -= $id('newsreader-title').clientHeight;
        limitHeight -= $id('newsreadercontrols').clientHeight;
        limitHeight -= $id('allnewsbutton').clientHeight;		
		//alert(limitHeight);
        //console.log(">>limitHeight=%d", limitHeight);

        var totalHeight = 0;
        var i;

        for (i=0; i<newsBlocksCount; i++)
        {
            newsBlocks[i].style.display = "inline-block"; // IE hack : force news blocks to "have layout" in order to force IE to record the height
            totalHeight += newsBlocks[i].clientHeight;
			
			//alert(newsBlocks[i].clientHeight+' / '+totalHeight);
            //console.log("clientHeight=%d, totalHeight=%d > %s", newsBlocks[i].clientHeight, totalHeight, (totalHeight > limitHeight)?'hidden':'visible');

            if (totalHeight > limitHeight)
            {
	            // IE specifics
                newsBlocks[i].style.display = "none";
            }
        }

        return newsBlocks[0]; // for later : auto-load 1st news
    }
    else // sometimes (when?) the "blocknews" elements are not grabbed by getElementsByClass(), even when body onload is fired
    {
        //console.log('Retry...');
		//alert('Retry...');
        setTimeout("adjustNewsCount();", 500);
    }

    return null;
}

function setMenuHandlers()
{
    var i;

    // persistent background
    var submenuItems = getElementsByClass("submenu");
    var submenuItemsCount = submenuItems.length;

	for (i=0; i<submenuItemsCount; i++)
	{
		submenuItems[i].onmouseover = function() {
			this.parentNode.firstChild.style.backgroundColor = '#ffffff';
		};

		submenuItems[i].onmouseout = function() {
			this.parentNode.firstChild.style.backgroundColor = '';
		};
	}

    /* *** */

    isIE6 = /msie|MSIE 6/.test(navigator.userAgent);

    if (isIE6)
    {
        var menuItems = getElementsByClass("mainmenuitem");
		var menuItemsCount = menuItems.length;

        for (i=0; i<menuItemsCount; i++)
        {
			if (menuItems[i].childNodes[1])
			{
				menuItems[i].onmouseover = function() {
					this.childNodes[1].style.display = 'block';
				};

				menuItems[i].onmouseout = function() {
					this.childNodes[1].style.display = 'none';
				};
			}
        }
    }
	
    /* *** */

    // IE hack (top shortcuts + find analyst form overlap)
	$id('headermenu').onmouseover = function() {
		var centerAreaContainer = $id('contentareacenter');
		var newsContainer = $id('contentareanews');
		var contentContainer = $id('contentarea');

		if (centerAreaContainer) centerAreaContainer.style.zIndex = '-1';
		if (newsContainer) newsContainer.style.zIndex = '-1';
		if (contentContainer) contentContainer.style.zIndex = '-1';
	};

	$id('headermenu').onmouseout = function() {
		var centerAreaContainer = $id('contentareacenter');
		var newsContainer = $id('contentareanews');
		var contentContainer = $id('contentarea');

		if (centerAreaContainer) centerAreaContainer.style.zIndex = '0';
		if (newsContainer) newsContainer.style.zIndex = '0';
		if (contentContainer) contentContainer.style.zIndex = '0';
	};
}

function adjustStyles4IE()
{
    // submenu position
    var submenuItems = getElementsByClass("submenu");
    var submenuItemsCount = submenuItems.length;

    if (submenuItemsCount > 0)
    {
        var i;

        for (i=0; i<submenuItemsCount; i++)
        {
            submenuItems[i].style.margin = '0px -6px';
        }
    }
}

/* *** */

function displayLoginActionPanel()
{
    show('login-action-panel');

    /* IE hacks */
    var newsContainer = $id('contentareanews');
    if (newsContainer) newsContainer.style.zIndex = '-1';
	
	var loginPanel = $id('login-action-panel');
	if (loginPanel)
	{
		loginPanel.style.zIndex = '200';
	}
	
    $id('login').style.zIndex = '201'; 
}

function hideLoginActionPanel()
{
    var loginPanel = $id('login-action-panel');
    if (loginPanel) hide('login-action-panel');

    /* IE hacks */
    var newsContainer = $id('contentareanews');
    if (newsContainer) newsContainer.style.zIndex = '0';
    
    $id('login').style.zIndex = '';
    if (loginPanel) loginPanel.style.zIndex = '';
}

/* *** */

function minimizeMap()
{
    $id('map').style.height = '38px';

    hide('news-reader-opener');
    show('news-reader');
}

function maximizeMap()
{
    $id('map').style.height = '445px';

    hide('news-reader');
    show('news-reader-opener');
}

/* *** */

function getURLParms()
{
    var parms = new Object();

    //console.log(window.location.search);

    // remove the ?
    var searchString = window.location.search.slice(1, window.location.search.length);

    var paramsPairs = searchString.split("&");
    var currentPair;

    for (i=0; i<paramsPairs.length; i++)
    {
        currentPair = paramsPairs[i].split("=");
        parms[currentPair[0]] = currentPair[1];
    }

    //console.log(parms);

    return parms;
}

/* *** */

function restoreDefaultFieldValue(id, defaultValue)
{
    var elem = $id(id);

    if (elem)
    {        
        if (elem.value == '')
        {
            elem.style.color = '#9F9FA0';
            elem.value = defaultValue;
        }
    }
}

function clearDefaultFieldValue(id, defaultValue)
{
    var elem = $id(id);

    if (elem)
    {
        elem.style.color = '#000000';
        
        if (elem.value == defaultValue)
        {            
            elem.value = '';
        }
    }
}

/* *** */

function loadProfileSuggestions()
{
    var profileSelect = $id('nav-profile');
    var currentProfile = profileSelect.options[profileSelect.selectedIndex].value;

    if (currentProfile == "") return;

    $id('nav-suggestions-content').innerHTML = '';
    show('nav-profile-hourglass');
    
    var loader = new XMLLoader();

    loader.setURL(baseURL+'load-resources.php');

    loader.setMethod('GET');
    loader.addParam('items', 'profile-suggestions');
    loader.addParam('profileID', currentProfile);

    loader.addCallBack(this, "onSuggestionsLoaded");

    loader.load();
}

function onSuggestionsLoaded(oXML)
{    
    var response = oXML.responseText;
    //console.log(oXML);
    
    hide('nav-profile-hourglass');
    $id('nav-suggestions-content').innerHTML = response;

    $id('nav-choose-info').innerHTML = '<a href="#">'+labels['HideSuggestions']+'</a>';

    $id('nav-choose-info').onclick = function() {
        $id('nav-suggestions-content').innerHTML = '';
        $id('nav-profile').selectedIndex = 0;
        $id('nav-choose-info').innerHTML = labels['ChooseProfileInfo'];
    };
}

function loadSocietyNews()
{    
    var languageSelect = $id('society-news-language');
    var currentLanguage = languageSelect.options[languageSelect.selectedIndex].value;
    
    var typeSelect = $id('society-news-type');
    var currentType = typeSelect.options[typeSelect.selectedIndex].value;

    var type = (currentType != '') ? typeSelect.options[typeSelect.selectedIndex].innerHTML : labels['AllNewsTypesTitle'];
    var lang = (currentLanguage != '') ? languageSelect.options[languageSelect.selectedIndex].innerHTML : '';
    
    var fullTitle = (lang != '') ? type + ' ' + labels['In'] + ' ' + lang : type + ' ' + labels['In'] + ' ' + labels['AnyLanguage'];
    $id('newsreader-title').innerHTML = fullTitle;

    $id('newslist').innerHTML = '';
    show('newslist-hourglass');
	
    var loader = new XMLLoader();
	//alert(loader);
    loader.setURL(baseURL+'load-resources.php');

    loader.setMethod('GET');
	// hack to avoid the cache fx
    loader.addParam('dummy', new Date().getTime()); 
	loader.addParam('items', 'last-society-news');
    loader.addParam('newsLanguage', currentLanguage);
    if (currentType != '') loader.addParam('newsType', currentType);

    loader.addCallBack(this, "onSocietyNewsLoaded");

    loader.load();
}

function onSocietyNewsLoaded(oXML)
{
    var response = oXML.responseText;
    //console.log(onSocietyNewsLoaded, arguments);
	//alert('onSocietyNewsLoaded');
    hide('newslist-hourglass');

    if (response != '')
    {
		var readerOpened = Boolean($id('news-reader').style.display == 'block');
	
        $id('newslist').innerHTML = response;		

        var firstNews = adjustNewsCount();

        if (firstNews) loadSingleNews(firstNews.id, readerOpened);
    }
    else
    {
        $id('newslist').innerHTML = '<p>'+labels['NoNews']+'</p>';
    }
}

function loadSingleNews(newsID, display)
{
    var languageSelect = $id('society-news-language');
    var currentLanguage = languageSelect.options[languageSelect.selectedIndex].value;

    var typeSelect = $id('society-news-type');
    var currentType = typeSelect.options[typeSelect.selectedIndex].value;
    
    $id('news-reader-content').innerHTML = '';

    if (display == true)
    {        
        minimizeMap();
        show('news-hourglass');
    }

    var loader = new XMLLoader();

    loader.setURL(baseURL+'load-resources.php');

    loader.setMethod('GET');
    loader.addParam('items', 'single-news');
    loader.addParam('currentNewsID', newsID);
    loader.addParam('newsLanguage', currentLanguage);
    if (currentType != '') loader.addParam('newsType', currentType);

    loader.addCallBack(this, "onSingleNewsLoaded", display);

    loader.load();
}

function onSingleNewsLoaded(oXML, display)
{
    var response = oXML.responseText;
    //console.log(oXML);

    if (display == true)
    {
        hide('news-hourglass');
    }

    $id('news-reader-content').innerHTML = response;
}

/* *** */

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 or higher.
{
    for (var i=0; i<document.images.length; i++)
    {
        var img = document.images[i];
        var imgName = img.src.toUpperCase();

        imgName=img.src.toUpperCase();

        if (imgName.substring(imgName.length-3,imgName.length)=="PNG")
        {
            img.outerHTML=
                "<span "+(img.id?"id='"+img.id+"' ":"")+(img.className?"class='"+img.className+"' ":"")+(img.title?"title=\""+img.title+"\" ":"")
                +"style=\"width:"+img.width+"px;height:"+img.height+"px;"+(img.align=="left"?"float:left;":(img.align=="right"?"float:right;":""))
                +(img.parentElement.href?"cursor:hand;":"")+"display:inline-block;"+img.style.cssText+";"
                +"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+img.src+"',sizingMethod='scale');\"></span>";
        }
    }
}

/* *** */

function hideNewsIFrame()
{
    show('iframe-hourglass');
    $id('newsIFrame').style.visibility = 'hidden';
}

function displayNewsIFrame()
{
    hide('iframe-hourglass');
    $id('newsIFrame').style.visibility = 'visible';
}

function hideContextNews()
{
    hide('displaynews-button');
    hide('contextnewscontainer'); 
    show('newslistcontainer');       
}

function displayContextNews()
{
    hide('newslistcontainer');
    show('contextnewscontainer');
    show('displaynews-button');
}

function loadNewsInContext(newsID)
{
    var newsTitle = $id('title-'+newsID);
    var newsSociety = $id('society-'+newsID);

    $id('news-title').innerHTML = newsTitle.innerHTML;
    $id('news-society').innerHTML = newsSociety.innerHTML;

    displayContextNews();
    hideNewsIFrame();

    $id('newsIFrame').src = newsTitle.attributes.getNamedItem('title').value;
     
    /* *** */

    var currentNewsBlock = $id(newsID);
    var prevNewsBlock = currentNewsBlock.previousSibling;
    var nextNewsBlock = currentNewsBlock.nextSibling;

    while (prevNewsBlock)
    {
        if (prevNewsBlock.className == 'blocknews') break;
        prevNewsBlock = prevNewsBlock.previousSibling
    }

    while (nextNewsBlock)
    {
        if (nextNewsBlock.className == 'blocknews') break;
        nextNewsBlock = nextNewsBlock.nextSibling
    }

    //console.log('Current >> ID=%s', newsID);

    if (prevNewsBlock)
    {
        var prevNewsID = prevNewsBlock.id;
        var prevSociety = $id('society-'+prevNewsID).innerHTML;
        var prevTitle = $id('title-'+prevNewsID).innerHTML;

        //console.log('Previous >> ID=%s / %s / %s', prevNewsID, prevSociety, prevTitle);

        $id('prev-news').innerHTML = '<a href="#" class="more-previous" id="prev-news-link">'+labels['PreviousNews']+'</a>';
        $id('prev-news').innerHTML += '<em id="prev-news-society">'+prevSociety+'</em><strong id="prev-news-title">'+prevTitle+'</strong>';
        $id('prev-news-link').onclick = function() { loadNewsInContext(prevNewsID); };

        show('prev-news');
    }
    else
    {
        hide('prev-news');
    }

    /* *** */

    if (nextNewsBlock)
    {
        var nextNewsID = nextNewsBlock.id;
        var nextSociety = $id('society-'+nextNewsID).innerHTML;
        var nextTitle = $id('title-'+nextNewsID).innerHTML;

        //console.log('Next >> ID=%s / %s / %s', nextNewsID, nextSociety, nextTitle);

        $id('next-news').innerHTML = '<a href="#" class="more-next" id="next-news-link">'+labels['NextNews']+'</a>';
        $id('next-news').innerHTML += '<em id="next-news-society">'+nextSociety+'</em><strong id="next-news-title">'+nextTitle+'</strong>';
        $id('next-news-link').onclick = function() { loadNewsInContext(nextNewsID); };
        
        show('next-news');
    }
    else
    {
        hide('next-news');
    }

    /* *** */

    adjustContextNavigationHeight();
}

function adjustContextNavigationHeight()
{
    var prevNewsBlockHeight = 0;
    var nextNewsBlockHeight = 0;

    if ($id('prev-news')) prevNewsBlockHeight = $id('prev-news').clientHeight;
    if ($id('next-news')) nextNewsBlockHeight = $id('next-news').clientHeight;

    var maxHeight = Math.max(Math.max(prevNewsBlockHeight, nextNewsBlockHeight), $id('navcenter').clientHeight);

    $id('contextnewsnavigation').style.height = maxHeight+'px';
}

function displayFlashMap()
{
    // flash map
    var so = new SWFObject(baseURL+"map.swf", "app", "100%", "100%", "8", "#f");
    so.addParam("menu", "false");
    so.addParam("quality", "best");
    so.addParam("scale", "noscale");
    so.addParam("swliveconnect", "true");
    so.addParam("allowFullScreen", "true");
    so.addParam("allowScriptAccess", "always");
    so.addParam("flashVars", "local=true");
    so.addParam("wmode", "transparent"); // to be sure the main menu is over the map
    var swf = so.write("map");
}

/* DOM READY */

DomReady.ready(function() {
    // body font size
    setBodyFontSize();
	
	// IE hacks
    var isIE = '\v'=='v';

    if (isIE)
    {        
        var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
        var isIE7 = /msie|MSIE 7/.test(navigator.userAgent);

        if (isIE6 ||isIE7)
        {
            adjustStyles4IE();
            //window.attachEvent("onload", correctPNG);
        }
    }

    // focus handlers for the login fields
    var loginField = $id('ln');

    if (loginField)
    {
        loginField.onfocus = function() {
            clearDefaultFieldValue('ln', labels['Username']);
            displayLoginActionPanel();
        };
    
        loginField.onkeydown = function() {
            var lnVal = $id('ln').value;
            if ((lnVal != '') && (lnVal != labels['Username']))
            {
                $id('newpassword').style.display = 'block';
            }
            else
            {
                $id('newpassword').style.display = 'none';
            }
        }
    }

    var loginPass = $id('lp');

    if (loginPass) loginPass.onfocus = function() {
        clearDefaultFieldValue('lp', labels['Password']);
        displayLoginActionPanel();
    };

    // click handler to hide the login panel
    document.onclick = function(e) {
        var event = e || window.event;

        if (event.target)
        {
            targ = event.target;
        }
		else if (event.srcElement)
        {
            targ = event.srcElement;
        }

        var parent = targ.parentNode;
        
        while (parent != null)
        {
            if (parent.id == 'login') break;
            parent = parent.parentNode;
        }

        if (parent == null)
        {
            hideLoginActionPanel();

            // login fields
            restoreDefaultFieldValue('ln', labels['Username']);
            restoreDefaultFieldValue('lp', labels['Password']);
        }
    };

    // menu rollover
    setMenuHandlers();
	
    // index page only
    if ($id('Website'))
    {
        displayFlashMap();

        // news reader opener
        $id('news-reader-opener').onclick = function() { minimizeMap(); };
        
        // focus/blur handlers for the 'find analyst' field 
        $id('searchtext').onfocus = function() { clearDefaultFieldValue('searchtext', labels['FindAnalystInfo']); };
        $id('searchtext').onblur = function() { restoreDefaultFieldValue('searchtext', labels['FindAnalystInfo']); };
    }
    else if ($id('Roster'))
    {
        // focus/blur handlers for the generic search form
        $id('searchtext').onfocus = function() { clearDefaultFieldValue('searchtext', labels['FindAnalystInfo']); };
        $id('searchtext').onblur = function() { restoreDefaultFieldValue('searchtext', labels['FindAnalystInfo']); };

        // focus/blur handlers for the advanced search form
        /*$id('lastname').onfocus = function() { clearDefaultFieldValue('lastname', ''); };
        $id('lastname').onblur = function() { restoreDefaultFieldValue('lastname', ''); };*/
        $id('city').onfocus = function() { clearDefaultFieldValue('city', ''); };
        $id('city').onblur = function() { restoreDefaultFieldValue('city', ''); };
    }
    else if ($id('SocietiesMapPage'))
    {
        displayFlashMap();
    }
});

function homepageOnLoad()
{
    //alert('homepageOnLoad');
    //if (supersleight) supersleight.run();
	
	// last society news
	loadSocietyNews(true);
	
    // main menu > li items width
    /*var menuEntries = getElementsByClass("mainmenuitem");
    var entriesCount = menuEntries.length;

    var totalWidth = $id('headermenu').clientWidth;
    var singleWidth = Math.floor(totalWidth/entriesCount);

    for (var i=0; i<entriesCount; i++)
    {
        menuEntries[i].style.width = singleWidth + 'px';
    }*/
}
function sendRequest(){
	var form=$('#activation-form');
	form.find('input#action').val('request');
	form.submit();
}

/**
 * EPF Buttons/Links "Widgets"
 * 
 */
(function(){
	
	/**
	 * Dev or Public ?
	 */
	var env;
	
	
	if ('/Dev'==window.location.pathname.substring(0, 4)) {
		env = 'Dev';
	} else {
		env = 'Public';
	}//END
	
	function login(ev) {
		alert('Please login');
	};
	
	function requestToken(ev) {
		
		
		$.ajax({
			url: 'http://www.ipa.org.uk/' + env + '/PrivateSpaceMember/get-epf-token.php',
			dataType: 'json',
			success: function(response, status, xhr) {
				if (response.success) {            				
					var newWin, url;
					url = 'http://www.epf-fep.org/Public/authenticate.php?token=' + response.token + '&expiresDate=' + encodeURI(response.expiresDate) + '&ip=' + encodeURI(response.ip);
					newWin = window.open(url, 'epfWindow');
					if (window.focus) {
						newWin.focus();
					}
				} else {
					//console.log('error in getting a token');
				}
			},
			error: function(xhr, status, error) {
				/* to implement */
				//console.log('???errror????');
			}
		});
	};
	
	function init(ev) {
		
		var linkHtml,
			btnHtml,
			isLogged;
		
		/**
		 * currentUser is a global variable defined in common.xsl
		 * 
		 * it looks like this
		 * {
		 * 		logged: true|false
		 * }
		 * 
		 * true if we find a node /RESPONSE/RESULTS[@name='visitor']
		 */
		
		if (('undefined' == typeof currentUser) || !('logged' in currentUser)) {
			linkHtml = '<strong>(A JavaScript error has occured)</strong>';
			btnHtml  = linkHtml;
			isLogged = false;
		} else if (currentUser.logged) {
			linkHtml = '<a class="logged">Go to EPF</a>';
			btnHtml  = '<a class="logged"><img width="225" height="36" src="http://www.ipa.org.uk/' + env + '/images/epf-connected.png" alt="Go to EPF"/></a>';
			isLogged = true;
		} else {
			linkHtml = '<a class="notlogged">Please login</a>';
			//btnHtml  = '<strong>LOGIN BUTTON?</strong>';
			btnHtml  = '<a class="notlogged"><img width="225" height="36" src="http://www.ipa.org.uk/' + env + '/images/epf-notconnected.png" alt="Go to EPF"/></a>';
			isLogged = false;
		}//END

		$('span.epf_link').each(function(index){
			$(this).html(linkHtml);
			if (isLogged) {
				$(this).click(requestToken);
			} else {
				$(this).click(login);
			}
		});
		
		$('span.epf_button').each(function(index){
			$(this).html(btnHtml);
			if (isLogged) {
				$(this).click(requestToken);
			} else {
				$(this).click(login);
			}
		});
	};
	
	$(document).ready(init);
	
})();