$(document).ready(function() {

	/*
	 * Touch device
	 */
	
	if(('ontouchstart' in document.documentElement) || ($.browser.opera && (screen.width < "801"))) {
		$("body").addClass("touchDevice");
	}

	/**
	* Setting backgroundcolor to Veidekke-red when page is loaded
	*/
	window.onload = function(){ $('body').addClass('body-background'); }
	
    /**
     * Adapt sideCar (far right column) for different screen sizes
     */

    // @small screens
    if (screen.width <= '1024') {

        // Add small screens class
        $('#sideCar').addClass('lowRes');

        // Toggle slide tabs
        $('#sideCar').mouseenter(function() {
            $(this).stop().animate({width: '154px'});
        }).mouseleave(function() {
            $(this).stop().animate({width: '14px'});
        });
    }

    // @medium screens
    if ((screen.width > '1024') && (screen.width <= '1280')) {

        // Add class for small screens
        $('#sideCar').addClass('midRes');
    }

    // @big screens
    if (screen.width > '1280') {

        // Add class for small screens
        $('#sideCar').addClass('highRes');
    }


    /**
     * Sidecar position control
     */
    function sideCarCtrl() {

        // Get element positions
        var posFixedItems = $('#fixedItems').position().top + $('.section.head').height() + $('.section.nav').height() + 10;
        var posFixedItemsOnly = Math.ceil($('#fixedItems').position().top + 9);
        var posMain = Math.ceil($('#main').offset().left);

        // Position if fixedItems in sideCar is outside browser viewport
        if (document.documentElement.scrollTop > posFixedItems || self.pageYOffset > posFixedItems) {
            $('#sideCar').css('position', 'fixed');
            $('#sideCar').css('top', '-' + posFixedItemsOnly + 'px');
            if (screen.width <= '1024') {
                $('#sideCar').css('right', '0');
            }
            else {
                $('#sideCar').css('left', (posMain + 980));//976
            }
        }
        // ..and inside browser viewport
        else if (document.documentElement.scrollTop < posFixedItems || self.pageYOffset < posFixedItems) {
            $('#sideCar').css('position', 'absolute');
            $('#sideCar').css('top', '0');
            if (screen.width <= '1024') {
                $('#sideCar').css('right', '-14px');
            }
            else {
                $('#sideCar').css('left', '980px');//976px
            }
        }
    }

    // Fire on scroll
    window.onscroll = function() {
        sideCarCtrl();
    }
    // Fire on resize
    $(window).resize(function() {
        sideCarCtrl();
    });


    /**
     * Sidecar hover and focus effect
     */
    $('#sideCar .social').mouseenter(function() {
        $(this).addClass('active');
    }).mouseleave(function() {
        $(this).removeClass('active');
    })

    $('#sideCar ul li').mouseenter(function() {
        $(this).addClass('active');
    }).mouseleave(function() {
        $(this).removeClass('active');
    })
    $('#sideCar ul li a').focus(function() {
        $(this).parent().addClass('active');
    }).blur(function() {
        $(this).parent().removeClass('active');
    })


    /**
     * Feeds hover and focus effect
     */
    $('.feedList li').mouseenter(function() {
        $(this).addClass('active');
    }).mouseleave(function() {
        $(this).removeClass('active');
    })
    $('.feedList li a').focus(function() {
        $(this).parent().parent().parent().addClass('active');
    }).blur(function() {
        $(this).parent().parent().parent().removeClass('active');
    })


    /**
     * Flickr hover and focus effect
     */
    $('.flickr a').bind('mouseenter focus', function() {
        // $(this).find('img').addClass('active');
        $(this).find('img').animate({
            opacity: '1',
            filter: 'alpha(opacity=100)',
            '-moz-opacity': '1'
        }, 100);
    }).bind('mouseleave blur', function() {
        // $(this).find('img').removeClass('active');
        $(this).find('img').animate({
            opacity: '0.7',
            filter: 'alpha(opacity=70)',
            '-moz-opacity': '0.7'
        }, 300);
    })

    /**
     * Multimedia hover and focus effect
     */
    $('.multimedia a').bind('mouseenter focus', function() {
        // $(this).find('img').addClass('active');
        $(this).find('img').animate({
            opacity: '1',
            filter: 'alpha(opacity=100)',
            '-moz-opacity': '1'
        }, 100);
    }).bind('mouseleave blur', function() {
        // $(this).find('img').removeClass('active');
        $(this).find('img').animate({
            opacity: '0.7',
            filter: 'alpha(opacity=70)',
            '-moz-opacity': '0.7'
        }, 300);
    })


    /**
     * Focus list effects
     */
    $(".hasImages").find('li a').bind('mouseenter focus', function() {
        if ($(this).attr('class') !== 'selected') {
            $(this).parent().parent().find('li a').removeClass('selected'),
                    $(this).parent().parent().find('li a img').animate({opacity: "hide"}, "fast"),
                    $(this).addClass('selected'),
                    $(this).find('img').animate({opacity: "show"}, "fast");
        }
    });
    // $(".hasImages").find('li a').find('span').css('padding-bottom', '0');

    // Activate first item in focusList on page load

    // $(".hasImages .list").find('li:first a').addClass('selected');
    // $(".hasImages .list").find('li:first img').animate({opacity: "show"}, "slow");


    // Set span width according to image width for lists without .narrow class
    $(".hasImages").each(function() {
        if (!$(this).hasClass('narrow')) {
            // var spanWidth = $(this).find("img:first").width() + 6;
            // $(this).find("span").css('margin-left', spanWidth + 'px');
            //var spanHeight = (Math.round($(this).find("img:first").height() - 2) / 3) - 9;
            //$(this).find("span").css('min-height', spanHeight + 'px');
        }

        if ($(this).hasClass('narrow')) {
            // var ulTop = $(this).find("img:first").height() + 15;
            // $(this).find("ul").css('padding-top', ulTop + 'px');
        }
    });

    // As above, but with image on right side
    $(".hasImages.rightSideImage").each(function() {
        if (!$(this).hasClass('narrow')) {
            var spanWidth = $(this).find("img:first").width() + 6;
            $(this).find("span").css({
                'margin-right': spanWidth + 'px',
                'margin-left': '0'
            });
        }
    });

    // Set .list height according to image height and .text width according to first image width
    $(".hasImages.hasText").each(function() {
        var listHeight = $(this).find("img:first").height();
        $(this).find(".list").css({
            'min-height': listHeight + 'px'
        });
        if ($(this).hasClass('rightSideImage')) {
            // As above, but with image on right side
            $(this).each(function() {
                if (!$(this).hasClass('narrow')) {
                    var textWidth = $(this).find("img:first").width() + 1;
                    // $(this).find(".text").css({
                    //    'margin-right': (textWidth + 6) + 'px',
                    //    'margin-left': '0'
                    // });
                    // $(this).find("ul li a img").css({
                    //    'right': '0',
                    //    'padding-left': '20px'
                    // });
                }
            });
        } else {
            // As above, but with image on left side
            $(this).each(function() {
                if (!$(this).hasClass('narrow')) {
                    var textWidth = $(this).find("img:first").width();
                    // $(this).find(".text").css({
                    //    'margin-left': (textWidth + 6) + 'px',
                    //    'margin-right': '0'
                    // });
                    // $(this).find(".list ul").css({
                    //    'margin-left': (textWidth + 12) + 'px',
                    //    'margin-right': '5px'
                    // });
                    // $(this).find("ul li a img").css({
                    //    'left': '0',
                    //    'padding-right': '20px'
                    // });
                }
            });
        }
        
     // IE 7 exceptions
		if($.browser.msie && $.browser.version.substr(0,1) < 8) {
			if($(this).hasClass("rightSideImage")) {
				var textHeight = $(this).find(".text").height();
				$(this).css({
					'position': 'relative'
				});
				$(this).find(".list").css({
					'left': '0',
					'width': '558px',
					'min-height': '78px'
				});
				$(this).find(".list ul").css({
					'position': 'relative'
				});
				$(this).find("ul li a img").css({
					'margin-top': '-65px'
				});
			}
			else {
				var textHeight = $(this).find(".text").height();
				var listheight = $(this).find("img:first").height() + 4;
				$(this).css('position', 'relative');
				$(this).find(".text").css({
					'position': 'absolute',
					'top': '56px',
					'width': '300px'
				});
				$(this).find(".list").css({
					'min-height': listheight
				});
				$(this).find(".list ul").css({
					'margin-top': textHeight +'px'
				});
			}
		}
        
        
    });
    
    


    /**
     * Focus item effects
     */
    // $(".focusItem").each(function() {
    //     // Set .text width according to image width
    //     var textWidth = $(this).find("img:first").width() + 2;
    //     if (textWidth > 2) {
    //         if ($(this).hasClass('imageOnRight')) {
    //             $(this).find(".text").css('margin-right', textWidth + 'px');
    //         } else {
    //             $(this).find(".text").css('margin-left', textWidth + 'px');
    //         }
    //     }
    // });


    /**
     * Projects list hover and focus effect
     */
    $('.list').each(function() {
        //$(this).find('ul li:first').css('background-image', 'none');
        // 		$(this).find('div.list li').each(function(){
        // 			if(!$(this).hasClass('personalFacts')) {
        // 				var textWidth = $(this).find("img:first").width();
        // 				if(textWidth > 2) {
        // 					if($(this).parent().parent().parent().hasClass('imageOnRight')) {
        // 						$(this).find("div").css('margin-right', (textWidth + 9) +'px');
        // 					} else {
        // 						$(this).find("div").css('margin-left', (textWidth + 9) +'px');
        // 					}
        // 				}
        // 			}
        // 		});

        $(this).find('li').mouseenter(function() {
            $(this).addClass('active');
        }).mouseleave(function() {
            $(this).removeClass('active');
        })

        if ($(this).hasClass('projectList')) {
            $(this).find('li a').focus(function() {
                $(this).parent().parent().parent().addClass('active');
            }).blur(function() {
                $(this).parent().parent().parent().removeClass('active');
            });
        }
    });

    /**
     * Related list hover and focus effect
     */
    $('.relatedList ul li').mouseenter(function() {
        $(this).addClass('active');
    }).mouseleave(function() {
        $(this).removeClass('active');
    });
    $('.relatedList ul li a').focus(function() {
        $(this).parent().parent().parent().addClass('active');
    }).blur(function() {
        $(this).parent().parent().parent().removeClass('active');
    });


    /**
     * Uniform (form element styling)
     */
    $("#main select").uniform();


    /**
     * Zebra styling of tables
     */
    $("#main table").each(function() {
        $(this).find("tr").mouseover(function() {
            $(this).addClass("over");
        }).mouseout(function() {
            $(this).removeClass("over");
        });
        $(this).find("tr:odd").addClass("alt");
        // $(this).find("tr:first").addClass("head");
    });


    /**
     * Floating images in main content
     */
    $("#main .frame .text").each(function() {
        // Get container (.frame) width
        var frameWidth = $(this).width();
        $(this).find("img").each(function() {
            var imgWidth = $(this).width();
            if (frameWidth > (imgWidth + 150)) {
                // Float image if there is room enough for floating text
                $(this).addClass("floating");
            } else {
                // Else don't float
                $(this).addClass("nonFloating");
            }
        });
    });


    /**
     * Toggle view formula
     */
    $('.hidden').css('display', 'none');
    $('.sendEmail').click(function() {
        $(this).parent().children('.sendEmailFormula').toggle();
        return false;
    });


    /**
     * Error message style handling
     */
    $(".error").focus(function() {
        $(this).removeClass("error");
    });
    
	/**
	 * Toggle sitemap
	 */
	$('#sitemapContent').hide();
	$(".sitemap h2 a").click(function() {
		$('#sitemapContent').slideToggle('slow');
		return false;
	});

	$('.module.hasText').bind("mouseenter mouseleave", toogleImageText);
	$('.module.hasText').click(function(){
		window.location = $(this).find("a").attr("href");
	});
	
	/**
	 * Front Page Module: list
	 */
	$('.module .dropdown dt a').click(function(){
		$('.dropdown dd ul').toggle();
		return false;
	});
	$('.module .dropdown dd ul li a').click(function(){
		var text = $(this).html();
		$(".dropdown dt a span").html(text);
		$(".dropdown dd ul").hide();
		var module = $(this).parents('.list_module');
		module.children('.text').hide();
		module.children('ul').hide();
		module.children('#list_'+this.id.split("_")[1]).show();
		return false;
	});
	
	$('.module.module_41 .title_box a,.module.module_42 .title_box a').each(function(){
		drawLines($(this).parent(), 49);
	});
	$('.module.module_31 .title_box a,.module.module_32 .title_box a').each(function(){
		drawLines($(this).parent(), 35);
	});
	$('.module.module_21 .title_box a,.module.module_22 .title_box a').each(function(){
		drawLines($(this).parent(), 28);
	});
	$('.module.module_11 .title_box a,.module.module_12 .title_box a').each(function(){
		drawLines($(this).parent(), 21);
	});
	
});

function drawLines(textBox, expectedHeight){
	var textHeight = textBox.height();
	var numberOfLines = Math.floor(textHeight/expectedHeight);
	var lineHeight = Math.round(textHeight/numberOfLines);
	var html = "";
	for(var i=1;i<numberOfLines;i++){
		html += '<div style="background: url(\'skins/gfx/backgrounds/bg-line.png\') center '+lineHeight*i+'px repeat-x;">';
	}
	html += textBox.html();
	for(var i=1;i<numberOfLines;i++){
		html += '</div>';
	}
	textBox.html(html);
}

function toogleImageText(){
	$(this).children('img').toggleClass("transparent");
	$(this).children('.text').toggle();
}

//Using this function to support Hugin-report feed.
function openNewsWindow(url) {
    // Set this url with the url as parameter.
    if (url != null) {
        window.location.href = String(window.location.href).split("?")[0] + "?externalUrl=" + escape(url);
    }
}


