
	    function load_map_script(callback) {
/*		if(typeof GMap2 == 'function') {
		    this[callback].apply(this);
		    return;
		}*/
		var script = document.createElement("script");
		script.setAttribute("src", "http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAAAYmq5hP6d4pdAiduNCy-xLRSoMFtQf1rtXgqm45pM2dgsJ1EthhSqiINZ-nfWmL7aug5hJ3pdUhGUZQ&async=2&callback="+callback);
		script.setAttribute("type", "text/javascript");
		script.setAttribute("id", "googlemaps_script");
		document.documentElement.firstChild.appendChild(script);
	    }

	    function load_map(address, div_id) {
		$("div#"+div_id).googlemap({
		controls: true,
		labels: true,
		zoom: 9,
		addresses: address,
		debug: false
		});
	    }

	    $.ajaxSetup({
		timeout:30000,
		error:function(ajaxRequest,errorStr) {
//		    $('#connection_failed').css('display','block').hide();
		    $('#connection_failed').show();
            $('#loading').hide();
		    setTimeout(function() {
			$('#connection_failed').hide();
		    },5000);
		}
	    });

	    /*Checkout functions */
            function update_vats(vat_data) {
		var vats = $('tr.vat');
		var new_vats = '';
		$.each(vat_data,function(i,vat) {
		   new_vats += '<tr class="vat"><td colspan="4">'+vat.label+'</td>';
		   new_vats += '<td class="number">'+vat.vat_total+'</td></tr>';
		});
		vats.before(new_vats);
		vats.remove();
	    }

            function update_shipping(data,widget) {
                if(data.success == true) {
                    $('#shipping_name').text(data.shipping['name']);
                    $('#shipping_rate').text(data.shipping['rate']);
		    update_vats(data.vats);
                    $('#total').text(data.total);
                } else {
                    widget.after(data.message);
                }
            }

            function update_payment(data,widget) {
                var success = data.success;
                if(data.success == true) {
                    $('#payment_name').text(data.payment['name']);
                    $('#payment_fee').text(data.payment['fee']);
		    update_vats(data.vats);
                    $('#total').text(data.total);
		    if(data.payment['type'] == '3') {
			$('#id_personal_number').parent().show();
		    }
		    else {
			$('#id_personal_number').parent().hide();
		    }
                } else {
                    widget.after(data.message);
                }
            }

	    /* Checkout functions end */

	    var isLoaded = false;

	    $(window).load(function() {
		isLoaded = true;
	    });
        
        function ie6_container_hack() {
            var newHeight = document.documentElement.clientHeight - 120;
            newHeight = newHeight + 'px';
            $('div.container').css('height',newHeight);
        }

        $(document).ready(function() {
	    $('.hidden_tr').load(function(e) {
	    	$(this).parent('td').parent('tr').hide();
	    });

	    $('.deliv_check').live('click', function(e) {
		var form = $(this).parents('form')[0];
		var deliv_address = form.deliv_address;
		var deliv_city = form.deliv_city;
		var deliv_postcode = form.deliv_postcode;
		deliv_address.attr('type','text');
	    });


	    $(':input').keydown(function(e) {
		if($(this).attr('type') != 'submit') {
		    if(e.keyCode == '13') {
			var tr = $(this).parent().parent();
			var nextinput = tr.next().children().children();
			if(nextinput.is(':input')) {
			    nextinput.focus();
			}
			else {
			    var submitbutton = tr.parent().parent().next();
			    if(submitbutton.attr('type') == 'submit') {
				submitbutton.focus();
			    }
			}
			e.preventDefault();
		    }
		}
	    });
            $('.fake_link').attr('href','');
            if($.browser.msie && parseInt($.browser.version) < 7) {
                /* A very ugly hack for a very ugly browser */
                ie6_container_hack();
                $(window).resize(function() {
                    ie6_container_hack();
                });
            }

            /* IE6 transparent PNGs */
            $('img#bild3').supersleight({shim:'/site_media/img/x.gif'});
            $('img#bild4').supersleight({shim:'/site_media/img/x.gif'});
            $('img#bild5').supersleight({shim:'/site_media/img/x.gif'});
            $('img#eilaslogo_img').supersleight({shim:'/site_media/img/x.gif'});
            $('img#headimg').supersleight({shim:'/site_media/img/x.gif'});

		    /*Checkout scripts begin */
		    $('.hidden_input').hide();
		    var pay = $('.payment_select:checked');
		    if(pay.length == 0 || pay.val() != "4") { //4 is the id of the credit payment option
				$('#id_personal_number').parent().hide();
		    }
		    $('.shipping_select').live('click',function(e) {
			var id = $(this).val();
			$.post('/ajax/update_shipping/', { shipping: id },
			/*
			Send POST data to server with XMLHttpRequest, recieve JSON data back
			on success:
			data:
			    success 
			    shipping_name
			    shipping_rate
			    total
			on failure:
			data:
			    success
			    message
			*/
			function(data) {
			    update_shipping(data,$(this));
			}, 'json');
		    });

		    $('.payment_select').live('click',function(e) {
			var id = $(this).val();
			$.post('/ajax/update_payment/', { payment: id },
			function(data) {
			    update_payment(data,$(this));
			},'json');
		    });

		    $('.hidden_input').live('blur',function(e) {
			$(this).hide();
			var id = '#' + $(this).attr('id') + '_label';
			var value = $(this).val();
			if(value == '') {
			    value = 'None';
			}
			$(id).text(value);
			$(id).show();
		    });
		    
		    $('.label').click(function() {
			$(this).hide();
			var id = '#' + $(this).attr('for');
			$(id).show();
		    });

		    $('.hidden_input').each(function () {
			var value = $(this).val();
			if(value == '') {
			    value = 'None';
			}
			$(this).after('<label for="'+$(this).attr('id')+'" class="label" id="'+$(this).attr('id')+'_label">'+value+'</label>');
		    });

		    /*Checkout functions end */

                $('#minicart').mouseenter(function() {
                    $('#minicart_content').show();
                });
                $('#minicart').mouseleave(function() {
                    $('#minicart_content').hide();
                });
                /* 
                   This function will load content according hash which is formed as the 
                   corresponding non-ajax urls, 
                   it will be called by clicks, history calls, initial loads with the hash.
                   On clicks, it will be called with the href of the link as hash, on history
                   and initial loads it will be called with the argument to # in the url 
                */
                function load_content(hash) {
                    var args = hash.split('/',6);
                    for(i=0; i < 6; i++) {
                        if(!args[i]) {
                            args[i] = '';
                        }
                    }
                    //arg[1] -> action, arg[1] and arg[2] -> arguments
                    var widget_id = args[1]+'_'+args[2]+'_'+args[3]+'_'+args[4]+'_'+args[5];
                    var widget = $('#'+widget_id);
                    if(widget.length > 0) {
                        /* If the widget has already been created previously, simply show it */
                        widget.show();
                        $('.content').not(widget).hide();
                        $('.extra').not(widget).hide();
                    }
                    else {
                        if(args[2] == 'show') {
                            var cl = 'info';
                        }
                        else {
                            var cl = 'content';
                        }
                        if(hash.charAt(hash.length-1) != '/') {
                            hash += '/';
                        }
                        $('#loading').toggle().hide();
                        $('#loading').removeClass('hidden_tab').show();
                        /*widget.load('/ajax'+hash);*/
                        $.get('/ajax'+hash, function(data, success) {
			    if(success) {
				$('.container').append('<div class="'+cl+' extra" id="'+widget_id+'"></div>');
				widget = $('#'+widget_id);
				widget.html(data);
				$('.content').hide();
				$('.extra').hide();

				/* Make sure the document has loaded completely before executing the show() */
				if(isLoaded) {
				    widget.show();

				//Register any slimbox enabled links as such
				widget.find("a[rel^='lightbox']").slimbox({closeKeys: [37, 27]});

                    $('#loading').hide();

                    //Workaround for Google Analytics
                    _gaq.push(["_trackPageview", '/ajax/'+hash ]);
				} else {
				    $(window).load(function() { 
					    widget.show();
                        $('#loading').hide();

                        //Workaround for Google Analytics
                        _gaq.push(["_trackPageview", '/ajax/'+hash ]);
				    });
				}

			    }
                        });
                    }
//                    $('.info').not(widget).hide();
                }

                function pageload(hash) {
                    if(hash && hash[0] != "?") {
                        load_content(hash);
                    }
                    else {
                        $('.extra').hide();
                        $('.content').hide();
                        $('.orig').show();
                    }
                }

                $.historyInit(pageload);

                var layer_index = 0;

                $('.info').hide();
                $('#darken').hide();
                $('.menu_container').hide();
		$('.menu_child_container').hide();
                $('#activity').hide();

		$('#toggle_register').click(function() {
		    $('#register').slideDown('medium');
		    $('#login').slideUp('medium');
		});

		$('#toggle_login').click(function() {
		    $('#login').slideDown('medium');
		    $('#register').slideUp('medium');
		});

		function truncchar(thestring, maxlength) {
		    var length = thestring.length;
		    if(length <= maxlength) {
			return thestring;
		    } else {
			return (thestring.substr(0,maxlength) + '...')
		    }
		}

                function show_activity_indicator(widget) {
                    width = widget.width();
                    height = widget.height();
                    offset = widget.offset();
                    $('div#activity').css(
                            {'width':width,
                             'height':height,
                             'left':offset.left,
                             'top':offset.top
                            }).show();
                }

                function hide_activity_indicator() {
                    $('div#activity').hide();
                }

            $('.show_image').live('click',function(e) {
		    //Workaround for live right-click bug
                if((!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 0)) {
                    $(this).parent().children('.show_image_large').show();
                }
			    e.preventDefault();
            });

            $('.show_image_large').live('click',function(e) {
		    //Workaround for live right-click bug
                if((!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 0)) {
                    $(this).hide();
                }
			    e.preventDefault();
            });


            $('.menu_accordion').live('click',function(e) {
		    //Workaround for live right-click bug
                if((!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 0)) {
                    $('.menu_container').not($(this).parent().next()).slideUp('medium');
                    $(this).parent().next().slideDown('medium');
                    if($(this).hasClass('fake_link')) {
			e.preventDefault();
                    }
                }
            });

            $('.menu_child_accordion').live('click',function(e) {
		    //Workaround for live right-click bug
                if((!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 0)) {
                    $('.menu_child_container').not($(this).parent().next()).slideUp('medium');
                    $(this).parent().next().slideDown('medium');
                    if($(this).hasClass('fake_link')) {
			e.preventDefault();
                    }
                }
            });


            $('a.history').live('click',function(e) {
                //Workaround for live right-click bug
                if(!$(this).hasClass("fake_link") && 
                    (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 0)) {
                    var index = this.href.indexOf('/',7);//exclude the host
                    hash = this.href.substr(index);
                    $.historyLoad(hash);
		    e.preventDefault();
                }
            });

                function update_minicart(data) {
                    var new_items = new Array();
                    $.each(data.items, function(i, item) {
                        var item_row = $('#item_'+item.cart_item);
                        if(item_row.length > 0) {
                            //Update existing item
                            $('#minicart_quant_'+item.cart_item).text(item.quant);
                            $('#minicart_price_'+item.cart_item).text(item.price);
                            //$('#minicart_item_total_'+item.cart_item).text(item.item_total);
                        } else {
                            //Mark item as new
                            new_items.push(item)
                        }
                    });
                    var table = $('#minicart_content');
                    $.each(new_items, function(i, item) {
                        //Add new item
                        var html = '<tr class = "item_row" id="item_'+item.cart_item+'">\n';
			html += '<td class = "item_name"><a class="history" title="'+item.name+'" href="/items/show/'+item.id+'/">'+truncchar(item.name,20)+'</a></td>\n';
                        html += '<td id="minicart_quant_'+item.cart_item+'" class = "item_quant number">'+item.quant+'</td>\n';
                        html += '<td id="minicart_price_'+item.cart_item+'" class = "item_price number">'+item.price+'</td>\n';
                        html += '</tr>';
                        $('#minicart_content').append(html);
                    });
                    $('#minicart_total').text(data.total);
                }

                $('.addbutton', this).live("click", function(e) {
		    //Workaround for live right-click bug
		    if((!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 0)) {
			var id = $(this).parent().children('#id_item_id').val();
			var quant = $(this).parent().children('#id_quantity').val();

            $('#minicart_totalrow').css("background-color","gray");
			$.post('/ajax/cart/add/', { item_id: id, quantity: quant }, 
			function(data) {
			    if(data.success == true) {
				update_minicart(data);
                    		$('#minicart_totalrow').css("background-color","#fce38f");
				setTimeout("$('#minicart_totalrow').css('background-color','transparent')",2000);
			    }
			    $("#minicart img").attr("src", orig_image);
			}, 'json');
			e.preventDefault();
		    }
                });

                function update_cart(data) {
                    var item_rows = $('.item_row'); //Select all item rows
                    for(i = 0; i < data.items.length; i++) {
                        var item = data.items[i];
                        var row_id = '#row_' + item['cart_item'];
                        var row = $(row_id);
                        row.children('.linetotal').text(item['item_total']);
                        item_rows = item_rows.not(row_id); //Delete this row from item_rows
                    }
                    item_rows.remove(); //Remove all items that aren't in use
                    $('#subtotal').text(data.subtotal);
                    $('#subtotal_a_d').text(data.subtotal_a_d);
                    $('#shipping_name').text(data.shipping['name']);
                    $('#shipping_rate').text(data.shipping['rate']);
                    $('#total').html(data.total);
                    //Remove the old discounts
                    $('.discount').remove();
                    //Replace with new discounts
                    var discount_html = '';
                    var i=0;
                    for(i=0; i<data.discounts.length; i++) {
                        discount = data.discounts[i];
                        discount_html += '\n' +
                        '<tr class="discount">\n' + 
                            '<td>' + discount['name'] + ' ' + discount['percent'] + '%</td>\n' +
                            '<td class="number">-' + discount['discount_amount'] + '</td>\n' +
                        '</tr>\n';
                    }
                    $('#subtotalrow').after(discount_html);
                }

                function reset_password(user_email, widget, t) {
                    $.post('/ajax/resetpassword/', { username: user_email },
                    function(data) {
                    /*
                        if(data.success == true) {
			    //widget.prev(".errorlist").remove();
			    //widget.prev('<ul class="notificationlist"><li>'+data.message+'</li></ul>');
                        } else {
			    //widget.prev(".errorlist").empty();
                            //widget.prev(".errorlist").append('<li>'+data.message+'</li>');
                        }
                        */
			if(data.success)
				t.after('<br /><span>Ett nytt lösenord har skickats till ' + user_email + '</span>')
			else
				t.after('<br /><span>Användaren ' + user_email + ' finns inte. Om du inte handlat i vår nya webshop förut, klicka på Ny kund ovan.</span>')
                    },'json');
                }

                function check_user_exists(user_email, widget) {
                    $.post('/ajax/check_user_exists/', { email: user_email },
                    function(data) {
                        if(data.success == true) {
			    widget.prev(".errorlist").remove();
			    widget.prev(".notificationlist").remove();
                            widget.after('<img src="/site_media/img/ok.png" />');
                        } else {
			    message = '<li>'+data.message;
                            if(data.error_type == 'user_exists') {
				message += '<br /><input type="button" class="button resetbutton" id="password_reset" value="'+data.reset_message+'" />';
                            }
                            message += '</li>';
			    if(widget.prev().is(".errorlist")) {
				widget.prev().empty();
				widget.prev().append(message);
			    }
			    else {
				widget.before('<ul class="errorlist">'+message+'</ul>');
			    }
                        }
                    },'json');
                }

/*                $('#password_reset',this).live("click", function() {
                    var email_input = $('#id_email');
                    var user_email = email_input.val();
                    reset_password(user_email, email_input);
		    e.preventDefault();
                });*/

                $('#id_email', this).live('change',function() {
                    var email = $(this).val()
                    check_user_exists(email, $(this));
		    e.preventDefault();
                });

                $('.resetbutton', this).live('click',function(e) {
                    var user_input = $(this).parents('form').find('#id_user');
		    if(user_input.length < 1) {
			var user_input = $(this).parents('form').find('#id_username');
		    }
                    var user_email = user_input.val();
		    $(this).hide();
                    reset_password(user_email, user_input, $(this));
		    $(this).show();

		    e.preventDefault();
                });

                $('.removebutton', this).live('click',function() {
                    var id = $(this).parent().children('#id_cart_item_id').val();

                    $.post('/ajax/cart/remove/', { cart_item_id: id },
                    function(data) {
                        if(data.success == true) {
                            update_cart(data);
                            update_minicart(data);
                        }
                    },'json');
		    e.preventDefault();
                });
                $('.updatebutton', this).live('click',function() {
                    par = $(this).parent().parent().children('#update');
                    var id = par.children('#id_cart_item_id').val();
                    var quant = par.children('#id_quantity').val();
                    /*
                    Send POST data to server with XMLHttpRequest, recieve JSON data back
                    data:
                        success (true or false)
                        items:
                            item['id']
                            item['name']
                            item['item_total']
                            item['quant']
                        shipping['name']
                        shipping['rate']
                        discounts:
                            discount['name']
                            disoount['percent']
                            discount['amount']
                            discount['discount_amount']
                        subtotal
                        subtotal_a_d //subtotal after discounts
                        total
                    */
                    $.post('/ajax/cart/update/', { cart_item_id: id, quantity: quant },
                    function(data) {
                        if(data.success == true) {
                            update_cart(data);
                            update_minicart(data);
                        }
                    }, 'json');
		    e.preventDefault();
                });

		if(!($.browser.msie && $.browser.version < 8)) {
		$('.description_extend_button').live('click',function() {
		    var extend = $(this).prev('.group_description_extend');
		    var extend_button = $(this);
		    if(extend.is(':hidden')) {
			extend.slideDown('medium');
			extend_button.text('Mindre');
		    } else {
			extend.slideUp('medium');
			extend_button.text('Mer');
		    }
		});
		} else {
			$('.description_extend_button').hide();
		}

            });


