jQuery.fn.swap = function(b){
    if (b == null) {
      return;
    } else {
      b = jQuery(b)[0];
      var a = this[0];
      var t = a.parentNode.insertBefore(document.createTextNode(''), a);
      b.parentNode.insertBefore(a, b);
      t.parentNode.insertBefore(b, t);
      t.parentNode.removeChild(t);
      return this;
    }
};

Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		
		if(this[i].toLowerCase() == p_val.toLowerCase()) {
			return true;
		}
	}
	return false;
}

function checkVariants(variants, mainArticle) {
		
	$.ajax({
	  type: "POST",
	  url: "/_common/_ajax/ajax_verify_variants.php",
	  data: "ajax-action=verifyVariant&mainArticle="+mainArticle+"&varianter="+variants,
	  cache: false,
	  dataType: 'json',
	  success: function(d){

		if(d['status'] === false) { // Vald variant kombination fanns inte
			$("#empty_p").html(d['data']);
		} else { // Varianten finns, då uppdaterar vi lite fält osv...
			// Uppdatera gömda fält
			$("input[name='artikelkod']").val(d['data']['artikelkod']);
			$("input[name='artikelgrupp']").val(d['data']['artikelgrupp_kod']);
			$("input[name='artikelkategori']").val(d['data']['artikelkategori_kod']);
			$("input[name='artikel_momssats']").val(d['data']['momssats']);
			
			// Är köprutan gömd? 
			if($("#buy_btn_container").is(":hidden")) {
				$("#buy_btn_container").show();
			}
			
			// Uppdatera synlig data
			
			$("#article_number_shown").animate({
				opacity: "0.4"
			},100,function() {
				$("#article_number_shown").html(d['data']['artikelkod']);
				$("#article_number_shown").animate({opacity: "1"}, 1000);
			});
			// Lagerstatus borttaget 091119 i väntan på ny lösning för att förhindra att cachen sätta om hela tiden
			// $("#warehouse_status").animate({
			// 	opacity: "0.4"
			// },100,function() {
			// 	$("#warehouse_status").html(d['data']['lagerstatus']);
			// 	$("#warehouse_status").animate({opacity: "1"}, 1000);
			// });
			if($(".staff_inkl_1").length) {
				$(".staff_inkl_1").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_inkl_1").html(d['data']['staff_inkl_1']);
					$(".staff_inkl_1").animate({opacity: "1"}, 1000);
				});
				$(".staff_exkl_1").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_exkl_1").html(d['data']['staff_exkl_1']);
					$(".staff_exkl_1").animate({opacity: "1"}, 1000);
				});
			}
			if($(".staff_inkl_2").length) {
				$(".staff_inkl_2").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_inkl_2").html(d['data']['staff_inkl_2']);
					$(".staff_inkl_2").animate({opacity: "1"}, 1000);
				});
				$(".staff_exkl_2").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_exkl_2").html(d['data']['staff_exkl_2']);
					$(".staff_exkl_2").animate({opacity: "1"}, 1000);
				});
			}
			if($(".staff_inkl_3").length) {
				$(".staff_inkl_3").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_inkl_3").html(d['data']['staff_inkl_3']);
					$(".staff_inkl_3").animate({opacity: "1"}, 1000);
				});
				$(".staff_exkl_3").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_exkl_3").html(d['data']['staff_exkl_3']);
					$(".staff_exkl_3").animate({opacity: "1"}, 1000);
				});
			}
			if($(".staff_inkl_4").length) {
				$(".staff_inkl_4").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_inkl_4").html(d['data']['staff_inkl_4']);
					$(".staff_inkl_4").animate({opacity: "1"}, 1000);
				});
				$(".staff_exkl_4").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_exkl_4").html(d['data']['staff_exkl_4']);
					$(".staff_exkl_4").animate({opacity: "1"}, 1000);
				});
			}
			if($(".staff_inkl_5").length) {
				$(".staff_inkl_5").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_inkl_5").html(d['data']['staff_inkl_5']);
					$(".staff_inkl_5").animate({opacity: "1"}, 1000);
				});
				$(".staff_exkl_5").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_exkl_5").html(d['data']['staff_exkl_5']);
					$(".staff_exkl_5").animate({opacity: "1"}, 1000);
				});
			}
			if($(".staff_inkl_6").length) {
				$(".staff_inkl_6").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_inkl_6").html(d['data']['staff_inkl_6']);
					$(".staff_inkl_6").animate({opacity: "1"}, 1000);
				});
				$(".staff_exkl_1").animate({
					opacity: "0.4"
				},100,function() {
					$(".staff_exkl_6").html(d['data']['staff_exkl_6']);
					$(".staff_exkl_6").animate({opacity: "1"}, 1000);
				});
			}
						
			$("#pris_exkl_moms").animate({
				opacity: "0.4"
			},100,function() {
				$("#pris_exkl_moms").html(d['data']['pris_exkl_moms']);
				$("#pris_exkl_moms").animate({opacity: "1"}, 1000);
			});
			$("#pris_inkl_moms").animate({
				opacity: "0.4"
			},100,function() {
				$("#pris_inkl_moms").html(d['data']['pris_inkl_moms']);
				$("#pris_inkl_moms").animate({opacity: "1"}, 1000);
			});
		}

	  }
	});
}
$(document).ready(function () {
	
	// FancyBox - Alla url:er som har klassen image på sig
	$("a.image").fancybox();
	// Slut - FancyBox
	
	// Login rutan
	$("#login").click(function(e) {
	    if($("#login_form_container").is(":hidden")) {
	    	$("#login_form_container").slideDown(300);
			$("#username_small").focus();
	    	if($("#smallbasket").is(":visible")) {
	    		$("#smallbasket").slideUp('fast');
	    	}
	    	return false;
	    } else {
	    	$("#login_form_container").slideUp('fast');
	    	return false;
	    }
	});
	
	$("#close_button").click(function() {
	    if(!$("#login_form_container").is(":hidden")) {
	    	$("#login_form_container").slideUp('fast');
	    	return false;
	    }
	});
	// Slut Loginrutan
	
	// Visa / göm kundvagnen
	$("#smallbasket_toggle").click(function() {
	    if ($("#smallbasket").is(":hidden")) {
	    	$("#smallbasket").slideDown(300,function() {
	    		$("#smallbasket_toggle").addClass("navOn");
	    	});
	    	if($("#login_form_container").is(":visible")) {
	    		$("#login_form_container").slideUp("fast");
	    	}
	    } else {
	    	$("#smallbasket").slideUp(function() {
	    		$("#smallbasket_toggle").removeClass("navOn");
	    	});
	    }
	    return false;
	});
	$("#close_button_smallbasket").click(function() {
	    if(!$("#smallbasket").is(":hidden")) {
	    	$("#smallbasket").slideUp('fast');
	    	return false;
	    }
	});
	// Slut visa/göm kundvagnen
	
	// ta bort artikel från kundvagnen, prompta användaren...
	$(".dellink").click(function() {
	    var answer = confirm('Ta bort artikelrad?');
	    if(!answer) { return false; }
	});
	// Slut prompt
	
	// Lägg i kundvagn notifier och orderhistoriktips notifier utseende
	$('#smallbasket_toggle, #orderhistory_notifier').bt({
		trigger: 'none',
		positions: 'bottom',
		fill: '#008000', 
	    cssClass: 'checkout_notifier',
	    strokeStyle: '#B7B7B7', 
	    spikeLength: 10, 
	    spikeGirth: 10, 
	    padding: 8, 
	    cornerRadius: 4
	    
	});
	 
	
	// Alla inputs och inloggninsnotifiers utseende
	$(":input,#password").each(function(i) {
	    $(this).bt({
			trigger: 'none',
			positions: 'right',
			fill: '#D14646', 
			cssClass: 'input_notifiers',
	    	strokeStyle: '#B76666', 
	    	spikeLength: 10, 
	    	spikeGirth: 10, 
	    	padding: 4, 
	    	cornerRadius: 4,
	    	clickAnywhereToClose: false
	    });
	});
	
	$(".cart_amount,#searchbutton").bt({
    	positions: 'right',
    	fill: '#008000', 
  		cssClass: 'checkout_notifier',
  		strokeStyle: '#B7B7B7', 
  		spikeLength: 10, 
  		spikeGirth: 10, 
  		padding: 8, 
  		cornerRadius: 4
  	});
 	
 	// Slut notifiers
 	
 	$('#checkout_form').submit(function() {
		if($('#form2_pass18:input').val() == $('#form2_pass_confirm19:input').val()) {
			return true;
		} else {
			$("#spanPass1").text("Lösenorden överenstämmer inte!").show().fadeOut(3000);
			$("#spanPass2").text("Lösenorden överenstämmer inte!").show().fadeOut(3000);
			return false;
		}
	});
 	
 	$('#form2_custtype2_1').click(function() {
 		$('#fieldset_foretag').fadeOut('fast',function() {
 			$(":input").each(function() {
 				$(this).btOff();	
 			});
 			
 			$('#fieldset_person').fadeIn('slow');
 		})
 	});

 	$('#form2_custtype2_2').click(function() {
 		$('#fieldset_person').fadeOut('fast',function() {
 			$(":input").each(function() {
 				$(this).btOff();	
 			});
 			
 			$('#fieldset_foretag').fadeIn('slow');
 		})
 	});
 	
 	$("#sendorderbutton").click(function() {
 		var answer = confirm('Är du säker på att du vill skicka beställningen?');
 		if(!answer) { return false; }
 	});
 	 	
	// Slut kundvagnen
	
	// checkboxarna på produktlistningen 
  $("#visa_bild").click(function() {
    if($(".products_image").is(":hidden")) {
      $.ajax({
        type: "POST",
        url: "/_common/_ajax/ajax_siteprefs.php",
        data: "ajax-action=toggleImages&showImages=1",
        success: function(msg){
          $(".products_image").fadeIn('slow');
          $(".product_price_base").removeClass('noimg');
          $(".product_price_base").each(function() {
            $(this).swap($(this).next());
          })
        }
      });
    } else {
      $.ajax({
        type: "POST",
        url: "/_common/_ajax/ajax_siteprefs.php",
        data: "ajax-action=toggleImages&showImages=0",
        success: function(msg){
          $(".products_image").fadeOut('fast');
          $(".product_price_base").addClass('noimg');
          $(".ingress").each(function() {
            $(this).swap($(this).next());
          })
        }
      });
    }
  });

	$("#visa_liten_bild").click(function() {
		if($(".product_image_small").is(":hidden")) {
			$.ajax({
 			  type: "POST",
 			  url: "/_common/_ajax/ajax_siteprefs.php",
 			  data: "ajax-action=toggleSmallImages&showSmallImages=1",
 			  success: function(msg){
 			    $(".product_image_small").fadeIn('slow');
 			  }
 			});
		} else {
			$.ajax({
 			  type: "POST",
 			  url: "/_common/_ajax/ajax_siteprefs.php",
 			  data: "ajax-action=toggleSmallImages&showSmallImages=0",
 			  success: function(msg){
 			    $(".product_image_small").fadeOut('fast');
 			  }
 			});
		}
	});
	
	$("#visa_inkl_moms").click(function() {
	
		// bool 1 = visa inkl moms
		// bool 0 = visa exkl moms
			
		var visa_eller_inte = $('#visa_inkl_moms').attr('checked')?1:0;
	
		$.ajax({
		  type: "POST",
		  url: "/_common/_ajax/ajax_siteprefs.php",
		  data: "ajax-action=toggleVatPrices&showInclVat="+visa_eller_inte,
		  success: function(msg){
			
			if(visa_eller_inte == 0) { // visa exkl moms
				
				$("span.pris_inkl_moms").each(function() {
					$(this).animate({
						"opacity": "hide"
					},300,function() {
						$(this).css({'display':'none'});
						$(this).parent().children("span.pris_exkl_moms").animate({
							"opacity": "show"
						},600);
					});
				});
				
				// 2010-05-26 Behanlda de stafflade priserna också
				/* Beh�vs ej?
				$("td.pris_inkl_moms").each(function() {
					$(this).animate({
						"opacity": "hide"
					},300,function() {
						$(this).css({'display':'none'});
						$(this).parent("tr").children("td.pris_exkl_moms").animate({
							"opacity": "show"
						},600);
					});
				}); */
			
			} else {
				
				$("span.pris_exkl_moms").each(function() {
					$(this).animate({
						"opacity": "hide"
					},300,function() {
						$(this).css({'display':'none'});
						$(this).parent().children("span.pris_inkl_moms").animate({
							"opacity": "show"
						},600);
					});
				});
				
				/* Beh�vs ej?
				$("td.pris_exkl_moms").each(function() {
					$(this).animate({
						"opacity": "hide"
					},300,function() {
						$(this).css({'display':'none'});
						$(this).parent("tr").children("td.pris_inkl_moms").animate({
							"opacity": "show"
						},600);
					});
				}); */
			}
			
		  }
		});
	});
	
	$("#form1_paymentmethod_2").click(function() {
		$("#supported_cards").toggle(300);
	});
	
	// Finns det med en hash i url:en när produkten laddas ?
	currentAnchor = document.location.hash;
	
	if(currentAnchor) {
		var variants = [];
		anchor = currentAnchor.slice(1);
		anchorArr = anchor.split(";");
		
		var num = anchorArr.length;
		var i = 0;
		while (i<num) {
			select = anchorArr[i].split("=");
			if(select.length) {
				if(select[1].search(/\+/)) {
					select[1] = select[1].replace(/\+/ig," ");
				}
				escaped = unescape(select[1]);
				variants.push(select[0]+"="+escaped.replace(/,/ig, "%"));
				
				$("#"+select[0]).val([escaped]);	
				
				
			}
			i++;
		}
		
		
		
		var mainArticle = $("input[name='huvudartikelkod']").val();
		checkVariants(variants, mainArticle);
		
		$("#variant_2 option").each(function() {
			selectedVal = $("#variant_1 option:selected").val();
			if(selectedVal != "#" && sel_variants['variant_1'][selectedVal].in_array($(this).val()) && $(this).val() != '#') {
				if($(this).attr("disabled") == true) {
					$(this).removeAttr("disabled");
				}
			} else {
				if($(this).val() != '#') {
					$(this).attr("disabled", true);
				}
			}
		});
		$("#variant_1 option").each(function() {
			selectedVal = $("#variant_2 option:selected").val();
			if(selectedVal != "#" && sel_variants['variant_2'][selectedVal].in_array($(this).val()) && $(this).val() != '#') {
				if($(this).attr("disabled") == true) {
					$(this).removeAttr("disabled");
				}
			} else {
				if($(this).val() != '#') {
					$(this).attr("disabled", true);
				}
			}
		});
	}
	
	// Verifiera variant kombination
	$("select[id^='variant_']").change(function() {
		
		var antal = $("select[id^='variant_']").length;
		var variants = [];
		continueToggle = true;
		
		id = $(this).attr("id");
		val = $(this).val();
		
		if(id == 'variant_1') {
				
			if($(this).val() == '#') {
				$("#variant_2 option:disabled").removeAttr("disabled");
				$("#price_container").hide();
				$("#buy_btn_container").hide();
				if($("#cloned_price_container").length) {
					$("#cloned_price_container").show();
				}
			} else {
				$("#variant_2 option").each(function() {
					if(sel_variants[id][val].in_array($(this).val()) && $(this).val() != '#') {
						if($(this).attr("disabled") == true) {
							$(this).removeAttr("disabled");
						}
					} else {
						if($(this).val() != '#') {
							$(this).attr("disabled", true);
						}
					}
				});
			}
		} 
		if(id == 'variant_2') {

			if($(this).val() == '#') {
				$("#variant_1 option:disabled").removeAttr("disabled");
				$("#price_container").hide();
				$("#buy_btn_container").hide();
				if($("#cloned_price_container").length) {
					$("#cloned_price_container").show();
				}
			} else {
				$("#variant_1 option").each(function() {
					if(sel_variants[id][val].in_array($(this).val())) {
						if($(this).attr("disabled") == true) {
							$(this).removeAttr("disabled");
						}
					} else {
						if($(this).val() != '#') {
							$(this).attr("disabled", true);
						}
					}
				});
			}
		}
		hashes = 0;
		$("select[id^='variant_']").each(function(i) {
			id = $(this).attr("id");
			val = $(this).val();
			
			if(val == '#') {
				hidePrice = true;
				hashes++;
				continueToggle = false;
			} else {
				variants.push(id+"="+val);
			}
		});
		
		//alert(showFromPrice)
		if(hashes == antal && continueToggle == false) {
			$("#price_container").hide();
			$("#cloned_price_container").fadeIn(300);
		}
		
		if(continueToggle) {

			if(!$("#cloned_price_container").length) {
				
				$("#price_container")
					.clone(false)
					.attr({id:'cloned_price_container'})
					.insertAfter("#price_container");

				$("#cloned_price_container").children().each(function(i) {
					$(this).attr({'id':'cloned_'+$(this).attr('id'), 'class':'cloned_'+$(this).attr('class')});
				});
			}
			
			
			// Visa först köpknappen och antal inputen
			$("#buy_btn_container").show();
			
			if($("#cloned_price_container").is(":visible")) {
				$("#cloned_price_container").hide();
				$("#price_container").show();
			}
			
			var mainArticle = $("input[name='huvudartikelkod']").val();
			checkVariants(variants, mainArticle);
		}
	});
	
		// Mouseover css på tabellerna
	/*
$(".products_table tbody tr").hover(function() {
		$(this).css('background-color','#D4E2FF');
	},
	function() {
		$(this).css('background-color','');
	});
*/
	// Slut mouse over på tabellerna

}); 
