/**
 * @copyright 2009 PEPPERMIND Digital Business Design, www.peppermind.de
 * @author Ralf Richtsteiger <ralf.richtsteiger@peppermind.de>
 * @version $Id: $
 * @package {package}
 */

jQuery(document).ready(function($) {

  $('#awaitpageload').remove();

  var obj = {};
  // pruefe Aktionshardware

  if (undefined !== window._thumbs) {
    try {
      obj = _thumbs.items[_thumbs.initial];
      if(obj['aktionHardware'] !== undefined) {
        displayAktionForHardware(obj);
      } else {
        $('#retentionTop').css('display','none');
      }
    } catch (e) {
    // TODO: handle exception
    }
  }

  // used selectors
  var thumbs = $('.left.thumbs ul'); // list with the thumbnails
  var thumb = 'li'; // selector of the thumbnail
  var thumbsCount = $(thumb, thumbs).length; // number of thumbnails
  var thumbHeight = $(thumb + ':first', thumbs).height(); // height of one thumbnail

  var controls = $('#modul .controls span'); // control elements for thumbnail list
  var cols = 4; // number of cols of thumbnails in a row
  var vendor = $('a:first', thumbs).attr('rel'); // id of the current vendor

  var visibleThumbs = 12; // current number of visible thumbs
  var visibleRows = visibleThumbs / cols; // visible thumbnails

  var details = '#retentionDetails .container > ul';
  var shop = (1 == $('body.shop, #shop-content').length); // to distinct between shop and retention
  
  var iPhoneIds = null;
  if(undefined !== window._thumbs) {
    if (_thumbs.iPhoneIds)
      iPhoneIds = _thumbs.iPhoneIds;
  }

  if ($().pngfix) {
    var collection = '.left img[alt*="unterschrift"], .medium img, .thickbox.hardware img, .thumbs a img, .onlinebonus img, #modul .details .con dd.pay span, #thumbsShadow, #simcard';
    $(collection).pngfix();
  }

  // iPhone Stoerer Show / Hide
  $.extend( {
    wrapperItem: function(method, a){
      var SAPHandy      =  "302116";
      var SAPCur        =  $(a).find('a.hardware[href$='+SAPHandy+']');
      var iPhoneStorer  =  $("#vvl-iphone-offer", "body");
      
      if (SAPCur.length > 0){
        if (method == 0)   iPhoneStorer.fadeOut();
        if (method == 1)   iPhoneStorer.fadeIn();
      }
    }
  });
  
 
  $('a:not(.thickbox)', thumbs).click(function() {
    var id = this.href.split('#')[1];
    changeRetentionDetails(id);
    return false;
  });

  $('#activation .trigger input').click(function() {
    //var goal = $(this).parents('fieldset:first').next('fieldset');
    if ($('#address-delivery').attr('checked')) {
      // reseten der einzelnen forms
      $('#deliveryForm_address').hide();
      $('#addrErrorInfo').hide();
      $('#deliveryForm_name').hide();
      $('#nameErrorInfo').hide();
    }

    $('#addrErrorInfo').hide();
    $('#nameErrorInfo').hide();

    $('#deliveryForm_address').toggle();
    $('#deliveryForm_name').toggle();

    if($('#deliveryForm_address').hasClass('addressError')) {
      $('#deliveryForm_address').show();
      if (!$('#address-delivery').attr('checked')) {
        $('#addrErrorInfo').show();
      }
    }
    if ($('#deliveryForm_name').hasClass('nameError')) {
      $('#deliveryForm_name').show();
      if (!$('#address-delivery').attr('checked')) {
        $('#nameErrorInfo').show();
      }
    }
  });

  $('#activation').submit(function() {
    _err = false;
    if (0 < $('.dataSheet').length) {
      if (!$(this.iphoneDataSheet).is(':checked') && $('#id_iphoneDataSheet').data('visible')) {
        $('.legal .dataSheet.error', this).slideDown('fast');
        _err = true;
      } else {
        $('.legal .dataSheet.error', this).slideUp('fast');
      }
    }
    if ($('#tariffList').length>0 && !($(this.tariff_soc).is(':checked'))) {
      $('#tariffList .error', this).slideDown('fast');
      _err = true;
    } else {
      $('#tariffList .error', this).slideUp('fast');
    }
    
    if (0 < $('#id_accept').length) { 
	    if (!$(this.accept).is(':checked')) {
	        $('.legal .accept.error', this).slideDown('fast');
	        _err = true;
	    } else {
	        $('.legal .accept.error', this).slideUp('fast');
	    }
    }
    
    if (_err)
      return false;
    else
      return true;
  });

  // init selection filter
  $('#modul .controls select').change(function() {
    initThumbController(thumbsCount, true);
    var v = $(this).val();
    if ('false' == v) {
      /*$(thumb, thumbs).show().css({
        opacity : 0
      }).fadeTo('fast', 1);*/
      $(thumb, thumbs).show();
      initThumbController(thumbsCount);
    } else {
      var showElems = $('a[rel="' + v + '"]', thumbs);
      var hideElems = $('a:not([rel="' + v + '"])', thumbs);
      /*$(hideElems).parent().fadeTo('fast', 0, function() {
        $(this).hide();
        $(showElems).parent().show().css({
          opacity : 0
        }).fadeTo('fast', 1);
      });*/
      //initThumbController(thumbsCount);
      $(hideElems).parent().hide();
      $(showElems).parent().show();
      initThumbController($(showElems).length);
      var elem = $(showElems).get(0);
      if (vendor != elem.rel) {
        changeRetentionDetails(elem.href.split('#')[1]);
        vendor = elem.rel;
      }
    }
  }).change();
  
  if (0 < controls.length) {
    try {
      // showCoopLogo(_thumbs.initial, $(details + ' > li:first'));
    } catch (e) {}
  }

  if (!controls.data('init')) {
    // init thumb controller
    initThumbController(thumbsCount, false);
  }

  /**
   * control the visibility of the cooperation logo - visible only for iphones
   * 
   * @param {Number} id - id of current visible item
   * @param {Object} scope - the object where the cooperation logo should be shown
   * @return {Boolean} current item is an iphone
   */
  function showCoopLogo(id, scope) {
    if (!shop && 0 < $('.cooperationLogo', scope).length) {
      $('.cooperationLogo', scope).hide();
      $('.onlinebonus', scope).show();
      $("dd.bonus_text", scope).show();
      $("dt.bonus_title", scope).show();
      // iPhone
      if (iPhoneIds.join(' ').split(id).length > 1) {
        $('.cooperationLogo', scope).show();
        $('.onlinebonus', scope).hide();
        $("dd.bonus_text", scope).hide();
        $("dt.bonus_title", scope).hide();
        return true;
      }
    }
    return false;
  }

  /**
   * change a list element to display details of an item which was selected by
   * the user
   *
   * @param {Number} id - id of the current selected hardware item
   * @param {String} sel - selector of the list element which must be modified
   */
  function changeItemDetails(id, sel) {
    var obj = $(sel);
    if (_thumbs) {
      var iPhone = iPhoneIds ? (iPhoneIds.join(' ').split(id).length > 1) : false;
      var t = _thumbs.items[id];
      // change image
      var I = new Image();
      $(I).load(function() {
        $('.hardware', obj).html(this);
        if($().pngfix)
          $(this).pngfix();
      }).attr('src', t.path);
      $('h2', obj).html(t.model);
      // change bullets
      var bullets = $('ul li', obj);
      for (var i = 0; i < bullets.length; i++) {
        el = $(bullets).get(i);
        if (t.bullets[i]) {
          $(el).html(t.bullets[i]);
          $(el).show();
        } else {
          $(el).hide();
        }
      }

      // change price info and links - differentiation shop - retention
      if (shop) {
        try {
          // function will be defined by mobilcom
          changeShopItemDetails(sel, id, t);
        } catch(e) {
          if (window.console)
            console.log(e);
        }
      } else {
        var spacer = 'item_id=';
        var link = $('a.thickbox:first', obj).attr('href').split(spacer);
        $('a.thickbox:not(.submit)', obj).attr('href', link[0] + spacer + id);
        if (0 < $('a.submit', obj).length) {
          link = $('a.submit', obj).attr('href').split(spacer);
          $('a.submit', obj).attr('href', link[0] + spacer + id);
        }

        if (0 < $('.con', obj).length) {
          // calculate and change price info
          var p = 0; // hardware price
          var v = 0; // voucher
          var onlineBonus = _thumbs.voucher;
          $('dd.price', obj).html(t.price.toString().split('.').join(',') + ' &euro;');
          if (iPhone) {
            //onlineBonus = 0;
            $('dd.price', obj).prepend('ab ').append('<sup>1)</sup>');
          }
          p = Number(t.price) + _thumbs.delivery - onlineBonus;

          // test values
          /*p = Math.round(Math.random() * 100);
          $('dd.price', obj).html(p + ' &euro;');
          p = p + _thumbs.delivery - _thumbs.voucher;*/
          if (0 > p) {
            v = Math.abs(p);
            p = 0;
          } else {
            p = String(p).split('.');
            if (2 == p.length)
              if(p[1][2] >= 5) {
            	  p = p[0] + ',' + (Number(p[1].slice(0, 2)) + 1);
              }
              else {
            	  p = p[0] + ',' + p[1].slice(0, 2);
              }
            else p = p[0];
          }
          $('dd.pay', obj).html(p + ' &euro;');
          if (0 < v) {
            v = String(v).split('.');
            if (2 == v.length)
	            if(v[1][2] >= 5) {
	          	  v = v[0] + ',' + (Number(v[1].slice(0, 2)) + 1);
	            }
	            else {
	          	  v = v[0] + ',' + v[1].slice(0, 2);
	            }            	
            else v = v[0];
            if (0 == $('dd.vouch', obj).length) {
              $('dd.pay', obj).after('<dt class="vouch">Ihre Gutschrift</dt><dd class="vouch"></dd>');
            }
            $('dd.vouch', obj).html('+' + v + ' &euro;');
            $('.vouch', obj).show();
          } else {
            $('.vouch', obj).hide();
          }
        }
      }
    }
  }

  /**
   * clone the first and only list item if required, change the item details and
   * animate and show the modified list item
   *
   * @param {Number} id - id of the current selected hardware item
   */
  function changeRetentionDetails(id) {
    var d = $(details);
    if (!d.data('cloned')) {
      var detail = $('li:first', d);
      d.parent().css({
        position : 'relative'
      });
      d.css({
        position : 'relative',
        left : '0px',
        width : (detail.width() * 2) + 'px'
      }).append(detail.css({
        float : 'left'
      }).clone(true)).data('cloned', true);
      d.data('dir', true).data('curr', _thumbs.initial).data('goal', '-' + detail.width() + 'px');
    }
    if (id != d.data('curr')) {
      d.data('curr', id);
      var goal = "0px";
      if (d.data('dir')) {
        changeItemDetails(id, details + ' > li:last');
        d.data('dir', false);
        goal = d.data('goal');
      } else {
        changeItemDetails(id, details + ' > li:first');
        d.data('dir', true);
      }
      // Aktionshardware
      if (!shop) {
        var obj = _thumbs.items[id];
        if(obj['aktionHardware'] !== undefined) {
          displayAktionForHardware(obj);
        } else {
          jQuery('#retentionTop').css('display','none');
        }
      }
      d.animate({
        left: goal
      }, 1500);
    }
  }

  /**
   * init thumbnail control
   *
   * @param {Number} nr - number of existent thumbnails
   * @param {Boolean} deactivate - clean up the thumbnail control
   */
  function initThumbController(nr, deactivate) {
    thumbs.css({
      top : '0px',
      position : ($.browser.msie && $.browser.version < 7) ? 'absolute' : 'relative'
    })
    if (deactivate || visibleThumbs >= nr) {
      $('#thumbsShadow').fadeOut('fast');
      controls.each(function() {
        var c = $(this);
        c.css({
          cursor : 'default',
          backgroundPosition: 'left ' + (c.is('.top') ? '-650' : '-680')+ 'px',
          display : 'none'
        }).unbind('click');
      });
    } else {
      $('#thumbsShadow').fadeIn('fast');
      var currentRow = 0; // first visible row
      var rows = Math.ceil(nr / cols); // number of rows of thumbnails
      controls.each(function() {
        var c = $(this);
        c.css({
          cursor : 'pointer',
          backgroundPosition: 'right ' + (c.is('.top') ? '-650' : '-680')+ 'px',
          display: 'block'
        });
        if (c.is('.top')) {
          c.css({
            cursor : 'default',
            backgroundPosition: 'left -650px'
          })
        }
        c.bind('click', function() {
          if (c.is('.top')) {
            if (0 != currentRow) {
              currentRow--;
            } else {
              return false;
            }
          } else if (c.is('.bottom')) {
            if (rows > (currentRow + visibleRows)) {
              currentRow++;
            } else {
              return false;
            }
          }
          thumbs.animate({
            top : '-' + (currentRow * thumbHeight) + 'px'
          }, 500, function() {
            controls.each(function() {
              var _c = $(this);
              _c.css({
                cursor : 'pointer',
                backgroundPosition: 'right ' + (_c.is('.top') ? '-650' : '-680')+ 'px'
              });
            });
            $('#thumbsShadow').fadeIn('fast');
            if (0 == currentRow || rows == (currentRow + visibleRows)) {
              c.css({
                cursor : 'default',
                backgroundPosition: 'left ' + (c.is('.top') ? '-650' : '-680')+ 'px'
              });
              if (rows == (currentRow + visibleRows))
                $('#thumbsShadow').fadeOut('fast');
            }
          });
          return false;
        });
      });
    }
    controls.data('init', true);
  }

  function setIphoneDataSheet(id) {
    if (undefined !== window._IPhoneTariffDataSheets) {
      $('.legal .dataSheet.text').slideDown('fast');
      $('#id_iphoneDataSheet').data('visible', true);
      var link = $('label[for=id_iphoneDataSheet] a');
      var href = window._IPhoneTariffDataSheets[id];
      $(link).attr('href', href);
    }
  }
  // dynamischer tarifwechsel bei aktivierung (preise und tarifdaten tauschen sich aus)

  jQuery('#activation #tariffList.dynamic .tariffTable input[name="tariff_soc"]').bind('click', function(){
      var _orig_tariff_id = jQuery('#activation #tariffList .tariffTable tr.currentTariff').attr('id').split('t_')[1];
      _tariff_id = this.parentNode.parentNode.id.split('t_')[1];
      _tariff_soc = $(this).val().substr(0, 8);
      _tariff = possibleTariffs[_tariff_id];
      _detaillink = jQuery('td.name a', this.parentNode.parentNode).attr('href');

      // tarifdetails
      jQuery('#retentionTariff').fadeOut('fast', function() {
          if (_tariff) {
              if (_tariff_id == _orig_tariff_id)
                  jQuery('#retentionTariff h2').html('Ihr aktueller Tarif');
              else
                  jQuery('#retentionTariff h2').html('Ihr gewählter Tarif');
              jQuery('#retentionTariff h4').html(_tariff.tariff_name);
              if (jQuery('#retentionTariff #linkTariffdetails').length>0) {
                  if (_detaillink)
                      jQuery('#retentionTariff #linkTariffdetails').attr('href', _detaillink).removeClass('hidden');
                  else  // oder ausblenden, wenn kein link da?
//                      jQuery('#retentionTariff #linkTariffdetails').attr('href',
//                          jQuery('#retentionTariff #linkTariffdetails').attr('href').replace(/tariffID=\d+/g, 'tariffID='+_tariff_id));
                        jQuery('#retentionTariff #linkTariffdetails').addClass('hidden');
              }
              var _lis = ' ';
              if (_tariff.bullets.length>0) {
                  for (var i=0;i<_tariff.bullets.length;i++)
                      _lis += '<li>'+ _tariff.bullets[i] +'</li>';
              }
              jQuery('#retentionTariff ul').html(_lis).removeClass('hidden');
              setIphoneDataSheet(_tariff_soc);
              jQuery('#retentionTariff').fadeIn('fast');
          }
      });

      // preise
      jQuery('#retentionPrice').fadeOut('fast', function(){
          jQuery('#retentionPrice dd.price').html(_tariff.hwPrice  + ' &euro;');
          jQuery('#retentionPrice dd.pay').html('<span>&nbsp;</span>' + _tariff.payPrice);
          if (_tariff.payPrice != '0,00 &euro;')
              jQuery('#retentionPrice .vouch').css( {display: 'none'} );
          else {
              rewriteVoucherSpanElements( _tariff.hwPrice);
              jQuery('#retentionPrice dd.vouch').html( _tariff.voucher);
              jQuery('#retentionPrice .vouch').css( {display: 'block'} );
          }
          jQuery('#retentionPrice p.blatant').html( _tariff.blatant);
          if ($().pngfix) {
            $('dd.pay span').pngfix();
          }
          jQuery('#retentionPrice').fadeIn('fast');
      });
    });

});

/**
 * erzeugt die span elemente mit den "geldscheinen" fuer die anzeige
 * der gutschrift.
 */
function rewriteVoucherSpanElements(value) {
    jQuery('#voucher span').remove();        // remove all span elements with voucher values

    var numvalue = value.split(",");         // e.g 180,00
    value = Number(numvalue[0]) + _voucher;  // first element from splitet string and the voucher

    var print = new Array();
    var parts = new Array(100, 50, 20, 10, 5);
    var part;
    var elem;

    for (elem in parts) {
        part = Math.floor(value/parts[elem]);
        if (0 == part) continue;
        for (part; part > 0; part--) {
          print.push(parts[elem]);
        };
        value = value % parts[elem];
    }
    var count = 0;
    for (var i = 0; i < print.length; i++) {
      jQuery('#voucher').append('<span class="voucher row_' + count + ' note_' + print[i] + '">&nbsp;</span>');
      count++;
    }
}

/**
 * Anzeige Aktionshardware
 */
function displayAktionForHardware(obj) {
  var bgBos;
  jQuery('#retentionTop').removeClass();

  var val = obj['aktionHardware']['col'];
  var txt = obj['aktionHardware']['text'];
  var cls = '';
  switch (val) {
    case "FF8000": // ORANGE
      cls = 'retentionAction01';
      bgPos = '0px 0px';
      break;
    case "0000FF": // LIGHTBLUE
      cls = 'retentionAction02';
      bgPos = '0px -50px';
      break;
    case "00FF00": // GREEN
      cls = 'retentionAction03';
      bgPos = '0px -100px';
      break;
    case "000000": // DARKGREEN
      cls = 'retentionAction04';
      bgPos = '0px -150px';
      break;
    default:
      var val = null;
      break;
  }
  if (val != null) {
    jQuery('#retentionTopText').text(txt);
    jQuery('#retentionTop').addClass(cls).css({
       display : 'block',
       backgroundPosition : bgPos
    });
  }
}

