window.tr=function(){ if(window.console)if(console.log) console.log.apply(console, arguments); };
//window.tr = function(){ if((typeof console)!='undefined'){ console.log.apply(console,arguments); }else{ return; alert(Array.prototype.join.call(arguments,' ')); }};
//window.tr = function(){ alert('NOTRACE'); };

window.timer = function(name){ timer.a.push({ t:(new Date()).getTime(), name:name }); };
window.timer.a = [];
window.timer.results = function(){ var s=''; var a=timer.a;
  for(var i=1;i<a.length;i++)  s+=a[i].name+': '+((a[i].t-a[i-1].t)/1000)+'\n';
  s+='TOTAL: '+((a[a.length-1].t-a[0].t)/1000)+'\n';
  alert(s);
};
window.timer();


(function($){
  $.fn.shuffle = function() {
    var allElems = this.get();
    var shuffled = $.map( allElems, function(){
      var random = Math.floor(Math.random() * allElems.length);
      var randEl = $(allElems[random]).clone(true)[0];
      allElems.splice(random, 1);
      return randEl;
    });
 
    this.each(function(i){
      $(this).replaceWith($(shuffled[i]));
    });
    return $(shuffled);
  };
})(jQuery);


var onResize = function(){
  var SITE_MIN_WIDTH = 1000;
  var w = $(window).width();
  w = w*0.80;
  w = Math.max(w, SITE_MIN_WIDTH);
  w = Math.min(w, 1280);
  $('#wrapper').width(w);
}

window.MSIE_lte_7 = false;
window.MSIE6 = false;
window.initWrapperIE6 = function(){ // called by a script immediately after #wrapper
  window.MSIE_lte_7 = $('body.MSIE-lte-7').length > 0;
  window.MSIE6 = $('body.MSIE6').length > 0;
  if(MSIE_lte_7){
    $(window).resize(onResize);
    onResize();
  }
}

function initOldIE(){
  if(MSIE_lte_7){
    var $mt = $('#meltosagmezeje-terkep');
    $mt.find('.varos').hover(function(){ var $t=$(this);
        $t.find('.on').show();
      },function(){ var $t=$(this);
        $t.find('.on').hide();
      }
    );
    $('a.tovabb').append('<span class="tovabb_after_ie">»</span>');
    //$('.content-kiemelt').after('<br>');
    //$('.title-blocky').after('<br>');
  }
}

// TESTIMONIES //
function initTestimonies(){
  $('.testimonies').each(function(){ initTestimony($(this)); });
}
function initTestimony( $t ){
  var fadeTime  = 0.5*1000;
  var staticTime = $t.attr('data-static-time')*1000;

// var staticTime = 1*1000;
// var fadeTime  = 0.5*1000;

  var $a = $t.find('li.testimony-item').shuffle();
  if( $a.length < 2 ) return;
  $t.find(' > .before-js').removeClass('before-js');

  var forcePause = false;
  window.testimony_video_off = function(){ forcePause=false;  };
  window.testimony_video_on  = function(){ forcePause=true;   };
  var limit=function(a,l,h){ return Math.min(Math.max(a,l),h); }
  var fade01=function(p){ p=limit(p,0,1); return Math.sin(Math.PI*(p-0.5))/2+0.5 };
  var mix=function(p,a,b){ return a*(1-p)+p*b; }
  var scl=function(p,a,b,e,f){ return (p-a)/(b-a)*(f-e)+e; }
  var between=function(a,l,h){ return (l<=a)&&(a<=h); }

  function noFilters( $t ){
    $t.each(function(i,e){ if(e.style.filter) e.style.filter=''; });
  }

  function setOpacity( $t, p ){
    if      ( p >= 1 ){ $t.css({  'display':'block',  'visibility':'visible', 'opacity':1  }); noFilters($t);
  //}else if( p <= 0 ){ $t.css({  'display':'block',  'visibility':'hidden',  'opacity':1  }); noFilters($t);
    }else if( p <= 0 ){ $t.css({  'display':'none',   'visibility':'visible', 'opacity':1  }); noFilters($t);
    }else{              $t.css({  'display':'block',  'visibility':'visible', 'opacity':p  });
    }
  }

  function initItems(ri){
    $a = $t.find('li.testimony-item'); // new order
    setOpacity( $a,       0 );
    setOpacity( $a.eq(0), 1 );
    $a       .css('position','absolute');
    $a.eq(ri).css('position','relative');
  }

  initItems(0);
  var $parent = $a.eq(0).parent();

  var stepTime = jQuery.fx.interval;
  var pd = stepTime / fadeTime;
  var animating = false;
  var isFlash0,isFlash1,hasFlash;
  var p = 0;

  function setPhase(p){
  }
  function animate(){
    if( !animating ){
      if( forcePause ){
        setTimeout( animate, 500 );
        return;
      }
      // begin fade
      animating = true;

      if( $a.eq(0).height() < $a.eq(1).height() ){ // taller slide -> posrel
        initItems(1);
        $parent.prepend( $a.eq(1) );
      }

      isFlash0 = $a.eq(0).is('.testimony-item-flash') 
      isFlash1 = $a.eq(1).is('.testimony-item-flash');
      hasFlash = isFlash0 || isFlash1;
      p = 0;
      //if(hasFlash) p=1; // skip animation if flash
    }

    p += pd;
    if(hasFlash){
      if(isFlash0){
        setOpacity( $a.eq(0), p<=0 ? 1:0  ); // current -> 0
        setOpacity( $a.eq(1), fade01(  p) ); // new -> 1
      }else{
        setOpacity( $a.eq(0), fade01(1-p) ); // current -> 0
        setOpacity( $a.eq(1), p<1 ? 0:1   ); // new -> 1
      }
    }else{ // normal fade
      setOpacity( $a.eq(0), fade01(1-p) ); // current -> 0
      setOpacity( $a.eq(1), fade01(  p) ); // new -> 1
    }

    if( p < 1 ){
      setTimeout( animate, stepTime );
    }else{ // p >= 1, end of fade
      animating = false;
      $parent.append( $a.eq(0) );
      initItems(0);
      forcePause = false;
      setTimeout( animate, staticTime );
    }
  }

  setTimeout( animate, staticTime);
}// init testimonies








function doMenuClick(event){
  $t = $(this);
  $myli = $t.parent();
  $nli  = $t.parent().siblings();//':not(.simalink)'
  var slideTime=300;
  $myli.find('> ul').slideToggle(slideTime);
  $nli .find('> ul').slideUp    (slideTime);
  event.preventDefault();
}

function initLeftMenu(){
  var group=[]; // permanent var
  group.sel=null;
  $('#menu-left ul.depth-1').css('display','block');
  //var menus = $('ul#menu-left > li:not(.current-menu-ancestor,.current-menu-parent,.current-menu-item)');
  var $menus = $('ul#menu-left li:has(> ul)'); // with submenus
  var $menuslide = $menus.filter(':not(.simalink)');
      $menuslide.find('> a').click(doMenuClick);
  var $menuclose = $menus.filter(':not(.current-menu-ancestor, .current-menu-parent, .current-menu-item)'); // , .current-menu-item
      $menuclose.find('> ul').hide();
}


// lenyitható szöveges tartalmak
function initCollapsibleContent(){
  var $c = function( $o ){
    var $content = $o.nextUntil('.opened-content + *');
    $content = $content.filter(':not(.opener,.opener-hidden)');
    //var $content = $o.nextUntil('.opened-content');
    //$content = $content.add( $content.last().next() );
    //$content.css('background','yellow');
    return $content;
  }

  var cn = 'opener-content-collapsed';
  $('#content .opener, #content .opener-hidden')
  .each(function(){
    var $t = $(this);
    $t.addClass(cn);
    if(MSIE_lte_7) $t.append('<span class="opener-content-collapsed-after-ie"></span>');
    $c($t).slideUp(0);
  })
  .css('cursor','pointer')
  .click(function(){
    var $t = $(this);
    if( $t.hasClass(cn))  $c($t).slideDown();  else  $c($t).slideUp();
    $t.toggleClass(cn);
    if($t.is('.opener-hidden'))  $(this).slideUp();
  });
}





function initMeltosagmezejeTerkep(){
  var $terkep = $('#meltosagmezeje-terkep');
  if($terkep.length<=0)return;
  var $l=$('#meltosagmezeje-terkep-varosnev');
  var $v=$terkep.find('.varos');
  $v.each(function(){ var $t=$(this);
    $t.data('varos', $t.text());
    $t.text('').html('<div class="off">&nbsp;</div><div class="on">&nbsp;</div>');
  }).hover(function(e){ var $t=$(this);
    $l.show().text( $(this).data('varos') );
  },function(e){ var $t=$(this);
    $l.hide();
  });
}



function initHighSlide(){
  hs.addSlideshow({
    repeat: true
  });

  //hs.debug=true;
  hs.graphicsDir = '/scripts/highslide/graphics/';
  hs.align = 'center';
  hs.transitions = ['expand', 'crossfade'];
  hs.fadeInOut = true;
  hs.showCredits = false;
  hs.dimmingOpacity = 0.5;
  hs.dimmingDuration = 150;
  hs.outlineType = 'rounded-white';

  hs.captionEval = 'my_getCaption(this);';
  window.my_getCaption = function(expander){
    var $t = $(expander.a);
    return $t.find('.my-gallery-image-description').html();
    //return $t.closest('.my-gallery-thumbnail, .my-gallery-medium-item-box').find('.my-gallery-image-description').html();
  };

//   hs.onKeyDown = function(sender, e){ /* Disable closing the gallery on arrow keys extending the first or last image */
//     var code = e.keyCode;
//     var exp = hs.getExpander();
//     var imageNumber = exp.getAnchorIndex() + 1;
//     var groupLength = hs.anchors.groups[exp.slideshowGroup || 'none'].length;
//     if ((code == 34 || code == 39 || code == 40) && imageNumber == groupLength) return false; // hit next on the last image
//     if ((code == 33 || code == 37 || code == 38) && imageNumber == 1) return false; // hit previous on the first image
//   }

  // Hungarian language strings
  hs.lang = {
    cssDirection: 'ltr',
    loadingText: 'Kép betöltése...',
    loadingTitle: 'Mégsem',
    focusTitle: 'Előrehozás',
    fullExpandTitle: 'Eredeti méret (f)',
    creditsText: 'Készítette: Highslide JS',
    creditsTitle: 'A Highslide JS honlapjának megnyitása',
    previousText: 'Előző',
    nextText: 'Következő',
    moveText: 'Mozgat',
    closeText: 'Bezárás',
    closeTitle: 'Bezárás (esc)',
    resizeTitle: 'Átméretez',
    playText: 'Indítás',
    playTitle: 'Diavetítés indítása (szóköz)',
    pauseText: 'Szünet',
    pauseTitle: 'Diavetítés szüneteltetése (szóköz)',
    previousTitle: 'Előző (bal nyíl)',
    nextTitle: 'Következő (jobb nyíl)',
    moveTitle: 'Áthelyez',
    fullExpandText: 'Teljes méret',
    number: '%1/%2',
    restoreTitle: 'Klikk ide: bezárás, klikk + nyomva tart: áthelyezés. Bal / jobb nyíl: előző / következő kép'
  };
};

function initFacebook(){
  $('#facebook-box').html('<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2FMagyar.Hospice.Alapitvany&amp;width=196&amp;height=100&amp;connections=0&amp;colorscheme=light&amp;show_faces=false&amp;stream=false&amp;header=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:196px; height:100px; margin: -4px;" allowTransparency="true"></iframe>');
}


initHighSlide();

$(function(){
  timer('$ready');

  initLeftMenu();
  timer('initLeftMenu');

  initOldIE();
  timer('initOldIE');

  if(window.initTestimonyFlash){
    initTestimonyFlash(); // defined in -my-testimony.php
    timer('initTestimonyFlash');
  }

  initTestimonies();
  timer('initTestimonies');

  initMeltosagmezejeTerkep();
  timer('initMeltosagmezejeTerkep');

  initCollapsibleContent();
  timer('initCollapsibleContent');

  //initFacebook();
  //timer('initFacebook');

//  timer.results(); return;
});

