// products.js
var products = ({
	init: function(){
		
		$('#weights-go-button').click(function(ev){
			ev.preventDefault();
			var nextUrl = "/products/consumer-products/motor-oil";
			if($('#grade-select').val() != "0"){
				nextUrl += "/" + $('#grade-select').val();
			}
			window.location = nextUrl;
		});

		$('#categories-go-button').click(function(ev){
			ev.preventDefault();
			var nextUrl = "/products/brands";
			if($('#categories-select').val() == ''){return}
			if($('#categories-select').val() != "0"){
				nextUrl += "/" + $('#categories-select').val();
			}
			window.location = nextUrl;
		});
				
	},
	carousel: ({
		carouselContent: [],
		itemList: [],
		selIndex: 0,
		init: function(){
			jQuery(document).ready(function() {
				
            var previewRequest = $.get('/include/environment.jsf', {reqVar: 'previewString'}, function(ps){
               isPreview = window.location.href.indexOf(ps) == -1 ? false : true;
               previewString = ps;





      				// generate global, category, subcategory from url
      				var url = window.location.href.toString().split("/");
      				var cats = new Array();
      				for (k in url) if(url[k]) cats.push(url[k])

      				var global = cats[3];
      				var cat = cats[4];
      				var subcat = cats[5];

      				$("#products-carousel").css('opacity',0);

      				var reqData = {global: global};

      				if(isPreview){
      				   if(global == "preview"){
      				      global = "consumer-products";
      				   }

         				reqData = {global: global, preview: "true"};
                  }            

      				$.get('/include/products/landing-carousel-xml.jsf', reqData, function(xml){

      					var json = $.xml2json(xml);
      					products.carousel.carouselContent = json;
      					products.carousel.itemList = json.carouselItem;

      					// init carousel 
      				    jQuery('#products-carousel').jcarousel({
      				    	start: 0,
      						scroll: 4,
      						visible: 5,
      						buttonNextHTML: null,
      						buttonPrevHTML: null,
      						buttonNextCallback: products.carousel.nextCallback,
      						buttonPrevCallback: products.carousel.prevCallback,
      						initCallback: function(carousel){

      							$("#products-carousel").css('opacity',1);

      							// create and insert custom prev and next buttons, because we need to hijack their functinality
      							// for this instance of the carousel
      							var carouselContainer = $('.jcarousel-container');

      							carouselContainer.append("<div class=\"jcarousel-next jcarousel-next-horizontal\" style=\"display: block; z-index:11; \" disabled=\"false\"/>");
      							carouselContainer.append("<div class=\"jcarousel-prev jcarousel-prev-horizontal\" style=\"display: block; z-index:11;  \" disabled=\"false\"/>");

      							var next = $(".jcarousel-next");
      							var prev = $(".jcarousel-prev");							

      							var cRef = carousel;

      							next.bind("click",function(e){
      								e.preventDefault();
      								if($(this).attr("disabled") == "true"){return false;}
      								if(products.carousel.selIndex == (cRef.last-1)){
      									cRef.next();
      								}
      								products.carousel.selIndex++;
      								products.carousel.setupItems();


      							});


      							prev.bind("click",function(e){
      								e.preventDefault();
      								if($(this).attr("disabled") == "true"){return false;}

      								if(products.carousel.selIndex == (cRef.first-1)){
      									cRef.prev();
      								}
      								products.carousel.selIndex--;
      								products.carousel.setupItems();	


      							});
      						}
      				    });

      					products.carousel.setupItems();
      					$(".jcarousel-item a").each(function(i){
      						var mIndex = i;
      						$(this).attr("id","link-"+i);

      						$(this).bind("click",function(e){

      							if($(this).attr("href") == $("#carousel-link").attr("href")){
      								window.location.href = $(this).attr("href");
      							}else{
      								e.preventDefault();
      								var clicked = parseFloat($(this).attr("id").split("link-")[1]);
      								products.carousel.selIndex = clicked;
      								products.carousel.setupItems();
      							}


      						});	

      					});

      				});
      			});






            });



		},
		setupItems: function(carousel, state){
			var items = $(".jcarousel-item");
			
			items.each(function(i){
				if(i == (products.carousel.selIndex)){
					$(this).animate({
						opacity: 1
					});
					
				}else{
					$(this).animate({
						opacity: 0.5
					});
				}
			});	
				// see if we need to enable/disable prev or next buttons
				switch(parseFloat(products.carousel.selIndex)){
				case 0:
					$(".jcarousel-prev").addClass("jcarousel-prev-disabled-horizontal");
					$(".jcarousel-prev").attr("disabled",true);
					$(".jcarousel-next").removeClass("jcarousel-next-disabled-horizontal");				
					$(".jcarousel-next").attr("disabled",false);
					break;
				case items.length-1:
					$(".jcarousel-next").addClass("jcarousel-next-disabled-horizontal");				
					$(".jcarousel-next").attr("disabled",true);
					$(".jcarousel-prev").removeClass("jcarousel-prev-disabled-horizontal");
					$(".jcarousel-prev").attr("disabled",false);
					break;
				default:	
					$(".jcarousel-prev").removeClass("jcarousel-prev-disabled-horizontal");
					$(".jcarousel-prev").attr("disabled",false);
					$(".jcarousel-next").removeClass("jcarousel-next-disabled-horizontal");
					$(".jcarousel-next").attr("disabled",false);
					break;
				}
				
				
			
			products.carousel.fetch(products.carousel.selIndex);
			
		},
		carouselCB: function(carousel, item, i, state, evt, e){
			
			products.carousel.fetch(products.carousel.selIndex);
	
		},
		fetch: function(index){
			var newContent = products.carousel.carouselContent.carouselItem[index];
			var cImage = $('#carousel-lg-img');
			var headline = $("#carousel-headline");
			var cDesc = $('#carousel-desc');
			var link = $("#carousel-link");

			var catcher = $("#carousel-catcher");

			// generate global, category, subcategory from url
			var url = window.location.href.toString().split("/");
			var cats = new Array();
			for (k in url) if(url[k]) cats.push(url[k])

			var global = cats[3];
			var cat = cats[4];
			var subcat = cats[5];

			
			catcher.animate({
				left: '-999px'
			},600,'easeInSine',function(){
			
				var genHref = "/products/";
				
				// add global category
				genHref += products.carousel.carouselContent.shortname + "/";
								
				// add category
				genHref += newContent.name;
				
				cImage.attr("src",newContent.image);
				headline.html(newContent.friendlyName);
				cDesc.html(newContent.desc);

            if(isPreview){
               genHref += "/" + previewString;
            }

				// pluralize, baby!
				var pluralString = " Products";
				// vps 'products' aren't products, they're services, so just add an 's'
				if(global == 'valvoline-professional-series'){
					pluralString = "s";
				}
				var cta = newContent.friendlyName;
				
				if(newContent.friendlyName.charAt(newContent.friendlyName.length-1)!="s"){
					cta += pluralString;
				}
				link.html("View All " + cta);
				
            if(genHref.lastIndexOf("/") == genHref.length){
   				link.attr('href',genHref + "/");			
            }else{
   				link.attr('href',genHref);			               
            } 
				

				
				if(global != 'brands'){
					
					// swap out promos				
					var promos = newContent.promos;
					var promoBuckets = $('.promo');

					promoBuckets.animate({
						opacity: 0
					},200,function(){

						promoBuckets.each(function(index){
							var cPromo = promos.item[index];
							var header = cPromo.promoheader;
							var body = cPromo.body;
							var img = cPromo.image;
							var cta = cPromo.cta;
							var link = cPromo.link;
							var external = cPromo.external;						

                     if(isPreview && (external == "false")){
                        link += previewString;
                     }

						
							$(this).children(".promo-copy").children("h2").html(header);
							$(this).children(".promo-copy").children("p").html(body);
							$(this).children(".img-container").children("a").attr("href",link);
							$(this).children(".img-container").children("a").children("img").attr("src",img);
							$(this).children(".promo-copy").children("div.promo-button").children("div.promo-fill").children("a").html(cta);
							$(this).children(".promo-copy").children("div.promo-button").children("div.promo-fill").children("a").attr('href',link);
							if(external == "true"){
								$(this).children(".promo-copy").children("div.promo-button").children("div.promo-fill").children("a").attr("class","ext");
							}
							
							if(link.indexOf(".swf") != -1){
								$(this).children(".img-container").children("a").attr("rel","shadowbox;width=650;height=350");
								$(this).children(".promo-copy").children("div.promo-button").children("div.promo-fill").children("a").attr("rel","shadowbox;width=650;height=350");
								Shadowbox.init();
								// Call setup explicitly to ensure that the events get re-set after clearing the cache because init doesn't do anythign on subsequent calls
								Shadowbox.setup();
							}else{
								$(this).children(".img-container").children("a").attr("rel","");
								$(this).children(".promo-copy").children("div.promo-button").children("div.promo-fill").children("a").attr("rel","");
								Shadowbox.clearCache();
								// Call setup explicitly to ensure that the events get re-set after clearing the cache because init doesn't do anythign on subsequent calls
								// Call setup here as well, otherwise only the right bucket will work with SWFs
								Shadowbox.setup();
							}
						  
						});
					
					}).animate({
						opacity: 1
					},600);
				
				}
				
				catcher.animate({
					left: '0px'
				},600,'easeOutSine');
				
			});
		}
		
	}),
	trigger: ({
		init: function(section){
			// this is used to trigger a recalculation of the height of the left nav accordion
			// to account for several rendering errors
			var url = window.location.href.toString().split("/");
			var cats = new Array();
			for (i in url){
				 if(url[i]) cats.push(url[i]);
			}

			var global = cats[3];
			var cat = cats[4];
			var subcat = cats[5];

			switch(section){
				case "category":
				case "subcategory":
					products.trigger.global(global);
					products.trigger.category(cat);
				break;
				default:
					products.trigger.global(global);
				break;
			}
		},
		global: function(global){
			var globItems = $(".activate");
			globItems.each(function(index){
				if($(this).attr("href").indexOf(global) != -1){
					if($(this).hasClass("ui-state-active")){return;}
					$(".acc1").accordion("activate",index);
				}
			});
			
		},
		category: function(cat){
			
			var catItems = $(".activate2");
			catItems.each(function(index){
				if($(this).attr("href").indexOf(cat) != -1){
					if($(this).hasClass("ui-state-active")){return;}
					$(".acc2").accordion("activate",index);
				}
			});

			
		}
	})
});

prodDetail = ({
	init: function(){
		var bgPos = (ie6 == true ? '-362px' : '-371px');
		
		
		$('#details-tabs a').each(function(){
			if(!$(this).hasClass("here")){
				$(this).css( {backgroundPosition: "0 0"} )
				if(ie6 || ie7){
					$(this).css({
						backgroundPositionX: 0,
						backgroundPositionY: 0
					});
				}

			}else{
				if(ie6 || ie7){
					$(this).css({
						backgroundPositionX: 0,
						backgroundPositionY: bgPos
					});
				}
				
				
			}
		});
		
		$('#details-tabs a')
			.mouseover(function(){
				if(!$(this).hasClass("here")){
					$(this).stop().animate(
						{backgroundPosition:"(0 " + bgPos + ")"}, 
						{duration:500})
					}
				})
			.mouseout(function(){
				if(!$(this).hasClass("here")){
					$(this).stop().animate(
						{backgroundPosition:"(0 0)"}, 
						{duration:500})
					}
				})


				var tabs = $('.details-tab');
				var areas = $('#details-deets div.deets-container');

				jQuery.each(tabs,function(){						
						$(this).click(function(ev){
								ev.preventDefault();
								var clicked = this.id.split("details-")[1];
								jQuery.each(areas,function(){
										if(this.id.indexOf(clicked) != -1){
											this.style.display = "block";
										}else{
											this.style.display = "none";
										}

								});
								jQuery.each(tabs,function(){
										if(this.id.indexOf(clicked) != -1){
											$(this).addClass("here");
										}else{
											$(this).removeClass("here");
											$(this).stop().animate(
												{backgroundPosition:"(0 0)"}, 
												{duration:500})
										}

								});
						});


				});

					
	}

});

