/* External Links Sitewide */ 
function setupExternalLinks(){
  $('a[href^="http://"]').click( function() {
      var attr = $(this).attr('href');
      
      if( attr.search('website.com') < 0 ) {
        window.open( $(this).attr('href') );
        return false;
      } else {
        return true;
      }
    });
}
/* Pages With Forms */
function initOverlabelValidate(){

  $('form').each(function(){  // use .each for pages that have two forms on them ie Press pages
      $(this).validate();
  
    jQuery.extend(jQuery.validator.messages, {
      required: 'Required',
      email: 'Invalid Email'
    });

  });
}

/* Verically Align Objects */
(function ($) {
$.fn.vAlign = function() {
  return this.each(function(i){
  var ah = $(this).outerHeight();
  var ph = $(this).parent().height();
  var mh = (ph - ah) / 2;
  $(this).css({'margin-top': mh});
  });
};
})(jQuery);

function initPrimeNavAnimation(){
  // Main Navigation
  $('#primeNav .sub').each(function(){ // Set up visual display of each .sub
    var $this = $(this),
        $nav = $this.find('.nav'),
        $thumbs = $this.find('.thumbs'),
        navY = $nav.outerHeight();
    $thumbs.css('opacity', 0).find('li:not(.default)').hide();
    $nav.css('opacity', 0).find('a').hover(function(){
      var i = $(this).parent().index();
      $thumbs.show().find('li:eq('+(i+1)+')').fadeIn(50).siblings().fadeOut(50);
    }, function(){
      $thumbs.find('li:not(.default)').hide().end().find('li.default').show();
    });
    $nav.css('marginTop', -navY);
  /* alert(navY); */
  });

  $('.navBlock>ul>li').hover(function(){
      var $sub = $(this).find('.sub');
      if($sub.length){ 
        $(this).addClass('hover').find('>a').stop().animate({
          'width' : 332
        }, 250).css({
          'background' : '#f8931e',
          'color': '#000'
        });
        $('#sidebarLeft').find('#coverPage').stop().fadeTo(100, 0.75);
        setTimeout(function(){
          $sub.find('.thumbs').animate({'opacity' : 1}, 250);
          $sub.find('.nav').animate({'opacity' : 1}, 250);
        }, 250);
      }
    }, function(){
      // alert('something')
      //$(this).removeClass('hover').find('>a').stop().animate({    <-- original line before editing
      $('li.hover').find('>a').stop().animate({'width' : 149}, 150).css({ 
      'background' : 'transparent',
      'color': '#909090'
      });  
      $(this).removeClass('hover');
      $('#sidebarLeft').find('#coverPage').stop().fadeOut(500, 0);
      $(this).find('.thumbs').css('opacity', 0);
      $(this).find('.nav').css('opacity', 0);
  });

}

/* Option Dropdown */
function initFormDropDown() {
  $('.optionDropdown').each(function(){
    var id = $(this).attr('id');
    
    // setup the open/close glyph
    $('#'+id+' .open').click(function(){
      $(this).parents('.optionDropdown').toggleClass('listOpen');
      $('#'+id+' ul').slideToggle(); 
      return false; 
    });
    // set the default text ******** Talk to Dmitry about Languages for this
    $(this).find('.open').text(getDefaultDropdownText());

    // add click handlers to the items in the list
    $('#'+id+' ul li a').click(function(){
      var optText, val, name;
      var dropdown;

      optText = $(this).text();
      val = $(this).attr('id').split('_').slice(-1)[0];      
      name = $(this).attr('id').split('_').slice(0)[0];       
      dropdown = $(this).parents('.optionDropdown');

      // make the list close and set the text to the selected item
      commitDropdownSelection(dropdown, optText);
  
      dropdown.addClass('selected'); // move into commit drop down selection function

      // filter out the invalid items in child lists
      filterChildren(dropdown, val);
      if (val.indexOf("product") == 0) {
        $('#warrantyProductImg img').attr('src', 'images/products-warranty/' + val + '.jpg').parent('div').removeClass('hideImg');
      }
      
      // store selected value in a hidden text
      $('input[name='+name+']').attr('value', val);
      $('input#city').attr('value', val);

      // alert(name+', '+val)
      $('#'+id+'  ul').slideToggle();
      return false; 
    });
  
  });
}

function filterChildren(dropdown, selectedValue) {
  if(!dropdown || !selectedValue) {
    return false;
  }
  var childDropdown = getChildDropdown(dropdown);
    
  if(childDropdown.length) {
    var anchors = childDropdown.find('ul li a');
    // hide all the items in the child drop down
    anchors.parent().css('display','none');
    // show the items that match the selected parent value
    anchors.filter('a[id^=option_' + selectedValue + ']')
      .parent().css('display', 'block');
    // clear selections and reset state on child dropdown
    commitDropdownSelection(childDropdown, getDefaultDropdownText());
    resetChildDropdown(childDropdown);
  }
}
// get the child drop down that cascades based on the selection made 
// in the specified parentDropdown. The dropdowns are named using this pattern:  option_<parent>_<current>
function getChildDropdown(parentDropdown){
  var childSelector = 'div[id*=_' +
    getDropdownName(parentDropdown.attr('id')) + 
    '_]:first';
  return $('.optionDropdown').filter(childSelector);
}
// update a dropdown text and state to represent the selected item
function commitDropdownSelection(dropdown, selectedValue) {
  dropdown.toggleClass('listOpen')  
    .find('.open')
    .text(selectedValue);
}
// clean up the state of the specified child drop down and perform this function again (recursively)
// if we find that there is a child cascading dropDown (grandchild ) of the specified child (dropdown)
function resetChildDropdown(dropdown){
  // clear the selected text
  dropdown.find('.open').text(getDefaultDropdownText());
  // clear the visual styles 
  dropdown.removeClass('selected');
  dropdown.removeClass('listOpen');
  // if this drop down has a child then reset it recursively
  var grandChild = getChildDropdown(dropdown);
  if (grandChild && grandChild.length >0) {
    resetChildDropdown(grandChild);
  }
}
function getDefaultDropdownText(){
  // edit this for multi-language
  return 'Please Choose';
}
function getDropdownName(id){
  return  id.split('_').slice(-1)[0];
}



// Newsletter Signup
function newsletterSubmit(form){
    var data = $(form).serialize(),
        url = $(form).attr('action');

      $(form).css('opacity', 0.5);

    $.ajax({
      type  : "POST",
      /* cache : false, */
      url   : url,
      data  : data,
      dataType : 'html',
      success: function(data) {
        $('#stayInformedBox form').remove();
        $('.thankYouMsg').removeClass('hideTY');
        $('#stayInformedBox').append(data); 
        }
    });
    return false;
}
/* $('form').bind('submit', function() {
  return false;
}); */

function overVal(){
  if(jQuery.fn.validate) {
    $('#stayInformedFormBox').find('form').validate({ 
      submitHandler : newsletterSubmit });
  }
}  


function initFancyboxNewsletter(){
  /* Stay Informed Newsletter Form Submit */
  $("li#newsletterBtn a").fancybox({
    'hideOnContentClick' : false,
    'showCloseButton' : true,
    'enableEscapeButton' : true,
    'type' : 'ajax',
    'overlayColor' : '#000',
    'overlayOpacity' : '0.8',
    'onComplete' : overVal
    /* function() {
    $('#stayInformedFormBox').find('form').validate({ submitHandler : newsletterSubmit });
      $('#stayInformedFormBox form').validate({ submitHandler : newsletterSubmit });
    } */
  });
}


/* Pagination on multiple pages */
function pagez(e, w, n, c) {
  var $group = $(e+'>*'),
      pageCount = Math.ceil($group.length / n);
  for(var i = 0; i < $group.length; i+=n) {
    $group.slice(i, i+n).wrapAll('<'+w+' class="'+c+'" />');
  }
}

function initPaginateSetOfItems(){
  // (where we find the set of items, what we wrap them with, how many we're grabbing, class of wrapper)
  pagez('div.resultsCycle','ul',5,'');
  pagez('div.pressCycle','div',4,'pressBox');
  pagez('div.instructionsCycle', 'ul', 6, 'instructionsBox');

  // class to remove margin on every 3rd (last) thumbnail in the set
  $(".instructionsPg ul.instructionsBox li:nth-child(3n)").addClass('last'); 

}

/* Collections Options Specs Box*/
function initSpecsTooltip(){
  $('.specsTrigger a').click(function(){
    var $boxOspecs = $(this).parents('span').siblings('div#specsBox');
    if ($(this).hasClass('specsOpen')){
      $(this).removeClass('specsOpen');
      $boxOspecs.stop().fadeTo(500, 0);
      $('#swf_protect').stop().fadeTo(100, 0, function(){
        $(this).remove();
      });
    } 
    else {
      $(this).addClass('specsOpen');
      $boxOspecs.stop().fadeTo(500, 1).after('<div id="swf_protect" />');
      $('#swf_protect').stop().fadeTo(100, 0.75);
    }
    return false;
  });
  $('a.closeSpecs').click(function(){
    $(this).parents('div#specsBox').stop().fadeTo(500, 0);
    $('#swf_protect').stop().fadeTo(100, 0, function(){
      $(this).remove();
    });
    return false;
  }); 
}

function initOptionsGalleryCycle(){
  var cycleOpts = {
    speed : '200',
    timeout : 0,
    fx: 'fade',
    pager: '.optThumbNav',
    allowPagerClickBubble: true,
    pagerEvent: 'mouseover',
    /* pagerAnchorBuilder: function(idx, slide) {
          return '<li><a id="thumb_'+ slide.id +'" href="#" class="'+ slide.id +'"><img src="' + jQuery(slide).find('img').attr('src') + '" height="40" width="40" /></a></li>'; */
  pagerAnchorBuilder: function(idx, slide) { 
    return '.optThumbNav li:eq(' + idx + ') a';
    }
  }

  $.fn.cycle.updateActivePagerLink = function(pager, currSlideIndex) { 
    $(pager).find('li').animate({'opacity' : .9}).filter('li:eq('+currSlideIndex+')').animate({'opacity' : 1}, 'fast');
    $(pager).find('li').removeClass('activeSlide').filter('li:eq('+currSlideIndex+')').addClass('activeSlide');
  };
  // Inject pager and initialize cycle
  $('.optGalleryImg').cycle(cycleOpts);


  // Setup the gallery links to find their page based on their class attr
  $('.optThumbNav li').children('a').each(function(){
      var $thumbID = $(this).attr('id');
      var $slideIDforLink = $(this).attr('class');

      $('#'+ $thumbID).click(function(){
        $.post('/styles.php?q=' + $slideIDforLink); 
    return false;
      });
  });

  $(".optThumbNav li:nth-child(3n)").addClass('last'); 
}

//function initSwfObjectTaconite(){
//  var flashvars = {},
//          params = {},
//          attributes = {};
//  flashvars.url = movieUrl;
//  params.quality = "high";
//  params.scale = "exactfit";
//  params.wmode = "transparent";
//  params.bgcolor = "#000000";
//  params.allowfullscreen = "false";
//  /* params.allowscriptaccess = "sameDomain"; */
//  attributes.id = "flashBox";
//  attributes.name = "clerc-demo-glow";
//  swfobject.embedSWF("/lib/flash/clerc-demo-glow.swf", "alternateContent", "578", "578", "9.0.0", "lib/flash/expressInstall.swf", flashvars, params, attributes);
//}

// In the Collections Pages: The set of links that you click to see ie different watch straps
function setupStyleLinks(){

  $('.viewingControls li').children('a').each(function(){
      var $styleID = $(this).attr('id');
      var $idforLink = $(this).attr('class');

       $('#'+ $styleID).click(function(){
        $.post('/styles.php?q=' + $idforLink); 
          return false;
      });
  });

}

// Customizing taconite content replacement by adding fade in. 
// Used on the collections - options pages where you click to navigate in the thumbnail gallery
$.fn.replaceAndFadeIn = function(newContentElements) { 
    return this.each(function() { 
        // for each matching element, remove the current contents, hide the element, 
        // append the new contents and then fadeIn the element 
        $(this).empty().hide().append(newContentElements).fadeIn('fast'); 

      $('.cycleBox').cycle({
        timeout: 3000
      });
    initSpecsTooltip();
    setupStyleLinks();
    });
};

/* Pagination Cycle */
function initSearchResultsPager(){
  var resultsOpts = {
    speed : '100',
    timeout : 0,
    fx: 'fade',
    pager: '.pagination ul',
    nowrap:  1,
    pagerAnchorBuilder: function(idx, slide) {
        return '<li><a href="#">'+ (idx + 1) +'</a></li>'; 
      }
  }
  // Find uls in each each resultsBox
  var resultsGroup = $('.resultsCycle' ).children('ul');
  // Check to see if there are multiple ul then insert controls and start cycle
  if (resultsGroup.length > 1) {
    $('.resultsCycle').parent('#resultsBox').after('<div class="pagination"><span>Page</span><ul>');
    $('.resultsCycle').cycle(resultsOpts);
  } else {
    return false;
  }
}

/* Heritage Page */
function initFlipCycle(){
  
  var timeoutCallback2 = function(){ return Math.floor(4000 + Math.random()*3000)}  // randomize timeout
  
  function onBefore(startingSlide, currSlide, nextSlide, opts) {
    $(currSlide).addClass('activeImg');
  }
  
  /*
function onAfter(currSlide, nextSlide, opts){
    var nextImg = $.fn.cycle.nextSlide;
        $(this).flip({
        speed: 350,
            direction:'lr',
        color: '#000',
            content: nextImg
        });
  
    $(currSlide).removeClass('activeImg');
  }
*/

  $('.flipCycleBox').each(function(){
    $(this).cycle({
      timeout: 3500,
      speed: 1200,
      delay: -3500,
      before: onBefore,
      timeoutFn: timeoutCallback2
    });
    
    $(this).hover(function(){
      $('.flipCycleBox').cycle('pause').css({'overflow':'visible'});
    }, function () {
      $('.flipCycleBox').cycle('resume');
    });
  });
}


/* Innovation Page */
function initInnovationCycle(){
    
  var timeoutCallback = function() {return Math.floor(3500 + Math.random()*6000)}  // randomize timeout
  $('.innovCycleBox').cycle({
    timeout: 3000,
    speed: 2000,
    delay: -2000,
    timeoutFn: timeoutCallback
  });
  $('.innovCycleBox').each(function(){
    $(this).hover(function(){
      $(this).cycle('pause');
    }, function () {
      $(this).cycle('resume');
    });
  });
}

/* Press Page */
function initFancyboxPress() {
  $("li.imgPR a").fancybox({
    'hideOnContentClick' : false,
    'showCloseButton' : true,
    'enableEscapeButton' : true,
    'type' : 'ajax',
    'overlayColor' : '#000',
    'overlayOpacity' : '0.8'
  });
}

function initPressInstructionsCycle(){
  var cycleOpts = {
    speed : '100',
    timeout : 0,
    fx: 'fade',
    pager: '.pagination ul',
    nowrap:  1,
    pagerAnchorBuilder: function(idx, slide) {
        return '<li><a href="#">'+ (idx + 1) +'</a></li>'; 
      }
  }
  // Find uls in each each resultsBox
  var pressGroup = $('#pressPg .pressCycle').children('div.pressBox');
  var instructionsGroup = $('.instructionsPg .instructionsCycle').children('ul.instructionsBox');


  // Check to see if there are multiple ul then insert controls and start cycle
  if (pressGroup.length > 1) {
    $('#pressPg div.pressCycle').after('<div class="pagination"><span>Page</span><ul>').cycle(cycleOpts);
    /* $('#pressPg div.pressCycle').cycle(cycleOpts); */
  } else if (instructionsGroup.length > 1) {
    $('div.instructionsCycle').after('<div class="pagination"><span>Page</span><ul>').cycle(cycleOpts);
  } else {
    return false;
  }
}

/* Generic Cycle Cue */
function initCycle(){
  $('.cycleBox').cycle();
}

function initScrollbars(e){
  this.e = e;
  var inner = $(this.e).find('.innerBox').outerHeight(),
      outer = $(this.e).find('.viewport').height();
  if (inner > outer) {
    setTimeout(function(){
      $(this.e).tinyscrollbar({
        sizethumb: 63
      });
      $(this.e+' .thumb').css({'height':63});  
    }, 1000);
  } else {
    $(this.e).find('.scrollbar').remove().end().parent().css('background', 'transparent');
  }
}



/* Document Ready */
$(document).ready(function(){ 

  /* Vertically Align Homepage Caption */
  $('.caption p').vAlign();

  // Discovery Innovation Page
  $('#zoomerBox div, #flipBox .flipCycleBox').Zoomer({
    speedView:200,
    speedRemove:100,
    altAnim:false,
    debug:false
  });

  
  // Add class to first paragraph in #secondContent .infoBox (to add bg img)
  $('.infoBox p:first-child').addClass('first');

  // Add class to last li in navigation (to remove bg line img)
  $('#primeNav li:last-child').addClass('last');
  $('#primeNav .nav li:first-child').addClass('first');

  $('#collections>ul>li>a').click(function(){
  return false;
  });
  setupExternalLinks();
  initOverlabelValidate();  
  
  
  initFormDropDown();
  
  
  initPrimeNavAnimation();
  initFancyboxNewsletter();
  initPaginateSetOfItems() // make sure this happens before cycle
  initSpecsTooltip();
  initOptionsGalleryCycle()
  setupStyleLinks(); // the list of links on the product pg that change the style of the watch ie: strap/bracelet
  initSearchResultsPager();
  initFlipCycle();
  initInnovationCycle();
  initFancyboxPress();
  initPressInstructionsCycle();
  initCycle();
  
  if ($('.scrollBox').length) {
    initScrollbars('.scrollBox');
  }
  
  



});
