$(document).ready(function() {
  $("div.warning").fadeIn(2000).animate({opacity: 1.0}, 3000).fadeOut(1000, function() { $(this).remove(); } ); 
	$(".fadeIn").hide().fadeIn(1500);
	$(".fadeInSlow").hide().fadeIn(2500);

  $("div.round").corner("6px");

// --------------------------------------------------------
// Product Finder
// --------------------------------------------------------

$("#tabs").tabs();

// mins
var minL = $("#minL").attr("value");
var minW = $("#minW").attr("value");
var minD = $("#minD").attr("value");
// max
var maxL = $("#maxL").attr("value");
var maxW = $("#maxW").attr("value");
var maxD = $("#maxD").attr("value");

$('#findProducts').click(function(){
  var l = $('#fld_l').attr('value');
  var w = $('#fld_w').attr('value');
  var d = $('#fld_d').attr('value');
  $('#productResults').load("/pub/product_finder.php?l=" + l + '&w=' + w + '&d=' + d);
  $('.prodCatLinkWrapper').fadeIn();
  $('#prodCatWrapper').hide();
  return false;
});

$('#findProductRange').click(function(){
  var l = $('#sliderLVal').attr('value');
  var w = $('#sliderWVal').attr('value');
  var d = $('#sliderDVal').attr('value');
  // clean up data
  l = l.replace(/\s+/g,'');
  w = w.replace(/\s+/g,'');
  d = d.replace(/\s+/g,'');

  $('#productResults').load("/pub/product_finder.php?l=" + l + '&w=' + w + '&d=' + d);
  $('.prodCatLinkWrapper').fadeIn();
  $('#prodCatWrapper').hide();
  return false;
});

$('.prodCatLinkWrapper').hide().click(function(){
  $(this).fadeOut();
  $('#prodCatWrapper').fadeIn();
  $('#productResults').html('');
});

// setup master volume
$("#sliderL").slider({
      animate:true,
			range: true,
			min: (minL - 0.001),
			max: (maxL + 1),
			values: [minL, maxL],
			step: 0.125,
			slide: function( event, ui ) {
				$("#sliderLVal").val(ui.values[ 0 ] + " - " + ui.values[ 1 ] );
			}
});

$("#sliderW").slider({
      animate:true,
			range: true,
			min: (minW - 0.001),
			max: (maxW + 1),
			values: [minW, maxW],
			step: 0.125,
			slide: function( event, ui ) {
				$("#sliderWVal").val(ui.values[ 0 ] + " - " + ui.values[ 1 ] );
			}
});

$("#sliderD").slider({
      animate:true,
			range: true,
			min: (minD - 0.001),
			max: (maxD + 1),
			values: [minD, maxD],
			step: 0.125,
			slide: function( event, ui ) {
				$("#sliderDVal").val(ui.values[ 0 ] + " - " + ui.values[ 1 ] );
			}
});


$( "#sliderLVal" ).val($("#sliderL").slider( "values", 0 ) + " - " + $( "#sliderL" ).slider("values",1));
$( "#sliderWVal" ).val($("#sliderW").slider( "values", 0 ) + " - " + $( "#sliderW" ).slider("values",1));
$( "#sliderDVal" ).val($("#sliderD").slider( "values", 0 ) + " - " + $( "#sliderD" ).slider("values",1));



// --------------------------------------------------------
// Form Validation
// --------------------------------------------------------
    var options = { 
        target:        '#results'   // target element(s) to be updated with server response 
    }; 
  
  // validate form
  $(".validateMe").validate({
     submitHandler: function(form) {
        $(".form_wrapper").hide();
        $(form).ajaxSubmit(options);
     }
  });

// --------------------------------------------------------
// Auto complete
// --------------------------------------------------------
  var options, a;
  options = { serviceUrl:'/pub/autocomplete.php' };
  a = $('#fld_query').autocomplete(options);

// --------------------------------------------------------
// Forgot password reset
// --------------------------------------------------------

  $.fn.finishAjax = function(id, response){
  $('#usernameLoading').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
}

	$('#usernameLoading').hide();
	$('#fld_email_work').blur(function(){
	  $('#usernameLoading').show();
      $.post("/pub/check_email.php", {
        email: $('#fld_email_work').attr('value')
      }, function(response){
        $('#usernameResult').fadeOut();
        setTimeout("$(this).finishAjax('usernameResult', '"+escape(response)+"')", 600);
      });
    	return false;
	});

// --------------------------------------------------------
// Slide Show
// --------------------------------------------------------

// set container width
var pagerCount = $('#slideshow').attr("count");  
var pagerDivWidth = (pagerCount * 26);
$("#pager").width(pagerDivWidth);

//    $('#slideshow').after('<div id="pager">').cycle({
    $('#slideshow').after('').cycle({
      speed:5000,
      speedIn:500,
      speedOut:1000,
      timeout:2000,
      prev:   '#prev', 
      next:   '#next',      
      pager: '#pager',
      fastOnEvent: true,      
      sync: 1,
      delay:1000,
      // callback fn that creates a thumbnail to use as pager anchor 
      pagerAnchorBuilder: function(idx, slide) { 
        var imgalt = $(slide).children().eq(0).attr("alt");
        if (imgalt == null ) { imgalt = slide.alt; }
        return '<div id="banner_0' + idx + '" class="pager_box"><a href="#"><img src="/img/raven/pager_box.png" width="78" height="25" /></a></div>'; 
      }
      //after: onAfter
    }); 


  $('#slideshow_interior').cycle({
      speedIn:2500,
      speedOut:1500,
      sync: 1,
      delay:-1000
    });    

//	$("#stage_content_wide").fadeIn(900).animate({opacity: 1.0}, 2);
// { fx: 'scrollHorz', timeout:  2000, autostop: 1, end: function() { alert('The slideshow has ended.'); } }  
  
  $('#toggle').click(function(){
   $('div.showhide').slideToggle();
  });
  

/*
  $("[title]").mbTooltip({          // also $([domElement])..mbTooltip  >>  in this case only children element are involved
    opacity : .97,                  //opacity
    wait:1200,                      //before show
    cssClass:"default",             // default = default
    timePerWord:70,                 //time to show in milliseconds per word
    hasArrow:true,			            // if you whant a little arrow on the corner
    imgPath:"/img/tooltips/",
    ancor:"mouse",                  //"parent"  you can ancor the tooltip to the mouse position or at the bottom of the element
    shadowColor:"black"             //the color of the shadow
  });
*/  

  // contact form
  $('#form_contact').ajaxForm(function(data) {
    if (data==1){
      $('#success').fadeIn("slow");
      $('#form_contact').resetForm();
    } else {
      $('#errormsg').html(data).fadeIn("slow");
    }
  });
  

// --------------------------------------------------------
// country/state chain (contact form)
// --------------------------------------------------------

  var country = $('#fld_country');
  var state_txt = $('#fld_state_txt');
  var state_pd = $('#fld_state_pd');
  var zip_txt = $('#fld_zip');
  var phone_txt = $("#fld_phone");

  // note that we're assigning in reverse order
  // to allow the chaining change trigger to work
  country.selectChain({
      target: $('#fld_state_pd'),
      url: '/pub/state_prov_pulldown_chain.php',
      type: 'post',
      data: { selectionAttVal: "test", ajax: true }

  }).trigger('change');

$(country).change(function() { 
  // defaults
  $(state_pd).hide();
  $(state_txt).show();
  $(state_pd).attr('disabled','true');
  $(state_txt).attr('disabled','');  
  $(state_txt).attr('value','');
  // remove required classes
  $('#fld_city').removeClass('required');
  
  // check for phone + address formatting requirements:
  if ((this.value != "United States") && (this.value != "Canada")) { 
    // no phone formatting rules needed.
    $(phone_txt).removeClass('phone');
    $(zip_txt).removeClass('required');
    $(zip_txt).removeClass('zip');
    $("#lbl_zip").replaceWith('<label for="fld_zip" id="lbl_zip">Postal Code:</label>');

    // remove required * from label
    $('#lbl_city').replaceWith('<label for="fld_city" id="lbl_city">City:</label>');
    $('#lbl_state').replaceWith('<label for="fld_state" id="lbl_state">State:</label>');

  } else {   
    // reset phone formatting rules.
    $(phone_txt).addClass('phone');
    $(zip_txt).addClass('required');
    $(zip_txt).addClass('zip');
    $("#lbl_zip").replaceWith('<label for="fld_zip" id="lbl_zip">* Zip:</label>');
    
    // add required * from label
    $('#lbl_city').replaceWith('<label for="fld_city" id="lbl_city">* City:</label>');
    $('#lbl_state').replaceWith('<label for="fld_state" id="lbl_state">* State:</label>');

  }
  
});


// display pulldown only if there are cities for the selected state
$(state_pd).change(function() {        

  if ($(state_pd).size()==1) { 

    $(state_pd).show();
    $(state_txt).hide();
    $(state_pd).attr('disabled','');
    $(state_txt).attr('disabled','true');
    // add required class
    $('#fld_city').addClass('required');
    $(zip_txt).addClass('required');
    // change labels
//    $('#lbl_city').replaceWith('<label for="fld_city" id="lbl_city">* City:</label>');
//    $('#lbl_state').replaceWith('<label for="fld_state" id="lbl_state">* State:</label>');
//    $('#lbl_zip').replaceWith('<label for="fld_zip" id="lbl_zip">* Zip:</label>');

  }
  
});

  

// --------------------------------------------------------
// Box Grid (Staff Listing Page)
// --------------------------------------------------------
  var currentTallest = 0,
     currentRowStart = 0,
     rowDivs = new Array(),
     $el,
     topPosition = 0;

 $('.blocks').each(function() {
  
   $el = $(this);
   topPostion = $el.position().top;

   if (currentRowStart != topPostion) {

     // we just came to a new row.  Set all the heights on the completed row
     for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
       rowDivs[currentDiv].height(currentTallest);
     }

     // set the variables for the new row
     rowDivs.length = 0; // empty the array
     currentRowStart = topPostion;
     currentTallest = $el.height();
     rowDivs.push($el);

   } else {

     // another div on the current row.  Add it to the list and check if it's taller
     rowDivs.push($el);
     currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);

  }

  // do the last row
   for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
     rowDivs[currentDiv].height(currentTallest);
   }

 });
 
});
