var ajax_load = "<img class='loading' src='/skin/summit/images/loading.gif' alt='loading...' />";


// Custom JQuery UI scripts
$(document).ready(function() {
		jQuery.each($('select[name^="product_options"]'), function() {
			$(this).change(function() {
				//console.log($(this));
				//console.log($(this).attr('name'));
				//console.log($(this).attr('name').split("["));
				var optId = parseInt($(this).attr('name').split("[")[1]);
				//console.log(variants);
				//console.log("optId:", optId);
				
				var optVal = 0;
				$("#po" + optId +  " option:selected").each(function () {
					optVal = parseInt($(this).attr('value'));
				});
				//console.log("optVal: ", optVal);
				

				var selOpts = new Array();
				var selVals = new Array();
				jQuery.each($('select[name^="product_options"]'), function() {
					var k = parseInt($(this).attr('name').split("[")[1]);
					var v = 0;
					$("#po" + k +  " option:selected").each(function () {
						v = parseInt($(this).attr('value'));
					})
					selOpts[selOpts.length] = k;
					selVals[selVals.length] = v;
				});
				//console.log(selOpts);
				//console.log(selVals);


				$.each(variants, function(vIdx, v) {
					//console.log(arguments);
					if (v != undefined) {
						//console.log(v);
						//console.log(optId);
						//console.log(optVal);
						//console.log(v[1][optId]);
						if (parseInt(v[1][selOpts[0]]) == selVals[0] && parseInt(v[1][selOpts[1]]) == selVals[1]) {
							//console.log(v[0][5]);
							$('.prod_buy_control').attr('rel', v[0][5]);
						}
					}
				});

			});
		});


		
		// Nav dropdown pre-selected product
		$("li.navPrimary div.subContent div.content").children("ul").mouseenter(function() {
			$(this).find(".show").addClass("no_show");
			$(this).find(".show").removeClass("show");
			
		}).mouseleave(function() {
			$(this).find(".no_show").addClass("show");
			$(this).find(".no_show").removeClass("no_show");
		});		
		
		
		
		// PDP feature rendering
		//var myFeatureList = $("#pdp_feature_ul").text().split("|");
//		var myFeatureHTML = "";
//		
//		
//		jQuery.each(myFeatureList, function() {
//			  var currentFeature = this;
//			  
//			  myFeatureHTML += "<li>" + currentFeature + "</li>";
//		});
//		
//		$("#pdp_feature_ul").html(myFeatureHTML);
		
		
		// PDP feature icons
		//var myFeatureIcons = $("#pdp_feature_icons").text().split("|");
//		var myFeatureIconsHTML = "";
//		
//		jQuery.each(myFeatureIcons, function() {
//			  var currentFeature = this;
//			  
//			  myFeatureIconsHTML += "<img src='skin/summit/images/embed/feature_" + currentFeature.replace(/^\s+|\s+$/g, '') + ".jpg' />";
//		});
//
//		$("#pdp_feature_icons").html(myFeatureIconsHTML);
//		
//		


		//PDP Tool Tip
		$("#pdp_feature_icons img").each( function(i) {
		
			var myTitleSplit = $(this).attr("title").split("::");
			
			var myNewTitle = "<strong>" + myTitleSplit[0] + "</strong>" + "<br />" + myTitleSplit[1];
			
			$(this).attr("title", myNewTitle);
			
			$(this).tooltip();	
			
		});

		
		// Fly Fishing 101 - Flies 101
		$(".fly101_map area").each(function(i) {
			var myNewTitle = '<img src="'+$(this).attr('href')+'" />';
			
			$(this).attr("title", myNewTitle);
			
			$(this).tooltip();
			
			$(this).click(function(e){
				e.preventDefault();
			});
		});

		
		// RODS REELS OUTFITS MODEL SELECTION
		$(".model_category").click( function() {
			if ($(this).hasClass("cat_closed")) {			
				$(".cat_open").addClass("cat_closed");
				$(".cat_open").removeClass("cat_open");
				
				$(this).addClass("cat_open");
				$(this).removeClass("cat_closed");
			}
		});
		
		
		$(".prod_tr").click( function() {
			if( !($(this).hasClass("tr_selected")) ) {	
				
				$(".tr_selected").removeClass("tr_selected");
				$(this).addClass("tr_selected");
				
				var myId = $(this).attr("id");
				
				var myIdSplit = myId.split("_");
				var mySiblingId = "#prod_td_control_" + myIdSplit[myIdSplit.length - 1];
				
				$(mySiblingId).addClass("tr_selected");
			}
			
		});

/*
		$(".addthis_button").each(function(e) {
			//e.preventDefault();
			//console.log($(this).attr('id'), $(this).attr('rel'));
			addthis.button($(this).attr('id'), {}, {url: $(this).attr('rel'), title: "Pursuit Rod"});
			//return false;
		});
*/

		$("#socialMedia a").click(function(e) {
			_gaq.push(['_trackPageview', '/outbound/' + $(this).text()]);
		});
		
		$(".data-table:[summary=Authentication] button").click(function(e) {
			_gaq.push(['_trackPageview', '/Sign_In/Submit']);
		});
		
		$(".data-table:[summary=Add your review here] button").click(function(e) {
			_gaq.push(['_trackPageview', '/Review/Submit']);
		});
		
		$("form[name=registerform] button").click(function(e) {
			_gaq.push(['_trackPageview', '/Registration/Submit']);
		});
		
		$("#submit_registered_product").click(function(e) {
			_gaq.push(['_trackPageview', '/Register_Product/Save_Registration']);
		});
		
		$("#city-state-country-search input[type=submit]").click(function(e) {
			_gaq.push(['_trackPageview', '/Dealer_Locator/Submit']);
		});
		
		$("#contact_info a").click(function(e) {
			_gaq.push(['_trackPageview', '/Email/Info']);
		});
		
		$("#rod_warranty a").click(function(e) {
			_gaq.push(['_trackPageview', '/PDF/Warranty_Form/Rod_Warranty']);
		});
		
		$("#reel_warranty a").click(function(e) {
			_gaq.push(['_trackPageview', '/PDF/Warranty_Form/Reel_Warranty']);
		});
		
		$("#waders_warranty a").click(function(e) {
			_gaq.push(['_trackPageview', '/PDF/Warranty_Form/Waders_Warranty']);
		});
		
		$("#email_info a").click(function(e) {
			_gaq.push(['_trackPageview', '/Email/Info']);
		});
		
		$("#email_tech a").click(function(e) {
			_gaq.push(['_trackPageview', '/Email/Tech']);
		});
		
		$("#email_cs a").click(function(e) {
			_gaq.push(['_trackPageview', '/Email/Customer_Service']);
		});
		
		$(".email_warranty a").click(function(e) {
			_gaq.push(['_trackPageview', '/Email/Warranty']);
		});
		
		$("#email_jobs a").click(function(e) {
			_gaq.push(['_trackPageview', '/Email/Jobs']);
		});
		
		$("#add_photo_fb").click(function(e) {
			_gaq.push(['_trackPageview', '/Add_Photo_to_Gallery']);
		});
		
		$("#owners_manual a").click(function(e) {
			var file_name = $(this).text().replace(/ /g, "_");
			_gaq.push(['_trackPageview', '/PDF/Owners_Manual/' + file_name]);
		});
		
		$("#catalog_links a").click(function(e) {
			var catalog_year = $(this).text().substring(0, $(this).text().indexOf(' '));
			_gaq.push(['_trackPageview', '/PDF/catalog/' + catalog_year]);
		});
		
		$("#buy_now_dialog a").click(function(e) {
			var prod_name = $("#prod_header h2").text();
			if(!prod_name) {
				prod_name = $("#pdp_header h2").text();
			}
			var dealer_name = $(this).text();
			if(!dealer_name) {
				dealer_name = "Local_Dealer";
			}
			_gaq.push(['_trackPageview', '/outbound/Retailer/' + prod_name + '-' + dealer_name]);
		});
		
		$("#fb-like-container a").click(function(e) {
			_gaq.push(['_trackEvent', 'Facebook', 'Like']);
		});
		
		$(".fly_item a").click(function(e) {
			_gaq.push(['_trackEvent', 'Flies', 'Image Expand', $(this).attr('title')]);
		});
		
		$("#lingo_nav a").click(function(e) {
			_gaq.push(['_trackEvent', 'Fly Fishing Lingo', 'Alpha Select', $(this).text()]);
		});
		
		$("#head-gut-riffle-img a").click(function(e) {
			_gaq.push(['_trackEvent', 'Spotting Fish', 'Image Expand', 'Head-Gut-Riffle']);
		});
		
		$("#undercut-bank-img a").click(function(e) {
			_gaq.push(['_trackEvent', 'Spotting Fish', 'Image Expand', 'Undercut-Bank']);
		});
		
		$("#knot-tying-img a").click(function(e) {
			_gaq.push(['_trackEvent', 'Knot Tying', 'Image Expand', 'Knot Image']);
		});
		
		$("#mayfly-hatch-img a").click(function(e) {
			_gaq.push(['_trackEvent', 'Flies', 'Image Expand', 'Mayfly Hatch']);
		});
		
		$("#caddisfly-hatch-img a").click(function(e) {
			_gaq.push(['_trackEvent', 'Flies', 'Image Expand', 'Caddisfly Hatch']);
		});
		
		$("#stonefly-hatch-img a").click(function(e) {
			_gaq.push(['_trackEvent', 'Flies', 'Image Expand', 'Stonefly Hatch']);
		});
		
		$("#terr-hatch-img a").click(function(e) {
			_gaq.push(['_trackEvent', 'Flies', 'Image Expand', 'Terrestrials Hatch']);
		});
		
		$("#midges-hatch-img a").click(function(e) {
			_gaq.push(['_trackEvent', 'Flies', 'Image Expand', 'Midges-Scuds-Leeches Hatch']);
		});
		
		$("#dragon-hatch-img a").click(function(e) {
			_gaq.push(['_trackEvent', 'Flies', 'Image Expand', 'Dragonflies-Damselflies Hatch']);
		});
		
		$("#prod_suggest a").click(function(e) {
			if(!$(this).text()) {
				_gaq.push(['_trackEvent', 'CrossSell', 'Cross Sell Click', $(this).find("img").attr("alt")]);
			} else {
				_gaq.push(['_trackEvent', 'CrossSell', 'Cross Sell Click', $(this).text()]);
			}
		});
		
		$("#prod-compare-charts a").click(function(e) {
			var link_check = $(this).attr("rel");
			if(!link_check) {
				_gaq.push(['_trackPageview', '/PDF/Product_Comparison/' + $(this).attr("title")]);
			} else {
				_gaq.push(['_trackEvent', 'Product Compare', 'Image Expand', $(this).attr("title")]);
			}
		});
		
		$(".creviews-rating-box a").click(function(e) {
			var prod_name = $("#prod_header h2").text();
			if(!prod_name) {
				prod_name = $("#pdp_header h2").text();
			}
			var star_rating = $(this).parent().attr("class").replace("star-", "");
			star_rating = parseInt(star_rating) + 1;
			if(star_rating == 1) {
				star_rating = star_rating.toString() + " Star";
			} else {
				star_rating = star_rating.toString() + " Stars";
			}
			_gaq.push(['_trackEvent', 'Reviews', 'Star Rating', prod_name + " - " + star_rating]);
		});
		
		$("#read_all_reviews").click(function(e) {
			e.preventDefault();
			var prod_name = $("#prod_header h2").text();
			if(!prod_name) {
				prod_name = $("#pdp_header h2").text();
			}
			_gaq.push(['_trackEvent', 'Reviews', 'Read All Reviews', prod_name]);
			$("#read_all_reviews").hide();
			$("#hide_reviews").show();
			
			$(".review_hidden").each(function() {
				$(this).removeClass("review_hidden");
				$(this).addClass("review_shown");
			});
		});

		$("#hide_reviews").click(function(e) {
			e.preventDefault();
			$("#read_all_reviews").show();
			$("#hide_reviews").hide();
			
			$(".review_shown").each(function() {
				$(this).removeClass("review_shown");
				$(this).addClass("review_hidden");
			});
		});
		
		
		$("#write_a_review").click(function(e){
			e.preventDefault();
			_gaq.push(['_trackPageview', '/Review/Start']);
			$("#read_all_reviews").hide();
			$("#hide_reviews").hide();
			$("#prod_review_messages").hide();
			$("#write_a_review").hide();
			$("#review_form").show();
			$("#cancel_review").show();
		});

		
		$("#cancel_review").click(function(e) {
			e.preventDefault();
			
			$("#cancel_review").hide();
			$("#read_all_reviews").show();
			$("#hide_reviews").hide();
			$("#prod_review_messages").show();
			$("#write_a_review").show();
			$("#review_form").hide();
		});
		
		
		
		
		/* Swap Product Hero image when detail thumbnail is clicked on 
		$('.product_detail_thumbnail').click(function(e) {
			var hi = $('#product_hero_image');

			var xp = 210 - parseInt($(this).attr('bw'))/2;

			hi.attr('src', $(this).attr('bi'));
			hi.css('left', xp);
			
			$('.product_detail_thumbnail').each(function(idx, el) {
				$(el).removeClass('product_detail_selected');
			});
			
			$(this).addClass('product_detail_selected');
		});
		*/
		
		
		
		// Softgoods PDP Select Box
		jQuery.each($('select[name^="product_options"]'), function() {
			$(this).parent("form").css("position", "relative");
			//$(this).sb({ddCtx: function() { return $(this).parent("form"); }});
			$(this).sb();
		});



		/* 
		 * 
		 * Reels family page if there are multiple colors
		 * Make color select boxes fancy
		 * 
		 */
		jQuery.each($(".product_color"), function() {
			$(this).parent("form").css("position", "relative");
			$(this).sb({ddCtx: function() { return $(this).parent("form"); }});
		});
		
		$('.reels_cat .product_color').change(function(e) {
			$('option', this).each(function() {
				if (this.selected) {
	    			var id = $(this).parent().attr('id').replace("prodcolor_", "");

	    			$("#buynow_"+id).attr('rel', this.value);
	    			var atu = $("#addthis_"+id).attr('addthis:url');
	    			var atup = atu.split('=');

	    			$("#addthis_"+id).attr('addthis:url', atup[0] + "=" + this.value);
				}
			});

			e.preventDefault();
			return true;
		});

		
		$(".prod_buy_control").click(function(e) {
			var sku = $(this).attr('rel');
			if (sku == undefined) {
				sku = e.target.id.split('_')[1];
			}


			var pid = parseInt($(this).attr('pid'));
			if (isNaN(pid)) {
				pid = e.target.pid;
			}


			var opts = '';
			var optSels = $('select[name^="product_option"]');
			if (optSels) {
				$.each(optSels, function(idx, el) {
					opts += '&' + $(el).attr('name') + '='+$('#' + $(el).attr('id') + ' :selected').val();
				});
			}
	
			/*
			var qty = parseInt($('input[name="productid"]').val());
			if (isNaN($('#product_avail_input').val())) {
				var qty = 1;
			} else {
				var qty = parseInt($('#product_avail_input').val());
			}
			*/
			
			var addUrl = '/cart.php?mode=add&productid='+pid+opts+"&amount=";
			$('#overlay_buynow').attr('href', addUrl);
			
			$('#overlay_buynow').click(function(e) {
				e.preventDefault();

				var addUrl = '/cart.php?mode=add&productid='+pid+opts+"&amount=";
				$(this).attr('href', addUrl);
				var qty = parseInt($('#overlay_quantity').val());
				
				if (isNaN(qty)) {
					xAlert('<h3>Quantity must be a number</h3>', 'Invalid Quantity');
				} else if (qty < 1) {
					xAlert('<h3>Quantity must be 1 or more</h3>', 'Invalid Quantity');
				} else {
					$(this).attr('href', $(this).attr('href')+qty);
					window.location.href=$(this).attr('href');
				}
			});

			/*
			var qty = 1;
			var addUrl = '/cart.php?mode=add&productid='+pid+'&amount='+qty;
			//alert(addUrl);
			$('#overlay_buynow').attr('href', addUrl);
			*/
			
			$("#buy_now_dialog").css('display', 'block');
			e.preventDefault();
			var dlg = $('#basic-modal-content').modal({overlayClose: true});
			dlg.update(380, 640);
			$('#buy_now_dialog').css('width', '640px !important');

			//This is show loader image but not sure we want it though
			//$("#online_dealer_list").parent().css('display', 'block');
			//$("#online_dealer_list").html(ajax_load);
			
			$.getJSON("product_avail.php", { sku: sku }, function(json) {
				if (!isNaN(json.qty) && json.qty > 0) {
					$('.last_option p').css('display', 'block');
					$('.overlay_buy_control').css('display', 'block');
				} else {
					$('.last_option p').css('display', 'none');
					$('.last_option').append('<p>Currently Out of Stock</p>');
				}
			});

			$.getJSON("dealer_locator.php", { mode: 'locate_by_sku', sku: sku }, function(json) {
				$("#online_dealer_list").empty();
				
				if (json.length) {
					var link = $("");
					var odl = $("#online_dealer_list");
					odl.parent().css('display', 'block');
					
					for (var idx=0; idx<json.length; idx++) {
						//odl.html(odl.html() + "<a style='color: #000000;' target='_blank' href='" + json[idx].buy_url + "'><img src='/skin/summit/images/dealers/" + json[idx].dealer_name.toLowerCase() + ".jpg' /></a><br /><br />");
						//odl.html(odl.html() + "<a style='color: #000000;' target='_blank' href='" + json[idx].buy_url + "'>" + json[idx].dealer_name + "</a><br /><br />");
 						//odl.html(odl.html() + "<a style='color: #000000;' href='" + json[idx].buy_url + "'>" + json[idx].dealer_name + "</a><br /><br />");
 						link = $("<a />");
 						link.attr('href', json[idx].buy_url);
 						link.attr('target', '_blank');
 						if(json[idx].dealer_logo) {
 							link.append('<img src="/skin/summit/images/dealers/online/' + json[idx].dealer_logo + '">');
 						}
 						else {
 							link.text(json[idx].dealer_name);
 						}
 						link.click(function(e) {
							var prod_name = $("#prod_header h2").text().replace(/ /g, "-");
							if(!prod_name) {
								prod_name = $("#pdp_header h2").text().replace(/ /g, "-");
							}
							var dealer_name = $(this).text().replace(/ /g, "-");
							if(!dealer_name) {
								dealer_name = "Local_Dealer";
							}
							_gaq.push(['_trackPageview', '/outbound/Retailer/' + prod_name + '-' + dealer_name]);
 						})
 						link.appendTo(odl);
 						$("<br />").appendTo(odl);
 						$("<br />").appendTo(odl);
					}
					
				} else {
					var odl = $("#online_dealer_list");
					odl.css('overflow-y', 'hidden');
					odl.html('No online dealers <br />presently carry this product.<br /><br />Visit our dealer locator to find<br /> a Redington dealer near you.<br /><br /><h4><a href="/dealer_locator.php" style="color: #000000;">Locate a Dealer</a><h4>');
					//odl.parent().css('display', 'none');
					//$('#buy_now_dialog').css('width', '425px');
					//dlg.update(330, 610);
				}
			});

			return false;
		});


		// Get Facebook Albums
		if ($("#gallery_albums").attr('id') != undefined) {
			$("#gallery_albums").html(ajax_load);
			jQuery.getJSON("gallery.php?mode=gal&out=json", function(json, textStatus, xhr) {
				//console.log(arguments);
				$("#gallery_albums").empty();
				
				var num_items = 0;
				
				for (var p=0; p<json.data.length; p++) {
					
					if (parseInt(json.data[p].count) > 0) {
						jQuery('<div />', {
							id: 'album_'+json.data[p].id,
							rel: json.data[p].name,
							style: 'cursor: pointer; float: left; clear: none; margin: 5px; width: 150px;'
						}).appendTo('#gallery_albums').click(function() {
							getAlbumPhotos($(this).attr('rel'));
						});
	
						jQuery('<img/>', {  
							src: json.data[p].cover,
							rel: json.data[p].name,
							style: 'cursor: pointer;'
						}).appendTo('#album_'+json.data[p].id);
	
						jQuery('<p/>', {  
							'class': 'gallery_album_name',
							html: json.data[p].name,
							rel: json.data[p].name,
							style: 'cursor: pointer;'
						}).appendTo('#album_'+json.data[p].id);
	
						jQuery('<p/>', {  
							'class': 'gallery_album_count',
							html: json.data[p].count + " Photo" + ((parseInt(json.data[p].count) > 1) ? "s" : ""),
							rel: json.data[p].name,
							style: 'cursor: pointer;'
						}).appendTo('#album_'+json.data[p].id);
						
					}
					
					num_items += 1;
				}
				
				// Resize Gallery Images to 130px wide or high
				$('#gallery_albums div img').aeImageResize({ height: 130, width: 130 });
			
				createAlbumPagination(num_items);
			});
			
			getWallPhotos('FromWall');
			
		}
		
		// Remove sidebar elements from Logo Gear pages
		/*
		$("a.bread-crumb").each( function(i) {
			if ($(this).text() == "Logo Gear") { 
			
				$("#pdp_sidebar div").each( function(o) {
				
					if ( ($(this).find(".prod_share_control").size() > 0) || ( $(this).attr("id") == "pdp_header")) {
						$(this).find("br").css("display", "none");
						$(this).find(".prod_buy_control").css("float", "right");
						$(this).find(".prod_share_control").css("margin", "63pt 0 0 0");
						$(this).find(".prod_share_control").css("float", "left");
						
						if ( $(this).find(".prod_share_control").size() > 0 ) {
							$(this).css("padding-right", "20px");
						}
						
					}
					else { $(this).css("display", "none"); }
					
				});
				
			
			}
		});
		*/
		
});

function createAlbumPagination(num_items) {
	
	var num_pages = 0;
	var per_page = 4;
	
	if (num_items%per_page == 0) {
		num_pages = Math.floor(num_items/per_page);
	}
	else num_pages = Math.floor(num_items/per_page) + 1;
	
	for (var c = 1; c <= num_pages; c++) {
		if (c == 1) {
			$("#album_pagination").append("<li><a class='album_page_current'>" + c + "</a></li>");
		}
		else $("#album_pagination").append("<li><a>" + c + "</a></li>");
	}
	
	$("#album_pagination li a").click( function(){
		
		var my_num = parseInt($(this).text());
		var my_shift = (-230 * my_num) + 230;
		
		$("#gallery_albums").css("margin-top", my_shift.toString() + "px");
	
		$("#album_pagination li a.album_page_current").removeClass("album_page_current");
		$(this).addClass("album_page_current");
	});
	
}

function getWallPhotos(album) {
	if(album != 'FromWall') {
		_gaq.push(['_trackEvent', 'Image Gallery', 'Album Select', album]);
	}
	$("#gallery_photos").html(ajax_load);

	jQuery.getJSON("gallery.php?mode=photo&out=json&name="+album, function(json, textStatus, xhr) {
		$('#gallery_photos').empty();
		
		var num_gal_items = 0;
		
		for (var p=0; p<json.data.length; p++) {
			jQuery('<div />', {
				id: 'photo_'+json.data[p].id,
				//rel: json.data[p].images[0].source,
				rel: json.data[p].image,
				'class': 'gallery_photo'
			}).appendTo('#gallery_photos');

			jQuery('<a/>', {
				rel: 'shadowbox',
				//href: json.data[p].images[0].source,
				href: json.data[p].image,
				id: 'photolink_'+json.data[p].id,
				title: json.data[p].name,
				onClick: "_gaq.push(['_trackEvent', 'Image Gallery', 'Image Expand', 'Gallery Image'])"
			}).appendTo('#photo_'+json.data[p].id);
			
			jQuery('<img/>', {  
				//src: json.data[p].images[2].source
				src: json.data[p].image
			}).appendTo('#photolink_'+json.data[p].id);
			
			Shadowbox.setup($('#photolink_'+json.data[p].id));
		
			num_gal_items += 1;
		}
		
		// Resize Gallery Images to 130px wide or high
		$('#gallery_albums div img').aeImageResize({ height: 130, width: 130 });
		$('.gallery_photo img').aeImageResize({ height: 130, width: 130 });
		
		createGalleryPagination(num_gal_items);
		
	});	
	
}

function getAlbumPhotos(album) {
	if(album != 'FromWall') {
		_gaq.push(['_trackEvent', 'Image Gallery', 'Album Select', album]);
	}
	$("#gallery_photos").html(ajax_load);

	jQuery.getJSON("gallery.php?mode=photo&out=json&name="+album, function(json, textStatus, xhr) {
		$('#gallery_photos').empty();
		
		var num_gal_items = 0;
		
		for (var p=0; p<json.data.length; p++) {
			jQuery('<div />', {
				id: 'photo_'+json.data[p].id,
				rel: json.data[p].images[0].source,
				//rel: json.data[p].image,
				'class': 'gallery_photo'
			}).appendTo('#gallery_photos');

			jQuery('<a/>', {
				rel: 'shadowbox',
				href: json.data[p].images[0].source,
				//href: json.data[p].image,
				id: 'photolink_'+json.data[p].id,
				title: json.data[p].name,
				onClick: "_gaq.push(['_trackEvent', 'Image Gallery', 'Image Expand', 'Gallery Image'])"
			}).appendTo('#photo_'+json.data[p].id);
			
			jQuery('<img/>', {  
				src: json.data[p].images[2].source
				//src: json.data[p].image
			}).appendTo('#photolink_'+json.data[p].id);
			
			Shadowbox.setup($('#photolink_'+json.data[p].id));
		
			num_gal_items += 1;
		}
		
		// Resize Gallery Images to 130px wide or high
		$('#gallery_albums div img').aeImageResize({ height: 130, width: 130 });
		$('.gallery_photo img').aeImageResize({ height: 130, width: 130 });
		
		createGalleryPagination(num_gal_items);
		
	});	
	
}

function createGalleryPagination(num_items) {
	
	$("#gallery_pagination li").remove();
	
	var num_pages = 0;
	
	if (num_items%15 == 0) {
		num_pages = Math.floor(num_items/15);
	}
	else num_pages = Math.floor(num_items/15) + 1;
	
	for (var c = 1; c <= num_pages; c++) {
		if (c == 1) {
			$("#gallery_pagination").append("<li><a class='album_page_current'>" + c + "</a></li>");
		}
		else $("#gallery_pagination").append("<li><a>" + c + "</a></li>");
	}
	
	$("#gallery_pagination li a").click( function(){
		
		var my_num = parseInt($(this).text());
		var my_shift = (-435 * my_num) + 435;
		
		$("#gallery_photos").css("margin-top", my_shift.toString() + "px");
	
		$("#gallery_pagination li a.album_page_current").removeClass("album_page_current");
		$(this).addClass("album_page_current");
	});
	
}


function ScrollToElement(theElement) {
	var selectedPosX = 0;
	var selectedPosY = 0;
              
	while(theElement != null) {
		selectedPosX += theElement.offsetLeft;
		selectedPosY += theElement.offsetTop;
		theElement = theElement.offsetParent;
	}
                        		      
	window.scrollTo(selectedPosX, selectedPosY);
}




$(document).ready(function() {
	$('#select_category').change(function() {
		_gaq.push(['_trackEvent', 'Product Wall', 'Sort', $('#catForm').attr('action') + '/' + $('#select_category').val().toLowerCase()]);
		$('#catForm').attr('action', $('#catForm').attr('action') + '/' + $('#select_category').val().toLowerCase()).submit();
	});
	
	$('#select_category').sb();
	$('select[name="sort"]').sb();

});


$(document).ready(function(){
	var color_select = $('select[rel="Color"]');
	var container = $("#swatchContainer");
	var swatches = [];

	if (color_select.length == 1) {
		var options = color_select.children("option");
		var initial_swatch = color_select.children('option[selected="true"]').text();
		initial_swatch = $.trim(initial_swatch).toLowerCase();
		initial_swatch.replace(/[^a-zA-Z0-9]+/g, "_");
		
		color_select.bind("change",function(){
			$.each(swatches,function(i,el){
				el.removeClass("current_swatch");
			});			
			
			var selected_color = $(this).children('[value="'+$(this).val()+'"]').text();
			selected_color = $.trim(selected_color).toLowerCase();
			selected_color.replace(/[^a-zA-Z0-9]+/g, "_");
			
			$("#"+selected_color+".product_swatch").addClass("current_swatch");
		});

		options.each(function(index,element){
			var display_value = $(element).text();
			var text_value = $.trim(display_value).toLowerCase();

			var image_name = text_value.replace(/[^a-zA-Z0-9]+/g, "_");
			
			var image_type = ".jpg";
			var base_url   = "/skin/summit/images/swatches/"

			var swatch = $(document.createElement("span")).attr("id",image_name).attr("class","product_swatch");			
			swatch.attr("rel",$(element).val());						
			swatch.attr("title",display_value);						
            var image = base_url + image_name + image_type;
			swatch.css("background-image","url('"+image+"')");
			
			//swatch.tooltip();

			if(initial_swatch == image_name){
				swatch.addClass("current_swatch");
			}
			
			swatch.click(function(){
				// This selects the x index of the detailed images
				//   if we created detailed images of each swatch
				//   in the same order as the swatches then zoom
				//   will work for swatches as well
				var nth = ':nth-child(' + (index+1) + ')';
				$('.dpimages-icons-box').children(nth).trigger('click');

				var target_option = color_select.children('option[value="'+$(this).attr("rel")+'"]');
				target_option.attr("selected",true);
				
				var value = color_select.prev().children("a").children("span.value");
				//console.log(color_select.prev());
				value.text($(this).attr("rel"));
				
				var text = color_select.prev().children("a").children("span.text");
				//console.log(text);
				text.text($(this).attr("title"));

				color_select.trigger("change");
				return false;
			});
			
			swatches.push(swatch);			
			container.append(swatch);
		});		
		return true;
	}
	else{
		return false;
	}

});


/* Product Compare UI */
function toggleProduct(id, type) {

    if (compareids[type].indexOf(id) != -1) {
        $("*").css("cursor", "wait");
        $("body").css("cursor", "wait");

        compareids[type].splice(compareids[type].indexOf(id), 1);
        $.ajax({
            url: "/comparison_list.php?mode=delete&productid="+id,
            complete: function() {
                $("body").css("cursor", "default");
                $("*").css("cursor", "default");
            }
        });
    } else {
        if (compareids[type].length < 5) {
            $("*").css("cursor", "wait");
            $("body").css("cursor", "wait");

            compareids[type].push(id);
            $.ajax({
                url: "/comparison_list.php?mode=add&productid="+id,
                complete: function() {
                    $("body").css("cursor", "default");
                    $("*").css("cursor", "default");
                }
            });
        } else {
            var elName = 'input[name="productids['+id+']"]';
            $(elName).removeAttr("checked");
            xAlert('<h3>You have reached the maximum number of products to compare</h3>', 'Product Comparsion');
        }
    }
}

$(document).ready(function(){
    $('input[name^="productids["]').click(function() {
        var elName = $(this).attr("name");
        var elID = elName.replace(/[^0-9]/g, '');
        var type = $(this).attr('rel');
        toggleProduct(parseInt(elID), type);
    });

    $('.compare_control').click(function(e) {
        e.preventDefault();
    
        var type = $(e.currentTarget).attr('rel');
        var str = '';
        var trackingString = '';
        for (v=0; v<compareids[type].length; v++) {
            str += '&' + 'productids[' + compareids[type][v] + ']=Y';
            trackingString += (compareids[type][v] + ", ");
        }
    
        // need to add the product name to this tag:
        _gaq.push(['_trackEvent', 'Products', 'Compare', trackingString]);
    
        $.ajax({
            url: "/comparison_list.php?mode=add"+str,
            success: function() {
                window.location.href = '/comparison.php?mode=get_products' + str;
            }
        });
    });

    $('.comparelink').click(function(e) {
        e.preventDefault();
    
        var type = $(e.currentTarget).attr('rel');
        var str = '';
        var trackingString = '';
        for (v=0; v<compareids[type].length; v++) {
            str += '&' + 'productids[' + compareids[type][v] + ']=Y';
            trackingString += (compareids[type][v] + ", ");
        }
    
        // need to add the product name to this tag:
        _gaq.push(['_trackEvent', 'Products', 'Compare', trackingString]);
    
        $.ajax({
            url: "/comparison_list.php?mode=add"+str,
            success: function() {
                window.location.href = '/comparison.php?mode=get_products' + str;
            }
        });
    });

});


