;(function($) {
  $.efI18N = $.efI18N || {};
  if(!$.efI18N.quickShopping) {
    $.efI18N.quickShopping = {
      quantityLabel : 'Menge',
      sizeLabel : 'Größe',
      intoCart : 'In den Warenkorb legen',
      getSuccessHtml : function(name, size, price, quantity, variation) { 
        variationOut = (variation == 'Grösse' ? 'Gr.' : variation);
        return '<span><strong>Der Artikel wurde dem Warenkorb hinzugefügt:</strong></span><br class="clear" /><span>'+name+', ' + variationOut + ' '+size+', '+price+'<br /> Menge: '+quantity+'</span>'; 
      }
    };
  }
  
  $.extend({
    efQuickShopping : {
      containerId : 'quickshopping_layer',
      autoHideFrameSize : 200,
      autoHideTimeout : 200,
      //NMAG changed URL
      ajaxSubmitUrl : 'OrderItemAdd?storeId=10001&catalogId=10002&langId=-3&successMessage=quickshopping&errorViewName=efMinicart&URL=efMinicart&priceInfo=true&doPrice=N&',
      maxQuantity : 99,
      fieldNames : {
        //NMAG changed from productId to catEntryId and removed
        //productId : 'catEntryId',
        quantity : 'quantity',
        //NMAG changed from size to catEntryId
        size : 'catEntryId'
      }
    }
  });

  $.fn.extend({
    efQuickShopping : function(settings) {
//      alert('settings.categoryId: ' + settings.categoryId);
      $.efQuickShopping.settings = settings;
      $.efQuickShopping.ajaxSubmitUrl = 'OrderItemAdd?storeId=10001&catalogId='+settings.catalogId+'&langId='+settings.langId+'&comment='+settings.categoryId+'&successMessage=quickshopping&errorViewName=efMinicart&URL=efMinicart&priceInfo=true&doPrice=N&';
      if(helpers === null) { 
        _createHelpers(settings); 
      }
      return this.bind('click.efQuickShopping', _show);
    }
  });
  
  //{{{ private properties and methods
  // helper-elements: contains members 'wrap', 'ct' and 'shadow'
  var helpers = null;
  // shorthand notations for configuration aynd internationalization.
  var i18n = $.efI18N.quickShopping;
  var cfg = $.efQuickShopping;
  // mouse-position
  var mX=0, mY=0;
  // auto-hide-check timeout.
  var _ahcTimeout = null;

  //{{{ _createHelpers()
  /**
   * creates the helpers required to display the quick-shopping form.
   */
  function _createHelpers() {
    helpers = {};
    helpers.wrap = $(
        '<div id="' + cfg.containerId + '_wrap">'
      +   '<div id="' + cfg.containerId + '" />'
      +   '<div id="' + cfg.containerId + '_shadow" />'
      + '</div>'
    ).appendTo('body').hide();
    
    helpers.ct = $('#'+cfg.containerId, helpers.wrap);
    helpers.shadow = $('#'+cfg.containerId+'_shadow', helpers.wrap);
    
    helpers.ct.append(
        '<a class="btn_schliessen" >schließen</a>'
      + '<div id="qs_layer_contents">'
      +   '<span class="prd_price"></span><br class="clear" />'
      +   '<span class="prd_name"></span><br class="clear" />'
      +   '<form>'
      //NMAG removed
      //+    '<input id="qs_inp_prd_id" type="hidden" name="' + cfg.fieldNames.productId + '" />'
      +     '<label for="qs_inp_qty">' + i18n.quantityLabel + '</label>'
      +     '<select id="qs_inp_qty" name="' + cfg.fieldNames.quantity + '"></select><br class="clear" />'
      +     '<label for="qs_inp_size">' + i18n.sizeLabel + '</label>'
      +     '<select id="qs_inp_size" name="' + cfg.fieldNames.size + '"></select><br class="clear" />'
      +     '<button type="submit" class="btn btn_prm btn_in_den_warenkorb_legen">'
      +             i18n.intoCart + '</button>'
      +   '</form>'
      + '</div>'
      + '<div id="qs_response"></div>'
    );
    
    // fill in quantity option-values
    var qtyOptHtml = '';
    for(var i=1; i<=cfg.maxQuantity; i++) {
      qtyOptHtml += '<option value="' + i + '">' + i + '</option>';
    }
    
    $('#qs_inp_qty', helpers.ct).html(qtyOptHtml);
    
    //NMAG added listener for price change
    // change size function
    $('#qs_inp_size').change(_updateSizePrice);
    
    
    // submit-function
    $('button', helpers.ct).click(_submitData);
  }
  //}}}
  
  //{{{ _updateHelpers(ev)
  /**
   * updates the contents of the helper-object before the tooltip is shown.
   *
   * @param {EventObject} ev
   * @scope {DomElement}
   */
  function _updateHelpers(ev) {
    var productId = this.id.replace(/prd_qs_/,"");
    //NMAG changed to dynamic element attribute 'json'
    var avData = $.evalJSON($('#prd_qs_' + productId).attr('json'));
    helpers.json = avData;
    //NMAG removed
    //var prdData = efProductData.getDetails(productId);
    var sizeOptHtml = '';
    
    // add size option-values
    //NMAG changed loop
    for(var idx = 0; idx < avData.length; idx++){
      sizeOptHtml += '<option value="'+ avData[idx].id +'">' + avData[idx].n + '</option>';
    }
    //NMAG disabled select if only one valid size
    if(avData.length == 1){
      $('#qs_inp_size', helpers.ct).attr('disabled','true');
    } else {
      $('#qs_inp_size', helpers.ct).removeAttr('disabled');
    }
    // NMAG set header by variation
    helpers.variation_attribute = $('#prd_qs_' + productId).attr('variation');
    $('label[for=qs_inp_size]', helpers.ct).html(helpers.variation_attribute+':');
    
    // NMAG store product and category id for later use in CoreMetrics tag
    helpers.productId = $('#prd_qs_' + productId).attr('product');
    helpers.categoryId = $('#prd_qs_' + productId).attr('category');
    
    $('#qs_inp_size', helpers.ct).html(sizeOptHtml);
    $('#qs_inp_prd_id', helpers.ct).val(productId);
    //NMAG changed value
    $('.prd_price', helpers.ct).text(avData[0].p);
    //NMAG changed value
    $('.prd_name', helpers.ct).text($('#prd_name_' + productId).text());
    $('#qs_response', helpers.ct).hide();
    $('#qs_layer_contents', helpers.ct).show();
    
    // FIXME: adjust positioning: tooltips must not open outside the visible area
    helpers.wrap.css({left: ev.pageX, top: ev.pageY});
    
    // set to hidden so we can read out width and height
    helpers.wrap.css({visibility: 'hidden', display: 'block'});
    var ctWidth = helpers.ct.outerWidth(),
      ctHeight = helpers.ct.outerHeight();
    var screenWidth = $("html").width(),
      screenHeight = $("html").height();
    var tipLeft = ev.pageX,
      tipTop = ev.pageY;
    if(screenWidth < tipLeft + ctWidth + 5) {
      helpers.wrap.css({left: ev.pageX - ctWidth + "px"});
    }
    if(screenHeight < tipTop + ctHeight + 5) {
      helpers.wrap.css({top: ev.pageY - ctHeight + "px"});
    }
    helpers.shadow.css({width:ctWidth,height:ctHeight});
    helpers.wrap.css({display: 'none', visibility: 'visible'});
  }
  //}}}
  
  
  //NMAG added function
  //{{{ _updateSizePrice()
  /**
   * updates the price string in size selction.
   *
   * @scope {DomElement}
   */
  function _updateSizePrice() {
    $('.prd_price', helpers.ct).text(helpers.json[$('#qs_inp_size', helpers.ct).attr('selectedIndex')].p);
  }
  //}}}
  
  //{{{ _submitData()
  function _submitData() {
    //NMAG Send CoreMetrics ShopAction5Tag
    var formattedPrice = $('.prd_price', helpers.ct).html();
    var price = formattedPrice.replace("&nbsp;€", "").replace(",", ".");
    cmSetProduction();
    cmCreateShopAction5Tag(helpers.productId, $('.prd_name', helpers.ct).html(), $('#qs_inp_qty option:selected', helpers.ct).val(), price, helpers.categoryId);
    cmDisplayShop5s();
    //NMAG changed values
    $('#qs_inp_size', helpers.ct).removeAttr('disabled');
    var values = $('form :input', helpers.ct).serialize();
    var responseSuccess = $.efI18N.quickShopping.getSuccessHtml($('.prd_name', helpers.ct).html(), $('#qs_inp_size option:selected', helpers.ct).text(),
            $('.prd_price', helpers.ct).html(), $('#qs_inp_qty option:selected', helpers.ct).val(),helpers.variation_attribute);
    $('#qs_response', helpers.ct).html(responseSuccess);
    // alert(cfg.ajaxSubmitUrl + values);
    $.ajax({
      type: "POST",
      //NMAG changed URL
      url: cfg.ajaxSubmitUrl + values,
      data: values,
      success: function(resp) {
        $('#qs_layer_contents').hide();
        //NMAG set respond to mini shopping cart box
        $('#ts_shopping_cart').html(resp).show();
        respDom = $('#ts_shopping_cart');
        if($('#qs_errorBox', respDom).length == 1) {
          $('#qs_response', helpers.ct).html('<span class="error"><strong>' + $('#qs_errorBox', respDom).html() + "</strong></span>");
        }
        
        $('#qs_response', helpers.ct).show();
        // hide after 2 seconds
        window.setTimeout(_hide, 2000);
      },
      error: function(resp) {
        $('#qs_layer_contents').hide();
        $('#qs_response', helpers.ct).html($.efI18N.quickShopping.errorMessage).show();
        // hide after 2 seconds
        window.setTimeout(_hide, 2000);
      }
    });
    
    /* $.post(cfg.ajaxSubmitUrl, values, function(resp, st) {
      $('#qs_layer_contents').hide();
      $('#qs_response', helpers.ct).html(resp).show();
      // hide after 2 seconds
      //window.setTimeout(_hide, 2000);
    }); */
    
    
    return false;
  }
  //}}}
  
  //{{{ _show(ev)
  /**
   * @scope {DomElement}      the element for which the tooltip should be shown
   * @param {EventObject} ev  the event
   */
  function _show(ev) {
    _updateHelpers.call(this, ev);
    
    // unbind possibly remaining handlers
    $('.btn_schliessen', helpers.ct)
      .unbind('click.efQuickShopping')
      .one('click.efQuickShopping', _hide);
    
    // intialize mouse-position and start auto-hide handlers
    mX=ev.pageX; mY=ev.pageY;
    $('body').bind('mousemove.qsAutoHide', _trackMouse);

    _ahcTimeout = window.setTimeout(function() { _autoHideCheck.call(this); }, cfg.interval);
    
    // show container
    helpers.wrap.show();

    return false;
  }
  //}}}
  
  //{{{ _hide(ev)
  /**
   * @scope DOMElement  the element for which
   * @param EventObject  the event
   */
  function _hide(ev, callback) {
    _ahcTimeout = window.clearTimeout(_ahcTimeout);

    helpers.wrap.fadeOut(200);
    helpers.wrap.unbind('mouseover mouseout');
    $('body').unbind('mousemove.qsAutoHide');
  }
  //}}}
  
  //{{{ _autoHideCheck(s)
  /**
   * performs a check if the layer should be hidden based on mouse position.
   */
  function _autoHideCheck() {
    var wPos = helpers.wrap.position(),
      wWidth = helpers.ct.outerWidth(),
      wHeight = helpers.ct.outerHeight();
      
    var mxMin = wPos.left - cfg.autoHideFrameSize,
      mxMax = wPos.left + wWidth + cfg.autoHideFrameSize,
      myMin = wPos.top - cfg.autoHideFrameSize,
      myMax = wPos.top + wHeight + cfg.autoHideFrameSize;
      
    if(mX < mxMin || mX > mxMax || mY < myMin || mY > myMax) {
      $('body').unbind('mousemove.qsAutoHide');
      _hide();
    } else {
      _ahcTimeout = window.setTimeout(
          function() { _autoHideCheck.call(this); },
          cfg.autoHideTimeout
        );
    }
  }
  //}}}
  
  //{{{ _trackMouse(e)
  function _trackMouse(e) {
    mX=e.pageX;
    mY=e.pageY;
  }
  //}}}
})(jQuery);
