function showProvince(pCode) {
	$("#locations div.reseller-region").hide();
	if(pCode != "undefined") 
		$("#reseller-region-" + pCode).show();
	else 
		$("#no-resellers-region").show(); 
}

(function( $ ) {
  $.fn.selectRedirect = function() {
    this.change(function() {
			window.location = $(this).val();
		});
  };
})( jQuery );


$(document).ready(function() {
	
	$("select.addons").selectRedirect();
	
	$(".puff-minasidor input.default").keydown(function(e) {
  	if (e.keyCode == 13) {
    	document.location = $(".puff-minasidor .button a").attr("href");
      return false;
    }
  });
	
function submitSearch(search) {
 var query = search.find("input.search-field").val();
 if (!query)
  return;
 var url = search.find("a.search-button").attr("href");
 url += url.indexOf("?") > -1 ? "&" : "?";
 url += "query=" + encodeURIComponent(query);
 document.location = url;
}

	// Hook up tooltip
$("a.tool").tooltip({ offset: [55, -63],effect: 'slide'});
	   // tweak the position

	
 /*
    * All search-boxes requires three elements:
    *  div.search-box (container)
    *  input.search-query
    *  a.search-button
    */
    // Submit searches on mouse-clicks
    $("a.search-button").click(function() {
        submitSearch($(this).closest("div.search"));
        return false;
    });
    // Submit searches on ENTER-key
    $(".search-field").keydown(function(e) {
        if (e.keyCode == 13) {
            submitSearch($(this).closest("div.search"));
            return false;
        }
    });

my_form = new Form();
my_form.clearPassword("password-clear");
my_form.inlineLabels("default"); // Måste anropas innan "inputDefaults".
my_form.inputDefaults("default");
//my_form.enterSubmit("enter-submit");
my_form.validate("validate");

	// Toppuff Startsidan
	$(".right-column-start.toppuff").hover(function() {
		var id = $(this).attr("id").split("-");
		$(".right-column-start.toppuff.selected").removeClass("selected");
		$(this).addClass("selected");
		$(".banner-picture").hide();
		$("#banner-picture-"+id[1]).show();
	});

	// Setup cufon
	Cufon.replace('h1', { fontFamily: 'Futura Std' });
	Cufon.replace('.right-column-start.toppuff h3', { fontFamily: 'Futura Std' });
	
	
	// All input fields assigned with the class 'default' will
	// get their default values hidden when clicked, and reset again 
	// if the user leaves the field empty or hasnt changed anything
	// The searchfields needs an accompanying hidden input with the
	// same id but suffixed "-default" that contains the default value.
	$(".search-field").each(function() {
		var defaultVal = $(this).next(".defaultvalue").val();
		if (!$(this).val())
			$(this).val(defaultVal);
		$(this).focus(function() {
			if ($(this).val() == defaultVal)
				$(this).val("");
		});
		$(this).blur(function() {
			if ($(this).val() == "")
				$(this).val(defaultVal);
		});
	});
				
	// Validate forms
	/*$(".validate-form .validate").click(function() {
		if(validate($(this).parent())) {
			setStatus($(this).parent().parent(), true);
		}
		else {
			setStatus($(this).parent().parent(), false);
			return false;
		}
	});*/
	
	// Clear graphical error on required fields when correcting it
	/*$("input.required, textarea.required")
	.keydown(function() {
		clearError($(this));			
	});*/
	
	// Toggle on products
	$(".toggle a:not(.toggle .content a)").click(function() {
		$(this).next(".content").slideToggle();
		$(this).parent("li").toggleClass("expanded");
		return false;
	});
	
	/* Expandable modules */
	$(".module a.toggle").click(function() {
		$(this).hasClass("expanded") ? $(this).removeClass("expanded") : $(this).addClass("expanded");
		$(this).parent().next(".expandable").slideToggle();
		return false;
	});		
		
	// Hook up family product images with tooltips
	$("#family .tip-trigger").tooltip({
	   offset: [100, 0],
	   relative: true,
	   effect: 'slide'

	}).dynamic({ bottom: { direction: 'down', bounce: true } });
	
	// Hook up environment tooltips
	$("#environment .tip-trigger").tooltip({
	   offset: [10, -15],
	   relative: true,
	   effect: 'slide'

	}).dynamic({ bottom: { direction: 'down', bounce: true } });
	
	// Hook up mega-drops inspiration images with tooltips
	$(".mega-header .tip-trigger").tooltip({
	   offset: [40, 2],
	   relative: true,
	   effect: 'slide'

	}).dynamic({ bottom: { direction: 'down', bounce: true } });
	
	// Use javascript isntead of :hover for IE6 for megadrops
	if($.browser.msie && $.browser.version=="6.0") {
		$("#mega-drop li:not(#mega-drop li li)")
		.mouseover(function() {
			$(this).addClass("hover");
		})
		.mouseout(function() {
			$(this).removeClass("hover");
		});
	}
	
	// Convert option value to url and set location
	$("#filter select").change(function() {
		if ($(this).val())
		document.location = $(this).val();
    });
	
	// Init slideshow before fancybox
	slideshow();
	
	// Init fancybox for swf's
	$("a.fancy-swf").fancybox({
		'padding'			: 0,
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'swf'				: {
			'wmode'					: 'opaque',
			'allowfullscreen'		: 'true'
		}
	});
	
	// Init fancybox for inline content
	$("a.fancy-inline").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none'
	});
	
	// Init fancybox for images
	$("a.fancy").fancybox({
		'titlePosition': 'inside'
	

	});
	
});

// 
// Clear error on required fields
//
function clearError(obj) {
	if (obj.val())
		obj.removeClass("has-error");
}

//
// Show and hide the status text for a form
//
function setStatus(obj, val) {
	obj.find(".status p").hide();
	if(val) {
//		obj.find(".status .success").show();
	}
	else {
		obj.find(".status .error").show();
	}
}

//
// Validates all input and textarea children of the passed object.
// Adds a yellow background on required input/textareas that are not correctly filled.
//
/*function validate(obj) {
	
	var validated = true;
	
	obj.find(".required").each(function() {
		if($(this).val() == "" || $(this).val() == $(this).next(".defaultvalue").val()) {
			$(this).addClass("has-error");	
			validated = false;
		}
	});

	if (!validated) {
		return false;
	}
	else {
		return true;
	}
}*/

//
// Animate entrances
//
$(function() {
	
	var complete = true;
	
	if($("#entrances").length > 0) {
		var animatespeed 	= 1200;
		var intervalspeed 	= 400;
		var count 			= 0;
		var numImages 		= $("#entrances li").length;
		complete			= false;
		
		// hide elements using js
		$("#entrances li .info").hide();
		$("#entrances li .img-container img").css('bottom', -220);
		
		function slideIn() {

			var item 		= $("#entrances li").eq(count);
			var img 		= item.find("img");
			var info 		= item.find(".info");
			
			count++;
			
			img.animate({ 
				bottom: [-40, 'easeOutBack']
			}, animatespeed, false, function() {
				info.slideDown("fast", function() {
					if(count >= numImages) complete = true;
				});
			});

			clearInterval(interval);
			interval = setInterval(slideIn, intervalspeed - (count * 100));
			
			if(count >= numImages) {
				clearInterval(interval);
			}
		}
		
		interval = setInterval(slideIn, intervalspeed);
	}
	
	$(".hover-list li")
	.mouseover(function() {
		if(complete) {
			var infoContent = $(this).find(".info-content");
			var targetHeight = infoContent.children("a").outerHeight();
			
			if(!infoContent.hasClass("hover")) {
				infoContent.addClass("hover");
				infoContent.animate({ 
					height: [targetHeight, 'easeInOutBack']
				}, 350, true);
			}
		}
	})
	.mouseleave(function() {
		if(complete) {
			var infoContent = $(this).find(".info-content");
			
			infoContent.animate({ 
				height: [22, 'easeOutQuad']
			}, 200, true, function() {
				infoContent.removeClass("hover");
			});
		}
	});
});



//
// Article slideshow
//
function slideshow() {

	var elms = [];
	var instantiated = false;
	var index = 0;

	var toggleTo = function(elm) {
		if ($(".slideshow").length == 0) {
			var wrapper = $(".slideshow-container ul").parent();
			wrapper.html("<div class=\"slideshow\"><div class='image-holder'><img src=\"" + elms[elm].src + "\"/></div><p class=\"image-description\">" + elms[elm].caption + "</p></div>");
			
			if(elms[elm].highres.length > 0) {
				$(".slideshow .image-holder").append("<a class='fancy magnify' href='" + elms[elm].highres + "' title='" + elms[elm].caption + "'>"+ zoomTitle + "</a>");
				$(".magnify").show();
			}
			else { $(".magnify").hide(); }
			
			$(".slideshow img").load( function() {
				if (instantiated) {
					$(".slideshow").fadeIn("slow");
					wrapper.animate({
						"height": $(".slideshow").outerHeight()
					}, "slow");
				} else {
					wrapper.css("height", $(".slideshow").outerHeight());
					instantiated = true;
				}
			});
			
		} else {
			$(".slideshow").stop(true, true);
			$(".slideshow").fadeOut("normal", function() {
				$(".slideshow img").attr("src", elms[elm].src);
				$(".slideshow p").html(elms[elm].caption);
				if(elms[elm].highres.length > 0) {
					$(".slideshow a.magnify").attr({
						href: elms[elm].highres,
						title: elms[elm].caption
					});
					$(".magnify").show();
				}
				else { $(".magnify").hide(); }	
			});
			
		}
		$(".slideshow-nav a").removeClass("current");
		$(".slide-" + elm).addClass("current");
	};
			
	$(".slideshow-container li a").each( function() {
		elm = $(this);
		elms.push( {
			"src": elm.attr("href"),
			"caption": elm.text(),
			"thumb": $(elm.children("img")).attr("src"),
			"highres": elm.attr("title")
		} );
	});
	
	if (elms.length > 0) {
		var rows = 3;
		var firstInRow = "";
		
		$(".slideshow-container").addClass("loader");
		$("#related").prepend("<div class=\"slideshow-nav\"><ul></ul></div>");
		for (var i = 0, l = elms.length; i < l; i++) {
			if(i % rows == 0) firstInRow = "first";
			$(".slideshow-nav ul").append("<li class=\""+ firstInRow + "\"><a href=\"" + elms[i].src + "\" class=\"slide-" + i + "\"><img src=\"" + elms[i].thumb + "\"/><span></span></a></li>");
			firstInRow = "";
		}
		
		toggleTo(0);
		$(".slideshow-nav li a").live("click", function() {
			index = $(this).parent("li").index();
			toggleTo(index);
			return false;
		});
	}
}

//
// Hook up tabs
//
$(function() {
	$(".tabs .tab")
	.click(function() {
		var id = $(this).attr("id");
		if($("#"+id+"-content").length) {
			$(".tabs .active").removeClass("active");
			$(".tabs .tab-area").hide();
			$("#"+id+"-content").show().addClass("active");
			$(this).addClass("active");
		}
		return false;
	});

});

Form = function() {
	Form = this;
	Form.addSubmitAction = function(element, fieldClass) {
		if(element == "a") {
			$("a." + fieldClass).click(function() {
				$(this).closest("form").submit();
      		});
    	}
  	}
 
	Form.clearPassword = function(fieldClass) {
    	$("input." + fieldClass).each(function() {
    		$(this).after('<input type="text" name="'+$(this).attr("name")+'-clear" class="'+$(this).attr("class")+' '+fieldClass+'-clear" size="'+$(this).attr("size")+'" value="'+$(this).val()+'" />');
    		$(this).hide();
			$("input." + fieldClass + "-clear").removeClass("match");
			$("input." + fieldClass + "-clear").removeClass("required");
    	});
    	$("input." + fieldClass + "-clear").focus(function() {
    		$(this).hide();
    		var passwordField = $(this).prev("input." + fieldClass);
    		var defaultValue = passwordField[0].defaultValue;
    		passwordField.show();
    		passwordField.focus();
    		passwordField.blur(function() {
    			if($(this).val() == "" || $(this).val() == defaultValue) {
    				$(this).next("input." + fieldClass + "-clear").show();
    				$(this).next("input." + fieldClass + "-clear").val(defaultValue);
    				$(this).hide();
    			}
				passwordField.hasClass("error") ? $(this).next("input." + fieldClass + "-clear").addClass("error") : $(this).next("input." + fieldClass + "-clear").removeClass("error");
    		});
    	});
	}
 
	Form.inputDefaults = function(fieldClass) {
		$("input." + fieldClass).live("focus", function(){
			if($(this).val() == $(this)[0].defaultValue){ $(this).val(""); }
    	$(this).addClass("active");
    	$(this).blur(function(){
    		if($(this).val() == ""){
       		$(this).val($(this)[0].defaultValue);
       	}
				$(this).removeClass("active");
      });
    });
  }
	
	Form.inlineLabels = function(fieldClass) {
		var temp = 0;
		$("input." + fieldClass).each(function() {
			if($('label[for="'+$(this).attr("id")+'"]').html()) {
				var val = $('label[for="'+$(this).attr("id")+'"]').html();
				val = val.replace(/(<([^>]+)>)/ig,"");
				$(this)[0].defaultValue = val;
				$(this).val(val);
				$('label[for="'+$(this).attr("id")+'"]').hide();
			}
		});
  }
  	
  Form.enterSubmit = function(fieldClass) {
  	$("input." + fieldClass).keydown(function(event) {
    	if (event.keyCode == 13) {
      	$(this).closest("form").submit();
      }
    });
	}
	
	Form.validate = function(fieldClass) {
		var addSubmitValidation = false;
		$("input." + fieldClass).each(function() {
			addSubmitValidation = true; 
			// Check required
			if($(this).hasClass("required")) {
				$(this).blur(function(){
					Form.validateRequired($(this)) ? $(this).removeClass("error") : $(this).addClass("error");
				});
			}
			// Check email
			if($(this).hasClass("email")) {
				$(this).blur(function(){ 
					Form.validateEmail($(this)) ? $(this).removeClass("error") : $(this).addClass("error");
      	});		
			}
			// Check personnumber
			if($(this).hasClass("personnumber")) {
				$(this).blur(function(){ 
					Form.validatePersonnumber($(this)) ? $(this).removeClass("error") : $(this).addClass("error");
      	});		
			}
			// Check phone
			if($(this).hasClass("phone")) {
				$(this).blur(function(){ 
					Form.validatePhone($(this)) ? $(this).removeClass("error") : $(this).addClass("error");
      	});		
			}
			// Check match
			if($(this).hasClass("match")) {
				$(this).blur(function(){
					if(Form.validateMatch($(this))) {
						$("input.match").each(function() {
							$(this).removeClass("error");
						});
					} else {
						$("input.match").each(function() {
							$(this).addClass("error");
						});
					}
      	});		
			}
		});
		
		if(addSubmitValidation) {
			//$("input." + fieldClass + ":first").closest("form").submit(function() {
			//a.submit:first
			$("a.enter-submit:first").click(function() {
				var valid = true;
				var output = "";
				$("input." + fieldClass).each(function() {
					// Required
					if($(this).hasClass("required") && Form.validateRequired($(this))) {
						$(this).removeClass("error");
					} else if($(this).hasClass("required")) {
						$(this).addClass("error");
						valid = false;
					}
					// Email
					if($(this).hasClass("email") && Form.validateEmail($(this))) {
						$(this).removeClass("error");
					} else if($(this).hasClass("email")) {
						$(this).addClass("error");
						valid = false;
					}
					// Personnumber
					if($(this).hasClass("personnumber") && Form.validatePersonnumber($(this))) {
						$(this).removeClass("error");
					} else if($(this).hasClass("personnumber")) {
						$(this).addClass("error");
						valid = false;
					}
					// Phone
					if($(this).hasClass("phone") && Form.validatePhone($(this))) {
						$(this).removeClass("error");
					} else if($(this).hasClass("phone")) {
						$(this).addClass("error");
						valid = false;
					}
					// Match
					if($(this).hasClass("match") && Form.validateMatch($(this))) {
						$("input.match").each(function() {
							$(this).removeClass("error");
						});
					} else if($(this).hasClass("match")) {
						$("input.match").each(function() {
							$(this).addClass("error");
						});
						valid = false;
					}
				});
				
				return valid;
			});
		}
	}
	
	Form.validateRequired = function(field) {
		if(field.hasClass("default")) {
			return field.val() == "" || field.val() == field[0].defaultValue ? false : true;
		} else {
			return field.val() == "" ? false : true;
		}
	}
	Form.validateEmail = function(field) {
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		return emailPattern.test(field.val()) ? true : false;
	}
	Form.validatePersonnumber = function(field) {
		var persnr = field.val().replace(/-/g, "");
		persnr = persnr.replace(/ /g, "");
		return isNaN(persnr) || persnr.length < 10 ? false : true;
	}
	Form.validatePhone = function(field) {
		var phone = field.val().replace(/ /g, "");
		var phonePattern = /^[0-9-()+]{5,}$/;
		return phonePattern.test(phone) ? true : false;
	}
	Form.validateMatch = function(field) {
		var valid = true;
		$("input.match").each(function() {
			if(field.val() != $(this).val()) { valid = false; }
		});
		if(field.val().length < 6) { valid = false; }
		return valid;
	}
}
