/*
 * vAlign
 * From: http://cool-javascripts.com/jquery/vertical-alignment-of-contents-inside-an-element-using-jquery.html
 * Updated by ThinnerView, LLC to support alignment relative to viewport
 */
(function ($) {
    $.fn.vAlign = function(vport, margin_decal) {
      return this.each(function(i){
        var paddingPx = 10; //change this value as you need (It is the extra height for the parent element)
        $(this).html('<div>' + $(this).html() + '</div>');
        var el = $(this).children("div:first");
        var elh = $(el).height(); //new element height
        var ph = $(this).height(); //parent height
        if (vport) ph = $(document).height(); //consider viewport instead
        if(elh > ph) { //if new element height is larger apply this to parent
          $(this).height(elh + paddingPx);
          ph = elh + paddingPx;
        }
        var nh = ((ph - elh) / 2) + margin_decal; //new margin to apply
        $(el).css('margin-top', nh);
      });
    };
})(jQuery);

function loadGaleryImageToSelector(selector, src)
{
  var img = new Image();
  $(img).load(function () { 
      $(selector).removeClass('loading');
      $(selector).append($(this));
      $("#fs_pic_2").hide();
      if ($(".gallery-result img").length == 2)
      {
        $("#fs_pic_1").show();
        $("#fs_pic_2").fadeIn(3000).animate({left:20}, 1000);
      }
    })
    .error(function () {
      
    })
    .attr('src', src);
}

function supportedLanguage($lng)
{
  switch ($lng)
  {
    case 'en':
    case 'ja':
      return true;
    case 'fr':
      $.prompt('Bienvenue sur la nouvelle version de ThinnerView.com!<br>Nous travaillons actuellement à la traduction du site. Elle sera disponible dans quelques jours.<br>Merci de votre compréhension.');
      return false;
    case 'it':
      $.prompt('Benvenuti nella nuova versione di ThinnerView.com!<br>Attualmente stiamo lavorando sulla traduzione del sito. Sarà disponibile tra pochi giorni.<br>Grazie per la vostra comprensione.');
      return false;
    case 'es':
      $.prompt('Bienvenido a la nueva versión de ThinnerView.com!<br>En estos momentos estamos trabajando en la traducción del sitio. Estará disponible en unos pocos días.<br>Gracias por su comprensión.');
      return false;
    case 'de':
      $.prompt('Willkommen auf der neuen Version von ThinnerView.com!<br>Wir arbeiten derzeit an der Übersetzung der Website. Es wird in wenigen Tagen verfügbar sein.<br>Vielen Dank für Ihr Verständnis.');
      return false;
    default:
      return false;
  }
}

$(document).ready(function(){
  var bcTiming = 10000;
  var galleryVisible = 5;
  var galleryThHeight = 100;
  var timeoutHandle;

  function moveToNext()
  {
    $("#bc").trigger('click');
  }  
  
  function animateBcBox()
  {
    var target = $(".current").attr('id');
    var animate = $("#"+target+" .anim-from");
    animate.css('left', '-300px').hide();
    animate.fadeIn(3000).animate({left:10}, 1000);
    timeoutHandle = setTimeout(moveToNext,bcTiming);
  }
  
  function beforeStartCallback(items)
  {
    clearTimeout(timeoutHandle);
    //$(".anim-from").stop();
    //timeoutHandle = setTimeout(moveToNext,bcTiming);
  }

  function afterEndCallback(items)
  {
    var id = items.attr('id').substr(1,1);
    $(".current .anim-from").css('left', '-300px').hide();
    $(".current").removeClass('current');
    $("#e"+id).addClass('current');
    $(".carousel-link").css('background', '#FFFFFF');
    $("#"+id).css('background', '#FF9933');
    animateBcBox();
  }
  if ($("#bc").length)
  {
    //timeoutHandle = setTimeout(moveToNext,bcTiming);
    $("#0").css('background', '#FF9933');
  }
  $("#bc")
      .jCarouselLite({ 
        btnPrev : "#bc",
        speed		:	'500',
        btnGo		:	[ "#0", "#1", "#2", "#3", "#4", "#5"],
        visible		:	1,
        beforeStart: beforeStartCallback,
        afterEnd: afterEndCallback
      });
  //$("#e0").click();  
  animateBcBox();
  
  
  /* Gallery */
  $("#bcgal")
      .jCarouselLite({ 
        btnPrev : "#bcgalprev",
        btnNext : "#bcgalnext",
        speed		:	'500',
        circular: false,
        visible	:	galleryVisible,
        vertical: true
      });  
      
  $(".gallery-clickable").click(function(){
    var id = $(this).attr('id').replace('e', '');
    var top = Math.round((-1)*$("#gallery_ul").position().top);
    var cur = Math.round(top/galleryThHeight);
    if ( (id-cur) == (galleryVisible-1) )
      $("#bcgalnext").click();
    else if (id==cur)
      $("#bcgalprev").click();
    $(".gallery-clickable").css('border', '2px solid #FFFFFF');
    $(this).css('border', '2px solid #FF6633');
    $(".gallery-result").html('<div id="fs_pic_1" style="float:left;width:388px;height:508px;" class="loading"></div><div id="fs_pic_2" style="float:left;width:388px;height:508px;" class="loading anim-gal-from"></div>');
    var base =  $(this).attr('src').replace('-T.jpg', '');
    loadGaleryImageToSelector('#fs_pic_1', base+'-B.jpg');
    loadGaleryImageToSelector('#fs_pic_2', base+'-A.jpg');
  });
  $(".gallery-selected").click();
  
  /* Testimonials */
  $("#bctesti")
      .jCarouselLite({ 
        btnPrev : "#bctestiprev",
        btnNext : "#bctestinext",
        speed		:	'500',
        circular: false,
        visible	:	1
      });
  
  /* Fix for IE6&7 */
  /*
  if ($(".price-tag").length)
  {
    if ($(".price-tag").position().top != 370)
    {
      $(".price-tag").css('top', 'auto');
    }
  }
  else if ($("#product_glass").length)
  {
    if ($("#product_glass").position().top != -2)
    {
      $("#product_glass").css('top', '-235');
    }
  }*/
  
  /* Vertical Align */
  $(".valign").vAlign(false, 0);
  
  /* Language selection */
  $("#languageSelect").change(function() {
    if (supportedLanguage($(this).val()))
    {
      var loc = document.location.href;
      var slash = loc.lastIndexOf('/');
      var len = loc.length;
      loc = loc.substr(slash+1, (len-slash-1));
      if ( (loc == '') || (loc.length == 2) )
        document.location.href = $(this).val();
      else
      {
        var php = loc.indexOf('.php');
        var dash = loc.indexOf('-')
        if ( (php-dash) == 3 )
        {
          var newloc = loc.substr(0, dash+1) + $(this).val() + loc.substr(php, (len-php));
          document.location.href = newloc;
        }
        else
        {
          var newloc = loc.substr(0, php) + '-' + $(this).val() + loc.substr(php, (len-php));
          document.location.href = newloc;
        }
      }
    }
  });
});

