﻿jQuery(function () {
  initAddThis();
  //initValidations();
  initForhandlerDropDown();
  initKontaktFormManip();
  initdivisionsTable();
  initTClist();
});

window.onload = function () {
  orderCols();
  boxStat();
};

var gridHeight = 170, gridMargin = 12;
function orderCols() {
  //Fixer højderne på alle undersiders kolonneindhold
  jQuery("#ContentArea:not(.frontpage #ContentArea,) .col").each(function (i) {
    var col = jQuery(this), boxes = col.find(".box .boxInside");
    
    boxes.each(function (y) {
      var thisBox = jQuery(this),
          addMargin = thisBox.parent().children(".boxTop").css("display") === "none" && thisBox.parent().children(".boxBottom").css("display") === "none",
          boxOuterHeight = thisBox.outerHeight(),
          padding = parseInt(thisBox.css("padding-top")) + parseInt(thisBox.css("padding-bottom")),
          boxHeight = thisBox.height(),
          numberOfRows = Math.ceil(boxOuterHeight / (gridHeight + gridMargin)),
          calcHeight = numberOfRows * gridHeight + (gridMargin * (numberOfRows - 1)) - padding,
          isNotLast = thisBox.parent().next().is(".box");
      if (addMargin /*&& isNotLast*/) {
        thisBox.parent().css("margin-bottom", gridMargin);
      }
      thisBox.height(calcHeight);
    });
  });

  var frontpageBoxes = jQuery(".frontpage #ContentArea .col .box");
  if (frontpageBoxes[0]) {
    frontpageBoxes.each(function() {
      var thisBox = jQuery(this),
      boxOuterHeight = parseInt(thisBox.attr("backgroundImageHeight")),
      padding = parseInt(thisBox.css("padding-top")) + parseInt(thisBox.css("padding-bottom"));

      var addMargin = thisBox.parent().children(".boxTop").css("display") === "none" && thisBox.parent().children(".boxBottom").css("display") === "none",
          boxOuterHeight = thisBox.outerHeight(),
          padding = parseInt(thisBox.children(".boxBg").css("padding-top")) + parseInt(thisBox.children(".boxBg").css("padding-bottom")),
          boxHeight = thisBox.height(),
          numberOfRows = Math.ceil(boxOuterHeight / (gridHeight + gridMargin)),
          calcHeight = numberOfRows * gridHeight + (gridMargin * (numberOfRows - 1)) - padding;
      thisBox.children(".boxBg").height(calcHeight);
    });
  }
}

function initForhandlerDropDown() {
  jQuery("#ForhandlerSelect").bind("change", function () {
    var chosenoption = this.options[this.selectedIndex];
    if (chosenoption.value != "nothing") {
      window.location.href = chosenoption.value;
    }

  });
}

function initAddThis() {
  var newsList = jQuery("#ContentArea .box4 .newsList, #ContentArea .box4 .newsItem");
  if(newsList[0]){
    newsList.closest(".boxInside").append('<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=xa-4bf4f58e6de0955d"><img src="http://s7.addthis.com/static/btn/sm-share-en.gif" width="83" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4bf4f58e6de0955d"></script>');
  }
}
//function initValidations() {
//  
//  /*
//  settings skal sendes med i ReadyValidate metoden, når man gør een 
//  eller flere formularer klar til validering
//  */
//  var settings = {
//   /*
//    onFieldValidateFalse og onFieldValidateTrue
//    Sender man en string med i disse to vil de
//    blive sat som class på det enkelte felt,
//    hvis det validerer eller fejler.
//    Alternativt kan man sende en funktion med.
//    funktionerne bliver kaldt efter valideringsprocessen,
//    med følgende parametre:
//    onFieldValidateFalse(ele, failStr);
//    onFieldValidateTrue(ele);
//    */
//    onFieldValidateFalse: "fail",
//    onFieldValidateTrue: "valid",
//    /*
//    valArr er en samling af valideringer der skal køres på en eller flere formularer.
//    Det er ikke nødvendigvis alle valideringer der skal køres på samme formular
//    Pluginet vil teste om formularen indeholder nogle af felterne, men først on submit.
//    Rækkefølgen for er: valideringstype, css select der skal ramme feltet, fejlbesked, 
//    et antal ekstra parametre (bestemmes af valideringstypen)
//    */
//    valArr: [["notempty", "[name=AccessUserEmail]", "Email skal udfyldes"],
//              ["isMail", "[name=AccessUserEmail]", "Email skal være en email (logisk)"],
//              ["notempty", "[name=AccessUserName]", "Navn skal udfyldes"]]
//  };

//  jQuery("form.newsletterSubscribe, form.newsletterUnSubscribe").ReadyValidate(settings);

//}

  function initKontaktFormManip() {
    jQuery("select[name='fmanpkonaf']").parent().parent().css("display","none");
    jQuery("input[name='kontaktes_af']").parent().parent().css("display","none");
    jQuery("input[name='kontaktes_af']").parent().parent().prev().css("display","none");
    jQuery(".KontaktManip").append("<br />"+ jQuery("select[name='fmanpkonaf']").parent().html());
    jQuery("select[name='fmanpkonaf']").addClass("selectFormManipOrg");
    jQuery(".KontaktManip select").removeClass("selectFormManipOrg");
    jQuery(".KontaktManip select").addClass("selectFormManipNy");

    jQuery(".selectFormManipNy").change(function() {
      jQuery("input[name='kontaktes_af']").val(jQuery(".selectFormManipNy").val());
    });
  }



/* Divsions START */
String.prototype.trim = function () { return this.replace(/^\s+|\s+$/, ''); };

var divisionsTable, dataListCols, dataListCol1;
function initdivisionsTable() {
  divisionsTable = jQuery("#DivisionsTable");
  if (divisionsTable[0]) {
    dataListCols = divisionsTable.find(".dataListCol");
    dataListCol1 = dataListCols.filter("#DataListCol1");
    addGroupHeaders();
    splitDataList();
    finalizeDataList();
    divisionsLinks();
    initFirstDivisionItem();
  }
}

function addGroupHeaders() {
  var lastGroupHeader = "";
  dataListCol1.children().each(function (i) {
    var thisDD = jQuery(this);
    if (lastGroupHeader !== thisDD.attr("productgroups")) {
      lastGroupHeader = thisDD.attr("productgroups");
      thisDD.before("<dt>" + lastGroupHeader + "</dt>");
    }
  });
}

function finalizeDataList() {
  var lastEles = [];
  dataListCols.each(function (i) {
    var thisCol = jQuery(this);

    if (thisCol.children(":first")[0].tagName.toLowerCase() === "dd") {
      var lastDT = null;
      for (var y = i - 1; y >= 0; y--) {
        lastDT = jQuery(dataListCols[y]).children("dt:last");
        if (lastDT[0]) {
          break;
        }
      }
      thisCol.prepend(lastDT.clone());
    }

  });
}

function splitDataList() {
  var totalHeight = dataListCol1.height(), columnHeight = totalHeight / 3 +35;
  for (var i = 0; i < dataListCols.length - 1; i++) {
    var currentChildren = jQuery("#" + dataListCols[i].id).children(), heightCounter = 0;
    for (var y = 0; y < currentChildren.length; y++) {
      var thisChild = jQuery(currentChildren[y]);
      heightCounter += thisChild.outerHeight();
      if (columnHeight < heightCounter) {
        var grabFrom = y - 1;
        if (thisChild[0].tagName === "DD" && currentChildren[y - 1].tagName === "DT") {
          grabFrom = y - 2;
        } else if (thisChild[0].tagName === "DD") {
          thisChild.addClass("topItem");
        }
        jQuery(dataListCols[i + 1]).append(currentChildren.filter(":gt(" + grabFrom + ")"));
        break;
      }
    }
  }
}


function divisionsLinks() {
  jQuery(".medarb_link").each(function () {

    jQuery(this).click(function() {
      jQuery(".medarb_link").each(function () { jQuery(this).removeClass("medarb_valgt"); });
      jQuery(this).addClass("medarb_valgt");
      jQuery(".dataListColInfoArea").html(jQuery(this).parent().find("span").html());
    });

  });
}

function initFirstDivisionItem() {
  jQuery(".dataListColInfoArea").html(jQuery(".medarb_link:first").parent().find("span").html());
  jQuery(".medarb_link:first").addClass("medarb_valgt");
}

/* Divsions END */





function initTClist() {
  var nr = 1;
  if(jQuery(".tclist").length > 0) {
/*
    var cntTables = jQuery(".tclist table").length;
    var cntRows = jQuery(".tclist table tr").length;
    var cnt = cntRows - cntTables;
*/
   jQuery(".tclist table tr").each(function(){
      if(jQuery(this).attr("pid")) { 
        jQuery(this).find(".td1").prepend("<input type='hidden' name='ProductLoopCounter"+nr+"' id='ProductLoopCounter"+nr+"' value='"+nr+"' />"
+"<input type='hidden' name='ProductID"+nr+"' id='ProductID"+nr+"' value='"+jQuery(this).attr("pid")+"' />"
+"<input type='hidden' name='VariantID"+nr+"' id='VariantID"+nr+"' value='' />"
+"<input type='hidden' name='UnitID"+nr+"' id='UnitID"+nr+"' value='' />");
        jQuery(this).find(".td6").prepend("<input type='text' name='Quantity"+nr+"' />");
        nr = nr + 1;
      }
    });
  }
  jQuery("#multiForm a.tclink").bind("click",function() {
    jQuery("#multiForm").submit();
  });
}

function boxStat() {
  jQuery(".boxStat").each(function(){
    if(jQuery(this).find(".boxStatCI").attr("name")) { 
      _gaq.push(['_trackEvent', 'Hot Spots', jQuery(this).find(".boxStatCI").attr("name"), 'Visninger']);
    } else {
      _gaq.push(['_trackEvent', 'Hot Spots', jQuery(this).attr("name"), 'Visninger']);
    }
  });
}
