var responsiveThresholdWide = 900;
var responsiveThresholdNarrow = 600;

function initMaster() {
  if($.browser.mozilla) $("form").attr("autocomplete", "off");

  if (typeof AjaxPro != "undefined" && AjaxPro !== null) {
    AjaxPro.timeoutPeriod = 1000 * 10;
    AjaxPro.onTimeout = function(b, res) { ajaxTimeout(b, res); }
    AjaxPro.onLoading = function(b) { showBusy(b); }
    AjaxPro.onError = function(res) { ajaxError(res); }
  }

  $("#HeaderPuff").ajaxcontrol({toolbarLoaction:"top"});
  $("#articlepop div.ajaxControl").ajaxcontrol();

  if ($("#RelatedIntro").length > 0) {
    $("#RelatedIntro").ajaxcontrol();
    if ($("#RelatedIntro").html().length == 0)
      $("#relatedtop").css({"padding":"0","margin":"0"})
  }

  appendToMainMenu();

  var w = $(window), body = $("body");
  $(window).resize(function () {
    $("#toparea, #menubar").css("visibility","visible");
    $("body").removeClass("fluid").removeClass("fluidnarrow");

    if ($(window).width() < responsiveThresholdWide) {
      $("body").addClass("fluid");
      for (var i=0; i < _pad.length; i++) {
        $("#puff_" + _pad[i]).addClass('exclude');
        $("#menuarea li a[href$='" + _pad[i] + ".aspx'], #submenuarea li a[href$='" + _pad[i] + ".aspx']").each(function(){
          $(this).parent().addClass("exclude");
        });
      }
      if ($("#submenuarea ul li").length == 0)
        $(".menudivider").hide();
    }
    else $("body").removeClass("fluid");
    if ($(window).width() < responsiveThresholdNarrow) {
      $("body").addClass("fluidnarrow");
      $("#fbpuff, #recpuff, .intropuff").addClass("exclude");
      for (var i=0; i < _phone.length; i++) {
        $("#puff_" + _phone[i]).addClass('exclude');
        $("#submenuarea li a[href$='" + _phone[i] + ".aspx']").each(function(){
          $(this).parent().addClass("exclude");
        });
      }
      $("img").each(function() {
        if ($(this).parent().hasClass("puffimage"))
          $(this).css({width:$(this).attr("width"), height:$(this).attr("height")})
        $(this).removeAttr("width").removeAttr("height");
      });
      $("#artcontent table").each(function(){
        $(this).css("width","auto");
        var pw = $(this).parent().width();
        var cols = 0;
        $(this).find("tbody tr").each(function(){
          var acols = $(this).children("td").length;
          if (acols > cols) cols = acols;
        });
        var padding = $(this).attr("cellpadding");
        if (!padding) padding = 0;
        pw -= padding*cols*2;
        $(this).find("td *").css("max-width", pw/cols);
      });
    }
    else $("body").removeClass("fluidnarrow");
    closeSearch();
    try { windowResized();}
    catch (e) {};
  }).resize();

  if (!_loggedin) {
    Cufon.replace("h1,h2");
    try { appyPageCufon();}
    catch (e) {}
    Cufon.CSS.ready(initMaster2);
  }
  else
    initMaster2();

}

function initMaster2() {
  try { initAdmin();}
  catch (e) {};
  try { initPage();}
  catch (e) { nfndebug(e.message); };

}

function arrangePuffs(wrapper, callback) {
  var colwidth = 220;
  var vertgap = 15;
  if ($(window).width() < responsiveThresholdNarrow) {
    colwidth = 145;
    vertgap = 10;
    $(wrapper + ' div.puffimage img').each(function(){
      var h = parseInt($(this).attr("height"));
      if (!isNaN(h)) {
        h = h*125/200;
        $(this).attr({width:125, height:h}).css({width:125, height:h});;
      }
      else
        $(this).css({width:125, height:"auto"});
    });
  }

//  $(wrapper + ' div.puffimage img').removeAttr("width").removeAttr("height").css({width:imgwidth, height:"auto"});
  $(wrapper).divarrange({vertgap:vertgap, colwidth:colwidth, onReady:callback});
}

function appendToMainMenu() {
  if (_lang == 'se') {
    $("#menuarea ul").append(
      $("<li />").html("<span id='fblink' onclick='toggleFB()'></span>")
    ).append(
      $("<li />").html("<input id='inpsearch' onkeydown='return checkEnter(event);' onkeyup='return startSearch(event);return false;' type='text' />")
    );
  }
  else {
    $("#menuarea ul").append(
      $("<li />").html("<input id='inpsearch' onkeydown='return checkEnter(event);' onkeyup='return startSearch(event);return false;' type='text' />")
    );
  }
}

function arrangeReady(divid) {
  $(divid).css("visibility","visible");
  //Cufon.refresh("h1,h2");
}

function applyMasterCufon() {
/*  Cufon.replace("h1,h2");
  try { appyPageCufon();}
  catch (e) {}*/
}


function ajaxTimeout(b, res) {
  showBusy(false);
  nfndebug("Timeout i funktionen " + res.method);
}
function ajaxError(res) {
  showBusy(false);
  nfndebug(res.Message);
}
function showBusy(busy) {
  $("#ajaxbusy").css("display", (busy ? "block" : "none"));
}

function cyclePuffs() {
  $(".puffimage").each(function(){

    function slideTimeout(currElement, nextElement, opts, isForward, timeout) {
      var idx = opts.currSlide;
      var vals = timeout.split(',');
      return parseInt(vals[idx]);
    }

    var obj = this;
    if ($(obj).children().length > 1) {
      var effect="";
      var timeout="";
      $(obj).next().children().each(function(){
        var vals = $(this).html().split('|');
        if (effect.length > 0) {
          effect += ",";
          timeout += ",";
        }
        effect += vals[0];
        timeout += vals[1];
      });
      $(obj).cycle({
        fx:effect,
        speed:1000,
        timeoutFn: function(c,n,o,i){return slideTimeout(c,n,o,i,timeout);}
      });
    }
  });
}

var poppropcount = 0;
function popArticle(pageid) {
  Master.GetArticleProps(pageid, popArticle2);
}
function popArticle2(response) {
  poppropcount = 0;
  $("#HeaderPop").ajaxcontrol_setPropertyId(response.value[0], popArticle3);
  $("#IntroPop").ajaxcontrol_setPropertyId(response.value[1], popArticle3);
  $("#ArticleContentPop").ajaxcontrol_setPropertyId(response.value[2], popArticle3);
}
function popArticle3() {
  poppropcount++;
  if (poppropcount == 3) {
    Cufon.replace("#articlepop h1, #articlepop h2");
    $("#articlepop").show('normal');
  }
}

function checkEnter(e) {
  if(!e) e = window.event;
  var key = (e.which) ? e.which: e.keyCode;
  return key != 13;
}

var searchTimer = null;

function startSearch(e) {

  if (searchTimer) clearTimeout(searchTimer);
  if ($("#inpsearch").val().length > 2) {
    $("#inpsearch").css("background-image","url(../gfx/search_wait.gif)");
    searchTimer = setTimeout(doSearch, 500);
  }
  else {
    $("#inpsearch").css("background-image","url(../gfx/search.gif)");
    $('#searchpop').slideUp();
  }
  return checkEnter(e);
}

function doSearch() {
  Master.SiteSearch($("#inpsearch").val(), doSearch2);
}
function doSearch2(response) {
  if (response.error) {
    alert(response.error.Message);
    return;
  }
  clearTimeout(searchTimer);
  searchTimer = null;
  var pos = $("#inpsearch").offset();
  $("#searchpop_inner").html(response.value);
  $("#searchpop").css({left:pos.left-5, top:pos.top+20}).slideDown();
  $("#inpsearch").css("background-image","url(../gfx/search.gif)");
}

function closeSearch() {
  $("#inpsearch").val("");
  $('#searchpop').slideUp();
}

function toggleFB() {
  var pos = $("#fblink").offset();
  var left = pos.left - 5;
  var mleft = parseInt($("#fbfan").css("margin-left"),10);
  if (left+mleft < 0) left = -mleft+10;
  $("#fbfan").css({left:left, top:pos.top+20}).slideToggle("normal");
}

$(document).ready(function(){
   initMaster();
});

