var youTubeReady = false;
function onYouTubePlayerReady() {
  youTubeReady = true;
  $(".youtube-vid").each(function() {
    ytp = $(this).get(0);
    ytp.addEventListener("onStateChange", "onytplayerStateChange");
  });
}

$(function() {
	if($("body").hasClass("noJS")) { $("body").removeClass("noJS"); }
  $("body").addClass("jsEn");
	
	$("li.text-accessibility-links a").click(function(e) {
    $.getJSON(MIYOLib._conf.siteBaseURL+'/accessibility/textsize/' + $(this).attr("class") + '/?mode=ajax', function(data) {
      $("body")
        .removeClass("small")
        .removeClass("medium")
        .removeClass("large")
        .addClass(data.text_size);

    });
    $("li.text-accessibility-links a").removeClass('selected-size');
    $(this).addClass('selected-size');
    e.preventDefault();
	});

	$("a[href^='http://']")
  	.not("[href^='http://"+MIYOLib._conf.siteBaseURLNoProt+"']")
  	.each(function() {
  			this.target = "_blank";
  	});
  
  $("a[href^='https://']")
  	.not("[href^='https://"+MIYOLib._conf.siteBaseURLNoProt+"']")
  	.each(function() {
  			this.target = "_blank";
  	});

  $('#download-latest-brochure, .downloads-list a').each(function(){ this.target = '_blank'; });

  $("a.external").each(function() {
    this.target = "_blank";
  });

  Cufon.replace(".jl-font", { hover: true });
  // setTimeout("$('.blocked-title h1 cufon').css({marginTop:'-18px'});", 1000);

  placeYouTube();
  fakePositionFixed();
  handleSearchBoxes();
  handleReviews();
  handleCommentToggle();
  handleModules();
  handleHiresToggle();
  initExpandableSections();
  initMediaCarousel();
});

function fakePositionFixed() {
  // $headerHolder = $('#header-holder');
  $(window).resize(function(){
    $body = $('body');
    if($(window).width() < 960) {
      $body.addClass('thin');
    } else {
      $body.removeClass('thin');
    }
  });
}

function handleSearchBoxes() {
  $('#search-box, #search-bar').each(function(){
    $(this).click(function(){
      if($(this).val()=='Search') {
        $(this).val('');
      }
    }).blur(function(){
      if($(this).val()=='') {
        $(this).val('Search');
      }
    });
  });
}

function handleReviews() {
  $('.entry-reviews li').click(function() {
    $(this).find('p').slideToggle();
  });
}

function handleCommentToggle() {
  $('#comment-toggle').click(function(e) {
    $('#comment-hold').slideToggle();
    e.preventDefault();
  });
}

function stopYouTube() {
  $('.carousel-holder .youtube-vid').each(function() {
    var ytVidRef = this;
      if(youTubeReady == true) {
        if(typeof ytVidRef.pauseVideo == 'function') {
          ytVidRef.pauseVideo();
        }
      }
  });
}

function onytplayerStateChange(newState) {
  if(newState==1) {
    $(".carousel-holder").each(function() {
      container = this;
      clearInterval(container.animationDelay);
    });
  }
}

function placeYouTube() {
  if($.flash.available) {
    $(".youtube-replace").each(function() {
      var selfRef = this;
    
      selfRef.$vidInfo = $(selfRef).siblings(".youtube-vid-info");
      selfRef.$parentDiv = $(selfRef).parent();
    
      if(selfRef.$vidInfo.length > 0) {
        selfRef.vidID = selfRef.$vidInfo.attr("id");
      
        selfRef.$flashRef = $(selfRef).parent().flash({
          width:480,
          height:295,
    			swf: 'http://www.youtube.com/v/'+selfRef.vidID+'?enablejsapi=1&amp;hl=en_GB&amp;fs=1',
    			allowFullScreen: true,
    			allowscriptaccess: 'always',
    			wmode: 'transparent'
        });
      
        selfRef.$parentDiv.find("object").addClass("youtube-vid");
      }
    });
  }
}

function handleModules() {
  var thinner = {opacity: 1, left: '10px', width: '150px'};
  var wider = {opacity: 1, left: '0px', width: '171px' };

  var shorter = {height: '9px'};
  var taller = {height: '100%'};

  var bigger = {opacity: 0.8, left: '0px', height: '100%', width: '171px'};
  var smaller = {opacity: 1, left: '10px', height: '9px', width: '151px'};
  var speed = 500;
  var width_speed = 300;

  $('.module').not('.mini-module').each(function(){
    $this = $(this);

    if($this.hasClass('short-module')) {
      var height_speed = 150;
    } else {
      var height_speed = 300;
    }
    
    $(this).hover(function() {
      var $foreground = $(this).find('.module-foreground');
      $foreground.stop();
      $foreground.css(thinner).css(shorter);
      $foreground.animate(wider, width_speed, function(){
        $foreground.animate(taller, height_speed);
      });
    }, function() {
      var $foreground = $(this).find('.module-foreground');
      $foreground.stop();
      $foreground.css(wider).css(taller);
      $foreground.animate(shorter, height_speed/5, function(){
        $foreground.animate(thinner, width_speed/9);
      });
    });

    // $(this).hover(function() {
    //   $foreground = $(this).find('.module-foreground');
    //   $foreground.stop();
    //   $foreground.animate(bigger, speed);
    // }, function() {
    //   $foreground = $(this).find('.module-foreground');
    //   $foreground.stop();
    //   $foreground.animate(smaller, speed*3);
    // });


  });
}

function handleHiresToggle() {
  $('#hires-toggle-360').click(function(e) {
    $hiresthreesixty = $('#hires-three-sixty');
    $hiresvideo = $('#hires-video');
    $this = $(this);
    $hiresvideo.hide();
    $hiresthreesixty.show();
    $('#hires-toggle-pic').addClass('not-selected');
    $(this).removeClass('not-selected');
    e.preventDefault();
  });

  $('#hires-toggle-pic').click(function(e) {
    $hiresthreesixty = $('#hires-three-sixty');
    $hiresvideo = $('#hires-video');
    $this = $(this);
    $hiresvideo.show();
    $hiresthreesixty.hide();
    $('#hires-toggle-360').addClass('not-selected');
    $(this).removeClass('not-selected');
    e.preventDefault();
  });

}

function initExpandableSections() {
  $(".expandable-content").each(function() {
    var parentHold = this;
    parentHold.collapseOthers = false;
    
    if($(parentHold).hasClass("collapse-others")) {
      parentHold.collapseOthers = true;
      parentHold.$otherExpandables = $(parentHold).parent().find(".expandable-content");
    }
    
    parentHold.$blockHead = $(parentHold).find(".expand-trigger").not(".sub-expandable .expand-trigger")
      .css("cursor", "pointer")
      .hover(
        function () {
          if(!$(parentHold).hasClass("hovered")) {
            $(parentHold).addClass("hovered");
          }
        },
        function () {
          if($(parentHold).hasClass("hovered")) {
            $(parentHold).removeClass("hovered");
          }
        }
      )
      .click(function() {
        var headerRef = this;
        headerRef.originallyHadClass = true;
        
        if(!$(parentHold).hasClass("open")) {
          headerRef.originallyHadClass = false;
          
          if(parentHold.collapseOthers) {
            if(parentHold.$otherExpandables.length > 0) {
              parentHold.$otherExpandables.each(function() {
                var expandElement = this;
                
                if($(expandElement).hasClass("open")) {
                  $(expandElement).find(".expanded-content:first").slideToggle(600, function() {
                    $(expandElement).removeClass("open");
                  });
                }
              });
            }
          }
        }
        
        $(parentHold).find(".expanded-content:first").slideToggle(600, function() {
          if(headerRef.originallyHadClass && $(parentHold).hasClass("open")) {
            $(parentHold).removeClass("open");
          } else if(!headerRef.originallyHadClass && !$(parentHold).hasClass("open")) {
            $(parentHold).addClass("open");
          }
        });
        
        return false;
      });
  });
  
  $(".sub-expandable").each(function() {
    var subExpandHold = this;
    subExpandHold.collapseOthers = false;

    if($(subExpandHold).hasClass("collapse-others")) {
      subExpandHold.collapseOthers = true;
      subExpandHold.$otherExpandables = $(subExpandHold).parent().find(".sub-expandable");
    }

    subExpandHold.$blockHead = $(subExpandHold).find(".expand-trigger")
      .css("cursor", "pointer")
      .hover(
        function () {
          if(!$(subExpandHold).hasClass("hovered")) {
            $(subExpandHold).addClass("hovered");
          }
        },
        function () {
          if($(subExpandHold).hasClass("hovered")) {
            $(subExpandHold).removeClass("hovered");
          }
        }
      )
      .click(function() {
        var subHeaderRef = this;
        subHeaderRef.originallyHadClass = true;

        if(!$(subExpandHold).hasClass("open")) {
          subHeaderRef.originallyHadClass = false;
          
          if(subExpandHold.collapseOthers) {
            if(subExpandHold.$otherExpandables.length > 0) {
              subExpandHold.$otherExpandables.each(function() {
                var expandElement = this;

                if($(expandElement).hasClass("open")) {
                  $(expandElement).find(".sub-expand-content:first").slideToggle(600, function() {
                    $(expandElement).removeClass("open");
                  });
                }
              });
            }
          }
        }

        $(subExpandHold).find(".sub-expand-content:first").slideToggle(600, function() {
          if(subHeaderRef.originallyHadClass && $(subExpandHold).hasClass("open")) {
            $(subExpandHold).removeClass("open");
          } else if(!subHeaderRef.originallyHadClass && !$(subExpandHold).hasClass("open")) {
            $(subExpandHold).addClass("open");
          }
        });

        return false;
      });
  });
}

function initMediaCarousel() {
  var animRefs = {};
	$(".carousel-holder").each(function() {
		/*** Parent container with overflow hidden ***/
  	var container = this;
	
		/*** The ID for the carousel ***/
		container.carouselID = $(container).attr("id");
	
		/*** The controls holder to target during animation ***/
		container.$controls = $("#"+container.carouselID+"-nav");
	
		/*** The actual carousel content holder ***/
		container.$carousel = $(container).find('ul.carousel-content-list');
	
		/*** The items in the carousel to transition between ***/
		container.$mediaItems = container.$carousel.find('li');
	
		/*** Get an entry to calculate dimensions ***/
		container.$singleEntry = container.$mediaItems.filter(':first');
	
		/*** How wide each media entry is (with the border) ***/
		container.mediaEntryWidth = container.$singleEntry.outerWidth();
	
		/*** How many are visible at any given time ***/
		container.numberVisible = Math.ceil(($(container).innerWidth() / container.mediaEntryWidth));
	
		/*** How many slides do we have to transition? ***/
		container.slideCount = Math.ceil(container.$mediaItems.length / container.numberVisible);
	
		/*** Start by showing the first slide ***/
		container.currentSlide = 1;
	
		/*** Variable to hold slideAnimation call ***/
		container.slideAnimation;
	
		/*** Variable to hold gotoSlide call ***/
		container.gotoSlide;
	
		/*** The timeout holder ***/
		container.animationDelay;

    /*** The left arrow ***/
		container.leftArrow = $('.carousel-arrow-l', container);

    /*** The right arrow ***/
		container.rightArrow = $('.carousel-arrow-r', container);
		
		container.checkRealPos = function(isStart) {
			isStart = (typeof(isStart) == 'undefined')?false:true;
			 
			var caroStartPos = container.$carousel.position();
			var realPos = caroStartPos.left;
			var expectedPos = Math.abs((-1 * container.currentSlide * container.mediaEntryWidth));

			if(realPos != (-1 * expectedPos)) {
				if(realPos != 0) {
					if(isStart) {
						realPos = realPos - container.mediaEntryWidth;
					}
					container.currentSlide = Math.round((Math.abs(realPos) / container.mediaEntryWidth));
				} else {
					if(isStart) {
						container.currentSlide = 1;
					} else {
						container.currentSlide = 0;
					}
				}
			}
		}
	
		/*** We need to duplicate the content of the first and last slide content to make it seamless ***/
		container.$mediaItems.filter(':first').before(container.$mediaItems.slice(-container.numberVisible).clone().each(function() {
		  var firstMediaItem = this;
		  
			firstMediaItem.origID = $(firstMediaItem).attr("id");
			firstMediaItem.numericID = firstMediaItem.origID.substring((firstMediaItem.origID.lastIndexOf("-") + 1), firstMediaItem.origID.length);
			firstMediaItem.newID = container.carouselID+'-clone-entry-'+firstMediaItem.numericID;
			firstMediaItem.newLinkID = container.carouselID+'-carousel-clone-entry-link-'+firstMediaItem.numericID;
		
			$(firstMediaItem).find('a.linkover')
				.attr('id', firstMediaItem.newLinkID);
		
			$(firstMediaItem)
				.attr('id', firstMediaItem.newID)
				.addClass('cloned');
		}));
		container.$mediaItems.filter(':last').after(container.$mediaItems.slice(0, container.numberVisible).clone().each(function() {
		  var lastMediaItem = this;
		  
			lastMediaItem.origID = $(lastMediaItem).attr("id");
			lastMediaItem.numericID = lastMediaItem.origID.substring((lastMediaItem.origID.lastIndexOf("-") + 1), lastMediaItem.origID.length);
			lastMediaItem.newID = container.carouselID+'-clone-entry-'+lastMediaItem.numericID;
			lastMediaItem.newLinkID = container.carouselID+'-carousel-clone-entry-link-'+lastMediaItem.numericID;
		
			$(lastMediaItem).find('a.linkover')
				.attr('id', lastMediaItem.newLinkID);
			
			$(lastMediaItem)
				.attr('id', lastMediaItem.newID)
				.addClass('cloned');
		}));
	
		/*** Refresh the $mediaItems list ***/
		container.$mediaItems = container.$carousel.find('li');
	
		/*** Calculate the new width of the carousel content holder ***/
		container.newWidth = container.$mediaItems.length * container.mediaEntryWidth;
	
		container.checkRealPos(true);
	
		/*** Set new properties for the carousel content holder ***/
		container.$carousel.css('width', container.newWidth);
		container.$carousel.css('left', (-1 * container.currentSlide * container.mediaEntryWidth));
		container.$controls.find("#"+container.carouselID+"-link-"+container.currentSlide).addClass("selected");
		container.$mediaItems.find("#"+container.carouselID+"-entry-"+container.currentSlide).addClass("selected");
	
		if(container.slideCount < 2) return;
	
		container.gotoSlide = function(slideNo,navClick) {
      stopYouTube();
			navClick = (typeof(navClick) == 'undefined')?false:true;
		
			/*** Get where we currently think we are ***/
			var originalPos = container.currentSlide;
		
			/*** Check where we REALLY are ***/
			container.checkRealPos();
		
			/*** If they are not equivalent correct values ***/
			if(originalPos != container.currentSlide) {
				container.$carousel.css('left', (-1 * container.currentSlide * container.mediaEntryWidth));
			
				if(!navClick) {
					if(container.currentSlide >= container.slideCount) {
						slideNo = 2;
					} else {
						slideNo = container.currentSlide + 1;
					}
				}
			}
		
			/*** Used for setting "selected" class ***/
			var actualSlide;
		
			if(slideNo > container.slideCount) {
				actualSlide = 1;
			} else if(slideNo < 1) {
				actualSlide = container.slideCount;
			} else {
				actualSlide = slideNo;
			}
		
			/*** Determine the direction of the transition ***/
			var direction = slideNo < container.currentSlide ? -1 : 1;
		
			/*** Get the required slide shift ***/
			var slideShift = Math.abs(container.currentSlide - slideNo);
		
			/*** How much in pixels we are shifting ***/
			var leftShift = direction * container.mediaEntryWidth * container.numberVisible * slideShift;
		
			/*** Remove any that are previously set as selected ***/
			container.$controls.find("li.selected").removeClass("selected");
		
			/*** Set the taget frame to selected ***/
			container.$controls.find("li#"+container.carouselID+"-link-"+actualSlide).addClass("selected");
		
			container.$carousel.find('li.selected').removeClass("selected");
		
			container.$carousel.filter(':not(:animated)').animate({
				left: '-='+leftShift
			}, 500, function () {
				if (slideNo == 0) {
					container.$carousel.css('left', -(container.mediaEntryWidth * container.numberVisible * container.slideCount));
					slideNo = container.slideCount;
				} else if (slideNo > container.slideCount) {
					container.$carousel.css('left', -(container.mediaEntryWidth * container.numberVisible));
					slideNo = 1;
				}
			
				container.$carousel.find('li#'+container.carouselID+'-clone-entry-'+slideNo).addClass("selected");
				container.$carousel.find('li#'+container.carouselID+'-entry-'+slideNo).addClass("selected");
	
				container.currentSlide = slideNo;
			}); 
		
			container.currentSlide = slideNo;  
		
			clearInterval(container.animationDelay);
			container.animationDelay = setInterval(container.slideAnimation, 6000);            
		
			return false;
		}
	
		container.slideAnimation = function() {
			var jumpTo = container.currentSlide + 1;
		 
			container.gotoSlide(jumpTo);
		}
		
		container.$mediaItems.each(function() {
		  var mediaItemRef = this;
		  mediaItemRef.$keyLink = $(mediaItemRef).children("a:first");
		  mediaItemRef.$infoBar = mediaItemRef.$keyLink.find(".info-bar");
		  
		});
	
		container.$controls.find("li > a").each(function() {
		  var thisControlLink = this;
		  
			thisControlLink.origID = $(thisControlLink).parent().attr("id");
			thisControlLink.numericID = Number(thisControlLink.origID.substring((thisControlLink.origID.lastIndexOf("-") + 1), thisControlLink.origID.length));
		
			$(thisControlLink).click(function() {
				container.gotoSlide(thisControlLink.numericID,true);
				return false;
			});
		});

	container.leftArrow.click(function(e){
    container.gotoSlide(container.currentSlide-1);
    clearInterval(container.animationDelay);
	  e.preventDefault();
	});

	container.rightArrow.click(function(e){
    container.slideAnimation( );
    clearInterval(container.animationDelay);
    e.preventDefault();
	});

    container.animationDelay = setInterval(container.slideAnimation, 6000);
		
		var carouselIDString = container.carouselID;
		animRefs[carouselIDString] = container;
	});
}
