function startupscript(loadReader) {


    var topheader = document.getElementById('topheader');
    var topright = document.getElementById('topright');
    var pusher = document.getElementById('pusher');
    if (topheader && topright && pusher) {
        if (topheader.clientHeight > topright.clientHeight) {
            pusher.style.height = topheader.clientHeight - topright.clientHeight + 'px';
        }
    }
    if (loadReader) {
        $('a').each(function(index) {
            if ($('img', this).size() == 0 && $(this).attr('href') && ($(this).attr('href').endsWith('.pdf') || $(this).attr('href').endsWith('.doc') || $(this).attr('href').endsWith('.docx') || $(this).attr('href').endsWith('.odt') || $(this).attr('href').endsWith('.rtf')) &&
                ($(this).attr('href').startsWith('/') || $(this).attr('href').indexOf('/tyreso.se/') > 0 || $(this).attr('href').indexOf('www.tyreso.se/') > 0 || $(this).attr('href').indexOf('localhost/') > 0)) {

                if (this.parentNode.tagName == 'td' || this.parentNode.tagName == 'TD') {
                    $('<td style="width:19px;height:14px;" valign="top"><a class="listenLink" href="http://docreader.readspeaker.com/docreader/?cid=bodei&lang=sv_se&url=' + getEncodedUrl($(this).attr('href')) + '" target="_blank" title="L&#228;s upp denna fil" style="padding:5px 5px 0 0;display:block;"><img src="/templates/Styles/Images/listen-icon.gif" alt="L&#228;s upp denna fil" /></a></td>').insertAfter($(this).parent());
                }
                else {
                    $('<a href="http://docreader.readspeaker.com/docreader/?cid=bodei&lang=sv_se&url=' + getEncodedUrl($(this).attr('href')) + '" target="_blank" title="Läs upp denna fil" style="position:absolute;margin-left:5px;"><img src="/templates/Styles/Images/listen-icon.gif" alt="Läs upp denna fil" /></a>').insertAfter($(this));
                }
            }
        });
    }
}
function getEncodedUrl(url) {
    if (!url.startsWith('/')) {
        if (url.indexOf('localhost/') > -1) {
            return URLEncode('http://www.tyreso.se' + url.substring(url.indexOf('localhost/') + 9));
        }
        else {
            return URLEncode('http://www.tyreso.se' + url.substring(url.indexOf('.se/') + 3));
        }
    }
    else {
        return URLEncode('http://www.tyreso.se' + url);
    }
}
function URLEncode(url) {
    // The Javascript escape and unescape functions do not correspond
    // with what browsers actually do...
    var SAFECHARS = "0123456789" + 				// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()"; 				// RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";
   
    var plaintext = url;
    var encoded = "";
    for (var i = 0; i < plaintext.length; i++) {
        var ch = plaintext.charAt(i);
        
        if (ch == " ") {
            encoded += "+"; 			// x-www-urlencoded, rather than %20
        } else if (SAFECHARS.indexOf(ch) != -1) {
            encoded += ch;
        } else {
            var charCode = ch.charCodeAt(0);
            if (charCode > 255) {
                //Unicode Character cannot be encoded using standard URL encoding. (URL encoding only supports 8-bit characters.) A space (+) will be substituted.
                encoded += "+";
            } else {
                encoded += "%";
                encoded += HEX.charAt((charCode >> 4) & 0xF);
                encoded += HEX.charAt(charCode & 0xF);
            }
        }
    }

    return encoded;
}
// ---------------
// Toggles visibility of the specified element.
// ---------------
function toggleVisibility(elemId)
{
	var elem = document.getElementById(elemId);
	
	if (elem)
	{
		if (elem.style.display == 'none')
		{		
			elem.style.display = 'block';
		}
		else
		{			
			elem.style.display = 'none';
		}
	}
}

// ------------------------------------------------------------
// This function will fire a click event on the specified control when the 
// enter key is pressed in a text field. Attach this function to the 
// onkeypress-event on the text field like this:
// <input type="text" onkeypress="return fireClickOnEnter(event, 'IdOfControlToFireClickOn');">
// ------------------------------------------------------------
function fireClickOnEnter(evt, controlId)
{
    var control = document.getElementById(controlId);
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

    // If enter is pressed -> fire click-event on the control
    if (control && (keyCode == 13))
    {
        control.focus();
        control.click();
        return false;
    }
    else
    {
        return true;
    }
}

// ------------------------------------------------------------
// This function will fire a postbackon the specified control when the 
// enter key is pressed in a text field. Attach this function to the 
// onkeypress-event on the text field like this:
// <input type="text" onkeypress="return postbackOnEnter(event, 'IdOfControlToFirePostbackOn');">
// ------------------------------------------------------------
function postbackOnEnter(evt, controlId)
{
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

    // If enter is pressed -> do a postback
    if (keyCode == 13)
    {
		__doPostBack(controlId,'');
		return false;
    }
    else
    {
        return true;
    }
}

// ------------------------------------------------------------
// Returns the x coordinate of the specified object
// ------------------------------------------------------------
function findPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.clientLeft)
    {
        curleft += obj.clientLeft;
    }
    return curleft;
}

// ------------------------------------------------------------
// Encrypts the specfied string using the xor algorithm.
// The encrypted string can be decrypted by calling this method again
// with the same key.
// ------------------------------------------------------------
function xorEncryptString(str, key)
{
	var result = '';
	for (var i = 0; i < str.length; i++)
	{
		result += String.fromCharCode(key ^ str.charCodeAt(i));
	}
	return result;
}

// ------------------------------------------------------------
// Returns the y coordinate of the specified object
// ------------------------------------------------------------
function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.clientTop)
    {
        curtop += obj.clientTop;
    }
    return curtop;
}

// ------------------------------------------------------------
// Builds an html-page for printing
// ------------------------------------------------------------
function printPage(pagename, appRoot) 
{
	if (!window.print)
	{
		window.status = 'No print';
		return;
	}

	// Get the main content area and other stuff we need
	var contentdiv = document.getElementById('pagecontent');

	if (contentdiv)
	{
		var contentHtml = '<div style="width:475px;padding: 40px 40px 0 80px">';
		contentHtml += '<img src="/images/avantime/printmall_logotype.gif" border="0" alt="Optilon" />';
		contentHtml += '<img src="/images/avantime/printmall_streck.gif" border="0" alt="Optilon" />';
		contentHtml += '<div style="padding-top:40px;">';
		contentHtml += contentdiv.innerHTML + '</div></div>';
		
		var beginHtml = 
		      '<html>' +
			  '<head>' +
			  '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' + 
			  '<link rel="stylesheet" type="text/css" href="' + appRoot + 'Templates/Optilon/Styles/all.css">' +
			  '<title>Optilon - ' + pagename + '</title>' +
			  '<style> .printExclude { visibility: hidden; position: absolute; top: 0px; height: 0px } </style>' +
			  '</head>' +
			  '<body style="margin: 0px; background-image: none; background-color: #fff;">';

		var endHtml = '</body></html>';

		var printWin = window.open('about:blank','','width=700,height=600,scrollbars=yes,toolbar=yes');
		printWin.document.open();
		printWin.document.write(beginHtml + 
		                        contentHtml + 
		                        endHtml);
		printWin.document.close();

		printWin.print();
		printWin.close();
	}
}


// ------------------------------------------------------------
// Opens the Tipsa-window
// ------------------------------------------------------------
function openTipPage() {
    var pageId = $('#tipfriendlink').attr("href").replace('#', '');
	var width = 340;
	var height = 540;
    var left = (screen.width - width) / 2;
    var top	= ((screen.height - height) / 2) - 30;

    var win = window.open(gAppRoot + 'Pages/Edit/SendTip.aspx?pageid='+pageId, 'TipWindow', 'width='+width+',height='+height+',top='+top+',left='+left+',location=no,scrollbars=yes,menubar=no,toolbar=no,resizable=no,status=yes');
    win.focus();
}

function doClick(buttonName,e)
{
    //the purpose of this function is to allow the enter key to 
    //point to the correct button to click.
    var key;

     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

    if (key == 13)
    {
        //Get the button the user wants to have clicked
        var btn = document.getElementById(buttonName);
        if (btn != null)
        { //If we find the button click it
            btn.click();
            event.keyCode = 0
        }
    }
}


var getFFVersion = navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
var FFextraHeight = parseFloat(getFFVersion) >= 0.1 ? 16 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers

function resizeIframe(frameid) {

   var currentfr = document.getElementById(frameid);
   if (currentfr && !window.opera) {
       currentfr.style.display = "block";

       if (currentfr.contentDocument && currentfr.contentDocument.body && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
           currentfr.height = currentfr.contentDocument.body.offsetHeight + FFextraHeight;
       else if (currentfr.Document && currentfr.Document.body && currentfr.Document.body.scrollHeight) //ie5+ syntax
       {
           if (currentfr.Document.body.scrollHeight == 35)	//Avantime fix for hiding iframe if empty.
               currentfr.style.display = "none";
           else
               currentfr.height = currentfr.Document.body.scrollHeight;
       }
       if (currentfr.addEventListener)
           currentfr.addEventListener("load", readjustIframe, false);
       else if (currentfr.attachEvent) {
           currentfr.detachEvent("onload", readjustIframe);
           currentfr.attachEvent("onload", readjustIframe);
       }

   }
}


function readjustIframe(loadevt) {
   var crossevt = (window.event) ? event : loadevt
   var iframeroot = (crossevt.currentTarget) ? crossevt.currentTarget : crossevt.srcElement
   if (iframeroot)
       resizeIframe(iframeroot.id);
}
   
   
function showYoutubeVideo( url, insertIntoID, autoplay, width, height )
{
    var swfObject;

    if( autoplay == true )
        autoplay = "&autoplay=1;"
    else
        autoplay = "";
        
    swfObject = new SWFObject(url + "&enablejsapi=1&playerapiid=ytplayer" + autoplay, "ytapiplayer", width, height, "8", "#FFFFFF");
    swfObject.addParam( "wmode", "transparent" );
    swfObject.write( insertIntoID );
}

function addbookmark() {
    if (document.all) { 
        window.external.AddFavorite(bookmarkurl,bookmarktitle)
    }
}

function navigateToUrl(url) {
    if (url != '') {
        if (url.substring(0, 6) == "_blank") {
            window.open(url.substring(6));
        }
        else {
            window.location = url;
        }
    }
}

//Unobtrusive javascript handling for printpage and tip a friend
$(function () {
    $('#printlink').click(printPage);
    $('#tipfriendlink').click(openTipPage);
});


function printPage() 
{
	var da = (document.all) ? 1 : 0;
	var pr = (window.print) ? 1 : 0;
	
	if(!pr)
		return;
	
	var printArea = document.getElementById("printArea");
	
	if(printArea == null && da) 
		printArea = document.all.maincontentdiv;
	
	if(printArea) 
	{
		var sStart = "<html style=\"background-color: #FFFFFF;\"><head>" +
		    "<link rel=\"stylesheet\" type=\"text/css\" href=\"/Templates/Styles/CSS/all.css\">" +
		    "<link rel=\"stylesheet\" type=\"text/css\" href=\"/Templates/Styles/CSS/PuffStyles.css\">" +
		   // "<link rel=\"stylesheet\" type=\"text/css\" href=\"/Templates/Styles/CSS/print.css\">" +
		    "<style>.printExclude { display: none; }</style>" +
		    "</head><body onload=\"javascript:window.print();\" style=\"padding-top:15px;background-color: #FFFFFF;\">";
		sStop = "</body></html>";
		
		var w = window.open('','printWin','width=800,height=440,scrollbars=yes');
		wdoc = w.document;
		wdoc.open();
		wdoc.write( sStart + printArea.innerHTML );
		wdoc.writeln( sStop );
		wdoc.close();
	}
};
function StyleExternalLinks() {
    var content = document.getElementById('content');
    if (content) {
        var anchorLinks = content.getElementsByTagName('a');
        for (var i = 0; i < anchorLinks.length; i++) {
            var anchor = anchorLinks[i];
            var inner = anchor.innerHTML;
            
            if (!anchor.href.startsWith('/') && anchor.href.indexOf('tyreso.se') == -1 &&
                anchor.href.indexOf('www.tyreso.se') == -1 && anchor.href.indexOf('localhost') == -1 &&
                anchor.href.indexOf('mailto') == -1 && anchor.href != '' &&
                anchor.href.indexOf('javascript') == -1 && inner.indexOf('<img') != -1) 
            {
                if (anchor.className.indexOf('extLink') == -1) {
                    anchor.className = "extLinkoo";
                }
            }
        }
    }
}
function LoadImages(container, imgCollection) {

    for (var i = 0; i < imgCollection.length; i++) {
        $("<li></li>").append($("<img></img>").attr('src', imgCollection[i].url).attr('alt', imgCollection[i].alt)).appendTo(container);
    }
}
String.prototype.endsWith = function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
};
String.prototype.startsWith = function(str) {
    return this.indexOf(str) === 0;
};
