var map;

$(document).ready(function(){
	/* Rules for the product page */
	$(".colors li").click(function() {
		var active_classes = $(this).find(".preview").attr("class");
		$("#main_preview").attr("class", active_classes);
		$("#main_preview").removeClass("preview");
	});

	$(".colors li").mouseover(function() {
		$("#main_preview").css("visibility", "hidden");
	}).mouseout(function() {
		$("#main_preview").css("visibility", "visible");
	});

	/* Making all columns equal height */
	if ($("#columns").length > 0) {
		var max_height = 0;
		$(".column").each(function() {
			if ($(this).height() > max_height) {
				max_height = $(this).height();
			}
		});
		$(".column").each(function() {
			$(this).height(max_height);
		});
	}

	$(".submenu a").live("click", function() {
		var id = $(this).attr("id");
		id = id.split("link_");
		var $column = $("#"+id[1]);
		rearange_columns($column);
	});

	/* Frontpage media change */
	if ($("#movie_list").length > 0) {
		init_media();
	}

	$("#movies_label").click(function(event) {
		event.preventDefault();
		var active = $("#movie_list .active").attr("id");
		var active = active.split("_")[1];
		//console.log(active);
		//console.log($("#movie_"+active).attr("href"));
		$movie = $("#movie_"+active);
		//console.log($movie.attr("href"));
		if ($movie.is("object")) {
			$movie.css("display", "block");
			$movie.siblings(".close").show();
		} else if ($movie.attr("href").length > 0) {
			var flashvars = { 
				file: $movie.attr("href"), 
				autostart: 'true',
				screencolor: 'ffffff',
				controlbar: 'over',
				menu: 'false',
				abouttext: '',
				aboutlink: ''
			};

			var params = { 
				allowfullscreen: 'true', 
				allowscriptaccess: 'always', 
				wmode: 'opaque',
				menu: 'false'
			};
			swfobject.embedSWF("/scripts/jw/player-licensed.swf", "movie_"+active, "720", "395", "9.0.0", "/scripts/swfobject/expressInstall.swf", flashvars, params);

			// Movie element has been change by swfobject so we need to fetch it again
			$movie = $("#movie_"+active);
			$movie.css("display", "block");
			$movie.siblings(".close").show();
		}
	 });
	 
	 $(".close").click(function() {
		$(".close").hide();
		$("#media>li>object").hide();
	 });

	/* Activating the map */
	if ($("#map").length > 0) {
		if ($("#logo_xl").length == 1) {
			$('input[name="xl"]').click();
		}
		init_map();

		$('select[name="country_shop"]').change(function() {
			$(".active_country").removeClass("active_country");
			$("#country_"+$(this).val()).addClass("active_country");
			init_map();
		})

		$('.active_country select[name="region"]').live("change", function() {
			changeRegion($(this).val());
		});
		
		$('input[name="xl"]').change(function() {
			init_map();
			var region = $(".active_country select").val();
			changeRegion(region);
		});
	}
	
	/* Hide cart if empty */
	if (parseFloat($("#cart_price").html()) == 0) {
		$("#cart").hide();
	}
	
	/* Single shop map */
	if ($("#map2").length > 0) {
		init_single_map();
	}
	
	/* Adding a product to the shopping cart */
	$('#add2cart').click(function() {
		add2cart(this);
	});
	
	/* Register */
	init_input();
	$('select.amount').change(function() {
		var value = 0;
		var amount = 0;
		var total_value = 0;
		var vat = $('input[name="vat"]').val();
		var productnumber = $(this).attr("name").split("_")[1];
		//console.log(productnumber);

		$.getJSON(
			"/ajax.asp?action=update_cart",
			{
				"productnumber" : productnumber,
				"amount" : $(this).val()
			},
			function(data) {
				$("#cart_amount").html(data.amount);
				$("#cart_price").html(data.price);
				updateItemValue();
				updatePostensService(data.price);
				updateFreight();
				updateTotal();
				updateVat();
			}
		)
	});
	
	$('.remove_button').click(function() {
		var productnumber = $(this).siblings("select").attr("name").split("_")[1];
		var amount = 0;
		$.getJSON(
			"/ajax.asp?action=update_cart",
			{
				"productnumber" : productnumber,
				"amount" : amount
			},
			function(data) {
				$("#cart_amount").html(data.amount);
				$("#cart_price").html(data.price);
				validateForm();
				updateItemValue();
				updatePostensService(data.price);
				updateFreight();
				updateTotal();
				updateVat();
			}
		);
		$(this).parent("li").remove();
	});
	
	$('input[name="delivery_method"]').change(function() {
		updateFreight();
		updateTotal();
		updateVat();
	});
	
	$('input[name="send_to"]').change(function() {
		if ($(this).val() == 1) {
			$("#shipping_container").hide();
		} else {
			$("#shipping_container").show();
		}
	});
	
	$('#regsiter_form input').not('#regsiter_form input[name="Zip"], #regsiter_form input[name="ZipDelivery"]').change(function() {
		validateForm();
		/*
		if ($(this).val().length == 0) {
			$(this).val($(this).attr("title"));
		}
		*/
	});

	$('#regsiter_form input').not('#regsiter_form input[name="Zip"], #regsiter_form input[name="ZipDelivery"]').keyup(function() {
		/*
		if ($(this).val().length == 0) {
			$(this).val($(this).attr("title"));
		}
		*/
		validateForm();
	});
	
	/* Klarna */
	if ($("#person_number_container").length > 0) {
		$('#person_number_container input[type="text"]').focus(function(event) {
			$(this).select();
		});
		$('#person_number_container input[type="text"]').blur(function(event) {
			if ($(this).val() == "") {
				 $(this).val($(this).attr("title"));
			}
		});
		$('#person_number_container input').change(function() {
			validatePreOrder();
		});
		$('#person_number_container input[type="text"]').keyup(function(event) {
			validatePreOrder();
		});
	}


	$('#regsiter_form input[name="Zip"]').change(function() {
		$.ajax({
			url: '/getCityByZip.asp?zip='+$(this).val(),
			success: function(data) {
				if (data.length > 0) {
					$('#regsiter_form input[name="City"]').val(data);
				} else {
					$('#regsiter_form input[name="Zip"]').val("");
					$('#regsiter_form input[name="City"]').val("");
				}
				validateForm();
			}
		});
	});
	
	$('#regsiter_form input[name="ZipDelivery"]').change(function() {
		$.ajax({
			url: '/getCityByZip.asp?zip='+$(this).val(),
			success: function(data) {
				if (data.length > 0) {
					$('#regsiter_form input[name="CityDelivery"]').val(data);
				} else {
					$('#regsiter_form input[name="ZipDelivery"]').val("");
					$('#regsiter_form input[name="CityDelivery"]').val("");
				}
				validateForm();
			}
		});
	});
	
	$('#person_number_container input[name="f_postnr"]').change(function() {
		$.ajax({
			url: '/getCityByZip.asp?zip='+$(this).val(),
			success: function(data) {
				if (data.length > 0) {
					$('#person_number_container input[name="f_sted"]').val(data);
				} else {
					$('#person_number_container input[name="f_postnr"]').val("");
					$('#person_number_container input[name="f_sted"]').val("");
				}
				validatePreOrder();
			}
		});
	});
	
	$('#pre_order_form input').change(function() {
		validatePreOrder();
	});
	
	$('#continue').click(function() {
		$("#regsiter_form").submit();
	});
	
	init_search();
	
	$("#radio_link").click(function(event) {
		event.preventDefault();
		popitup($(this).attr("href"));
	});
	
	
	$("#ready2pay").click(function(event) {
		event.preventDefault();
		$("#pre_order_form").submit();
	});
	
	$(".color_selection").change(function(event) {
		if ($(this).find(":selected").val() >= 0) {
			$("#main_preview").attr("class", "c_"+$(this).find(":selected").val());
			$("#main_preview").removeClass("preview");
		}
	});
	
	$('input[name="paymethod"]').change(function(event) {
		if ($(this).val() == "invoice") {
			$("#person_number_container").show();
		} else {
			$("#person_number_container").hide();
		}
	});
	
	/*
	$('#person_number_container input[name="pnr"]').keyup(function(event) {
		if ($(this).val().length == 11) {
			$.getJSON(
				"/kreditor/getaddress_json.asp",
				{
					"PNR" : $(this).val()
				},
				function(data) {
					if (data.result.status == "success") {

						$('#person_number_container input[name="pnr"]').addClass("ok");

						$('#person_number_container input[name="f_fornavn"]').val(data.result.address.first);
						$('#person_number_container input[name="f_etternavn"]').val(data.result.address.last);
						$('#person_number_container input[name="f_adresse"]').val(data.result.address.address);
						$('#person_number_container input[name="f_postnr"]').val(data.result.address.zip);
						$('#person_number_container input[name="f_sted"]').val(data.result.address.city);
						$('#person_number_container input[name="f_land"]').val(data.result.address.country);
						$("#invoice_info").show();
					} else {
						$('#person_number_container input[name="pnr"]').removeClass("ok");
					}
					validatePreOrder();
				}
			)
		}
	});
	*/
	
	$(".contact_form input, .contact_form textarea").keyup(function() {
		validateContact();
	});
	$(".contact_form input, .contact_form textarea").change(function() {
		validateContact();
	});
	$(".sendform").click(function(event) {
		$(".contact_form>li.hidden").removeClass("hidden");
		$.ajax({
			url: "/contact.asp",
			type: "POST",
			data: $("#contact").serialize(),
			success: function(data) {
				$(".contact_form>li.hidden").removeClass("hidden");
				$(".sendform").remove();
				$("#contact input, #contact select, #contact textarea").attr("disabled", "disabled");
			}
		});
		event.preventDefault();
	});
});

function updateVat() {
	var items_value = parseFloat($("#item_value span").html());
	var freight_value = parseFloat($("#freight_value span").html());
	var vat = parseFloat($('input[name="vat"]').val());
	
	$("#vat_value span").html((items_value+freight_value)*vat);
}

function updatePostensService(total_value) {
	var free_delivery = $('input[name="free_delivery"]').val();
	var nonfree_delivery = $('input[name="service_package"]').val();
	
	if (total_value > free_delivery) {
		$('#service_package .freight_price span').html(0);
	} else {
		$('#service_package .freight_price span').html(nonfree_delivery);
	}
}

function updateFreight() {
	var $element = $('input[name="delivery_method"]:checked');
	
	var new_label = $element.siblings('.freight_label').html();
	var new_value = $element.siblings('.freight_price').find('span').html();

	$('#transport_label').html(new_label);
	$('#freight_value span').html(new_value);
}

function updateItemValue() {
	var amount;
	var value;
	var total_value;

	total_value = 0;

	$('#products_in_cart li').each(function() {
		amount = parseFloat($(this).find('select.amount').val());
		value = $(this).find('.product_price span').html();
		value = value.replace(",", ".");
		value = parseFloat(value);
		total_value += value * amount;
	});

	$('#item_value span').html(total_value);
	$('#total_item_value span').html(total_value);
}

function updateTotal() {
	var value_items = $('#item_value span').html();
	var value_freight = $('#freight_value span').html();
	
	//console.log(value_items);
	//console.log(value_freight);
	
	$('#total_value span').html(parseFloat(value_items) + parseFloat(value_freight));
}

function add2cart(element) {
	var $element = $(element);
	var amount = $element.siblings('select[name="amount"]').val();
	var size = $element.siblings('select[name="size"]').val();
	var color = $element.siblings('select[name="color"]').val();
	var basenumber = $element.siblings('input[name="basenumber"]').val();
	var id = $element.siblings('input[name="id"]').val();
	
	if (size < 0 || color < 0) {
		$("#error").remove();
		$("#color_and_size_warning").show();
	} else {
		$("#color_and_size_warning").hide();
		/*
		console.log("Id: " + id);
		console.log("Amount: " + amount);
		console.log("Size: " + size);
		console.log("Color: " + color);
		console.log("Basenumber: " + basenumber);
		console.log("Productnumber: " + basenumber + color + size);
		*/

		$.getJSON(
			$(element).parent("form").attr("action"),
			{
				"id" : id,
				"productnumber" : basenumber + color + size,
				"amount" : amount,
				"size" : size,
				"color" : color,
				"basenumber" : basenumber
			},
			function(data) {
				/* console.log(data); */
				if (data.error) {
					$("#feedback").remove();
					$("#error").remove();
					$element.after('<p id="error">'+data.error+'</p>');
				} else {
					$("#error").remove();
					if (data.feedback) {
						if ($("#feedback").length > 0) {
							$("#feedback").html(data.feedback);
						} else {
							$element.after('<p id="feedback">'+data.feedback+'</p>');
						}
					}
					$("#cart_amount").html(data.amount);
					$("#cart_price").html(data.price);
					$("#cart").show(); // cart is hidden if the value in it is equal to zero, hence we need to show it.
				}
			}
		);
	}
}

function rearange_columns($element) {
	var $list = $element.parent();
	$list.remove($element);
	$list.prepend($element);
}

function init_media() {
	var active_banner;
	$media = $("#movie_list a").live("click", function() {
		active_banner = $(this).attr("id").split("_");
		$("#movie_list .active").removeClass("active");
		$(this).addClass("active");
		$previous = $(".active_media").removeClass("active_media").addClass("passive_media").show();
		$("#banner_"+active_banner[1]).removeClass("passive_media").addClass("active_media");
	});
	
	$("#next_movie").live("click", function() {
		var $next = $("#movie_list .active").parent().next().children("a");
		if ($next.length > 0) {
			$next.click();
		} else {
			$("#movie_list li:first-child a").click();
		}
	});

	$("#prev_movie").live("click", function() {
		var $prev = $("#movie_list .active").parent().prev().children("a");
		if ($prev.length > 0) {
			$prev.click();
		} else {
			$("#movie_list li:last-child a").click();
		}
	});
	
}

function init_map() {
	var selector;
	if ($('input[name="xl"]').is(":checked")) {
		/* selector = ".country .shop_element.hasXL .coordinate" */
		selector = ".active_country .shop_element.hasXL .coordinate"
	} else {
		selector = ".active_country .shop_element .coordinate"
	}

	var coordinates = new Array("60.457218", "8.349609", "4");
	//var coordinates = $("#coord_"+$('.active_country select[name="region"]').val()).html().split(",");
	var latlng = new google.maps.LatLng(coordinates[0], coordinates[1]);
	var myOptions = {
		zoom: parseInt(coordinates[2]),
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var content;

	map = new google.maps.Map(document.getElementById("map"), myOptions);

	var infowindow = new google.maps.InfoWindow();
	/* Using coordinates*/
	$(".shops").empty();
	$(selector).each(function(i) {

		$(this).parent().clone().appendTo(".shops");
	
		coordinates = $(this).html().split(",");
		if ($.trim(coordinates).length > 0) {
			latlng =  new google.maps.LatLng(coordinates[0], coordinates[1]);

			var marker_content = $(this).parent().html();

			var marker = new google.maps.Marker({
				position: latlng,
				title: $(this).siblings(".shopname").html()
			});

			marker.setMap(map);

			google.maps.event.addListener(marker, 'click', function() {
				infowindow.setOptions({
					content: marker_content
				});
				infowindow.open(map, marker);
			});
			
			var classes = $(this).parent("li").attr("class").split(" ");
			$(".shops ."+classes[0]+"."+classes[1]).live("click", function(event) {
				content = $(this).html();
				google.maps.event.trigger(marker, 'click');
			});
		}
	});
	
	$('.shops li').sort(sortAlpha).appendTo('.shops');  
	
	google.maps.event.addListener(map, 'click', function() {
		infowindow.close();
	});
}

function sortAlpha(a,b){  
	return a.innerHTML > b.innerHTML ? 1 : -1;  
};  

/* This function only shows one shop in the map view. Showed when a shop is clicked in the search results */
function init_single_map() {
	var myOptions, latlng;
	var coordinates = $.trim($('.coordinate').html());
	
	/* There is only one element in the list so now it does not matter if that element exceeds it boundaries */

	if (coordinates.length > 0) {
		coordinates = coordinates.split(',')
		latlng = new google.maps.LatLng(coordinates[0], coordinates[1]);
		myOptions = {
			zoom: 8,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById("map2"), myOptions);
		var infowindow = new google.maps.InfoWindow();
		
		var marker = new google.maps.Marker({
			position: latlng,
			title: $(".shopname").html()
		});

		marker.setMap(map);
		
		var marker_content = $(".shop_element").html();
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.setOptions({
				content: marker_content
			});
			infowindow.open(map, marker);
		});
	} else {
		latlng = new google.maps.LatLng(59.811685 ,15.007324);
		myOptions = {
			zoom: 5,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById("map2"), myOptions);
	}
}

function changeRegion(id) {
	var selector;

	if ($('input[name="xl"]').is(":checked")) {
		selector = "#shops_"+id+" ul li.hasXL"
	} else {
		selector = "#shops_"+id+" ul li";
	}

	$(".shops").empty();
	$(selector).clone().appendTo(".shops");
	var coordinates = $("#coord_"+id).html();
	if ($.trim(coordinates).length > 0) {
		coordinates = coordinates.split(",");
		var latlng =  new google.maps.LatLng(coordinates[0], coordinates[1]);
		map.setCenter(latlng);
		map.setZoom(parseInt($.trim(coordinates[2])));
	}
}

/* Validate functions related to purchase of products */
function validatePreOrder() {
	var valid = true;
	var value;
	var $element;
	
	$element = $('#order_information input[name="accept_terms"]:checked');
	value = $element.val();
	if (!validateTerms(value)) {
		//console.log("accept_terms " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}
	
	$element = $('#order_information input[name="chkcountry"]:checked');
	value = $element.val();
	if (!validateCountry(value)) {
		//console.log("chkcountry " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}
	
	$element = $('#order_information input[name="paymethod"]:checked');
	value = $element.val();
	if (!validatePayment(value)) {
		//console.log("paymethod " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");

		if (value == "invoice") {
			$element = $('#person_number_container input[name="pnr"]');
			value = $element.val();
			if (value.length != 11) {
				valid = false;
				$element.addClass("badinput");
			} else {
				$element.removeClass("badinput");
			}

			$element = $('#person_number_container input[name="accept_state_address"]:checked');
			value = $element.val();
			if (value == 1) {
				//console.log("chkcountry " + value);
				$element.removeClass("badinput");
			} else {
				valid = false;
				$element.addClass("badinput");
			}
		}
	}

	if (valid) {
		$("#fillOutInfo").hide();
		$("#ready2pay").show();
	} else {
		$("#fillOutInfo").show();
		$("#ready2pay").hide();
	}
}

function validateForm() {
	var valid = true;
	var value;
	var $element;

	$element = $('#order_information input[name="FirstName"]');
	value = $element.val();
	if (!validateFirstname(value)) {
		//console.log("FirstName " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	$element = $('#order_information input[name="LastName"]');
	value = $element.val();
	if (!validateSurname(value)) {
		//console.log("LastName " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	$element = $('#order_information input[name="Address"]');
	value = $element.val();
	if (!validateAddress(value)) {
		//console.log("Address " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	$element = $('#order_information input[name="Zip"]');
	value = $element.val();
	if (!validateZip(value)) {
		//console.log("Zip " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	$element = $('#order_information input[name="Email"]');
	value = $element.val();
	if (!validateEmail(value)) {
		//console.log("Email " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	$element = $('#order_information input[name="Mobile"]');
	value = $element.val();
	if (!validatePhonenumber(value)) {
		//console.log("Mobile " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	$element = $('#order_information input[name="send_to"]:checked');
	value = $element.val();
	if (!validateShipping(value)) {
		//console.log("send_to " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	var cart_amount = parseInt($("#cart_amount").html());
	
	//console.log(cart_amount);

	if (valid && cart_amount > 0) {
		$("#fillOutInfo").hide();
		$("#continue").show();
	} else {
		$("#fillOutInfo").show();
		$("#continue").hide();
	}
}

function validateContact() {
	var valid = true;
	var value;
	var $element;
	
	$element = $('.contact_form input[name="forename"]');
	value = $element.val();
	if (!validateFirstname(value)) {
		//console.log("forename " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}
	
	$element = $('.contact_form  input[name="surname"]');
	value = $element.val();
	if (!validateSurname(value)) {
		//console.log("surname " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}
	
	$element = $('.contact_form input[name="email_address"]');
	value = $element.val();
	if (!validateEmail(value)) {
		//console.log("email_address " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}
	
	$element = $('.contact_form  input[name="phonenumber"]');
	value = $element.val();
	if (!validatePhonenumber(value)) {
		//console.log("phonenumber " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}
	
	$element = $('.contact_form  textarea[name="comment"]');
	value = $element.val();
	if (value.length == 0) {
		//console.log("phonenumber " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	if (valid) {
		$(".sendform").attr("disabled", "");
	} else {
		$(".sendform").attr("disabled", "disabled");
	}
}

function validateFirstname(firstname) {
	if (firstname.length > 0 && firstname != "fornavn*") {
		return true;
	} else {
		return false;
	}
}

function validateSurname(surname) {
	if (surname.length > 0 && surname != "etternavn*") {
		return true;
	} else {
		return false;
	}
}

function validateAddress(address) {
	if (address.length > 0 && address != "adresse*") {
		return true;
	} else {
		return false;
	}
}

function validatePhonenumber(phonenumber) {
	if (phonenumber.length > 7 && phonenumber != "mobil nummer*") {
		return true;
	} else {
		return false;
	}
}

function validateZip(zip) {
	if (zip.length > 0 && zip != "postnummer*") {
		return true;
	} else {
		return false;
	}
}

/* Unknown source. First used in Nordkyn and modified here. I do not remeber where I got it from before that project. Seems to work */
function validateEmail(email) {
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 

	if (email.match(re)) {
		return true;
	} else {
		return false;
	}
}

function validateShipping(shipping) {
	if (shipping == "1") {
		return true;
	} else if (shipping == "2") {
		return validateShippingAddress();
	} else {
		return false;
	}
}

function validatePayment(payment) {
	if (payment == "card" || payment == "invoice") {
		return true;
	} else {
		return false;
	}
}

function validateTerms(termsCheck) {
	if (termsCheck == "1") {
		return true;
	} else {
		return false;
	}
}

function validateCountry(countryCheck) {
	if (countryCheck == "1") {
		return true;
	} else {
		return false;
	}
}

function validateShippingAddress() {
	var valid = true;
	var value;
	var $element;
	//console.log("[Shipping information]");
	
	$element = $('#order_information input[name="FirstNameDelivery"]');
	value = $element.val();
	if (!validateFirstname(value)) {
		//console.log("FirstNameDelivery " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}
	
	$element = $('#order_information input[name="LastNameDelivery"]');
	value = $element.val();
	if (!validateSurname(value)) {
		//console.log("LastNameDelivery " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	$element = $('#order_information input[name="AddressDelivery"]');
	value = $element.val();
	if (!validateAddress(value)) {
		//console.log("AddressDelivery " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	$element = $('#order_information input[name="ZipDelivery"]');
	value = $element.val();
	if (!validateZip(value)) {
		//console.log("ZipDelivery " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}

	$element = $('#order_information input[name="MobileDelivery"]');
	value = $element.val();
	if (!validatePhonenumber(value)) {
		//console.log("MobileDelivery " + value);
		$element.addClass("badinput");
		valid = false;
	} else {
		$element.removeClass("badinput");
	}
	
	return valid;
}

/*  Takes initial values and saves it into the title */
function init_input() {
	$('#regsiter_form input[type="text"]').each(function() {
		$(this).attr("title", $(this).val());
	});

	if ($('input[name="send_to"]:checked').val() == 2) {
		$('#shipping_container').show();
	}

	$("#back2cart").click(function(event) {
		event.preventDefault();
		$("#regsiter_form").submit();
	});
	
	if ($("#regsiter_form").length > 0) {
		validateForm();
		$('#regsiter_form input[type="text"]').focus(function(event) {
			if ($(this).val() == $(this).attr("title")) {
				$(this).select();
			}
		});
		
		$('#regsiter_form input[type="text"]').blur(function(event) {
			if ($(this).val() == "") {
				$(this).val($(this).attr("title"));
				return false;
			}
		});
	}
}

function init_search() {
	$('#search').focus(function() {
		$(this).val("");
	});
}

function popitup(url) {
	newwindow=window.open(url,'name','height=222,width=400');
	if (window.focus) {newwindow.focus()}
	return false;
}
