jQuery.noConflict();

jQuery(function(){
  jQuery('a[href*=#]').click(function() {
  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    && location.hostname == this.hostname) {        
      var jQuerytarget = jQuery(this.hash);
      jQuerytarget = jQuerytarget.length && jQuerytarget || jQuery('[name=' + this.hash.slice(1) +']');
      if (jQuerytarget.length) {
        var targetOffset = jQuerytarget.offset().top;
        jQuery('html,body').animate({scrollTop: targetOffset}, 1000);
        return false;
    }
    }
  });
});

jQuery(function() {
	jQuery('a[rel*=external]').click( function() {
		window.open(this.href);
		return false;
	});
});

jQuery.expr[':'].icontains = function(obj, index, meta, stack){
	return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
};

jQuery.fn.tabbinate = function() {
	var o = jQuery(this[0])
	var first = false;
	o.children("li").each(function() {
		jQuery("#"+jQuery(this).attr("id")+"-box").hide();
		if ( !first ) {
			first = true;
			jQuery(this).tabbinateChange();
		}
		jQuery(this).click(function() { jQuery(this).tabbinateChange() });
	});
};

jQuery.fn.tabbinateChange = function() {
	if ( !jQuery(this[0]).hasClass("not-allow") ) {
		jQuery(".tabbinate-active").removeClass("tabbinate-active");
		jQuery(".tabbinate-active-box").hide().removeClass("tabbinate-active-box");
	
		jQuery(this[0]).addClass("tabbinate-active");
		activeBox = jQuery(".tabbinate-active").attr("id");
		jQuery("#"+activeBox+"-box").show().addClass("tabbinate-active-box");
	}
};

function tabbinateChange(obj) {
	jQuery(obj).tabbinateChange();
}

function smoothTo(destination) {
	if (jQuery("a[name="+destination+"]").length) {
		elem = jQuery("a[name="+destination+"]");
		var targetOffset = (parseInt(elem.offset().top)-40)+"px";
		jQuery('html,body').animate({scrollTop: targetOffset}, 1000);
	}
}
jQuery.fn.reloadLightbox = function(resize) {
  dheight = parseInt(jQuery(window).height())-150;
  dwidth = dheight*(1+(1/3));

	if ( typeof resize !== 'undefined' && resize == true) 
	  jQuery(this).slimbox({imageFadeDuration:0, overlayFadeDuration:0, slideWidth: dwidth, slideHeight: dheight});
	else
    jQuery(this).slimbox({imageFadeDuration:0, overlayFadeDuration:0});
}

jQuery.fn.lightBox = function() { jQuery(this).reloadLightbox(true); }

jQuery.fn.restorable = function(){
  jQuery(this).each(function() {
  	jQuery(this).data("originalValue", jQuery(this).val());
  	jQuery(this).focus(function(){
  		if(jQuery(this).val() == jQuery(this).data("originalValue")){
  			jQuery(this).val("");
  		};
  	});
  	jQuery(this).blur(function(){
  		if(jQuery(this).val() == ""){
  			jQuery(this).val(jQuery(this).data("originalValue"));
  		}
  	});
  	return this;
  });
}

function badFixSelectBoxDataWidthIE() {
  if (jQuery.browser.msie) {
    jQuery('select').each(function() {
      if(jQuery(this).attr('multiple') == false) {
        jQuery(this).mousedown(function() {
            if(jQuery(this).css("width") != "auto") {
                var width = jQuery(this).width();
                jQuery(this).data("origWidth", jQuery(this).css("width")).css("width", "auto");

                // If the width is now less than before then undo
                if(jQuery(this).width() < width) {
                    jQuery(this).unbind('mousedown');
                    jQuery(this).css("width", jQuery(this).data("origWidth"));
                }
            }
        })

        // Handle blur if the user does not change the value
        .blur(function() {
            jQuery(this).css("width", jQuery(this).data("origWidth"));
        })

        // Handle change of the user does change the value
        .change(function() {
            jQuery(this).css("width", jQuery(this).data("origWidth"));
        });
      }
    });
  }
}


/*********************
 * PRODUCT PAGE
 *********************/	

function popImg(url) {
	jQuery("#product-main-img").attr('src',url);
}

function changeActiveTab(obj,linkid) {
	if (jQuery("#" + linkid).length > 0) {
		jQuery(".product-information-holder").children("li.active").removeClass("active");
		jQuery(obj).addClass("active");
		jQuery(".product-information-wrap").children("div.active").hide();
		jQuery("#" + linkid).show().addClass("active");
	}	
}

function fitModelResult(title,msg) {
	jQuery("#fit-my-model").children("h5").html(title);
	jQuery("#fit-my-model").children("p").html(msg);
}

function trim(str) {
    if(!str || typeof str != 'string')
        return null;
    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

/*********************
 * SHOP BY BRANDS PAGE
 *********************/	
 
 
function shopByBrandsSlider() {
  
  jQuery("ul.shopbyx-az-toolbar li a").unbind('click');
  jQuery("ul.shopbyx-az-toolbar li.active").click(function() {
    jQuery('ul.shopbyx-az-toolbar li.selected').removeClass('selected');
    letter = jQuery(this).attr('id');
    jQuery('.'+letter).addClass('selected');
    letter = letter.replace('letter-','');

    jQuery(".letter-group-active").hide().removeClass("letter-group-active");
    jQuery("#letter-group-"+letter).show().addClass("letter-group-active");
  });

  jQuery(".letter-group").hide();
  
  jQuery('ul.shopbyx-az-toolbar > #letter-a').addClass('selected');
  jQuery("#letter-group-a").show().addClass("letter-group-active");
 
}

/*********************
 * CATEGORY PAGE
 *********************/	

var autoselectFilter;

function ajaxLayeredNavigation() {
  jQuery(".layered-navigation-filter").unbind('click').click(function() {
    
    if (jQuery(this).hasClass('layered-navigation-filter-Category'))
      return false;
    
    jQuery("#catalog-data-wrapper").fadeTo(0, 0.3);
    jQuery("#catalog-loading").show();
    
    url = jQuery(this).attr('href');
    jQuery.post(
      url,
      { layout: "ajax" },
      function(data) {
        jQuery("#catalog-data-wrapper").replaceWith(data).fadeTo(0, 1); 
        jQuery("#catalog-loading").hide();
        ajaxLayeredNavigation();
      }
    );
    return false;
  });  
}

function ajaxLeftLayeredNavigation() {
  jQuery(".layered-navigation-filter").unbind('click').click(function() {
    
    jQuery(".col-main,.col-left").fadeTo(0, 0.3);
    jQuery("#catalog-loading").show();
    
    /*
    if (jQuery(this).hasClass('layered-navigation-filter-Category')) {
      window.location.href=jQuery(this).attr('href');    
      return true;
    } 
    */   
    
    url = jQuery(this).attr('href');
    jQuery.post(
      url,
      { layout: "ajax" },
      function(json) {
        jQuery("#search_mini_form").replaceWith(json.search);
        jQuery(".col-left").html(json.left).fadeTo(0,1);
        jQuery(".col-main").html(json.content).fadeTo(0, 1); 
        jQuery(".breadcrumbs").html(json.breadcrumbs);
        refreshCufon();
        
        jQuery("#catalog-loading").hide();
        jQuery('.search-as-type').restorable();
        ajaxLeftLayeredNavigation();
        startEndlessScroll();
        
      },
      'json'
    );
    return false;
  });  
}

function filter(element) {
  clearTimeout(autoselectFilter);
  var value = jQuery(element).val();
  var id = jQuery(element).attr('id');
  
  jQuery(element).parent().prev().attr('id','op_'+id);

  noresultsElem = jQuery('#'+'op_'+id).children('.filter-no-results-found');
  noresultsElem.hide();
  
  if (value == '') {
    jQuery('#'+'op_'+id+' li').show();
    noresultsElem.hide();
  } else {  
    jQuery('#'+'op_'+id+' a:not(:icontains(' + value + '))').parent().hide();
    jQuery('#'+'op_'+id+' a:icontains(' + value + ')').parent().show();
    
    numElements = jQuery('#'+'op_'+id+' li:visible').length;
    
    if ( numElements == 1) {
      autoselectFilter = setTimeout(function(){ jQuery('#'+'op_'+id+' a:visible').click() }, 1500); 
    } else if ( numElements == 0) {
       noresultsElem.show();
    } else if ( numElements <= 10) {
       
    } else {
      
    }
  }
}

function isScrolledIntoView(elem,threshold){
  if (jQuery(elem).length) {
    var docViewTop = jQuery(window).scrollTop();
    var docViewBottom = docViewTop + jQuery(window).height();
  
    var elemTop = jQuery(elem).offset().top+ threshold;
    var elemBottom = elemTop + jQuery(elem).height();
  
    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
  }
}

var endlessScrollinView = false;
var pageinView = '';
var currentPage = '1';
var currentItems = '';

function refreshDisableEndless() {

  jQuery(".disable-endless").unbind('click').toggle(function() {
    endlessScrollinView = true;
    jQuery(".disable-endless").html('Click here to enable this feature').addClass('no-endless');
  }, function() {
    endlessScrollinView = false; 
    jQuery(".disable-endless").html('Click here to disable this feature').removeClass('no-endless');
  });
  
}

function startEndlessScroll() {

  if ( jQuery(".pager-next-page").length ) {
    jQuery(".infinite-content").show().data('originalPosition', jQuery(".infinite-content").offset().top ).hide();
  }
  
  pageinView = jQuery(".endless-page-number");
  endlessScroll();
  
}

function endlessScroll() {

  jQuery(window).unbind('scroll').scroll(function() {
 
    if ( jQuery(window).scrollTop() >= jQuery(".infinite-content").data('originalPosition') ) {
      jQuery(".infinite-content").show().stop().animate({"top": (jQuery(window).scrollTop() + 30 - jQuery(".infinite-content").data('originalPosition')) + "px"}, "fast" );
      
      if ( !jQuery(".fix-pager-bottom").length ) {
        jQuery(".last-toolbar").clone().insertAfter(".first-toolbar").addClass('fix-pager-bottom').removeClass('last-toolbar');
        jQuery(".fix-pager-bottom").click(function() { return false; });
      } else if ( !jQuery(".fix-pager-bottom").is(":visible") )
        jQuery(".fix-pager-bottom").show();
    } else {
      jQuery(".fix-pager-bottom, .infinite-content, #pager-scroll-box").hide();
      currentPage = 1;
      pageinView = false;
    }
    
    if ( jQuery(window).scrollTop() >= jQuery(document).height()-1200 && jQuery(window).scrollTop() >= jQuery(".infinite-content").data('originalPosition') ) {
      jQuery(".fix-pager-bottom").hide();
    }
    
    // To aid performance, only do this every 200px scrolled.
    if ( Math.round(jQuery(window).scrollTop()/100)*100 % 200 !== 0)
      return true;   
      
    // Do this whenever the page moves more than X
    if ( !isScrolledIntoView(pageinView,500) ) {
      jQuery(".endless-page-number").each(function () {
        if( isScrolledIntoView(jQuery(this),500) ) {
          pageinView = jQuery(this);
          currentPage = jQuery(this).html();
          currentItems = jQuery(this).parent().parent().children(".endless-items-count").html();
          
          if ( jQuery(".fix-pager-bottom").length && jQuery("#toolbar-"+currentPage).length ) {
            jQuery(".fix-pager-bottom").html( jQuery("#toolbar-"+currentPage).html() );
          }          
          
          extrahtml = "<h2>Page "+currentPage+"</h2><h4>Your are currently viewing page "+currentPage+" in "+jQuery("h1").html()+"</h4><span>"+currentItems+"</span>";
          jQuery("#pager-scroll-box").html(extrahtml).show();
        }
      });
    }      

    // Do this only when it reaches the end of the products
    if (isScrolledIntoView('#end-of-results',-600) && !endlessScrollinView) {
    
      endlessScrollinView = true;      
      url = jQuery(".last-toolbar .pager-next-page").attr('href');
      
      if (url == undefined) {
        endlessScrollinView = true;
        return true;
      }
      
      json = false;   

      jQuery.post(
        url,
        {
          layout: "endlessscroll",
          limit:5
        },
        function(json){          
          jQuery(".last-toolbar").removeClass("last-toolbar").hide();
          
          lastElement = jQuery(".listing-type-grid").slice(-1);
          lastElement.after(json.results);
         
          nextItems = jQuery(".last-toolbar .pager tr:first td:first").html();
          nextPage = jQuery(".last-toolbar .pages .on").html();
          extrahtml = "<div class='neverending'><h4>Page <span class='endless-page-number'>"+nextPage+"</span></h4><span class='right'>The next page of results will continue to load as you scroll.</span><br class='clear'/><span class='left endless-items-count'>"+nextItems+"</span><span class='disable-endless right'>Click here to disable this feature</span></div><br class='clear' />";
          
          lastElement.after(extrahtml);
          
          if ( jQuery(".last-toolbar").attr('id') == '' && nextPage != '') {
            jQuery(".last-toolbar").attr('id','toolbar-'+nextPage);
            jQuery(".fix-pager-bottom").html( jQuery("#toolbar-"+currentPage).html() );
          }          

          endlessScrollinView = false;
          
          refreshDisableEndless();
          endlessScroll();
        },
        'json'
      );    

    }

  })
}

/*********************
 * SITEWIDE
 *********************/	  

function refreshCufon() {
  Cufon.replace(['.cufon-t','#nav > li.level0 > a']);  
}

jQuery(document).ready(function(){

	/*********************
	 * SITEWIDE
	 *********************/	  
	 
	 refreshCufon();
	 badFixSelectBoxDataWidthIE();
	 jQuery(".top-cart").click(function() {
	   window.location.href='/checkout/cart/' 
	 });

	/*********************
	 * HOMEPAGE
	 *********************/	  

	jQuery("#home-slider").easySlider({
		auto: true,
		continuous: true,
		controlsShow: false,
		speed: 800,
		pause: 5000
	});


	/*********************
	 * SHOP BY BRANDS
	 *********************/	  
	 
	 shopByBrandsSlider();

	/*********************
	 * CATEGORY PAGE
	 *********************/	
  
  //ajaxLeftLayeredNavigation();
  //startEndlessScroll();
  jQuery('.search-as-type').restorable();
  
	
	/*********************
	 * PRODUCT PAGE
	 *********************/	
	
  if(jQuery("#product-image-lightbox").length) {
     jQuery('#product-image-lightbox a[rel=lightbox]').lightBox();
     jQuery('#product-image-lightbox a[rel=lightbox_plus]').lightBox();
  }

	// Active tab tool
	if (jQuery(".product-information-wrap").length) {
		jQuery(".product-information-holder").children("li").click(function() {
			var linkid = trim(jQuery(this).text().toLowerCase()).replace(/[^a-z]/g,"-") + "-box";
			changeActiveTab(jQuery(this),linkid);
		});
	}
	
	// Image zoom tool
	if (jQuery("#product-main-img-container").length) {
		jQuery("#product-main-img-container").toggle(function(){
			jQuery("#product-main-img").css({'position':'absolute','z-index':'2'}); 
				}, function () {
			jQuery("#product-main-img").css({'position':'relative','z-index':'0'}); 
		});
	}
	
	// Fit my model search tool
	if (jQuery("#fit-my-model").length) {
		
		jQuery("#fit-my-model-input").focus( function() {
			if (jQuery("#list-fits_product").length) {
				changeActiveTab(jQuery("#fits-these-models-tab"), "fits-these-models-box");
			} else {			
				changeActiveTab(jQuery("#description-tab"), "description-box");
			}
		});
		
		jQuery("#fit-my-model-submit").click( function() {
			
			var modelNo = jQuery("#fit-my-model-input").val();
			
			// Check the fits these models first
			if (jQuery('#list-fits_product:icontains("'+modelNo+'")').length && modelNo.length ) {		
				changeActiveTab(jQuery("#fits-these-models-tab"), "fits-these-models-box");
				
				jQuery('#list-fits_product').removeHighlight().highlight(modelNo);
				fitModelResult("You're in business","It looks like the part will fit your "+modelNo+". <span onclick='productAddToCartForm.submit()'>Order this part now!</span>");
				
			} else {
				
				// If it doesn't exist, check the description
				if (jQuery('#description-box:icontains("'+modelNo+'")').length && modelNo.length ) {	
					jQuery('#description-box').find(".product-specs").removeHighlight().highlight(modelNo);
					changeActiveTab(jQuery("#description-tab"), "description-box");
					fitModelResult("You're in business","It looks like the part will fit your "+modelNo+". <span onclick='productAddToCartForm.submit()'>Order this part now!</span>");
				} else {
					// If nothing at all is found, give up
					fitModelResult("Oh no!","It doesn't look like the part fits, but this list is not comprehensive, please call to check!");
				}
				
			}
			return false;
		});
	}
	
	if (jQuery("#expand-tools").length) {
		jQuery("#expand-tools").toggle(function () {
			jQuery("#list-of-related-tools").css("overflow","visible");
			var imageSrc = jQuery(this).find("img").attr('src').replace("more","less");
			jQuery(this).find("img").attr('src',imageSrc)
		}, function() {
			jQuery("#list-of-related-tools").css("overflow","hidden");
			var imageSrc = jQuery(this).find("img").attr('src').replace("less","more");
			jQuery(this).find("img").attr('src',imageSrc)
		});
	}
	
	/*********************
	 * CHECKOUT
	 *********************/
		
  if (jQuery("#checkoutSteps-tabs").length) {	 	 
  	jQuery("#checkoutSteps-tabs").children("li").each(function() {
  		
  		var targetStep = (jQuery(this).attr("id")).replace("-tab","");
  		var targetSection = targetStep.replace("opc-","");
  		
  		jQuery(this).click(function() {
  			
  			if( !jQuery("#"+targetStep).hasClass("allow") ) {
  				if (!jQuery(this).hasClass("not-allow") ) { jQuery(this).addClass("not-allow") }
  			} else {
  				jQuery(this).removeClass("not-allow");
  				checkout.gotoSection(targetSection);
  			}
  			
  		});
  	});
  }
	
	if(jQuery('.advanced-search').length) {
	  
	  jQuery('#fits_product').after('<div id="fits_product_notice">Select one or several manufacturers...</div>');
	  jQuery('#product_manufacturers').change( function() { 
	      jQuery("#fits_product_notice").html(jQuery("#fits_product_notice_loading").html());
	      manufacturers = jQuery('#product_manufacturers').val();
	      if(manufacturers != null) {
  	      var html = jQuery.ajax({url: "/ajaxmodels", 
          async: false, type: "POST", 
          dataType:"html", 
          data: ({search_term : manufacturers}) 
          }).responseText;
          jQuery("#fits_product").show();
          if(html.length) {
            jQuery("#fits_product_notice").hide();
            jQuery("#fits_product").show();
            jQuery("#fits_product").html(html);
          }
          else {
            jQuery("#fits_product").hide(); 
            jQuery("#fits_product_notice").show();
            jQuery("#fits_product_notice").html('No filters available for the selection.');
          }
        }
        else {
         jQuery("#fits_product").hide(); 
         jQuery("#fits_product_notice").show();
        }
	  
	  });
	}
	/*********************
	 * WORDPRESS
	 *********************/	
	var maxWidth = 700;
	 
	if(jQuery('.single .entry').length) {
	  
	  jQuery('.single .entry img').each(function() {
	      
	      widthP = jQuery(this).attr('width');
	      if(widthP > maxWidth) {
	        heightP = jQuery(this).attr('height');
	        newHeight = (heightP*maxWidth)/widthP;
	        
	        jQuery(this).attr('width',maxWidth);
	        jQuery(this).attr('height',newHeight);
	        
	        parentA = jQuery(this).parent('a');
          if(parentA.length)
            parentA.reloadLightbox(true);
	      }
	    
	  });
	  
	}
	 
	 
	/*********************
	 * GENERAL
	 *********************/	
	
	jQuery(".tabbinate").tabbinate();
			
});
