(function($){

  var settings = {
        speed: 350 //animation duration
      , easing: "linear" //use easing plugin for more options
      , padding: 10
      , constrain: false
    }
    , $window = $(window)
    , stickyboxes = []
    , methods = {

          init:function(opts){
            settings = $.extend(settings,opts);
            return this.each(function () {
              var $this = $(this);
              setPosition($this);
              stickyboxes[stickyboxes.length] = $this;
              moveIntoView();
            });
          }

        , remove:function(){
            return this.each(function () {
              var sticky = this;
              $.each(stickyboxes, function (i, $sb) {
                if($sb.get(0) === sticky){
                reset(null, $sb);
                stickyboxes.splice(i, 1);
                return false;
                }
              });
            });
          }

        , destroy: function () {
            $.each(stickyboxes, function (i, $sb) {
              reset(null, $sb);
            });
            stickyboxes=[];
            $window.unbind("scroll", moveIntoView);
            $window.unbind("resize", reset);
            return this;
          }

      };


  var moveIntoView = function () {
    $.each(stickyboxes, function (i, $sb) {
      var $this = $sb
        , data = $this.data("stickySB");
      if (data) {
        var sTop = $window.scrollTop() - data.offs.top
          , currOffs = $this.offset()
          , origTop = data.orig.offset.top - data.offs.top
          , animTo = origTop;
        //scrolled down out of view
        if (origTop < sTop) {
					//make sure to stop inside parent
          if ((sTop + settings.padding) > data.offs.bottom)
            animTo = data.offs.bottom;
          else animTo = sTop + settings.padding;
        }
		  if ( animTo < 0 ) {
			 animTo = 0; 
		  }
        $this
          .stop()
          .animate(
              {top: animTo}
            , settings.speed
            , settings.easing
        );
      }
    });
  }

  var setPosition = function ($sb) {
    if ($sb) {
      var $this = $sb
        , $parent = $this.parent()
        , parentOffs = $parent.offset()
        , currOff = $this.offset()
        , data = $this.data("stickySB");
      if (!data) {
        data = {
            offs: {} // our parents offset
          , orig: { // cache for original css
                top: $this.css("top")
              , left: $this.css("left")
              , position: $this.css("position")
              , marginTop: $this.css("marginTop")
              , marginLeft: $this.css("marginLeft")
              , offset: $this.offset()
            }
        }
      }
      //go up the tree until we find an elem to position from
      while (parentOffs && "top" in parentOffs
        && $parent.css("position") == "static") {
        $parent = $parent.parent();
        parentOffs = $parent.offset();
      }
      if (parentOffs) { // found a postioned ancestor
        var padBtm = parseInt($parent.css("paddingBottom"));
        padBtm = isNaN(padBtm) ? 0 : padBtm;
        data.offs = parentOffs;
        data.offs.bottom = settings.constrain ?
          Math.abs(($parent.innerHeight() - padBtm) - $this.outerHeight()) :
          $(document).height();
      }
      else data.offs = { // went to far set to doc
          top: 0
        , left: 0
        , bottom: $(document).height()
      };
		
		var $top = Math.floor(currOff.top - data.offs.top);
		
		if ( $top < 0 ) {
			$top = 0;
		}
		
      $this.css({
          position: "absolute"
        , top: $top + "px"
        , left: Math.floor(currOff.left - data.offs.left) + "px"
        , margin: 0
        , width: $this.width()
      }).data("stickySB", data);
    }
  }

  var reset = function (ev, $toReset) {
    var stickies = stickyboxes;
    if ($toReset) { // just resetting selected items
      stickies = [$toReset];
    }
    $.each(stickies, function(i, $sb) {
      var data = $sb.data("stickySB");
      if (data) {
        $sb.css({
            position: data.orig.position
          , marginTop: data.orig.marginTop
          , marginLeft: data.orig.marginLeft
          , left: data.orig.left
          , top: data.orig.top
        });
        if (!$toReset) { // just resetting
          setPosition($sb);
          moveIntoView();
        }
      }
    });
  }

  $window.bind("scroll", moveIntoView);
  $window.bind("resize", reset);

  $.fn.stickySidebar = function (method) {

    if (methods[method]) {
      return methods[method].apply(
          this
        , Array.prototype.slice.call(arguments, 1)
      );
    } else if (!method || typeof method == "object") {
      return methods.init.apply(this, arguments);
    }

  }

})(jQuery);


$(document).ready(function() {
	
	if ( $("#wcis").length ) {
		$("#wcis img").hover(function() {
			$(this).animate({opacity: "1"}, 600);
		}, function() {
			$(this).animate({opacity: ".2"}, 600);
		});
		$("#wcis_nobel").click(function() { window.open("http://www.nobelbiocare.com/en/products-solutions/implant-systems/nobelactive/default.aspx"); });
		$("#wcis_ankylos").click(function() { window.open("http://www.dentsply-friadent.com/en/528.htm"); });
		$("#wcis_mis").click(function() { window.open("http://www.mis-implants.com/"); });
	}
	
	if ( $("#tratamente_sticky").length ) {
		$("#treatment_height").height($("#treatment_height").height() + 20);
		$("#tratamente_sticky").stickySidebar({constrain: true});
		$(".tratament_right").stickySidebar({constrain: true});
	}

	$("#tratament").hover(function() { $(this).find("dl").show(); }, function() { $(this).find("dl").hide(); });

	$("#news").click(function() {
		$("#events_sel").fadeOut(500, function() {$("#news_sel").fadeIn(500);});
	});
	$("#events").click(function() {
		$("#news_sel").fadeOut(500, function() {$("#events_sel").fadeIn(500);});
	});

	$(".main_image .desc").show();
	$(".main_image .block").animate({ opacity: 0.85 }, 1000 );
	$(".image_thumb ul li:first").addClass('active');
	$(".main_image img").animate({ opacity:0.60}, 1, function() { $(this).animate({ opacity:1 }, 1000); });
	
	$(".image_thumb ul li").click(function (e) {
		$active = $(this); slideSwitchClick();
		e.preventDefault();
	}).hover(function(){ $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });
	
	playSlideshow = setInterval( "slideSwitchTimed()", 6000 );
	$('.main_image').hover(function() {
		clearInterval(playSlideshow);
	},
	function() {
		playSlideshow = setInterval( "slideSwitchTimed()", 6000 );
	});
	
	$(".tab").live("click", function() {
		if ( !$(this).hasClass("active") ) {
			$(".tab").removeClass("active");
			var $id = this.id.replace("t", "");
			$(this).addClass("active");
			$(".tratament").hide();
			$("#p"+$id+", #pp"+$id).show();
			var $height = $("#pp"+$id).height();
			var $height2 = $("#treatment_height").height();
			if ( $height > $height2 ) {
				$("#treatment_height").height($height + 20);
			}
			$(".tratament_right").stickySidebar("remove");
			$("#tratamente").stickySidebar("remove");
			$("#tratamente").stickySidebar({constrain: true});
			$(".tratament_right").stickySidebar({constrain: true});
		}
	});

	
	$("a.imgal").fancybox({'hideOnContentClick': true, 'overlayShow'	:	false});
	
	$(".fancy").fancybox({
			'autoScale'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'iframe',
			'overlayShow'		: false
	});
	
	$(".case_image_holder").hover(
		function () {
			var $caption = $(this).find(".case_caption");
			if ( $caption.text() != "" ) {
				$caption.fadeIn(300);
			}
		},
		function () {
			$(this).find(".case_caption").fadeOut(300);
		});

	$(".case_gallery img").live("click", function() {
		var $nr = this.id;
		var $iid = $(this).attr("class");
		var $id = $iid.split('_')[1];
		var $desc = $(this).attr("alt");
		var $full_img = "cazuri_img/"+$id+"/"+$nr+"";
		
		var $im = new Image();
		$im.src = $full_img;
		$($im).load(function() {
			$("#caseID_"+$id+" .case_left .case_image_holder a").attr("href", $full_img);
			$("#caseID_"+$id+" .case_left .case_image_holder img").animate({opacity:0.3}, 500, function() { $(this).animate({opacity:1}, 500).css("background-image", "url("+$full_img+")"); });
			$("#caseID_"+$id+" .case_left .case_image_holder .case_caption").html($desc);
		});
	});
	
});
	
function slideSwitchTimed() {
	$active = $('.image_thumb ul li.active').next();
	if ( $active.length == 0 ) $active = $('.image_thumb ul li:first');
	slideSwitch();
}

function slideSwitchClick() {
	slideSwitch();
}

function slideSwitch() {
	var $prev = $('.image_thumb ul li.active');
	$prev.removeClass('active');
	$active.addClass('active');
	var imgAlt = $active.find('img').attr("alt");
	var imgTitle = $active.find('a').attr("href");
	var imgDesc = $active.find('.block').html();
	var lnk = $active.find(".block").attr("id");
	switch ( lnk ) {
		case 'n1':
			$lnk = '/despre-noi';
		break;
		
		case 'n2':
			$lnk = '/cazuri';
		break;
		
		case 'n3':
			$lnk = '/echipa';
		break;
		
		default:
			$lnk = '';
		break;
	}
	$("#afla_lnk a").attr("href", $lnk);
	var imgDescHeight = $(".main_image").find('.block').height();
	if ( $(this).is(".active") ) {
		return false;
	} else {
		$(".main_image .block").animate({ marginBottom: -imgDescHeight }, 250,
					function() {
						$(".main_image .block").html(imgDesc).animate({ marginBottom: "0" }, 250);
						$(".main_image img").fadeOut(500, function() { $(this).attr({ src: imgTitle , alt: imgAlt }).fadeIn(500); });
					});
	}
	return false;
}

