//global flag for opened teasers
$cur_openTeaser = '';
originalCopy = '';

$(document).ready(function() {
     intElements();
     imageLoader(); 
   

if(navigator.userAgent.match(/like Mac OS X/i)){

     $('#menu ul li a').each(function(){
       if (this.parentNode.parentNode.parentNode.id != 'menu') return;
       var fc = $(this.parentNode).find('li:first-child');
       if (fc.length > 0) {
         fc.before('<li><a class="" href="'+this.href+'">Introduction</a></li>');
         //fc.before('<li><a class="'+this.className+'" href="'+this.href+'">Introduction</a></li>');
         this.href = '#';
       }
     });

}

     $('#supportingContent .teaserImage').each(function() {
     	if (!$(this).find('a')[0]) return;
     	var rel = $(this).find('a')[0].rel;
     	// Fix pretty photo relationships
     	$('a[rel^='+rel+']').prettyPhoto({
				showTitle:false,
				theme:'dark_rounded'
			});
        
	var sp = document.createElement('SPAN');
	sp.className = 'detailLink';
	sp.innerHTML = '<a href="" onclick="$($(\'a[rel^='+rel+']\')[0]).click(); return false;">View detail</a>';
	$(this.parentNode).find('.teaserContent p')[0].appendChild(sp);
	
     });
     
     //check for flash:
     var $hasFlash = swfobject.hasFlashPlayerVersion('7');
     
    var $url = document.location.href.split('/');
    var $currentPage = $url[$url.length-2];
    
    if (!$hasFlash && $currentPage == 'Motion+Graphics'){
      alert('Items in this section were developed using Adobe Flash. \nUnfortunately, It appears your browser doesn\'t support Flash.');
      $('.detailLink').css('display','none');
      $('.teaserImageLink').removeAttr('href');
      $('.teaserImageLink').removeAttr('rel');
    }
    
    if (!$hasFlash && $currentPage == 'Spec+Presentations'){
      alert('Items in this section were developed using Adobe Flash. \nUnfortunately, It appears your browser doesn\'t support Flash.');
      $('.detailLink').css('display','none');
      $('.teaserImageLink').removeAttr('href');
      $('.teaserImageLink').removeAttr('rel');
    }
     
     //hold onto original copy for swap back
      if($('body').attr('class') == 'peoplePage'){
         originalCopy = $('#content p').html();         
      }

});

function imageLoader(){
   counting = '0'
   $('#supportingContent img').each(function() {
      $(this).ready(function(){
         counting++;
         if(counting == $('#supportingContent img').size()){
            $('#bigDiv').css('visibility','visible');
            $('#bigDiv').animate({
                       opacity : '1',
                       filter: 'alpha(opacity=100)'
                       },
                       1000
                       );
         };
      });

   });
}

//rendering thumbnail slider elements
function intElements(){
     
     //add click event to thumbnails (open teaser box, relocate slider position)
     $('#supportingContent li').click(function(){ openTeaser(this) });
     
     $teaserThumbWidth = $('#supportingContent li .teaserThumb').width();
     $('#supportingContent li').css({
                                    width : '90px', //should be dynamic, issue with images loading v. script loading
                                    height : '90px',
                                    overflow : 'hidden',
                                    marginTop : '85px'
                                    });

     $('#linksToUrl:link').css('visibility','hidden');
     $('#linksToUrl:visited').css('visibility','hidden');
     
     //create slider container size
     $liWidth = $('#supportingContent li').outerWidth(true);
     $ulWidth = ($liWidth * $('#supportingContent ul li').size());
     
     $('#supportingContent').css('width', $liWidth*6); // make viewport size dynamic based on thumbs to show eg: *6
     
     $('#supportingContent ul').css({
                                    'width' : $ulWidth,
                                    'margin-left' : '25px' // make dynamic based on li margin-right
                                    });
     
      if($('#supportingContent ul li').size()<6){
         adjustMargin = (((6 - $('#supportingContent ul li').size())*142)/2);
         $('#supportingContent ul').css({ paddingLeft : adjustMargin });
     }else{
           //create arrows for navigation
            $('#bigDiv').append('<div id="arrow_holder"><div id="right_arrow">more</div><div id="left_arrow">less</div></div>');
            
            //add click event to arrows (move thumb slider function)
            $('#left_arrow').click(function(){ moveThumbs('left') });
            $('#right_arrow').click(function(){ moveThumbs('right') });
            $('#left_arrow').css('opacity','.15');
     }
     
         //add close button for teasers 
     $('.teaserContent').after('<a class="closeTeaser" href="#">CLOSE</a>');
     $('.closeTeaser').click(function(){ closeTeaser(this.parentNode) });
     
     if($('#linksToUrl').text == ''){
      alert('has URL');
     }
}

//handles clicks of arrows and moving thumbnails in slider
function moveThumbs($direction){
     
     if($cur_openTeaser != ''){
          
          $($cur_openTeaser).animate({
                         width: '90px',
                         height: '90px',
                         marginTop : '85px'
                         },
                         500
                         );

          //$fullMove = $('#supportingContent').width()-560;
          $($cur_openTeaser).find('.teaserThumb').css('display', 'block');
          $($cur_openTeaser).find('.teaserThumb').animate({
                                        opacity : '1',
                                        filter: 'alpha(opacity=100)',
                                        marginTop : '0px',
                                        marginLeft : '0px'
                                        },
                                        500
                                        );
          
          $($cur_openTeaser).find('.personImg').animate({
                                             width : '90px',
                                             height : '90px',
                                             marginTop : '-1px',
                                             marginLeft : '-1px'
                                             }, 1000
                                             );
          
          $($cur_openTeaser).click(function(){ openTeaser(this) });
          $('#linksToUrl:link').css('visibility','hidden');
          $('#linksToUrl:visited').css('visibility','hidden');
          $cur_openTeaser = '';
          $('#supportingContent ul').css('width', ($('#supportingContent ul').width()-510));
     }
     
     $position = $('#supportingContent ul').position();;
     
     //set slide limits
     $maxLeft = 0;
     $maxRight = $('#supportingContent').width() - $('#supportingContent ul').width();
     
     $fullMove = $('#supportingContent').width();
     
      if($('#supportingContent ul li').size()>6){
        if ($direction == 'left'){
            $tempMove = $position.left + $fullMove;
            if($tempMove>$maxLeft){
                $move = $maxLeft;
                $('#left_arrow').css('opacity','.15');
                $('#right_arrow').css('opacity','.5');
            }else{
                $move = $position.left + $fullMove;
                $('#right_arrow').css('opacity','.5');
            }
        } else {
            $tempMove = $position.left - $fullMove;
            if($tempMove<$maxRight){
                $move = $maxRight;
                $('#right_arrow').css('opacity','.15');
                $('#left_arrow').css('opacity','.5');
            }else{
                $move = $position.left - $fullMove;
                $('#left_arrow').css('opacity','.5');
            }
        }
        
        $animationSpeed = Math.abs(Math.abs($position.left)+$move)+1000;
        
        $('#supportingContent ul').animate({
                                            'left': $move
                                            },
                                            $animationSpeed
                                            );
         
         if($('body').attr('class') == 'peoplePage'){
            $('#content p').html(originalCopy);         
         }
      }
}
     
//function opens teaser view on thumbnail click.
//centers slider based on clicked thumb
function openTeaser($elementClicked){
     
     
    $('#supportingContent li').unbind('click');
     
    $openWidth = 510;
    $position_element = $($elementClicked).offset();
    $position_slider = $('#supportingContent ul').position();
    $position_view = $('#supportingContent');
    // Get x coordinate for view center
    var leftMost = $position_view.offset().left + ($position_view.width() / 2);
    // Move x cordinate to the left by half the size of the teaser window
    leftMost -= $openWidth / 2;
    // Calculate distance from clicked thumbnail
    var needToMove = $position_element.left - leftMost;
    $openMove = $position_slider.left - needToMove;
    
    //close the open teaser if it exists
     if($cur_openTeaser != ''){
          
          $position_openTeaser = $($cur_openTeaser).position();
          $position_clickedTeaser = $($elementClicked).position();
          
          //right
          if($position_clickedTeaser.left > $position_openTeaser.left){
               $openMove = $position_slider.left - 142;
          }
          
          //left
          if($position_clickedTeaser.left < $position_openTeaser.left){
               $openMove = $position_slider.left + 142;
          }
          
          //shrink container to allow correct movement for next teaser
          $('#supportingContent ul').css('width', ($('#supportingContent ul').width()-$openWidth));
          
     }

     
     $($elementClicked).find('.teaserThumb').css({
                                                  opacity : '0',
                                                  filter: 'alpha(opacity=0)',
                                                  display : 'none',
                                                  marginTop : '100px',
                                                  marginLeft : '300px' 
                                                  });

     $($elementClicked).find('.personImg').animate({
                                                  width : '170px',
                                                  height : '170px',
                                                  marginTop : '46px',
                                                  marginLeft : '23px'
                                                  }, 1000
                                                  );

     
     if($cur_openTeaser != ''){     
          $($cur_openTeaser).animate({
                                   width : '90px',
                                   height : '90px',
                                   marginTop : '85px'
                                   },
                                   1000
                                   );
         
         $($cur_openTeaser).find('.teaserThumb').css('display', 'block');
          $($cur_openTeaser).find('.teaserThumb').animate({
                                        opacity : '1',
                                        filter: 'alpha(opacity=100)',
                                        marginTop : '0px',
                                        marginLeft : '0px'
                                        },
                                        1000
                                        );
          
     $($cur_openTeaser).find('.personImg').animate({
                                                  width : '90px',
                                                  height : '90px',
                                                  marginTop : '-1px',
                                                  marginLeft : '-1px'
                                                  }, 1000
                                                  );
     
      $($cur_openTeaser).click(function(){ openTeaser(this) });
                        $('#linksToUrl:link').css('visibility','hidden');
                        $('#linksToUrl:visited').css('visibility','hidden');

     }
     
     $('#supportingContent ul').animate({
                                   'left': $openMove
                                   },
                                   1000
                                   );
     
     $($elementClicked).animate({
                     width: $openWidth,
                     height: '262px',
                     marginTop : '-1px'
                     },
                     1000, function(){
                        $('#linksToUrl:link').css('visibility','visible');
                        $('#linksToUrl:visited').css('visibility','visible');
                        $('#supportingContent li').click(function(){ openTeaser(this) });
                        $($elementClicked).unbind('click');
                     });
     
      if($('body').attr('class') == 'peoplePage' && $('#supportingContent .peopleQuote') != ''){
         $('#content p').html($($elementClicked).find('.peopleQuote').html());         
      }

     $cur_openTeaser = $elementClicked;
     
          //stretch container to fit resized teaser view
     $('#supportingContent ul').css('width', ($('#supportingContent ul').width()+$openWidth));

     
};

function closeTeaser($teaserToClose) {
   
  $($teaserToClose).animate({
                                   width : '90px',
                                   height : '90px',
                                   marginTop : '85px'
                                   },
                                   1000
                                   );
         
         $($teaserToClose).find('.teaserThumb').css('display', 'block');
          $($teaserToClose).find('.teaserThumb').animate({
                                        opacity : '1',
                                        filter: 'alpha(opacity=100)',
                                        marginTop : '0px',
                                        marginLeft : '0px'
                                        },
                                        1000,
                                       function (){
                                           $($cur_openTeaser).click(function(){ openTeaser(this) });
                                           $cur_openTeaser = '';
                                           $('#supportingContent ul').css('width', ($('#supportingContent ul').width()-510));

                                       });
          
     $($teaserToClose).find('.personImg').animate({
                                                  width : '90px',
                                                  height : '90px',
                                                  marginTop : '-1px',
                                                  marginLeft : '-1px'
                                                  }, 1000,
                                                  function (){
                                                      $($cur_openTeaser).click(function(){ openTeaser(this) });
                                                      $cur_openTeaser = '';
                                                      $('#supportingContent ul').css('width', ($('#supportingContent ul').width()-510));
                                                  });
     
                        $('#linksToUrl:link').css('visibility','hidden');
                        $('#linksToUrl:visited').css('visibility','hidden');
                        
      if($('body').attr('class') == 'peoplePage'){
         $('#content p').html(originalCopy);         
      }
      
      checkSliderPosition();
}


function checkSliderPosition() {
     
     if($('#supportingContent ul li').size()<6){
        
        $('#supportingContent ul').animate({
                                            'left': 0
                                            },
                                            1000
                                            );
        return;
     }
     
     $position = $('#supportingContent ul').position();;
     
     //set slide limits
     $maxLeft = 0;
     $maxRight = $('#supportingContent').width() - ($('#supportingContent ul').width()-510);
         
     if ($position.left > $maxLeft){
             $move = 0;
             $('#left_arrow').css('opacity','.15');
             $('#right_arrow').css('opacity','.5');
      }else{
         if ($position.left < $maxRight){
                 $move = $maxRight;
                 $('#right_arrow').css('opacity','.15');
                 $('#left_arrow').css('opacity','.5');
          }else{
             return;
          }
      }
     

     
     $animationSpeed = Math.abs(Math.abs($position.left)+$move)+1000;
     
     $('#supportingContent ul').animate({
                                         'left': $move
                                         },
                                         $animationSpeed
                                         );
}
