/**
 * Macwelt JS
 *
 * @author Martin ECKHARDT <meckhardt@idgcom.de>
 * @author Steffi BAHR <sbahr@idgcom.de>
 */

// Element das andeutet, dass gerade etwas geschieht.
var indicator = jQuery('<img src="/images/indicator.gif"/>');
/*****************************************************************************
  * Statistiken nachladen.
  *****************************************************************************/
function reloadStatistic (code,id) {
  var id = (!id) ? id = "" : "." + id;
  var get_rand = "d=" + (Math.random()*100000);
  var get_referer = "r=" + escape(document.referrer);
  var countIVW = new Image();
  var lowercode = code.toLowerCase();
  countIVW.src = "http://macwelt.ivwbox.de/cgi-bin/ivw/CP/" + code + "?" + get_referer + "&" + get_rand;
  var countSitestat = new Image();
  countSitestat.src = "http://de.sitestat.com/idgcom-de/macwelt/s?ajax_elemente." + lowercode + id + ".home&" + get_rand;
}

/*****************************************************************************
* rechten Block ausblenden für Galerie-Detailansicht
*****************************************************************************/
if(jQuery('div.sitebox').hasClass('detail_view')) {
  jQuery('div#container_right').hide();
  jQuery('div.sitebox.detail_view').css('width','700px');
}
/**
 * Intelli TXT
 */
function switchIntelliTxt (state) {
  document.location.href="http://macwelt.de.intellitxt.com/intellitxt/switch.asp?ipid=2628&state="+state+"&url="+encodeURIComponent(document.location.href);
}

/*****************************************************************************
  * Erweiterte Suche - keine Zeit aufs DOM zu warten :)
  *****************************************************************************/
jQuery('.search_tip').hide();
jQuery('.extended_search').hide();
jQuery('a.link_info').click(function() {
  var value = jQuery(this).attr('href').match(/#(\w+)/);
  if(value.length > 1) {
    jQuery('li.'+value[1]).toggle();
  }
  return false;
});

/*****************************************************************************
* Tab Komponente.
*****************************************************************************/
jQuery('.tab').click(function() {
  var index = jQuery('.tab').index(jQuery(this));
  // Geklicktes Tab hervorheben
  jQuery(this).removeClass('inactive').addClass('active')
              .siblings().removeClass('active').addClass('inactive');
  // Alle Tab Inhalte verstecken
  jQuery('#header_search_content_box table').hide();
  // Und nur den Inhalt sichtbar machen, das zum Tab gehört.
  jQuery('#header_search_content_box table:eq('+index+')').show();
  reloadStatistic('RC_TABCOMPO');
});

/*****************************************************************************
* Inline Gallerie
*****************************************************************************/
var click_function = function(){
  var a = jQuery(this);
  // Liste aller Bild IDs holen
  var images = jQuery.secureEvalJSON(a.parents('.box').find('#image_list').text())[0];
  var img = a.parents('.box').find('img');

  var first_index = 0;
  var last_index = images.length -1;

  var picnum = a.attr('href').match(/\/picnum\/(\d+)/)[1];
  var gallery_id = a.attr('href').match(/\/galid\/(\d+)/)[1];
  //korrekter Link für das Pop-Up
  var new_href = jQuery('a#popuplink').attr('href').replace(/picnum\/(\d+)/g,'picnum/'+picnum);
  jQuery('a#popuplink').attr('href', new_href);

  var ad = false;
  if (picnum == 4 && a.parents('.box').find('#mpu2').length == 0) {

    if(a.hasClass('prev')) {
      picnum = picnum * 1 + 1;
    }
    else {
      picnum = picnum * 1 - 1;
    }
    img.css({'display' : 'none'});
    a.parents('.box').find('p.image_description').css({'display' : 'none'});

    jQuery('div.ads').each(function() {
      if(jQuery(this).html().match(/;pos=mpu;/) != null) {
        a.parents('.box').find('h2.title + table')
          .after('<div id="mpu2" class="gallery-mpu" style="margin-bottom:10px;">' +
            '<iframe frameborder="0" scrolling="no" style="width:338px;height:282px;overflow:hidden;" src="http://ad.de.doubleclick.net/adi/macwelt4.de/internet/news;abr=!webtv;kw=[keyword];gkw=[googlekeyword];pos=mpu2;tax1=;tax2=;tax3=;tax4=;dcopt=ist;sz=336x280,300x250;tile=8;ord='+Math.floor(Math.random()*1e9)+'?"></iframe>' +
            '</div>');
      }
    });

    ad = true;
  }

  if(a.hasClass('prev')) {
    picnum = picnum * 1 - 1;
  }

  if (ad == false) {
    img.css({'display' : ''});
    a.parents('.box').find('p.image_description').css({'display' : ''});
    a.parents('.box').find('#mpu2').remove();

    // AJAX um die Bildbeschreibung zu ermitteln
    jQuery.ajax({
      type:'GET',
      url:'/gallery/refreshInlineGallery',
      data: "image_id="+images[picnum],
      dataType:'html',
      beforeSend:function() {
        a.parents('.box').find('.image_description').html(indicator).show();
      },
      success:function(html) {
        if(html != a.parents('.box').find('.image_description').html()) {
          a.parents('.box').find('.image_description').html(html);
        }
      },
      error:function (XMLHttpRequest, textStatus, errorThrown) {
      }
    });
  }

  // Hier gehts gefrickel los :)
  if(a.hasClass('next')) {
    // Wenn es noch kein Zurück Button gibt, wird dieser erzeugt und das "click"
    // Event an diesen gebunden.
    if(a.parents('.box').find('a.prev').length == 0) {
      var prev_link = jQuery('<a class="gallery_image prev button_back"> </a>');
      prev_link.bind('click', click_function);
      prev_link.appendTo(a.parents('.box').find('table:not(.header_container) td:eq(0)'));
    }
    // Der "Zurück Link" bekommt das href Attribut vom "Nächstes" Link.
    a.parents('.box').find('a.prev').attr('href', a.attr('href'));
    // Image Source Attribut auf das neue Image setzen.
    var img_src = img.attr('src').replace(/bdb\/\d+/, 'bdb/'+images[picnum]);
    img.attr('src', img_src);
    // Aktuellen Bildindex hochzählen.
    picnum = picnum * 1 + 1;
   a.parents('.box').find('table:not(.header_container) td:eq(1)').text('Bild ' + picnum + ' von ' + images.length);
    var href = a.attr('href').replace(/\/picnum\/\d+/, '/picnum/'+picnum);
    a.attr('href', href);
  } else if (a.hasClass('prev')) {
    a.parents('.box').find('a.next').attr('href', a.attr('href'));
    a.parents('.box').find('table:not(.header_container) td:eq(1)').text('Bild ' + ((picnum*1)+1) + ' von ' + images.length);
    //picnum = picnum * 1 - 1;
    var img_src = img.attr('src').replace(/bdb\/\d+/, 'bdb/'+images[picnum]);
    img.attr('src', img_src);
    var href = a.attr('href').replace(/\/picnum\/(\d+)/, '/picnum/'+picnum);
    a.attr('href', href);
  } else {
    // Do nothing
  }

  // Anzeigen oder Verstecken der Links.
  if(picnum > first_index) {
    a.parents('.box').find('a.prev').show();
  } else {
    a.parents('.box').find('a.prev').hide();
  }
  if(picnum > last_index) {
    a.parents('.box').find('a.next').hide();
  } else {
    a.parents('.box').find('a.next').show();
  }

  // Slug aus dem Titel der Galerie erzeugen
  var slug = gallery_id + '.' +a.parents('.box').find('h2.title').html().toLowerCase().replace(/\s/g, '-');
  
  reloadStatistic('RC_GALKASTEN', slug);
  return false;
}
// "click" Event an Bildergallerie hängen
jQuery('.bildergalerie a.prev, .bildergalerie a.next').click(click_function);


/*****************************************************************************
  * Zeug was geladen werden muss, wenn das Dokument fertig geladen ist.
  *****************************************************************************/
jQuery(document).ready(function() {
  /*****************************************************************************
  * Thema der Woche.
  *****************************************************************************/
  var index = 0;
  jQuery('#topic-images li').hover(
    function() {
      index = jQuery('#topic-images li').index(this);
      jQuery('#topics .topic:not(:eq('+index+'))').hide();
      jQuery('#topics .topic:eq('+index+')').show();
      jQuery(this).css({'background': '#ddd'});
    },
    function(){
      jQuery(this).css({'background': 'transparent'});
    }
  );

  /*****************************************************************************
  * Archiv
  *****************************************************************************/
  var popup = jQuery('<div id="archive_popup"/>');
  jQuery('.Num_Pos').hover(
    function(e){
      var day = jQuery(this).attr('rel');
      // Position des Tages auf der Page.
      var pos = jQuery(this).position();
      // XHR
      jQuery.ajax({
        type:'GET',
        url:'/archive/listArchiveArticles',
        data: "day="+day,
        dataType:'html',
        beforeSend:function() {
          popup.html(indicator);
        },
        success:function(html) {
          popup.html(html).appendTo('body');
          // Popup an der Position des Tages orientieren.
          // Die Höhe des Popups muss dafür zusätzlich ermittelt werden.
          var top = pos.top - 5;
          popup.css({position: 'absolute',
                    left: pos.left+'px',
                    top: top+'px'});
          // Workaround für die Höhe des Popups.
          var height = popup.height();
          top = top - height;
          popup.css({top: top+'px'});
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
          // Fehler wenn XHR fehlschlägt
          popup.html('.. ein Fehler ist aufgetreten.');
        }
      });
    },
    function(){
      // Popup löschen bei mouseout
      popup.remove();
    }
  );

  /*****************************************************************************
  * Wissensquiz
  *****************************************************************************/
  jQuery(".letter").click(function () {
    jQuery(".idgAjaxlist").html('<div class="treffer_archive">Inhalt wird geladen ...</div>')
                          .load('/idgAjaxlist/index/letter/' + jQuery(this).text() + '/maxrow/20/id_page/362/').slideDown();
  });

   /*****************************************************************************
  * Dropdown aus Navi
  *****************************************************************************/
  //Bilder- und CSS Anpassungen für die iPhone-Welt-Version des Dropdowns
  var iwPrefix = "";

  //Ändere CSS und Bilder für iPhoneWelt ab
  jQuery('link').each(function() {
    if(jQuery(this).attr('href').match(/\/css\/iphone.*\.css/g)) {
      iwPrefix = "iw_";
      jQuery('#logobox #partnerseiten').css({
        'margin-top': '0px',
        'margin-left': '0px'});
    }
  });

  //Wenn über der das Logo gehovert wird, soll das Dropdown eingeblendet werden
  jQuery('#logobox').hoverIntent(function() {
    jQuery('#partnerseiten').stop().fadeIn("fast").css('display','inline');
  },function(){
    jQuery('#partnerseiten').css('display','none');
  });

  jQuery('#pcwelt_area').mouseover(function(){
	  jQuery('#partnerseiten').attr('src','/images/'+iwPrefix+'pc_aktiv.png');
  }).mouseout(function(){
	  jQuery('#partnerseiten').attr('src','/images/'+iwPrefix+'logo_dropdown_inaktiv.png')
  });

  jQuery('#digitalworld_area').mouseover(function(){
	  jQuery('#partnerseiten').attr('src','/images/'+iwPrefix+'dw_aktiv.png');
  }).mouseout(function(){
	  jQuery('#partnerseiten').attr('src','/images/'+iwPrefix+'logo_dropdown_inaktiv.png')
  });

  jQuery('#speedmeter_area').mouseover(function(){
	  jQuery('#partnerseiten').attr('src','/images/'+iwPrefix+'sm_aktiv.png');
  }).mouseout(function(){
	  jQuery('#partnerseiten').attr('src','/images/'+iwPrefix+'logo_dropdown_inaktiv.png')
  });

  //kann nur bei iPhoneWelt auftreten
  jQuery('#macwelt_area').mouseover(function(){
	  jQuery('#partnerseiten').attr('src','/images/iw_mw_aktiv.png');
  }).mouseout(function(){
	  jQuery('#partnerseiten').attr('src','/images/iw_logo_dropdown_inaktiv.png')
  });

  //kann nur bei Macwelt auftreten
  jQuery('#iphonewelt_area').mouseover(function(){
	  jQuery('#partnerseiten').attr('src','/images/iw_aktiv.png');
  }).mouseout(function(){
	  jQuery('#partnerseiten').attr('src','/images/logo_dropdown_inaktiv.png')
  });

  /*****************************************************************************
  * Google Box Suchergebnisse nach Referer
  *****************************************************************************/
  // Funktion die ermittelt, ob der Referrer Google ist
  var googleReferrer = function() {
    if (document.referrer && document.referrer.length) {
      var q = document.referrer.match(/http:\/\/.*google.*[\?&](?:as_)?q=([^&]*)/);
      // Wenn von Google
      if (q && q.length > 1) {
        return true;
      }
    }
    return false;
  }

  jQuery.extend({
    isGoogleReferrer: googleReferrer
  });

  var googleBox = jQuery(".googleBox");
  if(jQuery.isGoogleReferrer()) {
    // Aus dem JSON String Objekt machen
    var payload = jQuery.secureEvalJSON(googleBox.text());
    jQuery.ajax({
      type:'GET',
      url:'/search/googleBoxIndex',
      data: "query="+payload.query+ "&maxrows="+payload.maxrows+"&showtitlebar="+payload.showtitlebar+"&title="+payload.title,
      dataType:'html',
      beforeSend:function() {
        googleBox.html(indicator).show();
      },
      success:function(html) {
        googleBox.html(html).show();
      },
      error:function (XMLHttpRequest, textStatus, errorThrown) {
        // Fehler wenn XHR fehlschlägt
        googleBox.html('Die Google Suche konnte nicht durchgeführt werden.');
      }
    });
  }

  /*****************************************************************************
  * Bookmarks
  *****************************************************************************/
  jQuery('a.link_bookmark').click(function() {
    var url = jQuery(this).attr('href');
    var title = jQuery(this).attr('title');
    if (window.sidebar) {
        // firefox
        window.sidebar.addPanel(title, url, "");
    } else if(document.all) {
        // IE
        window.external.AddFavorite(url, title);
    }
    return false;
  });

  /*****************************************************************************
  * Komponente Tab Teaser
  *****************************************************************************/
  jQuery.fn.extend({
    getHash: function() {
      var hash = this.attr('href').match(/#(\d+)/);
      return (hash.length > 1) ? hash[1] : null;
    }
  });

  jQuery('a.tab_teaser').click(function() {
    var component_id = jQuery(this).getHash();
    var type = jQuery(this).attr('title');
    // Entfernen der active Klasse
    jQuery(this).parents('div.content_container_top')
                .find('li.active')
                .removeClass('active');
    // Hinzufügen der active Klasse zum Parent Node des geklickten Element
    jQuery(this).parent()
                .addClass('active');
    var container = jQuery(this).parents('div.content_container_top')
                                .find('div.content_container');
    // AJAX um die Komponente zu ermitteln
    jQuery.ajax({
      type:'GET',
      url:'/page/tabTeaserDetail',
      data: "type="+type+"&component_id="+component_id,
      dataType:'html',
      beforeSend:function() {
        //jQuery('.image_description').html(indicator).show();
      },
      success:function(html) {
        container.replaceWith(html);
      },
      error:function (XMLHttpRequest, textStatus, errorThrown) {
      }
    });
    return false;
  });

  /*****************************************************************************
  * Bei Registrierung
  *****************************************************************************/
  var fnc = function() {
    if(jQuery(this).attr('checked') == true) {
      jQuery('#extended_forum_alias, #extended_gtc').parents('tr').show();
    } else {
      jQuery('#extended_forum_alias, #extended_gtc').parents('tr').hide();
    }
  }
  
  jQuery('form#register #extended_add_forum').each(fnc);
  jQuery('form#register #extended_add_forum').click(fnc);

});

/*****************************************************************************
  * Für iPad Abo-Shop Elemente ausblenden.
  *****************************************************************************/
var userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf("ipad") !== -1 ) { 
  jQuery('#mwaboformularbox').parent().hide();
  jQuery('#navi li:eq(1)').hide();
  jQuery('#navi li:eq(2)').hide();
  jQuery('div[class^=content_container]').each(function(){
      if(jQuery(this).find('a.tab_teaser').filter(":first").html() == 'Die neue Macwelt') {
	  jQuery(this).hide();
      }
  })
}

/*****************************************************************************
* TextAds
*****************************************************************************/
// Detailansicht in Liste
jQuery('#textad-list tr.more').hide();

// Bei Klick auf Details togglen
jQuery('#textad-list a.more').click(function() {
  var trElem = jQuery(this).parents('tr').next('tr');
  if(trElem.is(':hidden')) {
    trElem.fadeIn('slow');
  } else {
    trElem.fadeOut('fast');
  }
});


var max_chars = {};

var counter = function() {
  var length = jQuery(this).val().length;

  var updateElem = jQuery(this).parent().find('.left-letters');
  var countElem = jQuery(this).parent().find('strong:first');

  if(!max_chars[jQuery(this).attr('id')]) {
    max_chars[jQuery(this).attr('id')] = countElem.html();
  }

  var newval =  parseInt(max_chars[jQuery(this).attr('id')]) - length;

  if(newval < 1) {
    newval = 'Kein';
  }

  updateElem.html(newval);
}

// Zeichen in einem Input Feld / Textarea Feld zählen
jQuery('.count-letters').each(counter);
jQuery('.count-letters').keyup(counter);

function wfd_textad_publish_on_read_linked()
  {
    jQuery("#textad_publish_on_jquery_control").val(jQuery("#textad_publish_on_year").val() + "-" + jQuery("#textad_publish_on_month").val() + "-" + jQuery("#textad_publish_on_day").val());

    return {};
  }

  function wfd_textad_publish_on_update_linked(date)
  {
    jQuery("#textad_publish_on_year").val(date.substring(0, 4));
    jQuery("#textad_publish_on_month").val(date.substring(5, 7));
    jQuery("#textad_publish_on_day").val(date.substring(8));
  }

  function wfd_textad_publish_on_check_linked_days()
  {
    var daysInMonth = 32 - new Date(jQuery("#textad_publish_on_year").val(), jQuery("#textad_publish_on_month").val() - 1, 32).getDate();
    jQuery("#textad_publish_on_day option").attr("disabled", "");
    jQuery("#textad_publish_on_day option:gt(" + (daysInMonth) +")").attr("disabled", "disabled");

    if (jQuery("#textad_publish_on_day").val() > daysInMonth)
    {
      jQuery("#textad_publish_on_day").val(daysInMonth);
    }
  }

(function(jQuery) {
	jQuery.datepicker.regional['de'] = {
		clearText: 'löschen', clearStatus: 'aktuelles Datum löschen',
		closeText: 'schließen', closeStatus: 'ohne Änderungen schließen',
		prevText: 'Früher', prevStatus: 'letzten Monat zeigen',
		prevBigText: '&#x3c;&#x3c;', prevBigStatus: '',
		nextText: 'Vor', nextStatus: 'nächsten Monat zeigen',
		nextBigText: '&#x3e;&#x3e;', nextBigStatus: '',
		currentText: 'heute', currentStatus: '',
		monthNames: ['Januar','Februar','März','April','Mai','Juni', 'Juli','August','September','Oktober','November','Dezember'],
		monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
		monthStatus: 'anderen Monat anzeigen', yearStatus: 'anderes Jahr anzeigen',
		weekHeader: 'Wo', weekStatus: 'Woche des Monats',
		dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
		dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		dayStatus: 'Setze DD als ersten Wochentag', dateStatus: 'Wähle D, M d',
		dateFormat: 'dd.mm.yy', firstDay: 1,
		initStatus: 'Wähle ein Datum', isRTL: false,
		showMonthAfterYear: false, yearSuffix: ''};
	jQuery.datepicker.setDefaults(jQuery.datepicker.regional['de']);
})(jQuery);

  jQuery(document).ready(function() {
    var day = new Date();
    day.setDate(day.getDate()+1);
    jQuery("#textad_publish_on_jquery_control").datepicker(jQuery.extend({}, {
      minDate:    day,
      maxDate:    new Date(2014, 12 - 1, 31),
      beforeShow: wfd_textad_publish_on_read_linked,
      onSelect:   wfd_textad_publish_on_update_linked,
      showOn:     "button",
      buttonImage: "/images/calendar.png",
      buttonImageOnly: true,
      buttonText: 'Erscheint am ...',
      hideIfNoPrevNext: true,
      nextText:   'Später',
      prevText:   'Früher'
    }, jQuery.datepicker.regional["de"], {}, {dateFormat: "yy-mm-dd"}));
  });

  jQuery("#textad_publish_on_day, #textad_publish_on_month, #textad_publish_on_year").change(wfd_textad_publish_on_check_linked_days);

