// Open the dialog for Tag picker
function OpenTagPickerDialog(url)
{
    var HeightVindu = screen.availHeight - 90;
    var WidthVindu = screen.availWidth;
    var xVindu = WidthVindu/2-500;
    var retVal = window.showModalDialog(url,'','resizable:yes;scroll:yes;dialogWidth:1000px;dialogHeight: ' + HeightVindu + 'px;dialogLeft:'+ xVindu +'; dialogTop=0');
    return retVal;
}

 
// Function that starts the wcwImagePickerDialog and write values to the fields in the 
//
// url - Url to call the pickerdialog with
// TextBoxFieldID - ClientIDfor the textbox to write the selected items to
//clearButtonID  - ClientID for the clearbutton
function StartTagPickerDialogFromPageLayoutAndWriteValues(url,textBoxFieldID)
{
    var currentTags = $( textBoxFieldID ).value;
    var retVal = OpenTagPickerDialog(url + "?currentPageTags=" + encodeURIComponent( currentTags ) );
    
    if( retVal != null)
    {
        var textBoxField = document.getElementById(textBoxFieldID);
        textBoxField.value = decodeURIComponent( retVal );
        //var clearButton = document.getElementById(clearButtonID);
        //clearButton.disabled = false;  
    }
}

function toggleSearchFilter()
{
    $$('#archiveFilterTrigger a')[0].toggleClassName('expanded');
    Effect.toggle('filterContainer', 'appear', {duration:0.2});
}

// Function for checking if an event has bubbled from a child element
function bubbledFromChild(element, event)
{
    var target = event.element();
    if (target === element) target = event.relatedTarget;
    return (target && target.descendantOf(element));
} 

function addAnnualReportMenuEventEffect(element)
{
    Event.observe($$('#' + element + ' a')[0], 'mouseover', function(event)
    {
        if(!bubbledFromChild(this, event))
        Effect.BlindDown($$('#' + element + ' .sectionCopy')[0], {duration: 0.2});
    });
    Event.observe($$('#' + element + ' .sectionCopy')[0], 'mouseout', function(event)
    {
        if(!bubbledFromChild(this, event))
        Effect.BlindUp($$('#' + element + ' .sectionCopy')[0], {duration: 0.2});
    });
}

/* Annual Report Search */
function searchAnnualReport(searchKey, variation)
{
    window.location = '/AnnualReport2008/' + variation + '/Search/Pages/Default.aspx?k=' + escape(searchKey);
}

/* Download Centre */
// For toggling filefolders
function toggleDownloadCentreFolder(elem, executer)
{
	$(executer).toggleClassName('expanded');
	Effect.toggle(elem, 'blind', { duration: 0.2 });
}

// For toggling Your Downloads
function toggleYourDownloadDetails()
{
	$('downloadDetails').toggleClassName('expanded');
	Effect.toggle('downloadDetails', 'blind', { duration: 0.2 });
	if($('downloadDetails').hasClassName('expanded'))
	{
		if(downloadCentreLanguage == 'no')
	    {
		    $('toggleYourDownloadsButton').update('Skjul detaljer...');
		}
		else
		{
		    $('toggleYourDownloadsButton').update('Hide details...');
		}
	}
	else
	{
	    if(downloadCentreLanguage == 'no')
	    {
	        $('toggleYourDownloadsButton').update('Vis detaljer...');
	    }
		else
		{
		    $('toggleYourDownloadsButton').update('Show details...');
		}
	}
}

// For adding and removing items form Your Downloads by checkbox click
function toggleItemInYourDownloads(title, checked, id, type, url)
{
	if(checked == true)
	{
		//Add item
		addDocumentToYourDownloads(title, id, type, url)
	}
	else
	{   
	    //Remove item
		removeDocumentToYourDownloads(id, type);
	}
}

// For adding an item to Your Downloads
function addDocumentToYourDownloads(title, id, type, url)
{
	if(type == 'pdf')
	{
		var newLi = new Element('li');
		newLi.setAttribute('id', type + id);
		newLi.update('<h6>' + title + '</h6><div class="directDownload"><a class="pdf" href="' + url + '">Pdf</a></div><div class="removeDownload"><a href="#" onclick="removeDocumentToYourDownloads(&quot;' + id + '&quot;, &quot;pdf&quot;); return false;">X</a></div>');
		$$('#downloadDetails .folderGroupLevel .fileLevel')[0].insert({
			'top': newLi
		});
		$('noPdf').setStyle({display: 'none'});
	}
	if(type == 'xls')
	{
		var newLi = new Element('li');
		newLi.setAttribute('id', type + id);
		newLi.update('<h6>' + title + '</h6><div class="directDownload"><a class="xls" href="' + url + '">Xls</a></div><div class="removeDownload"><a href="#" onclick="removeDocumentToYourDownloads(&quot;' + id + '&quot;, &quot;xls&quot;); return false;">X</a></div>');
		$$('#downloadDetails .folderGroupLevel .fileLevel')[1].insert({
			'top': newLi
		});
		$('noXls').setStyle({display: 'none'});
	}

	updateNumberOfDocuments();
	
	if($('downloadDetails').hasClassName('expanded') == false)
	{
	    toggleYourDownloadDetails();
	}
}

// For removing an item from Your Downloads
function removeDocumentToYourDownloads(id, type)
{
	$(type + id).remove();
	if(type == 'pdf')
	{
		// Unchecks checkbox
		$$('#' + id + ' .addToDownloads input')[0].checked = false;
		
		// If no docs turn on default message
		if($$('.yourDownloads .pdf li:not(#noPdf)').length == 0)
		{
			$('noPdf').setStyle({display: 'block'});
		}
	}
	else if(type == 'xls')
	{
		// Unchecks checkbox
		$$('#' + id + ' .addToDownloads input')[1].checked = false;
		
		// If no docs turn on default message
		if($$('.yourDownloads .xls li:not(#noXls)').length == 0)
		{
			$('noXls').setStyle({display: 'block'});
		}
	}
	
	// Update number of docs in Your Downloads
	updateNumberOfDocuments();
	
	if($$('.yourDownloads .pdf li:not(#noPdf)').length == 0 && $$('.yourDownloads .xls li:not(#noXls)').length == 0)
	{
	    if($('downloadDetails').hasClassName('expanded') == true)
	    {
	        toggleYourDownloadDetails();
	    }
	}
}

// For updating number of docs in Your Downloads
function updateNumberOfDocuments()
{
    // Counts rows and updateds counter
	var totalDocuments = $$('.yourDownloads .pdf li:not(#noPdf)').length + $$('.yourDownloads .xls li:not(#noXls)').length;
	$('numberOfDocuments').update(totalDocuments);
}

function initDownloadCentre()
{
    $$('.downloadCentre li h6').each(function(elem){
        var headingHeight = elem.getHeight();
        var topmargin = (48 - headingHeight) / 2;
	    elem.setStyle({
		    marginTop: topmargin + 'px'
	    })
    });
    $$('.downloadCentre .folderLevel .fileLevel, .downloadCentre #downloadDetails').each(function(elem){
        $(elem).setStyle({
    	    display: 'none'
        });
    });
    $$('.downloadCentre .folderLevel h5 a').each(function(elem){
        $(elem).toggleClassName('expanded');
    });
    
    $('aspnetForm').reset();
}

function harvestCheckedDocuments()
{   
    $$('.addToDownloads input:checked').each(function(elem){
        $(elem).ckecked = false;
    });
    /*$$('.addToDownloads input:checked').each(function(elem){
        var clickEvent = $(elem).readAttribute('onclick');
        var docUrl = clickEvent.substring(clickEvent.indexOf("/"), clickEvent.indexOf("')"));
        var docType = docUrl.substring(docUrl.indexOf('.') + 1)
        var itemId = $(elem).readAttribute('onclick').split("'")[1];
        toggleItemInYourDownloads(elem.value, elem.checked, itemId, docType, docUrl);
    });*/    
}

/* Glossary */
function hightlightGlossaryPhrases( lang )
{

    if(lang == 'en')
	{
		var glossaryLinkText = '<a href="/AnnualReport2008/en/Glossary/">See Global glossary</a>';
	}
	else
	{
		var glossaryLinkText = '<a href="/AnnualReport2008/no/Glossary/">G&aring; til global ordliste</a>';
	}
	
	var highlightStartTag = '<span class="glossaryWord" onmouseover="toggleGlossaryExplainer(this);" onmouseout="toggleGlossaryExplainer(this);">';
	var highlightEndTag =  '<span class="glossaryPhrase"><h5>- ';
	var highlightEndTag2 = '</h5><p>&ldquo;';
	var highlightEndTag3 = '&rdquo;</p><div>' + glossaryLinkText + '</div></span></span>';
 
	if(!$$('.artSec')[0] || typeof($$('.artSec')[0].innerHTML) == "undefined")
	{
		return false;
	}
	
	var glossaryContent = $$('.artSec')[0].innerHTML;
	for( var i in glossary )
	{
		if( glossary[ i ] && glossary[ i ][ 0 ] && glossary[ i ][ 1 ] )
		{
		    var _regex = new RegExp( "\\b(" + glossary[ i ][ 0 ] + ")\\b", "gi");
		    if( _regex.test( glossaryContent  ) )
		    {
			    glossaryContent = glossaryContent.replace( _regex, highlightStartTag + '$1 ' + highlightEndTag + '$1' + highlightEndTag2 + glossary[ i ][1] + highlightEndTag3 );
		    }
		}
	}
	$$('.artSec')[0].innerHTML = glossaryContent;
}


function toggleGlossaryExplainer(elem)
{
	$(elem).toggleClassName('activeGlossaryWord');
}

// Glossary Page
function highlightChosenGlossaryWord()
{
    $$('.glossaryIndex li').each(function(elem){
       Event.observe(elem, 'click', function(){
            $$('.glossaryIndex li').each(function(elem){
               $(elem).removeClassName('active');
            });
            $(this).addClassName('active');
       });
    });
}

// Download Centre Breadcrumb
function manipulateDownloadCentreBreadcrumb()
{
    if(downloadCentreLanguage == 'no')
    {
        $('ctl00_siteMapPath').update(' <span>/</span> <span><a href="/AnnualReport2008/no/">Norsk</a></span> <span>/</span> <span class="selected">Nedlastingssenter</span>');
    }
    else
    {
        $('ctl00_siteMapPath').update(' <span>/</span> <span><a href="/AnnualReport2008/en/">English</a></span> <span>/</span> <span class="selected">Download Centre</span>');
    }
}
