﻿function documentWrite(someData) {
    document.writeln(someData);
}

// Kollar om en viss plugin existerar
// nameOfPlugin (string): namnet på pluginen, t.ex: "Flip4Mac"
function pluginExists(nameOfPlugin) {
    for (var i = 0; i < navigator.plugins.length; i++){
        if (navigator.plugins[i].name.indexOf(nameOfPlugin) != -1) {
            return true;
        }
    }    
    return false;
}

function trim(input) {
    if (input) {
        return input.replace(/^\s*/, "").replace(/\s*$/, "");
    } else {
        return "";
    }
}

// Lägg till en trim funktion till String
String.prototype.trim = function () {
    return trim(this.valueOf());
}


// Jämför en sträng med en annan och returner om de är lika eller ej
// valfri andra parameter: ignoreCase (default false)
String.prototype.equals = function(other) {        
    if (this.valueOf().length != other.toString().length) {
        return false;
    }
    var a = this.toString();
    var b = other.toString();
    if (arguments.length > 1 && arguments[1]) {
        // Case insensitive
        a = a.toLowerCase();
        b = b.toLowerCase();   
    }
    
    for (var i = 0; i < a.length; i++) {
        if (a.charAt(i) != b.charAt(i)) {
            return false;
        }
    }
    
    return true;
}

function isValidEmail(input) {
    return input !== null && input.length > 0 && input.search(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/gi) >= 0;
}

String.prototype.isEmail = function() {
    return isValidEmail(this.valueOf());
}

function openWindow(url, width, height) {
    return window.open(url, "_blank", "directories=0,height=" + height + ",width=" + width + ",location=0,scrollbars=1,status=0,toolbar=0", true);
}

function printObject(objectId, queryKey) {
    objectId = parseInt(objectId, 10);
    if (!isNaN(objectId) && objectId > 0) {        
        window.open("Print.aspx?" + queryKey + "=" + objectId, "_blank", "directories=0,scrollbars=1,status=0,toolbar=0,width=510,height=500");
    }
}

function flashObject(moviePath, width, height) {
    return '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="' + width + '" height="' + height + '">'+
          '<param name="movie" value="' + moviePath  + '" />'+
          '<param name="quality" value="high" />'+
          '<param name="menu" value="false" />'+
          '<param name="wmode" value="opaque" />'+
          '<param name="bgcolor" value="#ffffff" />' +
          '<param name="scale" value="noborder" />' +
          '<param name="allowScriptAccess" value="sameDomain" />' +
          '<embed src="' + moviePath  + '" width="' + width + '" height="' + height + '" wmode="opaque" quality="high" scale="noborder" allowScriptAccess="sameDomain" bgcolor="#ffffff" pluginspage="http://www.adobe.com/go/getflashplayer" type="application/x-shockwave-flash" menu="false"></embed>'+
        '</object>';
}

function flashObjectCustom(moviePath, width, height, settings) {
    var paramList = [];    
    var embedList = [];
    for (paramName in settings) {
        paramList.push('<param name="' + paramName + '" value="' + settings[paramName].toString() + '" />');
        embedList.push(paramName + '="' + settings[paramName].toString() + '"');
    }
    
    var objectTag = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="' + width + '" height="' + height + '">' + 
        '<param name="movie" value="' + moviePath  + '" />' + 
        paramList.join('');
    
    var embedTag = '<embed src="' + moviePath  + '" width="' + width + '" height="' + height + '" ' + embedList.join(' ') + 
        ' pluginspage="http://www.adobe.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>';
    
    return objectTag + embedTag + "</object>";
}

function audioObject(fileUrl, mimeType) {
    return '<embed src="' + fileUrl + '" width="400" height="20" autoplay="true" loop="false" type="' + mimeType + '"></embed>';
}


function documentWriteln(output) {
    document.writeln(output);
}

function reloadPage() {
    document.location.href = document.location.href;
}

// För spamskydd
function sendMessage(username, hostname) {
    document.location.href = "mailto:" + username + "@" + hostname;
}

// För spamskydd
function getMail(username, hostname) {
    return username + "@" + hostname;
}

//Byter en bilds källbild
function swap(id, imgPath) {
    $("#" + id).attr("src", imgPath);
}

//
function windowHeight(){
	var alto= 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		alto= window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		alto= document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		alto= document.body.clientHeight;
	}
	return alto;
}

function SetWindowHeight()
{
    setTimeout(SetWindowHeightCallback, 0);
}
function SetWindowHeightCallback()
{
    var _windowHeight = windowHeight();
    var RefDiv = document.getElementById('Page');
    RefDiv.style.height = 'auto';
	var _height = RefDiv.offsetHeight;

    if(_height<_windowHeight)
    {
        RefDiv.style.height = _windowHeight + 'px';
    }
}

var _appPath = ""; // Sätts av ett startup-script
function mapPath(virtualPath) {
    return virtualPath.replace("~", _appPath);
}

function resizeFloor() {
    // Placera "golvet"            
    var top = ($("div#MainOuter").height() - 109);            
    var height = Math.max(112, $(document).height() - top);            
    $("div#Floor").css("top", top + "px");
    $("div#Floor").css("height", height + "px");
}

function mainMenuMouseEnter(eventObject, sender, eventData) {
    // Nollställ timern
    clearResetTimer();
    
    if (typeof(sender) == "undefined") {
        return;
    }
    
    // Dölj alla andra undermenyer
    if (typeof(eventData) != "undefined") {
        $("#Header div.SubMenu[id!=" + eventData.subMenuId + "]").hide();
    }
    
    $("div#Header div.MainMenu a.Arrow[id!=" + sender.parentNode.id + "]").removeClass("Arrow");
    $("div#Header div.MainMenu a.DarkArrow[id!=" + sender.parentNode.id + "]").removeClass("DarkArrow");
    
    // Sätt aktuell menu till Selected
    if ($(sender).hasClass("Current")) {
        $(sender).addClass("DarkArrow");
    } else {
        $(sender).addClass("Arrow");
    }
    
    // Visa den aktuella undermenyn
    if (eventData && typeof(eventData) != "undefined") {                                
        $("div#" + eventData.subMenuId).fadeIn(250);                
        $("div#" + eventData.subMenuId).bind("mouseenter", clearResetTimer);
        $("div#" + eventData.subMenuId + " a").bind("mouseenter", clearResetTimer);
        $("div#" + eventData.subMenuId).bind("mouseout", resetMenu);
    }
}

var _resetTimer = null;
function clearResetTimer() {
    //var msg = "clearResetTimer: ";
    
    if (_resetTimer != null) {
        clearTimeout(_resetTimer);    
        _resetTimer = null;          
        //msg += "cleared";
    } else {
        //msg += "ignored";
    }    
    //console.log(msg);
}

function resetMenu() {
    //var msg = "resetMenu: ";
    
    if (_resetTimer == null) {
        _resetTimer = setTimeout(function () {
            
            $("div#Header div.MainMenu.Current").addClass("DarkArrow");
            
        }, 1500);    
        //msg += "initialized";
    } else {
        //msg += "ignored";
    }            
    //console.log(msg);
}

function mainMenuMouseOut(eventObject, sender, eventData) {
    resetMenu();
}

function CountdownTimer(year, month, day, hour, minute) {
    var inst = this;
    
    inst.targetDateUTC = Date.UTC(year, month, day, hour, minute, 0, 0);
    
    this.update = function() {
        var now = new Date();
        var diffMs = Math.max(0, inst.targetDateUTC + (now.getTimezoneOffset() * 60000) - now.getTime());        
        var totalDays = diffMs / (24 * 3600 * 1000);
        var days = parseInt(Math.floor(totalDays), 10);            
        var partialDay = parseFloat(Math.max(0, totalDays - days));
        var partialHours = 24 * partialDay;
        var hours = parseInt(Math.floor(partialHours), 10);            
        var partialMinutes = parseFloat(Math.max(0, partialHours - hours));
        var minutes = parseInt(Math.floor(partialMinutes * 60), 10);            
        var seconds = parseInt(Math.floor(parseFloat((partialMinutes * 60) - minutes) * 60), 10);         
     
        $("p#TimerDays").html(padLeft(days.toString(), 3, "0"));
        $("p#TimerHours").html(padLeft(hours.toString(), 2, "0"));
        $("p#TimerMinutes").html(padLeft(minutes.toString(), 2, "0"));
        $("p#TimerSeconds").html(padLeft(seconds.toString(), 2, "0"));        
     
        setTimeout(inst.update, 500);
    }
    
    this.start = function() {
        setTimeout(inst.update, 500);
    }    
}

function padLeft(input, length, padCharacter) {
    if (typeof(input) == "undefined" || input.length >= length) {
        return input;
    }
    var padList = [];
    for (i = 0; i < (length - input.length); i++) {
        padList.push(padCharacter);
    }
    return padList.join("") + input;
}

function preLoadImage(imageUrl) {
        var image = new Image();
        image.src = imageUrl;
        return image;
    }    
function showNextArticle() {
    if (timerCancelPending) {
        return;
    }
    
    if ((currentIndex + 1) >= newsList.length) {
        currentIndex = 0;
    } else {
        currentIndex++;
    }
            
    var article = newsList[currentIndex];                            
    $("img#LatestNewsImage").attr("src", article.image.src);
    $("div#LatestNewsText").html(article.innerHtml);
    $("div#LatestNews div.Right div.Text p[id!=" + article.targetElementId + "]").removeClass("Current");
    $("#" + article.targetElementId).addClass("Current");
    
    if (!timerCancelPending) {
        timer = setTimeout(showNextArticle, articleDisplayTime);
    }
}   
function displayArticle(targetElementId) {
    clearTimeout(timer);
    timerCancelPending = true;
    for (var i = 0; i < newsList.length; i++) {
        if (newsList[i].targetElementId == targetElementId) {
            currentIndex = i;
            var article = newsList[currentIndex];                            
            $("img#LatestNewsImage").attr("src", article.image.src);
            $("div#LatestNewsText").html(article.innerHtml);
            $("div#LatestNews div.Right div.Text p[id!=" + article.targetElementId + "]").removeClass("Current");
            $("#" + article.targetElementId).addClass("Current");                
            break;
        }
    }
}

function hide(selector) {
    $(selector).addClass("Hidden");
}
function show(selector) {
    $(selector).removeClass("Hidden");
}
function toggleHidden(selector) {
    $(selector).toggleClass("Hidden");
}

function displayFlashPlayer(sender, flashPlayerIframeId) {
    $("#" + flashPlayerIframeId).attr("src", $("#" + flashPlayerIframeId + "_src").val());
    $("#" + flashPlayerIframeId).removeClass("Hidden");
    $(sender).remove();
}