// chart-refresh
var charts;
refreshCharts = function()
{
  $("img.minichart").each(function(){
    var src = $(this).attr('src');
    if(src) {
        var ieissdoof =  src.split('=');
        ieissdoof[ieissdoof.length-1] = parseInt(ieissdoof[ieissdoof.length-1]) + 30;
        $(this).attr('src', ieissdoof.join('='));
    }
  });
  setTimeout(refreshCharts, 60000);
}

refreshIVW = function(e)
{
  var tag = $("#ivwtag");
  var ieissdoof = tag.attr("src").split('d=');
  ieissdoof[0] = ieissdoof[0].replace('/home', '/content');
  ieissdoof[1] = Math.random()*100000;
  tag.attr('src', ieissdoof.join('d='));
  var m = $(this).attr('m');
  if(m)
  {
	  $.ajax({
		   type: "GET",
		   url: "/ajax/statistik.php",
		   data: "m=" + m + "&r=" + (new Date().getTime())
      });
  }
}

// semipush aka poll :D
var pushfields = {};
var pushfieldid = 1;
var pushtodo = {};

initPushables = function()
{
  $(".pushable").each(function()
  {
    var type = $(this).attr('push');
    if(type=="quotecontainer")
    {
      var instid = parseInt($(this).attr('instid')) || 0;
      var marketid = parseInt($(this).attr('marketid')) || 0;
      
      if(!pushfields['quote'])
      {
        pushfields['quote'] = {};
        pushtodo['quote'] = {};
      }
      $(this).find(".pushfield").each(function()
      {
        var field = $(this).attr('push');
        var fieldid = $(this).attr('id');
        if(!fieldid)
        {
          fieldid = 'push' + pushfieldid++;
          $(this).attr('id', fieldid);
        }
        if(!pushfields['quote'][instid+'-'+marketid+'-'+field])
        {
          pushfields['quote'][instid+'-'+marketid+'-'+field] = [];
          if(!pushtodo['quote'][instid+'-'+marketid])
          {
            pushtodo['quote'][instid+'-'+marketid] = [];
          }
        }
        pushtodo['quote'][instid+'-'+marketid].push(field);
        pushfields['quote'][instid+'-'+marketid+'-'+field].push(fieldid);
      });
    } else 
    if(type='indextopflop')
    {
      var indexid = parseInt($(this).attr('indexid'));
      if(!pushfields['indextopflop'])
      {
        pushfields['indextopflop'] = {};
        pushtodo['indextopflop'] = {};
      }
      $(this).find(".pushgroup").each(function()
      {
        var groupid = $(this).attr('push');
        $(this).find(".pushfield").each(function()
        {
          var field = $(this).attr('push');
          var fieldid = $(this).attr('id');
          if(!fieldid)
          {
            fieldid = 'push' + pushfieldid++;
            $(this).attr('id',fieldid);
          }
          if(!pushfields['indextopflop'][indexid+'-'+groupid+'-'+field])
          {
            if(!pushtodo['indextopflop'][indexid+'-'+groupid])
            {
              pushtodo['indextopflop'][indexid+'-'+groupid] = [];
            }
            pushfields['indextopflop'][indexid+'-'+groupid+'-'+field] = [];
            pushtodo['indextopflop'][indexid+'-'+groupid].push(field);
          }
          pushfields['indextopflop'][indexid+'-'+groupid+'-'+field].push(fieldid);
        });
      });
    }
  });
}

refreshQuotes = function()
{
  $.post("/ajax/query.php", {q:JSON.stringify(pushtodo), r:new Date().getTime()},
    function(req) {
      var result = JSON.parse( req );
      for(var i in result) {
        if(i=='quote') {
          for(var instid in result[i]) {
            for(var marketid in result[i][instid]) {
              for(var field in result[i][instid][marketid]) {
                var x = pushfields['quote'][instid +'-'+ marketid +'-'+ field];
                if(!x) {
                  x = pushfields['quote'][instid +'-'+ 0 +'-'+ field]
                }
                if(x) {
                  for(var j=0;j<x.length;j++) {
                    $("#" + x[j]).html(result[i][instid][marketid][field]);
                  }
                }
              }
            }
          }
        } else 
        if (i=='indextopflop') {
          for(var indexid in result[i]) {
            for(var group in result[i][indexid]) {
              for(var field in result[i][indexid][group]) {
                var x = pushfields['indextopflop'][indexid+'-'+group+'-'+field];
                if(x) {
                  for(var j=0;j<x.length;j++) {
                	  $("#" + x[j]).html(result[i][indexid][group][field]);
                  }
                }
              }
            }
          }
        }
      }
      result = x = i = instid = marketid = indexid = group = field = j = null;
      setTimeout(refreshQuotes, 60000);
    }
  );
}

scrollteaserScroll = function( teaserList, direction, dist ){
    var firstItem = $(teaserList).children().first();
    var itemWidth = parseInt(firstItem.css('width').replace(/px/,''))
                  + parseInt(firstItem.css('marginRight').replace(/px/,''))
                  + parseInt(firstItem.css('paddingRight').replace(/px/,''))
                  + parseInt(firstItem.css('paddingLeft').replace(/px/,''))
                  + parseInt(firstItem.css('borderRightWidth').replace(/px/,''))
                  + parseInt(firstItem.css('borderLeftWidth').replace(/px/,''))
                  ;
    if( direction === undefined )
		direction = 1;
	if( dist === undefined )
		dist = itemWidth;

    var itemCount = $(teaserList).children().size();
    var itemsShown = Math.ceil($(teaserList).parents('.scrollingteaser').find('.stage').css('width').replace(/px/,'') / dist);

	var targetX = parseInt($(teaserList).css('marginLeft').replace(/px/,'')) - ( dist * direction );
	targetX = Math.ceil((targetX < -((itemCount-itemsShown) * dist) ? -((itemCount-itemsShown) * dist) : targetX) / itemWidth) * itemWidth;
	targetX = targetX > 0 ? 0 : targetX;

	$(teaserList).animate({marginLeft: targetX },300);
}

$(document).ready(function(){ 
  // Tabs initialisieren
  $(".wotabs ul.tabbar a").bind("click", refreshIVW);

  // Chartupdates
  setTimeout(refreshCharts, 60000);
  
  // Kurs-Aktualisierung
  initPushables();
  refreshQuotes();
  
  $('.scrollingteaser .arr.left').click(function(e){ 
	  _gaq.push(['_trackEvent','Link intern', 'Scrollen links', 'Content, Content-Spalte, Container Video-Nachrichten, Pfeil links']);
	  scrollteaserScroll( $(e.target).parent().find('ul.items'), -1 ); 
  });
  $('.scrollingteaser .arr.right').click(function(e){ 
	  _gaq.push(['_trackEvent','Link intern', 'Scrollen rechts', 'Content, Content-Spalte, Container Video-Nachrichten, Pfeil rechts']);
	  scrollteaserScroll( $(e.target).parent().find('ul.items'), 1 ); 
  });

  showImagesInViewport();
  $(window).scroll(showImagesInViewport).resize(showImagesInViewport);
});

