// $Id: ernstings.novomind.js 2510 2010-03-11 09:48:28Z martins $
var $j = jQuery.noConflict();

function showAnchor(id) {
  $j('#' + id)[0].scrollIntoView(true);
};

// orderstrain general function
function toggleOsBoxes(varThis, isLink) {
  var thisParentDlboxSplit = varThis.parents("dl.boxSplit");

  // hide all innerBoxes
  var innerBoxes = thisParentDlboxSplit.find(".innerBox").not(".innerBoxFix");
    
  var belongingParent = varThis.parents("dl.boxSplitContentChoose");
  // check belonging radio input also because label/input are not clicked
  var belongingRadio = belongingParent.find("dt.chooseInput input.radio");

  
  // if is no link clicked
  if (isLink === false) {
    // NMAG only slide up if not disabled
    if(!belongingRadio.attr("disabled")) {
      innerBoxes.slideUp();
    }
  
    // show all fixed innerBoxes
    var innerBoxesFix = thisParentDlboxSplit.find(".innerBoxFix");
    innerBoxesFix.slideDown();

    // show the special default innerBoxes (mostly just one)
    var innerBoxDef = varThis.parents("dl.boxSplitContentChoose").find(".innerBoxDefault");
    innerBoxDef.slideDown();
  }

  // if is link clicked
  if (isLink === true) {
    // NMAG never check if link is clicked
    
    // hide all boxes which belong to the toggle Link
    belongingParent.find("dd.chooseLabel .innerBox").slideUp();

    // show the belonging form boxes (should be just one)
    belongingParent.find("dd.chooseLabel .innerBoxForm").slideDown();
  }
};

// orderstrain special function: abort form
  function osFormAbort(varThis) {
    var thisParentDL = varThis.parents("dl.boxSplitContentChoose");

    // hide all innerBoxes
    thisParentDL.find(".innerBox").slideUp();
    // show default box
    thisParentDL.find(".innerBoxDefault").slideDown();
  };

// sets modalWrap position to absolute after positioning through nyroModal
  function createShadow() {
    $j('#modalWrap').css({
      position: 'absolute'
    });
  };

// voucher paste
  function pasteVoucher(varThis, thisIdMain, thisIdNo) {
    var nextField = thisIdMain+(thisIdNo+1);
    nextField = $j("#"+nextField);

    if (thisIdNo < 3) {
      nextField.focus();
    } else {
      $j("button#submit_voucher").focus();
      $j("form#voucher_form").submit();
    }
  };
  
  function autoToTop(ev) {
    window.scrollTo(0, 0);
  }
  
  function limitTextarea(ev) {
    $j('textarea').counter({
      maxChars: 256,
      formatStr: "<span class='charsInfo'>Sie haben noch {1} Zeichen zur Verfügung.</span>",
      container: "p.limitText"
    });
  }
  
function openLayer(layername) {
   if(layername == 'lilalauneplayer') {
    jQuery.nyroModalManual({
        url: "http://www.ernstings-family.de/layer/layer.lilalauneSpot.html",
        forceType: 'iframe',
        height: 557,
        width: 587
    });	
  } 
}

/* Redirect to the given url */
function redirectOutofIframe( url ) {
  parent.location = url;
}

// Saves the current cateogry ID 
function saveCurrentCategory(categoryId) {
  jQuery.cookie("efCurrentCategory", categoryId, { path: '/', expires: 1 });
}

// Restores the current cateogry ID 
function restoreCurrentCategory(defaultCategoryId) {
  var categoryId = jQuery.cookie("efCurrentCategory");
  if (categoryId != null && categoryId != -1)
    return categoryId;
  else
    return defaultCategoryId;
}

// Clear the current cateogry ID 
function clearCurrentCategory() {
  saveCurrentCategory(-1);
}

$j(document).ready(function() {
  // initialize generic modal settings
  jQuery.extend(jQuery.fn.nyroModal.settings, {
    openSelector: '.modal',
    closeSelector: '.modalClose',
    titleFromIframe: false, 
    closeButton: '<a href="#" class="modalClose" id="modalClose" title="Fenster schließen">Fenster schließen</a>',
    /**
     * scroll to top before the modallayer and the loading-indicator is shown.
     */
    processHandler: function(ev) {
      window.scrollTo(0, 0);
    },
    /**
     * make position absolute in order to make the shadows work.
     */
    endFillContent: function() {
      $j('#modalWrap').css({position: 'absolute'});
    },
    /**
     * functionality for anchor links in scrollableModal
     */
    endShowContent: function() {    	
      // scrollableModal: gotoTop
      $j('a.link_zurueck_nach_oben').click(function() {
        $j('.scrollableModal').scrollTop(0);
        return false;
      });
      
      // scrollableModal: Sprungmarken in FAQ-Navi      
      $j(".scrollableModal #navi_myAcc a").each( function() {        
        var elId     = this.href.substring(this.href.indexOf('#'), this.href.length);        
        var anchorEl = $j(elId);
        
        $j(this).click( function() { 
          $j('.scrollableModal').scrollTop( anchorEl[0].offsetTop );
          
          return false;
        });        
      });
    },
    /**
     * default-error-message for http-error-responses
     */
    contentError: '<br /> Der angeforderte Inhalt konnte nicht geladen werden.'
      + ' Bitte versuchen Sie es später erneut.<br />'
      + '<a href="#" id="modalClose" class="modalClose" title="Fenster schließen">Fenster schließen</a>',
    /**
     * closes layer without animation
     */
    hideContent: function(elts, settings, callback) {
      elts.contentWrapper.hide(); callback();
    }
  });
  
  $j('.noscript').css({ display: 'block' });

  // add a target-attribute to let nyroModal know the corresponding pages should be shown in an iframe.
  $j('a.modal.iframe, form.modal.iframe').each(function() {
    this.target = '_blank';
  });
  
  $j('a.modal, form.modal').not('*[modalConfig]').nyroModal({
    minHeight: 100
  });

  $j('a.modal[modalConfig]').click(function(e) {
    var modalConfig=jQuery.evalJSON($j(this).attr('modalConfig'));
  modalConfig.url = $j(this).attr('href');
    
  $j(this).nyroModalManual(modalConfig);
  return false;
  });

  $j('a.recommend').nyroModal({
    endShowContent: limitTextarea,
    minHeight: 100
  });
  
  // sets prd_teaser to height 100%
  // Returns all inner prod. teasers within #content_main
  var prodTsIn = $j("#content_main .prd_ts_inner");

  prodTsIn.each(function(i){
    // get height from parent
    parItemHeight = $j(this).parent().height();
    // td height minus the border of inner div
    newItemHeight = parItemHeight - 1;
    // set new inner height
    $j(this).css("height", newItemHeight+"px");
  });

  // link a whole block (e.g. li)
  var linkAllItems = $j(".linkAll");
  linkAllItems.css("cursor","pointer");

  linkAllItems.not(".linkAllModal").click(function(e){
    var newHref = $j("a:first", this).attr('href');
    document.location = newHref;
    return false;
  });
  
  var linkAllItemsModal = $j(".linkAllModal");
  linkAllItemsModal.click(function(e){
    $j("a:first", this).click();
    return false;
  });
  
  
  // tags which inner tags should be decorated
  var decoTags = "p,a";
  linkAllItems.hover(
    function () { $j(this).find(decoTags).css("text-decoration","underline"); },
    function () { $j(this).find(decoTags).css("text-decoration","none"); }
  );

  // NMAG moved orderstrain operations to deliverypayment.js


  // voucher split for inputs
  $j("input.voucher_code").keyup(function () {
    var varThis = $j(this);
    if (varThis.focus()) {
      var thisId = varThis.attr("id");
      var thisIdLength = thisId.length;
      var thisIdMain = thisId.substr(0, thisIdLength-1);
      var thisIdNo = eval(thisId.substr(thisIdLength-1, thisIdLength));

      if ((varThis.val().length==15) && (thisIdNo==0)) {
        var parts = varThis.val().split("-");
        $j("input#"+thisIdMain+"0").val(parts[0]);
        $j("input#"+thisIdMain+"1").val(parts[1]);
        $j("input#"+thisIdMain+"2").val(parts[2]);
        $j("input#"+thisIdMain+"3").val(parts[3]);
        //alert("klick");
        $j("form#voucher_form button").focus();
        $j("form#voucher_form").submit();
      } else if (varThis.val().length == 3) {
        pasteVoucher(varThis, thisIdMain, thisIdNo);
      }
    }
  });
  
  
  
});

// FACT-Finder ClickInfo
function ffClickProduct(serverUrl, query, artId, artPos, artOrigPos, pageNum, artSimi, sessionId, artTitle, pageSize, origPageSize, eventName) {
  $j.ajax({
    type: 'POST',
    url: serverUrl,
    data: {
      query: query,
      id: artId,
      pos: artPos,
      origPos: artOrigPos,
      page: pageNum,
      simi: artSimi,
      sid: sessionId,
      title: artTitle,
      event: eventName,
      pageSize: pageSize,
      origPageSize: origPageSize
    },
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    cache: false,
    async: false
  });
}

// *** sidebar-functions ***
jQuery(function($) {
  function openStoresearchLayer(zipCode) {
    var storesearchBaseUrl = '/filialsuche/suche';
    $.nyroModalManual({
      url: storesearchBaseUrl + '/' + zipCode,
      width: 687, height: 605,
      forceType: 'iframe'
    });
  }
  
  // modallayer for storesearch
  $('#ts_order_fs').submit( function(ev) {
    var zipCode = $("#ts_order_fs input[name=zipCode]").attr("value");
    // only show the layer if a (possibly) valid zipcode is given.
    if(!zipCode.match(/^[0-9]+$/)) {
    	return false;
    }
    
    openStoresearchLayer(zipCode);
    return false;
  });
  
  // storesearch autocomplete
  var $input = $('#ts_myzip');
  if($input.length > 0) {
    $input.efStoresearchAutocomplete({
      suggestUrl : '/filialsuche/ajax/search',
      chooseBoxWidth : 200,
      onSelect : function(value, zipCode) {
        openStoresearchLayer(zipCode);
        $input.val(zipCode);
        
        return false;
      } 
    });
  }
  
  $j('#ts_order_nl').submit(function(e) {
    var submitUrl = "http://newsletter.ernstings-family.com/public/remotebox.jsp"
      + "?locale={locale}&uemail={uemail}";
    
    var uemailValue = jQuery('#ts_order_nl #ts_mailaddress').val();
    var localeValue = jQuery('#ts_order_nl #ts_locale').val();

    jQuery.nyroModalManual({
      url: submitUrl.replace('{uemail}', uemailValue)
                    .replace('{locale}', localeValue),
      width: 685, height: 481
    });
    
    e.preventDefault();
    e.stopPropagation();
    
    return false;
  });
  
  // layers opened from the sidebar
  $('#ts_herbstAktion a').nyroModal({
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
        + 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/herbstAktion/images/btn_close.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>',
    url: "http://static.ernstings-family.de/layer/herbstAktion/layer.iframe.herbstAktion.html",   
    forceType: 'iframe', width: 587, height: 552
  });
  
  $('#ts_kuschelwochen_spot a').nyroModal({
    url: "http://static.ernstings-family.de/tv-spot/kuschelwochen/layer.kuschelwochenSpot.html",
    forceType: 'iframe', width: 618, height: 627
  });
  
  $('#ts_at-werwirsind a').nyroModal({
    url: "http://static.ernstings-family.de/layer/werwirsind/layer.iframe.werwirsind.html",
    forceType: 'iframe', width: 737, height: 539
  });
  
  $('#ts_nikolaussale a').nyroModal({
    url: "http://static.ernstings-family.de/layer/nikolaussale/layer.iframe.nikolaussale.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/nikolaussale/images/btn_close_weiss.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });  

  $('#ts_nikolaussale_at a').nyroModal({
    url: "http://static.ernstings-family.de/layer/nikolaussale/layer.iframe.nikolaussale.at.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/nikolaussale/images/btn_close_weiss.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });  

  $('#ts_lottillxmas a').nyroModal({
    url: "http://static.ernstings-family.de/layer/lottillxmas/layer.iframe.lottillxmas.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/lottillxmas/images/btn_close_weiss.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });  

  $('#ts_lottillxmas_at a').nyroModal({
    url: "http://static.ernstings-family.de/layer/lottillxmas/layer.iframe.lottillxmas.at.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/lottillxmas/images/btn_close_weiss.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });  

  $('#ts_xmasbargain a').nyroModal({
    url: "http://static.ernstings-family.de/layer/xmasbargain/layer.iframe.xmasbargain.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/xmasbargain/images/btn_close_weiss.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });  

  $('#ts_xmasbargain_at a').nyroModal({
    url: "http://static.ernstings-family.de/layer/xmasbargain/layer.iframe.xmasbargain.at.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/xmasbargain/images/btn_close_weiss.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });  

  $('#ts_merchant-ot-year a').nyroModal({
    url: "http://static.ernstings-family.de/layer/merchant-ot-year/layer.iframe.merchant-ot-year.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#21165d; background:transparent url(http://static.ernstings-family.de/layer/merchant-ot-year/images/btn_close.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });  

  $('#ts_merchant-ot-year_at a').nyroModal({
    url: "http://static.ernstings-family.de/layer/merchant-ot-year/layer.iframe.merchant-ot-year.at.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#21165d; background:transparent url(http://static.ernstings-family.de/layer/merchant-ot-year/images/btn_close.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });  

  $('#ts_wintertschuess a').nyroModal({
    url: "http://static.ernstings-family.de/layer/wintertschuess/layer.iframe.wintertschuess.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/wintertschuess/images/btn_close_weiss.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });  

  $('#ts_wintertschuess_at a').nyroModal({
    url: "http://static.ernstings-family.de/layer/wintertschuess/layer.iframe.wintertschuess.at.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/wintertschuess/images/btn_close_weiss.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });
  
  $('#ts_wintertschuess_notice a').nyroModal({
    url: "http://static.ernstings-family.de/layer/wintertschuess/layer.iframe.wintertschuess_notice.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/wintertschuess/images/btn_close_weiss.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });  

  $('#ts_wintertschuess_notice_at a').nyroModal({
    url: "http://static.ernstings-family.de/layer/wintertschuess/layer.iframe.wintertschuess_notice.at.html",
    forceType: 'iframe', width: 587, height: 552,
    closeButton: '<a href="#" class="modalClose" id="modalClose" '
    	+ 'style="color:#ffffff; background:transparent url(http://static.ernstings-family.de/layer/wintertschuess/images/btn_close_weiss.gif) no-repeat scroll right 2px" '
        + 'title="Fenster schließen">Fenster schließen</a>'
  });

  $('#ts_bumcoop a').nyroModal({
    url: "http://static.ernstings-family.de/layer/bumcoop/layer.iframe.bumcoop.html",
    forceType: 'iframe', width: 587, height: 552
  });
  
  $('#ts_beutefuerdiemeute a').nyroModal({
	url: "http://static.ernstings-family.de/tv-spot/beutefuerdiemeute/layer.tvspot.beutefuerdiemeute.html",
    forceType: 'iframe', width: 618, height: 552
  });
  
  $('#ts_beutefuerdiemeute_at a').nyroModal({
	url: "http://static.ernstings-family.de/tv-spot/beutefuerdiemeute/layer.tvspot.beutefuerdiemeute_at.html",
    forceType: 'iframe', width: 618, height: 552
  });
  
  // handle the exchange of texts in the quality-teaser
  if($('div#ts_quality').length !== 0) {
    var currentTextId = Math.ceil(4 * Math.random());
    var updateTeaser = function() {
      var lastTextId = currentTextId;
      while(lastTextId === currentTextId) {
        currentTextId = Math.ceil(4 * Math.random());
      }
      $('.quality_tip').hide();
      $('#quality_tip_' + currentTextId).show();
    };
    
    updateTeaser();
    $('.link_quality_nextTip').click(updateTeaser);
  }
});
