$(window).load(function(){
  if (top.location != self.location) 
  {
    // Seite in einem Frame geladen
    
    //Ränder entfernen
    $('#left').css({ 'display' : 'none' });
    $('#right').css({ 'display' : 'none' });
    $('#page').css({ 'width' : '725px' });
    
    //Frame-Höhe automatisch anpassen
    
    var theFrame = $('#game', parent.document.body);
    theFrame.attr( 'height', $('#page').height() );
    theFrame.css({ 'height' : $('#page').height() });
    //alert( $('#page').height() );
    $('#loggedinmain-menu').css({ 'margin' : '155px 0 0 100px', 'left':'0' });
  }
  if($('#roundsNav-menu').attr('ID')!==null){
    gameoverView('football');
    }else if($('#gpdataNav-menu').attr('ID')!==null){
      gameoverView('gp');
    }else if($('#Tabs-menu').attr('ID')!==null){
      gameoverView('bl');
    }
  if( $('#left').css('display') == 'none' && $('#right').css('display') == 'none' )
  {
  
  }
  else
  {
    setPageHeight(); 
  }
  
  init();
  

  // select inputFixtureTipp on click
  var onInputFixtureTipp = function( ) { $(this).select(); };
  $('.inputFixtureTipp').bind('click', onInputFixtureTipp);

  //Fehlermeldungen:
  if($('#action-errors').attr('ID')!==null){
    //alert('fehler');
    showError();
  }

  $('.tippBtn').bind('click', tippWindow);
  
  if($('#reqLayer').attr('ID')!==null){
    $('#reqLayer').click(function(){openReqLayer(pageURL);return false;});
  }
});

function init(){
  var pageURL = window.location.href;
  var home = pageURL.indexOf('home');
  var mysection = pageURL.indexOf('mysection');
  var total = pageURL.indexOf('/total/');
  var magnus = pageURL.indexOf('/magnus/');
  var sparkassen = pageURL.indexOf('/spk2011/');
  /* LÄNDER */
  var de = pageURL.indexOf('/de/');
  var at = pageURL.indexOf('/at/');
  var cz = pageURL.indexOf('/cz/');
  var dk = pageURL.indexOf('/dk/');
  var gr = pageURL.indexOf('/gr/');
  var hu = pageURL.indexOf('/hu/');
  var ie = pageURL.indexOf('/ie/');
  var it = pageURL.indexOf('/it/');
  var nl = pageURL.indexOf('/nl/');
  var pl = pageURL.indexOf('/pl/');
  var sk = pageURL.indexOf('/sk/');
  var beFR = pageURL.indexOf('/beFR/');
  var beNL = pageURL.indexOf('/beNL/');
  var chFR = pageURL.indexOf('/chFR/');
  var chDE = pageURL.indexOf('/chDE/');
  
  if(magnus==-1)
  {
    $('.fixtures table tbody tr').each(function(e){$(this).mouseover( function(){iefixHoverRow(e);} )});
    $('.tipps table tbody tr').each(function(e){$(this).mouseover( function(){ietipHoverRow(e);} )});
    $('.standings table tbody tr').each(function(e){$(this).mouseover( function(){iestandHoverRow(e);} )});
  }
  
  
  if(home!==-1 && mysection!==-1){
    if(total==-1 && magnus ==-1 && sparkassen ==-1){ //hier werden die seiten aufgelistet, die NICHT mit setHome(); neu positioniert werden sollen
      setHome();
    }
  }
}

function setPageHeight(){
    var padHeight = $('#page').height()
    var padOffset = $('#page').offset(); 
   
    var ph = padHeight+padOffset.top+20;
    //alert(ph);
    $('#left').css({'height':ph });
    $('#right').css({'height':ph});
    $('#middle').css({'height':ph});     
}

/*
*
*   Ltur Tipp (Fake)Button
*
*/

var tippWindow = function tippBtn() {
  $('body').append('<div id="layer"><div id="errorBox"><span id="close">X</span>Ihre Tipps wurden gespeichert!</div></div>');
  $(window).resize(function(){
    var w=document.documentElement.clientWidth;
    $('#layer').css({'width':w+'px'});
  });
  $('#errorBox span').click(function(){$('#layer').remove();});
  $('#layer').click(function(){$('#layer').remove();});
};

/*
*
*   //Ltur Tipp (Fake)Button
*
*/



// Layer für Teilnahmebedingungen

function openReqLayer(purl){
  reqUrl = purl.substr(0,purl.lastIndexOf('/'))+'/requirements';
  //alert(reqUrl);
  $.ajax({
  url: reqUrl,
  cache: false,
  success: function(html){
    var pos1 = html.substring(html.indexOf('<h3>Teilnahmebedingungen</h3>'),html.length);
    var pos2 = pos1.indexOf('</div>');
    var content = pos1.substring(0,pos2);
    $('body').append('<div id="layer"><div id="errorBox"><span id="close">X</span>'+content+'</div></div>');
    $('#errorBox span').click(function(){$('#layer').remove();});
    $('body').click(function(){$('#layer').remove();});
    window.scrollTo(0,0);
    $(window).scroll(
      function(){
        var top = $(window).scrollTop();
        var height = $(window).height();
        $('#layer').css({'height':height+top+'px'});
      }
    );
    }
  });
}

var formHOLDER;
var formVAL;

function showError(){
  var errorMsg = $('#action-errors').html();
  $('body').append('<div id="layer"><div id="errorBox"><span id="close">X</span><ul class="action-errors">'+errorMsg+'</ul></div></div>');
  $('#errorBox span').click(function(){$('#layer').remove();});
  $('body').click(function(){$('#layer').remove();});
  $(window).scroll(
      function(){
        var top = $(window).scrollTop();
        var height = $(window).height();
        $('#layer').css({'height':height+top+'px'});
      }
    );
}


function setHome(){
    // Container existiert nicht bei allen Kunden ( z.B. Ltur, Lidl ) - Ohne die Abfrage gibt es einen JS-Fehler da der Wert Null ist
    if( $('#advert').offset() != null && $('#overviewWinnings').offset() != null ) {

      var p1 = $('#overviewWinnings').offset();
      var p2 = $('#advert').offset();
      var preisBottom = p1.top+$('#overviewWinnings fieldset').height();
      var werbungButtom = p2.top+$('#advert fieldset').height();
      var overSize = preisBottom-werbungButtom;
      var ADD = 15;
     if(preisBottom>werbungButtom){
        $('#advert').animate({'marginTop':overSize+ADD+'px'},100);
      } else if(preisBottom<werbungButtom) {
        $('#overviewWinnings').animate({'marginTop':overSize*-1 +ADD+'px'},100);
      }
      $('#overviewWinnings').show();

    }

}

function gameoverView(key){
    //aktives Element
    switch(key){
      case 'football': var firstactive = $('#roundsNav-menu').children(':first');
      break;
      case 'gp': var firstactive = $('#gpdataNav-menu').children(':first');
      break;
      case 'bl': var firstactive = $('#Tabs-menu').children(':first');
      break;
    }

    if(firstactive[0]!==undefined){
    if(key=='football'){
      var tables = new Array($('.fixtures'),$('.tipps'));
      var elements  = $('#roundsNav-menu').children('li');
      }else if(key=='gp'){
        var tables = new Array($('.curResDrivers'),$('.curResTeams'),$('.curWinningUsers'));
        var elements  = $('#gpdataNav-menu').children('li');
        }else if(key=='bl'){
          var tables = new Array($('.fixtures'),$('.tipps'),$('.standings'));
          var elements  = $('#Tabs-menu').children('li');
          }

    for(var i=0; i<tables.length; i++ ){
      tables[i].each(function(){
       $(this).css({'display':'none'});
      });
    }

    switchGroup(elements,firstactive.attr('ID'),key);
    elements.each(function(){
        var elmID = $(this).attr('ID');
        $('#'+elmID).click(function(){ switchGroup(elements,elmID,key); });
      });
    }
  
}


function iefixHoverRow(e){
  var fixRows = $('.fixtures table tbody tr');
  var tipRows = $('.tipps table tbody tr');
  
  //fixture hover
  fixRows.each(
    function(e){ $(fixRows[e]).hover(
      function(){
        if($(fixRows[e]).attr('class')!=='nohover'){
        $(fixRows[e]).css({'backgroundColor':'#999','color':'#fff'});
        $(tipRows[e]).css({'backgroundColor':'#999','color':'#fff'});
        }},
      function(){
        $(fixRows[e]).css({'backgroundColor':'','color':'#000'});
        $(tipRows[e]).css({'backgroundColor':'','color':'#000'});
      }
    );
    }
    );
}


function ietipHoverRow(e){
  //tipps hover
  var fixRows = $('.fixtures table tbody tr');
  var tipRows = $('.tipps table tbody tr');
  tipRows.each(
    function(e){ $(tipRows[e]).hover(
      function(){
        $(fixRows[e]).css({'backgroundColor':'#999','color':'#fff'});
        $(tipRows[e]).css({'backgroundColor':'#999','color':'#fff'});
        },
      function(){
        $(fixRows[e]).css({'backgroundColor':'','color':'#000'});
        $(tipRows[e]).css({'backgroundColor':'','color':'#000'});
      }

    );
    }
    );
}

function iestandHoverRow(e){
  //standings hover
  var standRows = $('.standings table tbody tr');
  standRows.each(
    function(e){ $(standRows[e]).hover(
      function(){
        $(standRows[e]).css({'backgroundColor':'#999','color':'#fff'});
        },
      function(){
        $(standRows[e]).css({'backgroundColor':'','color':'#000'});
      }

    );
    }
    );
}

function switchGroup(elements,elmID,key){
  elements.each(function(){$(this).removeClass('active');});
  // Fussball
  if(key=='football'){
    if(formHOLDER==undefined){
      formHOLDER = $('#fChampionsQuest').html();
      $('#fChampionsQuest').remove();
    }

    var elmFIX = 'fixtures'+elmID.substring(elmID.indexOf('_'),elmID.length);
    var elmTIP = 'tipps'+elmID.substring(elmID.indexOf('_'),elmID.length);
    var elmSTAND = 'standings'+elmID.substring(elmID.indexOf('_'),elmID.length);

    var contentAll = $('#prelimrounds').children('fieldset');
  }else if(key=='gp'){
    //GP
    var elmSTAND = 'standing'+elmID.substring(elmID.indexOf('_'),elmID.length);
    var contentAll = $('#gpdata').children('fieldset');
  }


  contentAll.each(function(){$(this).css({'display':'none'}); });
  $('#'+elmFIX).css({'display':'block'});
  $('#'+elmTIP).css({'display':'block'});


  $('.placeholderChampionsQuest').children().remove();
  $('#'+elmTIP).children('.placeholderChampionsQuest').append(formHOLDER);
  $('#fBonusQuest0').change( function(){
    formVAL =$('#fBonusQuest0 :selected').text();
  } );

  if(formVAL!==undefined){
   //alert(formVAL);
   $('#fBonusQuest0 :selected').text(formVAL);
  }



  $('#'+elmSTAND).css({'display':'block'});
  $('#'+elmID).addClass('active');

}

function saveTipp(form,elKey,inputKey,gameID) {
	var doAjax = false;
	var tippForm = $('#'+form);
	//alert(tippForm.serialize());		// string 'tippH=2&tippG=3'
	var aTipp = tippForm.serializeArray();
//	alert(aTipp[0]['name']+':'+aTipp[0]['value']);
//	alert(aTipp[1]['name']+':'+aTipp[1]['value']);

	var tippH = new Number(aTipp[0]['value']);
	var tippG = new Number(aTipp[1]['value']);
//	alert(tippH+' : '+tippG);
	if (isNaN(tippH)) {
//		alert(inputKey);
		$('#'+inputKey).val('');
		$('#'+inputKey).focus();
		if (elKey == 'H') {
			return false;
		}
	}
	if (isNaN(tippG)) {
		$('#'+inputKey).val('');
		$('#'+inputKey).focus();
		if (elKey == 'G') {
			return false;
		}
	}
	if ((tippH!='') && (tippG!=''))   {
		if ((aTipp[0]['value']>=0) && (aTipp[1]['value']>=0)) {
			//alert('A '+aTipp[0]['value']+' : '+aTipp[1]['value']);
			doAjax = true;
		} else {
			//alert('nicht > 0');
		}
	} else {
		if ((aTipp[0]['value']>=0) && (aTipp[1]['value']>=0)) {
			if (aTipp[0]['value']=='') {
				//alert('B1 '+aTipp[0]['value']+' : '+aTipp[1]['value']);
				return true;
			}
			if (aTipp[1]['value']=='') {
				//alert('B2 '+aTipp[0]['value']+' : '+aTipp[1]['value']);
				return true;
			}
			//alert('B3 '+aTipp[0]['value']+' : '+aTipp[1]['value']);
			doAjax = true; // to set e.g. 0:0 or 0:2 or 2:0
			//alert(tippH+' : '+tippG);
		} else {
			//alert('ist nicht != ""');
		}
	}

	if (doAjax == true) {
		var relUrl =  tippForm.attr('action');
		//alert('ajax request to save: '+gameID+' vars:'+tippForm.serialize());
		$.ajax({
			   type: "POST",
			   url: relUrl,
			   data: 'gameID='+gameID+'&'+tippForm.serialize(),
			   success: function(msg){
				$('#game_'+gameID).html(msg);	// display result in container
			     /*alert( "Data Saved: " + msg );*/
				/*alert($('#'+inputKey).next('input').attr('id'));*/
				$('#'+inputKey).next('input').focus().select();
			   }
		});
	}

	return true;
}

function saveAnswer(questionID) {
	var doAjax = true;
	var qForm = $('#fBonusQuest'+questionID);
	//alert(qForm.serialize());		// string 'tippH=2&tippG=3'

	if (doAjax == true) {
		var relUrl =  qForm.attr('action');
		//alert('ajax request to save: '+questionID+' url:'+relUrl+' vars:'+qForm.serialize());
		$.ajax({
			   type: "POST",
			   dataType: "html",
			   url: relUrl,
			   data: 'questionID='+questionID+'&'+qForm.serialize(),
			   success: function(msg){
				$('#ajaxBonusQuest'+questionID).html(msg);	// display result in container
			     /*alert( "Data Saved: " + msg );*/
				/*$('#'+inputKey).next('input').focus().select();*/
			   }
		});
	}

	return ;
}

function updateUserStats(relUrl) {
	$.ajax({
		   type: "POST",
		   dataType: "html",
		   url: relUrl,
		   data: 'dummy=0',
		   success: function(msg){
			$('#userstatsajax').html(msg);	// display result in container
		   }
	});
}

function checkNewResults(relUrl) {
	$.ajax({
		   type: "POST",
		   dataType: "html",
//		   async: false,
		   url: relUrl,
		   data: 'type=checkNewResults',
		   success: function(msg){
			$('#newresultsajax').html(msg);	// display result in container
		   }
	});
}
