/*try{if(!window.console||!console.firebug){var a=["log","debug","info","warn","error","assert","dir","dirxml","group","groupEnd","time","timeEnd","count","trace","profile","profileEnd"];window.console={};for(var i=0;i<a.length;++i){window.console[a[i]]=function(){}}}}catch(e){};
*/

// Array Remove - By John Resig (MIT Licensed)
// http://ejohn.org/blog/javascript-array-remove/

Array.remove = function(array, from, to) {
  var rest = array.slice((to || from) + 1 || array.length);
  array.length = from < 0 ? array.length + from : from;
  return array.push.apply(array, rest);
};


// Inspiration from Svend Tofte:
// http://www.svendtofte.com/code/usefull_prototypes/
Array.exists = function (array, x) {
    for (var i=0, index; index = array[i]; i++){
        if (index === x) return true;
    }
    return false;
};

/* Example:
    Array.filter([1,10,100], function(n){
        return n > 50
    })
*/
Array.filter = function(array, fn) {
    var arr = [];
    for (var i=0, index; index = array[i]; i++){
        if ( fn(index)) {
            arr.push(index);
        }
    }
    return arr;
}



function generateRandomNumbers(from, to, nr) {
    var list = {}, arr = [], rand;
    var bound = to - from;
    
    if (bound < (nr - 1)) {
        throw "Your bound is smaller than the number of items you want. (to - from) < nr"
    }
    // Fill our hash with random numbers
    while (nr > 0 ) {
        // Select a random number that's within the bound of from <=> to
        rand = Math.round(from + (Math.random() * (bound)) );

        if (typeof list[rand] == "undefined") {
            list[rand] = rand;
            nr--;
        }
    }
    // And finally convert it into an Array
    for(prop in list) {
        arr.push(list[prop]);
    }
    return arr;
}

function SymError() {
	return true;
}

window.ondomready=DomReady;

function DomReady(fn) {
    if ('Safari' == browser) {
        setTimeout(function() {
            if ('loaded' == document.readyState || 'complete' == document.readyState) {
                fn();
            } else {
                setTimeout(arguments.callee, 10);
            }
        }, 10);
    } else if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', fn, false);
    } else {
        document.onreadystatechange=function() { readyState(fn); }
    }
}

function readyState(fn) {
    if ('complete' == document.readyState) {
        fn();
    }
}


function setCookie(key, value, days)
{
    var expires = new Date();
    expires.setDate(expires.getDate()+days);
    document.cookie = key + '=' + value + ';expires=' + expires.toGMTString() + '; path=/';
}

function setPermCookie(key, value)
{
    var expires = new Date();
    expires.setDate(expires.getDate()+9999);
    document.cookie = key + '=' + value + ';expires=' + expires.toGMTString() + '; path=/';
}

function getCookie(key) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(key + "=");
        if (c_start != -1) {
            c_start = c_start + key.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";    
}



//window.onerror = SymError;

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;
var debugWindowOpen = false;
var request = new Array();

if (location.search) 
{ 
    var vals=location.search.substr(1).split("&");
    var request= new Array(); 
    for (var i in vals) { 
        vals[i] = vals[i].replace(/\+/g, " ").split("="); 
        request[unescape(vals[i][0])] = unescape(vals[i][1]); 
    } 
}

if (checkIt('konqueror')) {
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('safari')) browser = "Safari"
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "Internet Explorer"
else if (navigator.userAgent.indexOf("Firefox")!=-1) browser = "Firefox"
else if (!checkIt('compatible')) {
	browser = "Netscape Navigator"
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS) {
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac"
	else if (checkIt('win')) OS = "Windows"
	else OS = "an unknown operating system";
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

function SwitchElement(Object, helpElement) {	
	var obj = document.getElementById(Object);
	var obj2 = document.getElementById(helpElement);
	
	obj.style.top = findPosY(obj2) - obj.height+12+ 'px';	
	obj.style.left = findPosX(obj2)+ 'px';
	
	if (obj.style.display == 'none') {
		obj.style.display = '';
	} else {
		obj.style.display = 'none';
	}
}

function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;	
	return curtop;
}

//Kör när man för musen över en promenadbild
 function cursor(myEvent) {
	if (browser!="Safari") {
		follow = document.all? document.all.trail : document.getElementById("trail");
		follow.style.visibility ="visible";
		follow.style.top = myEvent.clientY+document.body.scrollTop;
		follow.style.left = myEvent.clientX+10;
	}
}
 
 //Kör när man för muset ut ur en promenadbild
 function cursorOut() {
 	if (browser!="Safari") {
		follow = document.all? document.all.trail : document.getElementById("trail");
		follow.style.visibility="hidden";
		follow.style.display="block";	
	}
}

//Kör när man klickar i en promenadbild
function cursorClick() {
 	if (browser!="Safari") {
		follow = document.all? document.all.trail : document.getElementById("trail");
		follow.style.visibility="hidden";	
		follow.style.display="none";	
	}
 }
 
//Tar hand om problemet med navigationsrutans fixering på Helskärmskartan i Firefox tidigare än 1.5
function firefoxFix() {	
	if (document.getElementById('navigationContent')) {
		if(browser=="Firefox") {
			if (version<1,5) {
				document.getElementById('navigationContent').style.visibility = "visible";
			}
		} else {
			document.getElementById('navigationContent').style.width = "100%";	
			document.getElementById('navigationContent').style.visibility = "visible";	
		}
	}
}

// För debugging i IE, lägg in följande <div> på en sida och anropa denna funktion från javascriptet.
// <div id="debugWindow" style="position:absolute; top:100px; right:10px; border: solid 1px black; padding: 5px 5px 5px 5px; background-color: #EFEFEF; text-align:left; font-size:9px; width:350px;display:none"></div>
function debugLog(text)
{
    if (browser == "Firefox" && console != null)
        console.log(text);
    else
    {
        var debugDiv = document.getElementById("debugWindow");
        if (debugDiv != null)
        {
            var open = (debugDiv.style.display == "block");
            
            if (!open)
                debugDiv.style.display = "block";
                
            debugDiv.innerHTML += text + "<br>";
        }
    }
}

/* Extends javascript's string object */
String.prototype.trim=function() {
    return this.replace(/^\s*|\s*$/g, "");
}
String.prototype.normalizeSpace=function() {
    return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
}
String.prototype.stripMarkup=function() {
    var s = this.replace(new RegExp('(<br[.*]>)', 'gi'), '[br]');
    s = s.replace(new RegExp('<[^>]*>', 'gi'), '');
    s = s.replace(new RegExp('(\\[br\\])', 'gi'), '<br />');
    s = s.replace(new RegExp('(\\n)', 'gi'), '<br />');
    return s;
}
String.prototype.contains=function(s) {
    return this.indexOf(s) > -1;
}
String.prototype.startsWith=function(s) {
    return this.substring(0, s.length) == s;
}
String.prototype.endsWith=function(s) {
    return this.substring(this.length - s.length) == s;
}

//Gets the verion of internet Explorer
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
function getInternetExplorerVersion()
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}


function stripHtml(s) {
    return s.replace(/(<([^>]+)>)/ig,""); 
}



function addOnloadEvent(fnc){
  if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", fnc, false );
  else if ( typeof window.attachEvent != "undefined" ) {
    window.attachEvent( "onload", fnc );
  }
  else {
    if ( window.onload != null ) {
      var oldOnload = window.onload;
      window.onload = function ( e ) {
        oldOnload( e );
        window[fnc]();
      };
    }
    else 
      window.onload = fnc;
  }
}


/* URL paramter parsing */

function UrlParam(key, value) {
    this.key = key;
    this.value = value;
}

/**
 * Dynamically load JavaScript (copied from HMapHelpers.loadScript in hmap.*.js). Extended with optional callback method.
 */
function loadScript(src, cb) {
    var callbackFunction = arguments[1] || false;
    
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.setAttribute('language', 'javascript');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', src);

    if (callbackFunction) {
        var loadFunction = function () {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                callbackFunction();
            }
        };

        script.onreadystatechange = loadFunction;
        script.onload = callbackFunction;
    }
    head.appendChild(script);
}

var UrlParameters = {

    params: [],

    get: function(key) {
        if (UrlParameters.params.length == 0)
            UrlParameters.parse();

        for (var i = 0; i < UrlParameters.params.length; i++) {
            if (UrlParameters.params[i].key == key)
                return UrlParameters.params[i].value;
        }

        return null;
    },

    parse: function() {
        var url = String(document.location);
        var urlParamString = String(url.split('?')[1]);
        var urlParamPairs = urlParamString.split('&');

        for (var i = 0; i < urlParamPairs.length; i++) {
            var pair = String(urlParamPairs[i]).split('=');
            if (pair.length == 2)
                UrlParameters.params.push(new UrlParam(pair[0], pair[1]));
        }
    }

}



function displaySplash(message, top, left, bottom, right, container)
{
    var splashContainer = null;
    var splashId = "splashContainer";
    var closeButtonId = "splash_buttonClose";

    if (document.getElementById(splashId))
        splashContainer = document.getElementById(splashId);
    else if (typeof (container) == 'String')
        splashContainer = document.getElementById(container);
    else if (typeof (container) == 'Element')
        splashContainer = container;    
    
    if (splashContainer == null)
    {
        splashContainer = document.createElement("div");
        splashContainer.id = splashContainer.name = "splashContainer";
        splashContainer.style.border = '2px black solid';
        splashContainer.style.backgroundColor = 'white';
        splashContainer.style.zIndex = '2000';
        splashContainer.style.textAlign = 'left';
        splashContainer.style.padding = '20px 10px 30px 10px';
        document.body.appendChild(splashContainer);        
    }    
            
    if (message.length > 0) {
                
        splashContainer.innerHTML = message;
        splashContainer.style.display = 'block';
        splashContainer.style.position = 'absolute';
        
        var marginTop;
        var marginLeft;

        splashContainer.style.top = '50%';
        splashContainer.style.left = '50%';
        splashContainer.style.marginTop = -Math.ceil(splashContainer.offsetHeight / 2) + 'px';
        splashContainer.style.marginLeft = -Math.ceil(splashContainer.offsetWidth / 2) + 'px';                

        if (typeof(top) != 'undefined' && top != null)
            splashContainer.style.top = top + "px";
        if (typeof (bottom) != 'undefined' && bottom != null)
            splashContainer.style.bottom = bottom + "px";
        if (typeof (left) != 'undefined' && left != null)
            splashContainer.style.left = left + "px";
        if (typeof (right) != 'undefined' && right != null)
            splashContainer.style.right = right + "px";
        
        var closeButton = document.getElementById(closeButtonId);

        if (closeButton == null) {
            closeButton = document.createElement("input");
            closeButton.id = "splash_buttonClose";
            closeButton.type = "button";
            closeButton.value = "Stäng";            
            closeButton.onclick = function() { document.getElementById(splashContainer.id).style.display = 'none' };
            splashContainer.appendChild(closeButton);
        }

        closeButton.style.position = 'absolute';
        closeButton.style.top = splashContainer.offsetHeight - 30 + 'px';
        closeButton.style.left = splashContainer.offsetWidth - 70 + 'px';
        
    }
}
