/* common.js */

//slideshow
$(function() {
 $( '#slideshow' ).css( { margin:0 } );
 $( '#slideshow a' ).each( function() { $( this ).css( { 'visibility':'visible' } ) } );
 $( '#slideshow a.load' ).each( function() {
    var innersrc = $( this ).attr( 'rel' );
    var inneralt = $( this ).attr( 'rev' );
    var ihtml = '<img src="' + innersrc + '" alt="' + inneralt + '" width="534" height="274" />';
    $( this ).html( ihtml );
 } );
	var startSlide = Math.floor( Math.random() * 6 );
 $('#slideshow').cycle({
		 timeout:       3000,
		 delay:         1,
   speed:         500,
		 prev:          '#prev',
   next:          '#next',
		 before:        onBefore,
		 pager:         '#nav',
   pagerEvent:    'mouseover',
   fastOnEvent:   true,
   pause:         1,
   random:        0 /*,  no random start for the month of december
   startingSlide: startSlide */
	});
    function onBefore() {
        $('#title').html(this.alt);
    }
});

$('#pauseButton').click(function() {
    $('#slideshow').cycle('pause');
});
$('#resumeButton').click(function() {
    $('#slideshow').cycle('resume', true);
});

//stand-alone trim functions
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,'');
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,'');
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,'');
}

//validate email address
function emailAddr_Test( emailAddr, alertTxt ){
  var email_regex = new RegExp( '^[a-zA-Z0-9_+\-.]+@[a-zA-Z0-9_+\-.]+[.][a-zA-Z]{2,4}$' );
  with( emailAddr ){
   if( ! email_regex.test( trim( emailAddr ) ) ){
    alert( alertTxt );
    return false;
   }
   else {
   return true;
   }
  }
 }

function getKudos(){
 //do not run Kudos for IE6 users
 if ( /msie\s6/.test( navigator.userAgent.toLowerCase() ) ) { return false; }

 //send height info to ajax kudo handler
 heightInfo = {};
 heightInfo[ "CONTAINER" ] = $( '#container' ).height();

 var altHeight = parseInt( $( 'input[name=CONTAINERHEIGHT]' ).val() );

 if ( altHeight > 0 ) { heightInfo[ "CONTAINER" ] = altHeight; }

 heightInfo[ "NAVBAR" ] = $( '.navBar:first' ).height();

 $.post( '/ajax/kudoH.cfm', heightInfo, kudosReady, 'json' );
}

function kudosReady( kudoData ){
 $( '#kudos' ).html( kudoData['TEXT'] );
}

var parseID = function( idToParse ) {
//var uPos = $.inArray( '_', idToParse );  this jquery function did not work in IE 8
var uPos = idToParse.indexOf( '_' );
 if( uPos > 0 ){
  return idToParse.substr( 0, uPos );
 }
 else { return; }
}

var toggleContainer = function( toggleOptID ) {
 //alert( 'toi = ' + toggleOptID );
 var moreImg = 'more.gif';
 var hideImg = 'hide.gif';
 if ( $( '#' + toggleOptID + '_moreHide' ).attr( 'class' ).match( /recommended/ ) ) {
    moreImg = 'recommended_show.gif';
    hideImg = 'recommended_hide.gif';
 }
 $( '#' + toggleOptID + '_container' ).slideToggle( 'slow' );
  if ( $( '#' + toggleOptID + '_moreHide' ) ){
   var src = ( $( '#' + toggleOptID + '_moreHide' ).attr( 'src' ) === '/images/zz_images/' + moreImg ) ? '/images/zz_images/' + hideImg : '/images/zz_images/' + moreImg ;
   $( '#' + toggleOptID + '_moreHide' ).attr( 'src', src );
  }
}

var toggleBasicContainer = function( toggleOptID ) {
 $( '#' + toggleOptID + '_container' ).slideToggle( 'slow' );
}

var keyup_delay = (function(){
 var timer = 0;
 return function(callback, ms){
 clearTimeout (timer);
 timer = setTimeout(callback, ms);
 };
})();

/* Favor Pack colorbox link */
function fpStyles( el ) {
   var fpHref = $( el ).attr( 'rel' );
   var fp = $( el ).attr( 'id' ).split( '_' )[0];
   var fpQty = $( '#' + fp + '_sel' ).val();
   var Qty = 'QUANTITY=' + fpQty;
   var fpStylesURL = fpHref + '&' + Qty;
   $( el ).colorbox( { width:910, innerHeight:470, iframe:true, overlayClose:false, href: fpStylesURL } );
}

function qtySelectHTML( data ){
   $( '#'+ data["ID"] ).html( data["HTML"] );
}

function postShare( refURL, type, section ) {
   //audit share item clicks
   $.post( '/ajax/shareH.cfm', { REFURL: refURL, TYPE: type, SECTION: section } );
}
function postShareGT( data ) {
   //callback function from google plus one - catalog top
   if( data && data["state"] == 'on' ) {
    $.post( '/ajax/shareH.cfm', { REFURL: data["href"], TYPE: 'G', SECTION: 'T' } );
   }
}
function postShareGS( data ) {
   //callback function from google plus one - side nav
   if( data && data["state"] == 'on' ) {
    $.post( '/ajax/shareH.cfm', { REFURL: data["href"], TYPE: 'G', SECTION: 'S' } );
   }
}
/* put all onloads here */
$(document).ready( function() {
     //alert( 'mode = ' + document.compatMode );
     var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
     var is_ff2 = /firefox\/2/.test( navigator.userAgent.toLowerCase() );
     var is_ie6 = /msie\s6/.test( navigator.userAgent.toLowerCase() );

     if( is_ff2 ) { $( '#container' ).css( { 'clear': 'both' } ); }

     if ( ! is_ie6 ) { $( '.dropShadow' ).dropShadow(); }

     $( '.newWin' ).click( function() {
        window.open( $( this ).val() );
     });
     $( '#thawte' ).colorbox( { iframe:true, innerWidth:720, innerHeight:600, href:"/support/privacy.htm" } );
     $('#BBB2').hover(function(){$(this).css({"backgroundPosition":"-100px 0px"});},function(){$(this).css({"backgroundPosition":"0px 0px"});});

     $( '.colorBox' ).colorbox();
     $( '.colorBoxIframe' ).colorbox( {width:"40%", height:"80%", iframe:true} );
     $( '.colorBoxLink' ).colorbox( {iframe:true, innerWidth:720, innerHeight:600} );
     $( '.colorBoxTall' ).colorbox( {iframe:true, innerWidth:720, innerHeight:700} );
     $( '.colorBoxMed' ).colorbox( {iframe:true, innerWidth:550, innerHeight:600} );
     $( '.colorBoxSmall' ).colorbox( {iframe:true, innerWidth:450, innerHeight:550} );
     $( '.colorBoxTiny' ).colorbox( {iframe:true, innerWidth:350, innerHeight:350} );
     $( '.colorBoxThin' ).colorbox( {iframe:true, innerWidth:350, innerHeight:600} );
     $( '.colorBoxStaff' ).colorbox( {iframe:true, innerWidth:700, innerHeight:355} );
     $( '.colorBoxStaffMed' ).colorbox( {iframe:true, innerWidth:800, innerHeight:450} );
     $( '.colorBoxStaffMedTall' ).colorbox( {iframe:true, innerWidth:800, innerHeight:510} );
     $( '.colorBoxStaffLarge' ).colorbox( {iframe:true, innerWidth:900, innerHeight:560} );
     $( '.colorBoxShapes' ).colorbox( {iframe:true, innerWidth:740, innerHeight:600} );
     $( '.colorBoxFavorPack' ).colorbox( {iframe:true, width:910, innerHeight:470, overlayClose:false} );
     //$( '.boxPreview' ).colorbox( { onOpen:function() { $( '#cboxLoadedContent' ).css( { 'margin-bottom':'1px' } ); }, width:910, innerHeight:470, iframe:true } );
     // onOpen, onLoad, and onComplete didn't seem to do anything here.
     $( '.boxPreview' ).colorbox( { width:910, innerHeight:470, iframe:true, overlayClose:false, scrolling:false } );
     //$( '.boxPreview' ).colorbox( { width:910, innerHeight:470, iframe:true, overlayClose:false } );
     $( '.tooltip' ).tooltip( {
	               delay: 0,
	             showURL: false,
	         bodyHandler: function() { return $($(this).attr("href")).html(); }
     });

     $( '.ttip' ).tooltip( { delay: 0, showURL: false } );

     $( '.trigger' ).click( function(){
        var optID = parseID( $( this ).attr( 'id' ) );
        toggleContainer( optID );
     });
     $( '.basicTrigger' ).click( function(){
        var optID = parseID( $( this ).attr( 'id' ) );
        toggleBasicContainer( optID );
     });

     /* side menus and top menus are very similar - they could be combined into one function */

       /* top menus */
      $( '.mainNav' ).children()
                     .addClass( 'menuColor' )
                     .hover(
         //hover on
         function() {
           var p = $( this ).position();
           var h = $( this ).height();
           var y = p.top + h;
           var c = 0;

           $( this ).addClass( 'menuHover' )   //.corners( 'top' ) - corners does not work well with IE
                    .find( 'ul:first' )
                    .css( { 'left': p.left + 'px', 'top': y  + 'px', 'display': 'block' } )
                    .find( 'ul' )
                    .each( function() { c += 1; });

           //if this is a single column menu, add the singleCol class to it.
           if ( c == 0 || is_ie6 ) { $( this ).addClass( 'singleCol' ); }

           $( this ).children().css( { 'padding-bottom': '6px' } );

         },

         //hover out
         function() {
           $( this ).removeClass( 'menuHover' ).find( 'ul:first' ).css( { 'display': 'none' } );
         }
      );

      $( '.separator' ).unbind();

      /* side menus */
      $( '.navBar').children()
            .addClass( 'menuColor' )
            .hover(
            //hover on
            function() {
            
            var p = $( this ).position();
            var h = $( this ).height();
            var w = $( this ).width();
            var y = p.top;
            var x = p.left + w;
            var c = 0;
            
            $( this ).addClass( 'menuHover' )
                    .find( 'ul:first' )
                    .css( { 'left': x + 'px', 'top': y  + 'px', 'display': 'block' } )
                    .find( 'ul' )
                    .each( function() { 
                       c += 1; 
                       $( this ).find( 'li:first' ).css( { 'padding-top': '6px' } ); 
                       $( this ).find( 'li:last' ).css( { 'padding-bottom': '6px' } ); 
                    } );
            
            if ( c == 0 || is_ie6 ) { 
               $( this ).addClass( 'singleColNavBar' );
               $( this ).find( 'li:first' ).css( { 'padding-top': '6px' } );
               $( this ).find( 'li:last' ).css( { 'padding-bottom': '6px' } );
               }
            else {
               var ulWidth = ( c * 205 ) + 'px';
               $( this ).find( 'ul:first' ).css( { 'width': ulWidth } );
            }
            
            
            var that = $( this ).find( 'ul:first' );
            var tH = parseInt( $( that ).height() );
            var tT = parseInt( $( that ).offset().top );
            var wH = parseInt( $( window ).height() );

            if ( ( tH + tT ) > wH ) {
               //the first time it draws tH is 6 pixels less than every time after.
               //alert( 'y = ' + y + '\ntH = ' + tH + '\nh = ' + h );
               //redraw the menu upside down
               $( that ).css( { 'top': ( y - tH + h ) + 'px' } );
            }
            
            },
            //hover out
            function() {
            
            $( this ).removeClass( 'menuHover' ).find( 'ul:first' ).css( { 'display': 'none' } );
      
      });
      
       
     $('.countChars').keyup(function(){
        var txtField = $(this).attr('id');
        if ( $( this ).is( 'textarea' ) ) {
           var maxLen = parseInt( $( this ).attr( 'title' ).match( /[0-9]+/ ) );
           $('#'+ txtField +'_counter').html($(this).val().length + ' of ' + maxLen + ' characters.');
        } else {
           $('#'+ txtField +'_counter').html($(this).val().length + ' of ' + $(this).attr('maxlength') + ' characters');
        }
     });

     $('#cartLink').hover(
       function() {
          //mouseover function
          var p = $( this ).offset();
          var w = $( '#miniCart' ).width(); /* doesn't have a width yet */
          w = 200;
          //determine right edge of #container, if p.left + w / 2 > right, shift the minicart leftward

          var h = $( this ).height();
          $( '#miniCart' ).css( {  'display': 'block', 'visibility': 'visible', 'left': ( p.left - w / 2 ) + 'px', 'top': ( p.top + h ) + 'px' } ).hover(
             function() { $( this ).show(); },
             function() { $( this ).hide(); }
          );
       },
       function() {
          $( '#miniCart' ).hide();
      });

     if( jQuery.support.opacity )( $( '.pGrid li p.box' ).corners( 'top' ) );

     /*Shapes and Sizes*/
       $( '.shapeType' ).click( function() {
        var selClass = $( this ).attr( 'rel' );
        $( '.shapeType' ).each( function() {
         $( this ).css( 'text-decoration', 'none' );
        });
        $( this ).css( 'text-decoration', 'underline' );
        $( '.shapeSelection' ).each( function() {
         if( $( this ).attr( 'id' ) == selClass ) { $( this ).css( 'display', 'inline-block' ); }
         else { $( this ).css( 'display', 'none' ); }
        });
       });

       $( '.shapeSelection' ).css( 'display', 'none' );
       $( '#L' ).css( 'display', 'inline-block' );
       $( '.shapeType[rel=L]' ).css( 'text-decoration', 'underline' );
       
       
       var lastQuery = $( '#query' ).val();
       /* search */
       $( '#query' ).focus( function() {
       	  //focus
       	  var presentVal = $( '#query' ).val();
       	  //if ( presentVal == lastQuery ) {
       	  if ( presentVal.toLowerCase() == 'enter your search' ) {
       	  	  $( this ).val( '' ); 
       	  } else { 
       	  	  //show/hide the search button
       	  	  presentVal === '' ? $( '#searchSubmit' ).css( { 'display':'none' } ) : $( '#searchSubmit' ).css( { 'display':'block' } );
       	  }
       	  $( this ).parent().addClass( 'focus' );
       	  $( '#searchForm' ).unbind( 'mouseenter mouseleave' );
       	  //end focus
       }).blur( function() {
       	  //blur
          var presentVal = $( '#query' ).val();
          $( this ).parent().removeClass( 'focus' );
          if( presentVal === '' ) {
             $( this ).val( lastQuery );
          }
          setTimeout( function() { $( '#searchSubmit' ).removeClass( 'active' ).attr( 'disabled', 'disabled' ) }, 200 ); //hide later
          $( '#searchForm' ).hover(
			          function() { 
			             if ( ( $( '#query' ).val() != lastQuery )  && ! ( $( '#query' ).val() === '' ) ) {
			                $( '#searchSubmit' ).addClass( 'active' ).removeAttr( 'disabled' );
			             }   
			          },
			          function() {
			             setTimeout( function() { $( '#searchSubmit' ).removeClass( 'active' ).attr( 'disabled', 'disabled' ) }, 200 ); //hide later
			          }
          );
          //end blur
       }).keyup( function() {
       	  //keyup
          $( '#query' ).val() === '' ? $( '#searchSubmit' ).removeClass( 'active' ).attr( 'disabled', 'disabled' ) : $( '#searchSubmit' ).addClass( 'active' ).removeAttr( 'disabled' );
          //end keyup
       });
});


