/**
* @author ehandelsbureauet
* this script is copyrighted and is not allowed to be used in any way without permission.
*
**/
var cookieMgr = {
  getExpDate: function (days, hours, minutes) {
    var expDate = new Date();
    if (typeof days == "number" && typeof hours == "number" &&
typeof minutes == "number") {
      expDate.setDate(expDate.getDate() + parseInt(days));
      expDate.setHours(expDate.getHours() + parseInt(hours));
      expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
      return expDate.toGMTString();
    }
  },
  getCookieVal: function (offset) {
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr == -1) {
      endstr = document.cookie.length;
    }
    return decodeURI(document.cookie.substring(offset, endstr));
  },
  getCookie: function (name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
      var j = i + alen;
      if (document.cookie.substring(i, j) == arg) {
        return this.getCookieVal(j);
      }
      i = document.cookie.indexOf(" ", i) + 1;
      if (i == 0) break;
    }
    return "";
  },
  setCookie: function (name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + encodeURI(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
  },
  deleteCookie: function (name, path, domain) {
    if (this.getCookie(name)) {
      document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
  }
};

var incomedata; //VAR FOR COOKIE RETURN

var prListUtilFunctions = {
  init: function () {

    if (!document.getElementById('prListUtilTagDIV')) {
      return;
    }
    document.getElementById('prListUtilTagDIV').style.display = "none";
    if (!document.getElementById('prListUtilTag')) {
      return;
    }
    this.prTXT = document.getElementById('prListUtilTag');
    document.getElementById('prListUtilA1').href = document.getElementById('utilLINK').innerHTML;
    document.getElementById('prListUtilIMG1').src = document.getElementById('utilIMAGE').innerHTML;
    document.getElementById('prListUtilTXT1').innerHTML = "<a href='" + document.getElementById('utilLINK').innerHTML + "'>KLIK HER FOR AT SE</a>";
    document.getElementById('prListUtilTXT2').innerHTML = "<a href='" + document.getElementById('utilLINK').innerHTML + "'>" + document.getElementById('utilNAME').innerHTML.toUpperCase() + "</a>";
    document.getElementById('prListUtilTagDIV').style.display = "block";
    this.cleanDIV();
  },
  cleanDIV: function () {

  }
}



image_url = new Array();
preLoadImgPrMenu();
var defaultTextSearchField = "INDTAST PRODUKTNAVN";
var defaultTextNewsFormNameField = "INDTAST DIT NAVN";
var defaultTextNewsFormEmailField = "INDTAST DIN EMAIL";
//Cufon.replace('h1');
Cufon.replace('h1', { fontFamily: 'estate' });
Cufon.replace('h4');
Cufon.replace('h5');
Cufon.replace('h3', {
  color: '#000000',
  hover: {
    color: '#838383'
  }
});



function preLoadImgPrMenu() { //PRELOAD MENUGRAPHICS
  if (document.images) {
    preload_image_object = new Image();
    // set image url        
    image_url.push = "/images/design/construction/prmenu_niv1.gif";
    image_url.push = "/images/design/construction/prmenu_niv1_h.gif";
    image_url.push = "/images/design/construction/prmenu_niv2.gif";
    image_url.push = "/images/design/construction/prmenu_niv2_h.gif";
    image_url.push = "/images/design/construction/prmenu_niv2_active.gif";
    var i = 0;
    for (i = 0; i <= image_url.length; i++)
      preload_image_object.src = image_url[i];
  }
}

/* DOCUMENTATION
* [fixPrMenuSpanTagMenu] fix problem with SPAN bold in prmenu
* [performImgScript] function for hover effect on images - eventclass
* [systemCategories] inserts headline on search, news and special offer in TD on prlist
* [insertFocusOnSearch] inserts onfocus on searchfield
* [categoryPictureList] moves productpictures from prmenu to listitems
* [redesignCatPage] redesigns the listed catpage to easier items
*/


function init() {
  fixPrMenuSpanTagMenu();
  performImgScript();
  systemCategories();
  insertFocusOnSearch();
  insertFocusOnNewsForm();
  categoryPictureList();
  moveProductMenu();
  showFrontpageTop();
  fixPriceCardPrice();
  changePrCardHeader();
  moveFrPageHeadlines();
  moveRelatedProducts();
  checkforBasketShipCookie();
  b2bScript.init();

  // MOVE PICTURE FROM SHORT DESCRIPTION UP TO NEWSPIC DIV
  $('#shortdepix').replaceWith($('#prCardShortDescrp').find('IMG'));

  if (document.getElementById('ProductList_TD')) {
    prListUtilFunctions.init();
  }



}



function attachValPopupBuyBtn() {
  if (document.myform) {

    document.myform.onsubmit += "alert('#');";
  }
}
function moveProductMenu() {

  var linkFinder = [];
  var linkNameFinder = [];
  var tempHTML = "";

  var prMenuA = document.getElementById('ProductMenu_Table').getElementsByTagName('A');

  for (var i = 0; i < prMenuA.length; i++) {
    if (prMenuA[i].className == "Deactiv_Productmenu" || prMenuA[i].className == "DeActiv_Productmenu") {
      if (prMenuA[i].parentNode.className == "RootCategory_Productmenu") {
        linkFinder.push(prMenuA[i].href);
        linkNameFinder.push(prMenuA[i].innerHTML);
      }
    }

    if (prMenuA[i].className == "Activ_Productmenu") {
      if (prMenuA[i].parentNode.className == "RootCategory_Productmenu") {
        linkFinder.push(window.location);
        linkNameFinder.push(prMenuA[i].innerHTML);
      }
    }
  }

  for (var i = 0; i < linkFinder.length; i++) {
    tempHTML += "<div class='topMenuLinkBox'><a href='" + linkFinder[i] + "'>" + linkNameFinder[i] + "</a></div>";
  }
  document.getElementById('prMenuTopInner').innerHTML = tempHTML;




}



function insertFocusOnSearch() {
  if (document.getElementById("Search_Form_Recode")) {
    var searchForm = document.getElementById("Search_Form_Recode");

    if (searchForm.elements["Keyword"]) {
      var field = searchForm.elements["Keyword"];
      field.value = defaultTextSearchField;
      field.onfocus = onFocusHandlerSearchField;
      field.onblur = onBlurHandlerSearchField;
    }
  }
}

function onFocusHandlerSearchField() {
  if (this.value == defaultTextSearchField) {
    this.value = "";
  }
}

function onBlurHandlerSearchField() {
  if (this.value == "") {
    this.value = defaultTextSearchField;
  }
}

function insertFocusOnNewsForm() {
  if (document.getElementById("frNewsForm")) {
    var searchForm = document.getElementById("frNewsForm");

    if (searchForm.elements["name"]) {
      var field = searchForm.elements["name"];
      field.value = defaultTextNewsFormNameField;
      field.onfocus = onFocusHandlerNewsFormNameField;
      field.onblur = onBlurHandlerNewsFormNameField;
    }

    if (searchForm.elements["email"]) {
      var field = searchForm.elements["email"];
      field.value = defaultTextNewsFormEmailField;
      field.onfocus = onFocusHandlerNewsFormEmailField;
      field.onblur = onBlurHandlerNewsFormEmailField;
    }
  }
}

function onFocusHandlerNewsFormNameField() {
  if (this.value == defaultTextNewsFormNameField) {
    this.value = "";
  }
}

function onBlurHandlerNewsFormNameField() {
  if (this.value == "") {
    this.value = defaultTextNewsFormNameField;
  }
}

function onFocusHandlerNewsFormEmailField() {
  if (this.value == defaultTextNewsFormEmailField) {
    this.value = "";
  }
}

function onBlurHandlerNewsFormEmailField() {
  if (this.value == "") {
    this.value = defaultTextNewsFormEmailField;
  }
}


function fixPrMenuSpanTagMenu() { //FIXES PROBLEM WITH BOLD IN PRMENU
  var tempSpan = document.getElementsByTagName('SPAN');
  for (var i = 0; i < tempSpan.length; i++) {
    if (tempSpan[i].className == "ProductMenu_MenuItemBold") {
      tempSpan[i].parentNode.innerHTML += tempSpan[i].innerHTML;
      tempSpan[i].style.display = "none";
      tempSpan[i].innerHTML = "";
    }
  }
}

function systemCategories() { // MAKES HEADLINES IN SEARCH RESULT
  if (window.location.pathname.match(new RegExp('^/shop/news'))) {
    document.getElementById('prListHeader').innerHTML = "<h1>Nyheder</h1>";
  }
  if (window.location.pathname.match(new RegExp('^/shop/specialoffer'))) {
    document.getElementById('prListHeader').innerHTML = "<h1>Tilbud</h1>";
  }
  if (window.location.pathname.match(new RegExp('^/shop/search'))) {
    document.getElementById('prListHeader').innerHTML = "<h1>Søgeresultat</h1>";
  }
}


// WOGWCLASSLIB
function performImgScript() { // READY FUNCTION FOR HOVER EFFECTS ON GIF
  eventImgArray = document.getElementsByTagName('A');
  for (var i = 0; i < eventImgArray.length; i++) {
    if (eventImgArray[i].className == 'eventClass') {
      addEvent(eventImgArray[i], "mouseover", processOver, false);
      addEvent(eventImgArray[i], "mouseout", processOut, false);
    }
  }
  //CLEANMEM
  eventImgArray = {};
}

function addEvent(elem, evtType, func, capture) {
  capture = (capture) ? capture : false;
  if (elem.addEventListener) {
    elem.addEventListener(evtType, func, capture);
  }
  else
    if (elem.attachEvent) {
      elem.attachEvent("on" + evtType, func);
    }
    else {
      elem["on" + evtType] = func;
    }
}

function processOver(evt) {
  evt = (evt) ? evt : window.event;
  var elem = (evt.target) ? evt.target : evt.srcElement;
  elem.src = elem.src.replace(/.gif/, "_h.gif")
}

function processOut(evt) {
  evt = (evt) ? evt : window.event;
  var elem = (evt.target) ? evt.target : evt.srcElement;
  elem.src = elem.src.replace(/_h.gif/, ".gif")
}

//WOGWCLASSLIB END




function categoryPictureList() {

  var imgs = {}; // Map img tag from url to img object
  // Find all images in menu, swap their a hrefs title into the place of the image
  var productMenu = document.getElementById("ProductMenu_Table");

  var img = productMenu.getElementsByTagName("IMG");

  for (var i = 0; i < img.length; i++) {
    var parent = img[i].parentNode; // The a tag
    var title = (parent.tagName == "B" ? parent.parentNode.title : parent.title); // title of a tag, which becomes link text
    var href = (parent.tagName == "B" ? parent.parentNode.href : parent.href)

    if (title) {
      imgs[href] = img[i];
      parent.innerHTML += title;
    }

  }

  // Find product list and move the image into that position
  var a = document.getElementsByTagName("A");

  for (var i = 0; i < a.length; i++) {

    if ((a[i].className == "SubCats_Prodlink")) {

      var a = document.getElementsByTagName("A");
      for (var i = 0; i < a.length; i++) {
        if ((a[i].className == "SubCats_Prodlink")) {

          var img = imgs[a[i].href];
          if (img) {
            var innerHTML = a[i].innerHTML;
            a[i].appendChild(img);
          }
        }
      }
    }
  }

  a = "";
  imgs = "";

  redesignCatPage();

}

/*
Finds the links sub to the current category and displays these
*/
function redesignCategoryList(){
	if(document.getElementById("catMenuInsert")){
		var placeToPut = document.getElementById("catMenuInsert");
		var previousContent = placeToPut.innerHTML;
		var catElement = "";
		placeToPut.innerHTML = catElement;
		
		
		var className = "SubCategory1_Productmenu";
		
		var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
	
		var allChildren = document.getElementsByTagName("*");
		var results = [];
		var links = [];
		var titles = [];
		
		var index = 0;
		var indexOfSelectedElement;
		var element;
		for(var i=0; (element=allChildren[i]) !=null ; i++){
			
			var elementClass = element.className;
			if(elementClass){
				if(elementClass.indexOf(className) != -1 && hasClassName.test(elementClass)){
					
					var toAdd = element.childNodes.length-2;
					results.push(element);
					links.push(element.childNodes[toAdd].href);
					titles.push(element.childNodes[toAdd].title);	
					if(element.childNodes[1].className){
						if(element.childNodes[1].className.indexOf("Activ_Productmenu") != -1){
							indexOfSelectedElement = index;
						}
					}
					index = index + 1;	
				}
			}	
			
		}	
	//	document.getElementById("catMenuInsert").innerHTML="";
	//	document.getElementById("category-picture-list").innerHTML = "";
		var list = "<div id='catWrapperRe'><div id='category-normal-list'><table style='width: 100%;'><tr>";

		for (var i = 0; i < results.length; i++) {
			if(i!=0 && i%5==0){
				list += "</tr><tr>";	
			}
			if(i!=indexOfSelectedElement){	
				list += "<td style='width: 20%; height:auto;'><div id = '"+i+"'class='catListBoxRe'><h2><a href='" +
					links[i] + "'>" + titles[i] 
					+"</h2></div></td>";
					
			}else{
				
				list += "<td style='width: 20%; height:auto;'><div id='"+i+"' class='catListBoxRe2'><h2><a href='" +
				links[i] + "'>" + titles[i]  +"</h2></div></td>";
			}
			
		}
		list+="</tr></table></div></div>";
		document.getElementById("catMenuInsert").innerHTML += list;
	
	}
	
}

function redesignCatPage() {
 
  htmlIns = "";

  //REDESIGN

  if (document.getElementById("category-picture-list")) {
    var findTags = document.getElementById("category-picture-list").getElementsByTagName("A");

    var findLink = [];
    var findImg = [];
    var findTxt = [];


    for (var i = 0; i < findTags.length; i++) {
		if(typeof findTags[i].lastChild.src=="undefined"){
		}else{
    	  findImg.push(findTags[i].lastChild.src);
		}
      findLink.push(findTags[i].href);
      findTxt.push(findTags[i].firstChild.nodeValue);
    }

    document.getElementById("category-picture-list").innerHTML = "";

    for (var i = 0; i < findLink.length; i++) {
      document.getElementById("category-picture-list").innerHTML += "<div class='catListBox'><h2><a href='" +
            findLink[i] +
            "'>" +
            findTxt[i] +
            "</h2><div class='catListImgBox'><a href='" +
            findLink[i] +
            "'><img src='" +
            findImg[i] +
            "'>" +
            "</a></div></div>";

    }

  }

}

function showFrontpageTop() {
  if (location.href.match('/shop/frontpage.html')) {
    if (document.getElementById('frTopText')) {
      document.getElementById('frTopText').style.display = "block";
    }
  }
}

function fixPriceCardPrice() {

  if (document.getElementById('prCardPriceTD')) {
    var cells = document.getElementById('prCardPriceTD').getElementsByTagName('TD');
    var priceCell = null;
    var pretext = [];

    for (var i = 0; i < cells.length; i++) {
      var clName = cells[i].className;

      if ((clName == "Price_ProductInfo")) {
        priceCell = cells[i];
      }
      else if (clName == "PriceText_ProductInfo_TD" || clName == "PriceAmount_ProductInfo_TD" || clName == "PriceUnit_ProductInfo_TD" || clName == "PriceBefore_ProductInfo_TD") {
        pretext.push(cells[i].innerHTML);
      }
    }

    var prTarget = document.getElementById('prCardPrice');
    prTarget.innerHTML = priceCell.innerHTML;

    var prPretextTarget = document.getElementById('prCardPricePretext');
    prPretextTarget.innerHTML = pretext.join(" ");


    var rows = document.getElementById('prCardPriceTD').getElementsByTagName('TR');

    for (var i = 0; i < rows.length; i++) {
      if ((rows[i].className == "Price_ProductInfo_TR")) {
        rows[i].style.display = "none";
      }
    }
  }
}

function changePrCardHeader() {
  var headlines = document.getElementsByTagName('H1');

  for (var i = 0; i < headlines.length; i++) {
    if ((headlines[i].className == "makeH6")) {
      headlines[i].parentNode.innerHTML = "<h6>" + headlines[i].innerHTML + "</h6>";

    }
  }
}

function moveFrPageHeadlines() {
  if (document.getElementById("frontpageHeadlines")) {
    var source = document.getElementById("frontpageHeadlines");

    if (document.getElementById("frTopText")) {
      var target = document.getElementById("frTopText");

      var h1Text = source.getElementsByTagName("h1")[0].innerHTML;
      var h2Text = source.getElementsByTagName("h2")[0].innerHTML;

      target.innerHTML = "<h4>" + h1Text + "</h4><h5>" + h2Text + "</h5>";
      source.style.display = 'none';
    }
  }
}


function moveRelatedProducts() {

  if (document.getElementById('prCardRelated')) {
    var htmlTxt = "";
    var relPicture = [];
    var relNameAndLink = [];

    var findDIVRel = document.getElementById('prCardRelated').getElementsByTagName('DIV');

    for (var i = 0; i < findDIVRel.length; i++) {

      if (findDIVRel[i].className == "prCardRelatedName") {
        relNameAndLink.push(findDIVRel[i].firstChild.firstChild.innerHTML);
      }

      if (findDIVRel[i].className == "prCardRelatedImg") {
        relPicture.push(findDIVRel[i].innerHTML);

      }

    }

    for (var i = 0; i < relPicture.length; i++) {
      htmlTxt += "<div class='prRelMiniPic'>" + relPicture[i] + "</div>";
    }

    if (relPicture.length > 0) {
      document.getElementById('prCardRelatedSpace').innerHTML = htmlTxt;
      document.getElementById('prCardRelatedBorder').style.display = "block";
    }

    //attach alt and title on relpic
    var relspacerPix = document.getElementById('prCardRelatedSpace').getElementsByTagName('DIV');
    for (var i = 0; i < relspacerPix.length; i++) {
      relspacerPix[i].firstChild.title = relNameAndLink[i];
      relspacerPix[i].firstChild.alt = relNameAndLink[i];
    }

  }
}





function checkforBasketShipCookie() {
  if (document.getElementById('basketTotPrice')) {
    if (navigator.cookieEnabled) {
      incomedata = cookieMgr.getCookie("checkforBasketShipCookie");

      if (incomedata == "") {
        // DO NOTHING 
      }
      if (incomedata == "deliverByStore") {
        commandStyling();
      }
    }

  } else if (!navigator.cookieEnabled) {
    //  USER HAS NO COOKIE HIDE FUNCTION
    document.getElementById('basketAltShipChBoxDIV').style.display = "none";
  }

  //ASSIGN SHIPPING METHOD IF COOKIE IS TRUE
  if (document.getElementById('ShippingMethodsContainer')) {

    if (navigator.cookieEnabled) {
      incomedata = cookieMgr.getCookie("checkforBasketShipCookie");


      if (incomedata == "") {
        // DO NOTHING BUT ASSIGN CLICK HANDLERS
        if (document.getElementById('ShippingMethodID48')) {
          document.getElementById('ShippingMethodID48').onclick = deleteCookieOnFreightMethod;
        }
        if (document.getElementById('ShippingMethodID57')) {
          document.getElementById('ShippingMethodID57').onclick = setCookieOnFreightMethod;
        }
      }
      if (incomedata == "deliverByStore") {

        if (document.getElementById('ShippingMethodID48')) {
          document.getElementById('ShippingMethodID48').onclick = deleteCookieOnFreightMethod;
          if (document.getElementById('ShippingMethodID48').checked == true) { document.getElementById('ShippingMethodID48').checked = false }

        }
        // AFHENT I BUTIK
        if (document.getElementById('ShippingMethodID57')) {
          document.getElementById('ShippingMethodID57').onclick = setCookieOnFreightMethod;
          if (document.getElementById('ShippingMethodID57').checked == false) { document.getElementById('ShippingMethodID57').checked = true }

        }



      }
    }

  }
}
function setCookieOnFreightMethod() {
  var data = "deliverByStore";
  var expDate = cookieMgr.getExpDate(2, 0, 0);
  cookieMgr.setCookie("checkforBasketShipCookie", data, expDate);
  window.location = "/shop/order2.html";
}
function deleteCookieOnFreightMethod() {
  var data = "";
  var expDate = cookieMgr.getExpDate(0, 0, 0);
  cookieMgr.setCookie("checkforBasketShipCookie", data, expDate);
  window.location = "/shop/order2.html";
}

function commandStyling() {
  var shippingFeeVar = (document.getElementById('basketShippingFee').innerHTML);
  var basketTotalPrice = (document.getElementById('basketTotPrice').innerHTML);

  shippingFeeVar = shippingFeeVar.replace(/\./ig, "");
  shippingFeeVar = shippingFeeVar.replace(/\,/ig, ".");
  basketTotalPrice = basketTotalPrice.replace(/\./ig, "");
  basketTotalPrice = basketTotalPrice.replace(/\,/ig, ".");
  parseFloat(basketTotalPrice);
  parseFloat(shippingFeeVar);

  document.getElementById('basketTotPrice').innerHTML = (basketTotalPrice - shippingFeeVar).toFixed(2);
  document.getElementById('basketShippingFee').innerHTML = "0,00";
  document.getElementById('basketAltShipChBox').checked = true;

  var data = "deliverByStore";
  var expDate = cookieMgr.getExpDate(1, 0, 0);
  cookieMgr.setCookie("checkforBasketShipCookie", data, expDate);

}

function shippingFeeChecked() {
  if (basketAltShipChBox.checked == true) {
    commandStyling();
  }
  if (basketAltShipChBox.checked == false) {
    deleteCookie();
    window.location = "/shop/showbasket.html";
  }
}


function deleteCookie() {
  var data = "";
  var expDate = cookieMgr.getExpDate(0, 0, 0);
  cookieMgr.setCookie("checkforBasketShipCookie", data, expDate);
}




var b2bScript = new b2bScript();



function b2bScript() {
  this.init = function () {

    if (document.getElementById('b2blogout')) {
      var html = '<p class="topMenuB2Bmessage">Du er nu logget ind med indkøbsaftale med Outshop.dk</p>';
      document.getElementById('topMenuTDNavigation').innerHTML += html;
    }



    if (document.getElementById('B2BLogin_TD')) {
      findBTNvar = document.getElementById('B2BLogin_TD').getElementsByTagName('INPUT');

      for (var i = 0; i < findBTNvar.length; i++) {

        if (findBTNvar[i].className == "SubmitButton_B2Blogin") {

          if (findBTNvar[i].value == "Login") {
            findBTNvar[i].className = "b2bModuleBtnLogin"
            findBTNvar[i].value = " ";
          };
          if (findBTNvar[i].value == "Send") {
            findBTNvar[i].className = "b2bModuleBtnSend"
            findBTNvar[i].value = " ";
          };
          if (findBTNvar[i].value == "Gem") {
            findBTNvar[i].className = "customerModuleBtnGem"
            findBTNvar[i].value = " ";
          };
        }
      }
    }
  }
}

