﻿if (document.location.href.indexOf("kuriren.com")>-1){ document.location = document.location.href.replace("kuriren.com","kuriren.nu");}
if (document.location.href.indexOf("lokusnorr.se")>-1){ document.location = document.location.href.replace("lokusnorr.se","kuriren.nu");}
if (document.location.href.indexOf("2007.kurir")>-1) { document.location = document.location.href.replace("2007.kurir","www.kurir");}


$(document).ready(function () {

    $("#tipsa_button").click(function () {

        var data = {};
        $("#tipsa_dialog :input").each(function () {
            data[$(this).attr("name")] = $(this).val() == null || $(this).val() == "" ? $(this).text() : $(this).val();
        });

        if (data['text'] == null || data['text'] == '') {
            alert("Ange text");
            return;
        }

        $(this).attr("disabled", "disabled");

        $.ajax({ url: "/inc/Tipsa.ashx",
            data: data,
            success: function (d) {
                $("#tipsa_button").attr("disabled", "");
                if (d == "") {
                    alert("Tipset är mottaget. Tack så mycket!");
                    $("#tipsa_dialog").dialog('close');
                }
                else
                    alert("Ett fel har uppstått. Var god prova senare");
            },
            error: function (d) {
                alert("Ett fel har uppstått. Var god prova senare");
                $("#tycktill_button").attr("disabled", "");
            },
            type: "POST",
            dataType: "text",
            contentType: "application/x-www-form-urlencoded;charset=utf-8"
        });
    });

    $("a#tipsakuriren").click(function () {

        //$("#player").css({ visibility: 'hidden' });
        $("#tipsa_dialog").dialog({ bgiframe: true, modal: true, draggable: false, title: 'Tipsa Kuriren', autoOpen: true, closeOnEscape: true, beforeclose: function () {
            //$("#player").css({ visibility: 'visible' });
        }
        }).dialog('open');
        return false;

    });


    $(".bildspel_link").click(function () {

        window.open($(this).attr("href"), "bildspel", "width=660, height=660");
        return false;

    });

    // plocka bort payex alternativet under abonnera
    $("#epaperBuySubscribtion input[value='payex']").parent().hide();

    $(".ArticleRightBanner").each(function () {
        if ($(this).height() < 20)
            $(this).hide();
    });

    var webbtvlink_to = null;
    $(window).scroll(function () {

        if (webbtvlink_to)
            clearTimeout(webbtvlink_to);

        webbtvlink_to = setTimeout(function () {
            $("a.webtv").each(function () {

                if (isScrolledIntoView(this))
                    $(this).click();

            });
        }, 500);

    });

    init_webbtv();

    if ($.browser.msie && parseInt($.browser.version) < 9)
        $("a.webtv").click();
});

function init_webbtv() {
    $("a.webtv").click(function (event) {
        event.preventDefault();
        var ref = $(this);
        var href = $(this).attr("href");
        var id = "c" + href.replace(/[^\d]/g, '');
        ref.attr("id", id);
        var param = {
            allowFullScreen: true,
            allowScriptAccess: 'always',
            scale: 'noscale',
            wmode: 'transparent',
            salign: 'lt'
        };

        swfobject.embedSWF("http://www.kuriren.nu/24norrbotten/articlePlayer.swf" + href, id, "468", "294", "9.0.0", null, param, null);


        return false;
    });

    $(window).triggerHandler("scroll");
}

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

        function querySt(ji) {
            hu = window.location.search.substring(1);
            gy = hu.split("&");
            for (i = 0; i < gy.length; i++) {
                ft = gy[i].split("=");
                if (ft[0] == ji) {
                    return ft[1];
                }
            }
        }


    function showLoader() {

       var offx, offy; 
        var el = ".blogedit:first";
       try {
           offx = $(el).offset().top;
           offy = $(el).offset().left;
        }
        catch (e) {
           offx = 0;
           offy = 300;
        }
        var top = parseInt($(el).height() / 2) + offy;
        var left = parseInt($(el).width() / 2) + offx;
        $("<div class=\"loader\" style=\"z-index:10000;position:absolute;background-color:#fff;padding:10px;border:5px solid #eee;\"><img src=\"http://www.kuriren.nu/graphics/ajax_load.gif\" /> Vänta ..</div>").css({ top: top + "px", left: left + "px" }).appendTo("body");

    }

    function hideLoader() {
        $(".loader").remove();
    }

remVal=false;
function show(id){
    if (document.getElementById(id)!==null){
        document.getElementById(id).style.display = "block";
    }
}

function hide(id){
    if (document.getElementById(id)!==null){
        document.getElementById(id).style.display = "none";
    }
}

function createAjaxStatIframe(){
    var iframeid = "ajaxstatframe";
    if(!document.getElementById(iframeid)){
        var iframe = document.createElement('iframe');
        iframe.name = iframeid;
        iframe.id = iframeid;
        iframe.style.display = "none";
        iframe.width = 100;
        iframe.height = 100;
        iframe.src = '/ajaxstatistik.aspx';
        document.body.appendChild(iframe);
    }else{
        var iframe = document.getElementById(iframeid);
        iframe.src = '/ajaxstatistik.aspx';
    }
}

function ajaxError(error){

    var stackTrace = error.get_stackTrace();
    var message = error.get_message();
    var statusCode = error.get_statusCode();
    var exceptionType = error.get_exceptionType();
    var timedout = error.get_timedOut();

    ajaxStopLoad();
    console.log("Ett fel uppstod med under kommunikation med servern, testa senare eller kontakta webmaster.\n"+message);
}

var isAjaxLoading = false;

function ajaxLoad(e,timeout){
var div = $get("AjaxLoaderGif");
    if (div===null){
        div = document.createElement("img");
        div.id = "AjaxLoaderGif";
        div.style.position = "absolute";
        div.style.zIndex = 2001;
        div.style.left = "-200px";
        div.style.visibility = "hidden"; 
        div.alt = "Vänta medans webbläsaren kommunicerar med servern";
        div.src = "/graphics/ajax_load.gif";
         if (bodyArr = document.getElementsByTagName("body"))
             { bodyArr[0].appendChild(div);}
    }
		
	div.style.visibility = "hidden"; 
			        
    if (e===null) { e = window.event; }
    if (e == null)
        e = {clientX:0, clientY:0};

    div.style.left = e.clientX + "px"; 

    div.style.top = (getScrollXY()[1] + e.clientY) + "px";
    
    if (typeof(timeout)!="undefined"){
        setTimeout("ajaxStopLoad()",timeout);
    }

//så att inte reloaden körs när man fyller ett formulär
isPageReloading = false;
    
    AjaxFlag = true;
    setTimeout("ajaxLoadNow()",300);
}
var AjaxFlag = false;
function ajaxLoadNow(){
    if (AjaxFlag){
        $get("AjaxLoaderGif").style.visibility = "visible";
    }
}

function ajaxStopLoad(){
isAjaxLoading = false;
AjaxFlag = false;
if ($get("AjaxLoaderGif")!==null){
    $get("AjaxLoaderGif").style.left = "-200px";
   }
}

function AjaxError(error){ // för bakåtkomp
    ajaxError();
}

function AjaxLoad(e,timeout){// för bakåtkomp
ajaxLoad(e,timeout);
}

function AjaxStopLoad(){
ajaxStopLoad();
}

//plockas ut getScrollXY()[0] eller höjd getScrollXY()[1]

function getScrollXY()
 {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' )
 {
    //Firefox compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
} 
else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) 
{
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } 
else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
 {
    //IE standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [scrOfX, scrOfY];
}

function getFlashTag(moviepath, width, height, tagname){
    document.write("<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 + "\" id=\"" + tagname + "\" align=\"middle\">");
    document.write("<param name=\"allowScriptAccess\" value=\"sameDomain\" />");
    document.write("<param name=\"movie\" value=\"" + moviepath + "\" />");
    document.write("<param name=\"quality\" value=\"high\" />");
    document.write("<param name=\"scale\" value=\"noborder\" />");
    document.write("<param name=\"bgcolor\" value=\"#ffffff\" />");
    document.write("<embed src=\"" + moviepath + "\" quality=\"high\" scale=\"noborder\" bgcolor=\"#ffffff\" width=\"" + width + "\" height=\"" + height + "\" name=\"" + tagname + "\" align=\"middle\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />");
    document.write("</object>");
}

function resizeImageViewer(height){ // ska inte den här bort?/LG
    alert(height);
}

function debug(message){
var div = document.getElementById("edgeDebugLayer");
    if (div===null){
div = document.createElement("div");
div.id = "edgeDebugLayer";
div.className = "btex";
div.style.position = "absolute";
div.style.left = "1000px";
div.style.top = "10px";
document.forms[0].appendChild(div);
}

       div.innerHTML += message+"<br />";

}

var isPageReloading = true;
function reload(time){ // laddar om sidan, finns på alla sidor
      setTimeout("if (isPageReloading) {document.location.reload();}", (time*60*1000));
}
var tinyMCELoaded = false;
function loadTinyMCE(){
        if (!tinyMCELoaded) {  
        s = document.createElement("script");
        s.language="javascript";
        s.type="text/javascript";
        s.src = "/tinymce/jscripts/tiny_mce/tiny_mce_src.js";
        document.forms[0].appendChild(s);
        }
       tinyMCELoaded = true;
}
/// nedan är till lokus i huvudet
function lokReset(){
	f = document.forms[0];
	if(f.strFreeText.value === "Sök annons") {
		f.strFreeText.value = "";
	}
}

function lokSE(){
args = arguments;
    e = args[0];
    if(e===null) {
        e = window.event;
    }
    if (e && e.keyCode === 13) {
        lokusSubmit();
    } else {
        return false;
    }

}

function lokusSubmit(){
	f = document.forms[0];
         _v = f.strFreeText.value;
	var strSearchPage = 'Exp_SearchStart.asp';
	var iCustomerType = '-1'; // 0 = foretag , 1 privat och -1 alla
	//f.NewUrl.value = strSearchPage + '?iCustomerType=' + iCustomerType + '&strFreeText=' + f.strFreeText.value;
	    url = "/lokus/default.aspx?strFreeText=" + _v+ "&iCustomerType=" + iCustomerType;
	    location.href = url;
}


function gotoLokusPage(){
	if(document.getElementById("LokusSelect").selectedIndex > 0){
		document.location.href = document.getElementById("LokusSelect")[document.getElementById("LokusSelect").selectedIndex].value;
	}
}

$(document).ready(function() {
      /*$(".Column1_2 h1, .Column1_2 h3").each(function() {
          if ($("span.sep", this).length == 0)
              $(this).append(" <span class=\"sep\" style=\"display:none\">|</span>");
      });*/
      //$("span.sep").fadeIn(1000);
});


    function cookie_check(ifd,ife) {
    	var s=ife.indexOf(ifd);
    	if(s==-1) {return "";}
        s+=ifd.length;
    	var e=ife.indexOf(";",s);
    	if(e==-1) {e=ife.length;}
    	return ife.substring(s,e);
    }

    function write_cookie() {
    	var da=new Date();
    	var m=da.getTime();
    	document.cookie="OAS_SC1="+m.toString()+";path=/;";
    	var v=cookie_check("OAS_SC1=",document.cookie);
    	if(v!=m.toString()){return false;}
    	da.setTime(m+3600000);
    	return true;
    }

//if (typeof(Sys) !== "undefined") {Sys.Application.notifyScriptLoaded();}




function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function getPathDirs() {
    var paths = [];
    var c = window.location.pathname.split('/');
    for (var i = 0; i < c.length; i++)
        if (c[i] != '')
            paths.push(c[i]);
    return paths;
}

// Förflytta till mobilsajt

var useragents = new Array('android', 'ericsson', 'iphone', 'htc', 'motorola', 'nokia', 'samsung', 'symbian', 'opera mini');
var ua = navigator.userAgent.toLowerCase();

if (readCookie('showMobile') != 'false') 
{
    for (var i = 0; i < useragents.length; i++) {
        if (ua.indexOf(useragents[i]) > -1) {
            if (confirm('Du verkar besöka webbplatsen med en mobil webbläsare. Vill du bli förflyttad till Kuriren i ett format anpassat för din mobila enhet?')) {
                var url = 'http://mobil.kuriren.nu';
                var artid = getParameterByName("articleid");
                if (artid != null && artid.length > 0)
                    url += "/?id=" + artid;
                else {
                    var paths = getPathDirs();
                    if (paths.length > 0 && paths[0] != 'start' && paths[0] != 'nyheter' && paths[0] != 'startsida')
                        url += "/?p=" + paths[0];
                }
                document.location = url;
                createCookie('showMobile', 'true', 30);
            }
            else {
                createCookie('showMobile', 'false', 30);
            }
            break;
        }
    }
}

