$(document).ready(function() {

	var config = {
		script: 'https://w.sharethis.com/button/buttons.js',
		timeout: 3000,
		id: "share-script"
	};

	var stLight = stLight || {options: function(){}};
	iLogo.loadScript(config.script, config.timeout, config.id);
	stLight.options({publisher: "18a5933c-ac59-45a1-abb6-e2be5f48e9f5", doNotHash: false, doNotCopy: false, hashAddressBar: false});

	$(document).on('click', "#js-pd-change-product, #complete-catalog, .ksa-list-products", function(e){
		e.preventDefault();
		var thisobj = this;
		//alert($(this).data('url'));
		$.ajax({
			url : $(thisobj).data('url'),
			dataType : "html",
			success : function (data) {
				$("#common-modal").find(".modal-body").html(data);
				$("#common-modal").modal('show');
			}
		}).fail(function (dt, b) {
			//$("#pp_color").html("Error: " + b);
			alert("Error: " + b);
			
		}).always(function (dt, b) {
			//alert("always" + dt.data.unit_price);
		});
	});
	
	$(document).on('click', ".ksa-product-detail", function(e){
															
		e.preventDefault();
		var thisobj = this;
		var productId = $(thisobj).data('id');
		var designId = $("#ksa_design_id").val();
		
		$("[name=product_id]").val(productId);
		//$(thisobj).closest("#inline_color_pallete");
		var colors_str = '';
		$(".inline_color_pallete" + productId + " li").each(function(index, value) {
			colors_str += '<li>';
			colors_str += '<a ';
			colors_str += ' title="' + $(this).attr('title') + '"';
			colors_str += ' data-color-value="' + $(this).data('color-value1') + '"';
			colors_str += ' style="' + $(this).attr('style') + '"';
			colors_str += ' data-product="' + productId + '"';
			colors_str += ' href="#"';
			colors_str += ' class="ogcolor tooltipester"';
			colors_str += ' data-id="' + designId + '"';			
			colors_str += '></a>';
			colors_str += '</li> ';
		});
		
		var data_source = $(thisobj).data('source');
		$("#ksa-colors-container").html(colors_str);
		if(data_source == 'color') {
			var selected_color = $(thisobj).data('color-value1');
			$("#ksa-colors-container").find('[data-color-value="'+ selected_color +'"]').trigger('click');
		} else {
			$("#ksa-colors-container").find('.ogcolor:first').trigger('click');
		}
		//alert(colors_str);
		$("#common-modal").modal('hide');
	});


	/*$("[name=product_id]").bind("change", function(){
		var $id = $(this).val();
		var $text = $(this).find("option:selected").text();
		$(".ogcolor").data("product", $id).removeClass("icon-ok");
		$(".product_text").html($text);
		setTimeout(function(){
			$(".ogcolor.active").trigger("click");
		}, 100);
	}).select2();*/
	
	console.log("before ogcolor click");
	
	$(document).on("click", ".ogcolor", function(e){
		e.preventDefault();
		var self = $(this);

		var productId = $("[name=product_id]").val();
		var parent = self.parents(".customize-panel");

		$('.ogcolor').css({
			'text-indent': 'inherit'
		}).html('').removeClass("active");

		var ok = $("<i class='icon-ok icon-white'></i>");
		if(self.data('color-value').replace(/[#_]/, '') == 'ffffff'){
			ok.removeClass('icon-white');
		}

        $("#personalizeBtn").attr("href", function(){
            $url = $(this).attr("href").replace(/p=[0-9]+&/, "p=" + productId+"&");
            //if product_color exists or not else append
            return $url;
        });
		
		var data_href = $(".js-sizechart-init").data('href');
		var data_width = $(".js-sizechart-init").data('width');
		var data_height = $(".js-sizechart-init").data('height');
		var size_chart_link = data_href.replace(/productidhere/, productId);
		
		var sizechart_url = "javascript:popupWin('" + size_chart_link + "', " + data_width + ", " + data_height + ")";
		$(".js-sizechart-init").attr('href', sizechart_url);

		self.append(ok).addClass("active");

		/*var buyBtn = parent.find("[data-action=quickbuy]");
		buyBtn.data("color", self.data("color-value"));
		buyBtn.data("product", productId);*/ // commented by ksa		
		//
		var $windowWidth = $(window).width();		
		if( $windowWidth <= 568 ){
			$("img[data-design-id="+self.data("id")+"_large]").each(function(){				
				var itemImage = $(this);
				if(itemImage.data("side") != 'design') {
					var _face = itemImage.data("side") || "front";
					var imageSource = "/ajax/color.php?id="+self.data("id")+"&face="+_face+"&color="+self.data("color-value").replace("#","_")+"&redirect&product_id="+productId;
					console.log(imageSource);
					//alert("changed image for " + _face + " as " + imageSource);
					
					itemImage.attr("data-src", imageSource);
					itemImage.attr("src", imageSource);
				} else {
					var imageSource = itemImage.data("src");
				}
			});
		} else {
			$("img[data-design-id="+self.data("id")+"_large]").each(function(){
				/*if($(this).data("color") != self.data("color-value")){*/				
				var itemImage = $(this);
				if(itemImage.data("side") != 'design') {
					var _face = itemImage.data("side") || "front";
					var imageSource = "/ajax/color.php?id="+self.data("id")+"&face="+_face+"&color="+self.data("color-value").replace("#","_")+"&redirect&product_id="+productId;
					console.log(imageSource);
					itemImage.attr("data-src", imageSource);
					itemImage.attr("src", imageSource);
				} else {
					var imageSource = itemImage.data("src");
				}
				console.log(imageSource);
			});
			
			$("img[data-design-id="+self.data("id")+"]").each(function(){
				/*if($(this).data("color") != self.data("color-value")){*/				
				var itemImage = $(this);
				if(itemImage.data("side") != 'design') {
					var _face = itemImage.data("side") || "front";
					var imageSource = "/ajax/color.php?id="+self.data("id")+"&face="+_face+"&color="+self.data("color-value").replace("#","_")+"&redirect&product_id="+productId;
					console.log(imageSource);
					itemImage.attr("data-src", imageSource);
					itemImage.attr("src", imageSource);
				} else {
					var imageSource = itemImage.data("src");
				}
			});
		}
		
		
		
		var price_qty_attr = $("[data-bind=price][data-id="+self.data("id")+"]").attr('data-price-qty');
		if (typeof price_qty_attr === typeof undefined || price_qty_attr === false) {
			price_qty_attr = 1;			
		}
		
		//zoom_images();
		console.log('price_qty_attr is '+ price_qty_attr);
		$.getJSON("/ajax/product.php?qty="+price_qty_attr+"&id="+self.data("id")+"&country="+countryId+"&action=design_price&json=1&product_color="+self.data("color-value")+"&product_id="+productId, function(d){
			$("[data-bind=price][data-id="+self.data("id")+"]").html(d.data.unit_price);
			if($.isPlainObject(d.data) && $.isArray(d.data.colors)){
				$("[data-color-value]").css("display", "none");
				$.each(d.data.colors, function(a, color){
					$("[data-color-value="+ color.replace("#", "_") +"]").show();
				});
				/*if(!$(".ogcolor.active").is(":visible")){
					$(".ogcolor:visible").first().trigger("click");
				}*/
			}
            if(window.history){
                window.history.replaceState({product_id: productId}, null, d.data.url.view);
            }
			$("#product_info").html(d.data.product_info);
			$("#design_info").html(d.data.design_info);
			$("#h1-heading-tag").html(d.data.h1_heading);
			
			image_lazy_loading();
			$(".js-qty").first().trigger('change');
		});
	});
	
	if($("#categories-tab-container").length > 0) {
		var design_id = $("#ksa_design_id").val();
		$.get('/ajax/product.php',{action:'get_categories_tabs', design_id: design_id},function(data){
			$("#categories-tab-container").html(data);
			
			$('.categories-tabs .nav-tabs a').click(function (e) {
				e.preventDefault()
				$(this).tab('show')
			})
			if($('#products-carousel35').length > 0) {
				image_lazy_loading();
				$('#products-carousel35').owlCarousel(carousel_options);
			}
			after_tabs();
			//$(".categories-tabs .nav-tabs .nav-link:first").click();
		});
	}
	
	// code for the size_type = 0 so that it only displayes one qty option and not different sizes based quantity options
	if($("#temp_qty").length > 0) {
		$("#temp_qty").on('change', function(){
			$("#qty_s").val($(this).val()).trigger('change');										  
		});	
	}
});

function after_tabs() {
	$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
		var target = $(e.target).attr("href"); // activated tab
		//if($(e.target).hasAttr('data-type')) {
			if($(e.target).data('type') == 'categories') {
				image_lazy_loading();
				$(target).find('.ksa-carousel').owlCarousel(carousel_options);
			}
		//}
		console.log(target);
	});	
}