 function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.parentNode;
    }
    return { top: _y, left: _x };
}

 var VariantTypes = new Array();
 $(document).ready(
        function() {
                              
           
            /**
            * General Handler
            * - Topmenu
            * - Login
            * - Search
            */
            if ( $("#navmenu").length > 0 ){
                
                // Adding handlers for Top navbar ( Login, basket, languate etc. )
                $("#navmenu>ul>li").bind("click", function(){
                    if ( $('#'+$(this).attr("name")+'Form').length > 0 ) {
                     
                        if ( $(this).is(".active") ){
                            $(this).removeClass("active");   
                            $('#'+$(this).attr("name")+'Form').hide();
                        }else{ 
                            $("#navmenu>ul>li").removeClass("active");
                            $("#navmenu>.container").css({'display':'none'});
                            $(this).addClass("active");   
                            $('#'+$(this).attr("name")+'Form').css({'left' : $(this).find('a:first').position().left + 'px' }).show();
                            $('#'+$(this).attr("name")+"Form input:first").focus();
                        }
                    }
                } );
                
                // Removes/updates items from the basket
                $(".ItemRemove").live('click', function(){
                    $.get( '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).attr('name') + '&Quantity=0', function(data, textStatus, XMLHttpRequest) {
                        $("#OrderForm").html('').html(data);
                      }
                    );          
                });
                $("#OrderFormTable>tbody>tr>.col3").live('change', function(){
                    $.get( '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).attr('name') + '&Quantity=' + $(this).find('input').val(), function(data, textStatus, XMLHttpRequest) {
                        $("#OrderForm").html('').html(data);
                      }
                    );
                });
            
            
            
                // Handlers for Login fields
                $(".username,.password").bind('focus', function(){
                    if ( $(this).val() == 'Brukernavn' ){
                        $(this).val('');
                        $(this).removeClass('inputDescription');
                    }
                }).bind('blur', function(){
                    if ( $(this).val() == '' ){
                        $(this).addClass('inputDescription');
                        $(this).val('Brukernavn');
                    }     
                });
            
                // Handler for the main navigation menu.                                  
                $(".menu>ul>li").bind("mouseenter",
                    function() {
                        $(this).children("a").addClass("active2");
                        $("a.active").addClass("activeTemp").removeClass("active");
                    }).bind("mouseleave", 
                    function() {
                        $(this).children("a").removeClass("active2");
                        $("a.activeTemp").addClass("active").removeClass("activeTemp"); 
                    }
                );
            
            
                // Searchbox Handler
                $("#s").focus(
                    function() {
                        if ($(this).val() == strings['searchString']) {
                            $(this).val("");
                        }
                    }
                ).blur(
                    function() {
                        if ($(this).val() == "") {
                            $(this).val(strings['searchString']);
                        }
                    }
                ).keypress(
                    function(event) {
                        // TODO: OLA?? autocomplete
                    }
                );
				
				// hide navboxes when click outside
				$("body").click(
					function(event) {
						console.log(event.clientX + " x " +event.clientY);
						var pos = getOffset($("#navmenu")[0]);
						console.log(pos);
						if (event.clientX < pos.left ||
							event.clientX > pos.left*1 + $("#navmenu").width()*1 ||
							event.clientY < pos.top ||
							event.clientY > pos.top*1 + $("#navmenu").height()*1
						) {
							var item = $("#navmenu").find(".active").removeClass("active");
							$('#'+item.attr("name")+'Form').hide();
						}
					}
				);
                
            } // END General Handlers
            
            
            
            /**
            * ProductPage Handlers
            * - Tabnavigation
            * - Slideshow/lightbox
            * - Buy buttons
            * etc.
            */
            if ( $("#productmenu").length > 0 ){
            
            /**
            * Tabpages on product page.
            */
            
                $("#productmenu>ul>li").bind("click", function(){
                    $(".tabs").hide();
                    var li = $(this);
                    var obj = $("#"+$(this).attr('name'));
                    $(obj).show(); 
                    $(this).parent().find('li').removeClass('active');
                    $(this).addClass('active');
                    
                    if ( $(obj).html().length > 100 )
                        return false;
                    
                    $(li).find('img').show();
                        
                    $.ajax({
                      url: '/index.php?page=wsProduct&Id='+ $(li).parent().attr('name') +'&getType=partial&isvariant=true&tpl=Product.'+ $(this).attr('name') +'.tpl',
                      type: 'get',
                      success: function(data, textStatus, XMLHttpRequest) {
                        $(obj).html(data);
                      },
                      complete: function ( XMLHttpRequest, textStatu ){
                        $(li).find('img').hide();  
                      } 
                    });
                });
                
                // Handler for Slideshow
                if ( $("a[rel='ProductSlide']").length > 0 ){
                    $("#imagecontainer").find('.large').bind( 'click', function(){
                        $("a[rel='ProductSlide']:last").click();
                    });
                    $("a[rel='ProductSlide']").colorbox();
                } 
                
                // Handler for variants
                $("#VariantSelector").bind("change", function(){
                    var Selected = $(this).val();
                    $(VariantTypes).each(function(idx){
                        if ( $(this)[0].ProductId == Selected ){
                            $("#ProductPriceForm").find("h1").html( $(this)[0].ProductPrice );
                            $("#ProductName").html( $(this)[0].ProductName );
                            $("#ProductPriceForm").find(".basket").attr({'name' : $(this)[0].ProductId });
                            $("#productmenu").find(".menu-product").attr({'name' : $(this)[0].ProductId });
                            $("#AdditionalProducts").html("");
                            
                            // Fill Additional products with choice from Variant.
                            $.ajax({
                                url: '/index.php?page=wsProduct&Id='+$(this)[0].ProductId +'&getType=partial&isvariant=true&tpl=Product.AdditionalProducts.tpl',
                                type: 'get',
                                success: function(data, textStatus, XMLHttpRequest) {
                                    $("#AdditionalProducts").html(data);
                                },
                                complete: function ( XMLHttpRequest, textStatu ){
                                },
                                'beforeSend' : function(xhr) {
                                    xhr.overrideMimeType('text/html; charset=iso-8859-1');
                                } 
                            });
                            
                            return false;
                        }
                    })
                }) 
                 
                
            }  
            
            
            // Handler for adding products to basket            
            if ( $(".basket").length > 0 ){
                $(".basket").live( 'click', function(){
                    $.ajax({
                      url: '/index.php?page=wsOrder&getType=partial&action=add&Aid=' + $(this).attr('name') + '&Quantity=' + $(this).prev().val(),
                      type: 'get',
                      success: function(data, textStatus, XMLHttpRequest) {
                        $("#OrderForm").html('').html(data);
                      },
                      'beforeSend' : function(xhr) {
                        xhr.overrideMimeType('text/html; charset=iso-8859-1');
                      }
                    });  
                });
            }
            
            
            
            if ( $(".submenuitemlink > a").length > 0 ) {
                $(".submenuitemlink > a").each( function(idx){
                    if ( $(this).html() == '' ){
                        $(this).parent().parent().parent().remove();
                    }
                }); 
                
            }
                                                   
            
        }
    );
    
    
    

