/*
N E W  F U N C T I O N S  I N D E X :
09. MAC DETECTION AND EDITS
10. CONTACT LISTS
11. FUNCTION LIST
12. SEARCH PAGE
13. SITEMAP LIST REPOSITIONING
14. EDITOR FORMS
15. MIL FORM BUTTON, IE6 DISABLED CLASS
15.5 MIL FORM BUTTON, IE7 WIDTH / FLICKER FIX
16. DATE PICKER
17. POSITION LIST PAGE
18. READWEB ('toolbar')
19. TV THUMBNAILS STYLING
20. BLOCKQUOTE (right quote)
21. MEDIA IMAGES: PLAY & PROMPT show/hide
22. COLLAPSING LEFT COL BOXES
23. RECRUITMENT DROPDOWNS
*/


function initJQueryFunctions()
{

(function($) {
    
    $("*").unbind("click");/*(If ajax loads this jQuery multiple times (Position List page), this lines stops 1 click having multiple events.)*/
    
    //loadGalleria($('#galleria'), $('#galleria-base'));
    //load all gallerias on the page
    var gallerias = $('.galleria');
    var galleriaBase = gallerias.siblings('.galleria-base');
    
    for(i=0; i < gallerias.length; i++) {
        loadGalleria(gallerias.get(i), galleriaBase.get(i));
    }
    
    //if no galleria has been initialized then init the galleria functionality so that popups can show gallerias
    if(gallerias.length==0 && $('.galleria-base').length != 0){
        initGalleriaObject();
    }
    
    
    $.fn.TipFriend = function(options) {
        $.extend({}, options);
        return this.bind('click', function() {
            //display overlay
            $('.modalBackground').remove();
            $('<div class="modalBackground" />').css({
                position: 'fixed',
                Zindex: '10000'
            }).appendTo('#aspnetForm');
            $('.modalBackground').css('display','block');
            
            //remove old popup if it exists
            $('.jpopup').remove();
            
            //Create modal window and attach form to it
            $('#aspnetForm').append(
                $('<div class="jpopup" />').css({
                    position: 'fixed',
                    left: '50%',
                    marginLeft: -5 - 400 / 2,
                    zIndex: '100001'
                }).append(
                    $('<div class="jpopup-content"/>').append(
                        $('<a class="closebtn" title="' + closeTxt + '" href="#"><span>' + closeTxt + '</span></a>')
                    ).append(
                        $('<div id="tipfriend-wrapper"/>').append(
                            $('<h4/>').html(tipfriendTitle)
                        ).append(
                            $('<h1/>').html($('#contentarea h1').html())
                        ).append(
                            $('<label />').html(yourname + '<span class="mandatory">*</span>')
                        ).append(
                            $('<input type="text" />').attr({
                                name : 'yourname',
                                id : 'your-name'
                            })
                        ).append(
                            $('<label />').html(myMail + '<span class="mandatory">*</span>')
                        ).append(
                            $('<input type="text" />').attr({
                                name : 'youremail',
                                id : 'your-email'
                            })
                        ).append(
                            $('<label />').html(friendMail + '<span class="mandatory">*</span>')
                        )
                        .append(
                            $('<input type="text" />').attr({ 
                                name : 'friendemail',
                                id : 'friend-email'
                            })
                        ).append(
                            $('<label />').html(message)
                        ).append(
                            $('<textarea name="message" rows="3" />')
                        ).append(
                            $('<span class="MilFormButton"><button type="submit" id="tip-a-friend">' + sendTxt + '</button></span>')
                        ).append(
                            $('<p class="infotext"/>').html(infotext + ' (<span class="mandatory">*</span>=' + mandatory + ')</span>')
                        )
                    )
                )
            );
            //position vertically
            var topPos;
            var bHeight = (document.documentElement.clientHeight || document.body.clientHeight);
            topPos = ((bHeight/2) - ($('.jpopup').height()/2));
            topPos = topPos + 'px';
        
            $('.jpopup').css('top',topPos);
            
            
           $('#tip-a-friend').SubmitTipFriend();
            return false;
            
            
        });
    }
    
    $.fn.SubmitTipFriend = function(options) {
        //close
        $('.closebtn, .modalBackground, .addThisModalBackground').click(function(){$('.jpopup').hide(); $('.modalBackground').hide(); $('.addThisModalBackground').hide(); $('.addThisjpopup').hide(); $('.largemapjpopup').css({visibility:'hidden'}); });

        $.extend({}, options);
        return this.bind('click', function() {
            //test email validation 
			var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
            var formValid = true;
            if(pattern.test($('#friend-email').val())){         
	           $('#friend-email').removeClass("error");
	           $('#friend-email').prev().removeClass("error");
	           $('#friend-email').prev().html(friendMail + '<span class="mandatory">*</span>');
            }
            else {
                $('#friend-email').addClass("error");               
                $('#friend-email').prev().addClass("error");
                $('#friend-email').prev().html(friendMail + '<span class="mandatory">*</span>' + ' (' + mailFailed + ')');
                formValid = false;
            }
            if(pattern.test($('#your-email').val())){         
	           $('#your-email').removeClass("error");
	           $('#your-email').prev().removeClass("error");
	           $('#your-email').prev().html(myMail + '<span class="mandatory">*</span>');
            }
            else {
                $('#your-email').addClass("error");               
                $('#your-email').prev().addClass("error");
                $('#your-email').prev().html(myMail + '<span class="mandatory">*</span>' + ' (' + mailFailed + ')');
                formValid = false;
            }
            if($('#your-name').val() != "") {
                $('#your-name').removeClass("error");
                $('#your-name').prev().removeClass("error");
                $('#your-name').prev().html(yourname + '<span class="mandatory">*</span>');
            }
            else {
                $('#your-name').addClass("error");
                $('#your-name').prev().addClass("error");
                $('#your-name').prev().html(yourname + '<span class="mandatory">*</span>' + ' (' + nameFailed + ')');
                formValid = false;
            }
            
            if(formValid) {
                //hide form and display loading
                $('#tipfriend-wrapper').css('visibility','hidden');
                $('.jpopup-content').append($('<img src="/images/ajax-loader.gif" class="ajax-loader" alt="' + loadingTxt + '" title="' + loadingTxt + '" />'));
                
                //get current page id
                var page = $('.tip-friend:first').attr("href");
                var idStringArray = page.match("[^a-zA-Z0-9_]id=[0-9]+");
                var pageid = "";
                if(idStringArray != null) {
                    pageid = idStringArray[0].substring(4, idStringArray[0].length);
                }
                var pageLang = page.substring(page.indexOf("?lang=")+6,page.indexOf("&"));
                
                //send mail
                $.post('/templates/Tipfriend.aspx', {
                        id : pageid,
                        friendemail : $('[name="friendemail"]').val(),
                        youremail : $('[name="youremail"]').val(),
                        message : $('[name="message"]').val(),
                        yourname : $('[name="yourname"]').val(),
                        json : 'true',
                        lang : pageLang
                    }, function(data) {
                        if(data.success == "true") {
                            $('.ajax-loader').css('display','none');
                            $('.jpopup-content').append($('<h1 class="successmsg"><span>' + msgSuccess + '</span></h1>'));
                        }
                        else {
                            $('.ajax-loader').css('display','none');
                            $('#tipfriend-wrapper').css('visibility','visible');
                            if(data.friendMail == "false") {
                                $('#friend-email').addClass("error");               
                                $('#friend-email').prev().addClass("error");
                                $('#friend-email').prev().html(friendMail +' (' + mailFailed + ')');
                            }
                            if(data.yourMail == "false") {
                                $('#your-email').addClass("error");               
                                $('#your-email').prev().addClass("error");
                                $('#your-email').prev().html(myMail + ' (' + mailFailed + ')');
                            }
                        }
                        
                    },"json");
            }
            return false;   
        });
    }
    
    $.fn.Zoom = function(options) {
        $.extend({}, options);
        return this.bind('click', function() {
            //display overlay
            $('.modalBackground').remove();
            $('<div class="modalBackground" />').css({
                position: 'fixed',
                Zindex: '10000'
            }).appendTo('#aspnetForm');
            $('.modalBackground').css('display','block');
            
             // Skapa grejerna
             var    source    = $(this).attr('href'),
                    image     = $('<img/>'),
                    // Grejen som bilden är i, göms utanför skärmen så man kan kolla hur stor bilden är
                    popup     = $('<div class="jpopup imgpop" />'),
                    popupWrapper = $('<div class="jpopup-content"/>');
            
            //close image
            $('.modalBackground, .addThisModalBackground').click(function(){$('.jpopup').hide(); $('.modalBackground').hide(); $('.addThisModalBackground').hide(); $('.addThisjpopup').hide(); $('.largemapjpopup').css({visibility:'hidden'}); });
            
            //appenda popup
            popupWrapper.appendTo(popup);
            popup.appendTo($('#aspnetForm'));

            image.appendTo(popupWrapper).bind('load', function() {
                popup.css({
                    display: 'block',
                    height: image.height() + 10,
                    marginLeft: -5 - image.width() / 2,
                    // Här kommer den in i synfältet igen :)
                    top: ((document.documentElement.clientHeight || document.body.clientHeight)/2) - (image.height()/2),
                    width: image.width() + 5,
                    position: 'fixed',
                    left: '50%',
                    marginLeft: -5 - image.width() / 2,
                    zIndex: '100001'
                });
            }).attr('src', source);
            // måste sättas efter bind, annars funkar inte onload i IE när bilden dras ur cache
            
            popup.bind('click', function() {
                $('.jpopup, .modalBackground').css({
                    display: 'none'
                });
            });
            return false;           
        });
    }
    
    $.fn.CreateLargeStateMap = function(options) {
        //close
        $('.closebtn, .modalBackground, .addThisModalBackground').click(function(){$('.jpopup').hide(); $('.modalBackground').hide(); $('.addThisModalBackground').hide(); $('.addThisjpopup').hide(); $('.largemapjpopup').css({visibility:'hidden'}); });
    
        $.extend({}, options);
        return this.bind('click', function() {
            $('.largemapjpopup').css({
                visibility:'visible'
            });
            //modal background
            $('.modalBackground').css({
                visibility:'visible',
                position:'fixed',
                display:'block'
            });
            return false;
        });
    }
    
    $.fn.AddThis = function(options) {
        $.extend({}, options);
        //close
        $('.closebtn, .modalBackground, .addThisModalBackground').click(function(){$('.jpopup').hide(); $('.modalBackground').hide(); $('.addThisModalBackground').hide(); $('.addThisjpopup').hide(); $('.largemapjpopup').css({visibility:'hidden'}); });

        return this.bind('click', function() {
            
            //position vertically
            var topPos;
            
            var bHeight = (document.documentElement.clientHeight || document.body.clientHeight);
            topPos = ((bHeight/2) - ($('.addThisjpopup').height()/2));
            topPos = topPos + 'px';
        
            $('.addThisjpopup').css('top',topPos);
            
            $('.addThisjpopup, .addThisModalBackground').css({
                display:'block'
            });
            return false;
        });
    }
    
    
    var interval;
    $.fn.Ticker = function(options) {
    	$.extend({}, options);
    	 return this.each(function() {
			//first create delimiter
			$(this).css('width', '194px');
			$(this).append($('<li class="news-restart">' + latestNews + '</li>'));
			var list = $(this);
		    var currentPos = 0;
		    var scrollHeight = $(this).height();
			
			var dllist = $(this).children('li');
			dllist.clone().appendTo($(this));
			dllist.clone().appendTo($(this));
			dllist.clone().appendTo($(this));
			
			interval = setInterval(function(){
				move();
			},80);
			
			$(this).hover(
                function() {
                    clearInterval(interval);
                },
                function() {
                    interval = setInterval(function(){
				        move();
			        },80);
                }
            );
			
	
			var move = function() {
				currentPos = currentPos + 2;
				if (currentPos <= scrollHeight) {
					list.css({
						top: '-' + currentPos + 'px'
					});
				}
				else {
					currentPos = 0;
					list.css({
						top: '-' + currentPos + 'px'
					});
				}
			}

    	});
	}
	
})(jQuery);
jQuery(function($) {
    $('.newsticker-container').css({overflow: 'hidden'});
    $('.tip-friend').TipFriend();
    $('.zoom').Zoom();
    //$('.GoogleMap220 img').Zoom();
    $('.Share').AddThis();
    $('.LargeState').CreateLargeStateMap();
    //$('.newsticker').Ticker();
    
    
    //check what font to use, fix for performance with cufon on IE
    if($.browser.msie){
        $(".gunplay, #recruit h2")
            .css("font-weight", "normal")
            .css("line-height", "1.0em")
            .css("font-family", "gunplay");
    }
    else{
        //$(".gunplay, h2").css("font-weight", "normal").css("line-height", "1.0em").css("font-family", "gunplay");
        Cufon.replace("#recruit h2")(".gunplay", { hover: true });
	    //Cufon.replace("#recruit h2");
    }
    
    
    if($.browser.msie) {
	    if($.browser.version < 7) {
	        $(window).scroll(function () {
	            var bHeight = (document.documentElement.clientHeight || document.body.clientHeight);
                topPos = ((bHeight/2) - ($('.jpopup').height()/2)) + (document.documentElement.scrollTop || document.body.scrollTop );
                topPos = topPos + 'px';
                $('.jpopup').css('top',topPos);
                
                topPos = ((bHeight/2) - ($('.addThisjpopup').height()/2)) + (document.documentElement.scrollTop || document.body.scrollTop );
                topPos = topPos + 'px';
                $('.addThisjpopup').css('top',topPos);
                
                topPos = ((bHeight/2) - ($('.largemapjpopup').height()/2)) + (document.documentElement.scrollTop || document.body.scrollTop );
                topPos = topPos + 'px';
                $('.largemapjpopup').css('top',topPos);
	        });
	    }
	}
});
//jQuery.noConflict();
jQuery(window).bind('unload', function() { jQuery('*').unbind(); });

function togglePlayDiv(id)
{
    if(document.getElementById(id).style.visibility == "hidden")
    {
        document.getElementById(id).style.visibility = "visible";
        
        // kod för att stoppa
    }else{
        document.getElementById(id).style.visibility = "hidden";
        
        // kod för att starta play
    }
    
    
}

	/* * * * * * * * * * * * * * * * * */
    /* 09. MAC DETECTION AND EDITS     */
    /* * * * * * * * * * * * * * * * * */
	var MacUser = false;
	if(navigator.appVersion.indexOf("Mac") !=-1){
		MacUser = true;
	}
	/*Mac nav tweak*/
	if(MacUser == true){
		$("#globalnavigation ul li a").css({
	        paddingTop:'7px',
			height:'25px'
	    });
	}

    /* * * * * * * * * * * */
    /* 10. CONTACT LISTS   */
    /* * * * * * * * * * * */
    // ContactListBox, 1) basic
    $(".ContactListBox ul li ul").hide(); //(Hides level2)
    $(".ContactListBox li span").click(function(){
        $ThisButton = $(this);
		$ThisButton.next("ul").slideToggle("fast", function(){
                $ThisButton.toggleClass("ContactListButtonToggle");
            })
		$ThisButton.parent().siblings().each(function(){
            $(this).children(":first").next("ul").slideUp("fast");
            $(this).children(".ContactListBox li span.ContactListButtonToggle").removeClass("ContactListButtonToggle");
        });
	});

    // ContactListBox, 2) 'SelectionView'
    //'.SelectionView' below cannot use slideToggle because doing so causes
    //Googlemap's location targets to start incorrectly

    //Closed state
    $("div.SelectionView").css({
        height:'1px',
        paddingTop:'0',
        paddingBottom:'0',
        backgroundColor:'#e1edf7',
        overflow:'hidden'
    });
    $(".ContactListBox li li span, .ContactListBox li span").click(function(){
        $ThisButton = $(this);
        if ($ThisButton.next("div.SelectionView").length){//Checking existence

            $SelectionView = $ThisButton.next("div.SelectionView");
            
            if($SelectionView.height() == 1){//is closed
                //measure height
                $OpenToHeight = $ThisButton.next("div.SelectionView").children(".contact-card").height() + 50;
                //open
                $ThisButton.next("div.SelectionView").animate({
                    height:$OpenToHeight
                });
                //restyle
                $ThisButton.next("div.SelectionView").css({
                    paddingTop:'',
                    paddingBottom:'',
                    backgroundColor:'#fff'
                });
            } else{//is open
                $SelectionView.animate({
                    //close
                    height:'1'
                }, function(){
                        //restyle
                        $SelectionView.css({
                        paddingTop:'0',
                        paddingBottom:'0',
                        backgroundColor:'#e1edf7'
                    });
                });
            }
            $ThisButton.parent().siblings().each(function(){
                //Close others
                $(this).children(":first").next("div.SelectionView").animate({
                    //close
                    height:'1'
                }, function(){
                        //restyle
                        $(this).css({
                        paddingTop:'0',
                        paddingBottom:'0',
                        backgroundColor:'#e1edf7'
                    });
                });
                $(this).children(".ContactListBox li span.ContactListButtonToggle").removeClass("ContactListButtonToggle");
            });

            //button style
            $ThisButton.toggleClass("ContactListButtonToggle");
        }
    });

    /* * * * * * * * * * * */
    /* 11. FUNCTION LIST   */
    /* * * * * * * * * * * */
    $(".SpecialisationsLists").hide(); //(Hides Specialisations)
    $(".SpecialisationsButtonWrap h3").click(function(){
        $ThisButton = $(this);
        //(chaining events:)
		$ThisButton.parent().next(".SpecialisationsLists").slideToggle("fast", function() {
               $ThisButton.toggleClass("iconMinus");
           }
		);		
	});
	
	/* * * * * * * * * * * */
    /* 12. SEARCH PAGE     */
    /* * * * * * * * * * * */
    $(".ess-option-group").hide();
    $("a.AdvancedSearchLink").click(function(){
        $ThisButton = $(this);
        $(".SearchHelp").hide();
        $ThisButton.toggleClass("AdvancedSearchLinkToggle");
        $(".ess-option-group").slideToggle("fast");
        $("a.HelpTextLink").removeClass("HelpTextLinkToggle");
    });
    $(".SearchHelp").hide();
    
    $("a.HelpTextLink").click(function(){
        $ThisButton = $(this);
        $(".ess-option-group").hide();
        $ThisButton.toggleClass("HelpTextLinkToggle");
        $(".SearchHelp").slideToggle("fast");
        $("a.AdvancedSearchLink").removeClass("AdvancedSearchLinkToggle");
        return false;
    });
    
    /* * * * * * * * * * * * * * * * * */
    /* 13. SITEMAP LIST REPOSITIONING  */
    /* * * * * * * * * * * * * * * * * */
    $(".MoveToColumn2").clone(true).appendTo(".Column2");
    $(".MoveToColumn3").clone(true).appendTo(".Column3");
    $(".Column1 .MoveToColumn2").remove();
    $(".Column1 .MoveToColumn3").remove();
    
    /* * * * * * * * * * * */
    /* 14. EDITOR FORMS    */
    /* * * * * * * * * * * */
    /*Add styles to Editor form page items*/
    $("#form-container input:text").addClass("EditorTextInput");
    $("#form-container input:radio").addClass("EditorRadio");
    $("#form-container input:checkbox").addClass("EditorCheckbox");
    $("#form-container input:password").addClass("EditorPassword");

    $("#form-container input:submit").wrap("<span class='MilFormButton'></span>");
    $("#form-container input:reset").wrap("<span class='MilFormButton'></span>");
    $("#form-container input:button").wrap("<span class='MilFormButton'></span>");

    /* * * * * * * * * * * * * * * * * * * * * * * */
    /* 15. MIL FORM BUTTON, IE6 DISABLED CLASSES   */
    /* * * * * * * * * * * * * * * * * * * * * * * */
    $(".MilFormButtonSmall.disabled").addClass('disabledSmall_IE6jQuery');
    $(".MilFormButton.disabled").addClass('disabled_IE6jQuery');
    $(".MilFormButtonLarge.disabled").addClass('disabledLarge_IE6jQuery');
    
    /* * * * * * * * * * * * * * * * * * * * * * * * * * */
    /* 15.5 MIL FORM BUTTON, IE7 WIDTH / FLICKER FIX     */
    /* * * * * * * * * * * * * * * * * * * * * * * * * * */
    /*IE6&7 form button WIDTH BUG:
        Usually this is fixed with: overflow:visible
        However this caused our 'sliding door' buttons to flicker in IE7.
        So instead, the code below corrects the width.*/
    if($.browser.msie) {
        if($.browser.version <= 7) {
            $(".MilFormButton input, .MilFormButtonSmall input, .MilFormButtonLarge input, .MilFormButton button").each(function(){
                $Width = $(this).width();
                if($Width >50){/*shorten only if wider than 50px*/
                    $Width = ($Width/100) *90;
                    $(this).css({width: $Width});
                    $(this).css({paddingRight: '0px'});
                    $(this).css({paddingLeft: '4px'});
                }
            });
        }
    }
    
    /* * * * * * * * * * */
    /* 16. DATE PICKER   */
    /* * * * * * * * * * */
    if ($('.date-pick').length){//Checking existence
        $('.date-pick').datePicker({startDate:'2000/01/01'});
    }

    /* * * * * * * * * * * * * * * */
    /* 17.2 JOB LIST PAGE           */
    /* * * * * * * * * * * * * * * */
    $(".JobDetails").hide(); //(Hides level2)
    
    /* Job List: Handles AutoExpanision of a specific job (is defined by a class called AutoExpand) */
    $(window).load(function() {
        $ThisRow = $(".job_table .AutoExpand");
        if($ThisRow.length > 0){
           $TargetDetails = $ThisRow.next("tr.Details").children(":first").children(":first").children(":first");
            // show details
            $TargetDetails.slideToggle("fast", function(){
            
                // bg colour
                $ThisRow.toggleClass("JobListButtonToggleTR");
                // arrow icon
                $ThisRow.children(":first").toggleClass("JobListButtonToggleTD");
                
                // close other details
                $ThisRow.parent().parent().parent().siblings(".Details").each(function(){
                    $ThisRow.children(":first").children(":first").children(":first").slideUp("fast");
                });
            })
            // reset other button's down arrows
            $ThisRow.siblings(".ButtonRow").each(function(){
                $ThisRow.removeClass("JobListButtonToggleTR");
                $ThisRow.children().removeClass("JobListButtonToggleTD");
            });
            window.scroll(0, $ThisRow.offset().top);
        }
    });
    
    /* Job List: Main Recruitment List */
    $(".job_table .ButtonRow").click(function(){
        $ThisButton = $(this);
        $TargetDetails = $(this).next("tr.Details").children(":first").children(":first").children(":first");
        
        // show details
        $TargetDetails.slideToggle("fast", function(){
        
            // bg colour
            $ThisButton.toggleClass("JobListButtonToggleTR");
            // arrow icon
            $ThisButton.children(":first").toggleClass("JobListButtonToggleTD");
            
            // close other details
            $(this).parent().parent().parent().siblings(".Details").each(function(){
                $(this).children(":first").children(":first").children(":first").slideUp("fast");
            });
        })
        // reset other button's down arrows
        $(this).siblings(".ButtonRow").each(function(){
            $(this).removeClass("JobListButtonToggleTR");
            $(this).children().removeClass("JobListButtonToggleTD");
        });
	});
	/* Job List: Main Recruitment List, extra detail close button */
	$(".JobDetails .Close").click(function(){
	    $ThisButton = $(this);
        $ThisButton.parent().parent().slideToggle('fast');
        /* Reset the original row button's appearance */
        $ButtonRowTarget = $ThisButton.parent().parent().parent().parent().parent().prev('.ButtonRow');
        $ButtonRowTarget.toggleClass("JobListButtonToggleTR");
        $ButtonRowTarget.children(":first").toggleClass("JobListButtonToggleTD");
        $BasketButtonRowTarget = $ThisButton.parent().parent().parent().parent().children(":first");
        $BasketButtonRowTarget.toggleClass("JobListBasketButtonToggle");
	});
	
	/* Job List: Main Recruitment List Row Mouseovers (CSS wouldn't work for IE6)*/
	$(".job_table .ButtonRow").mouseover(function(){
        $(this).addClass("jobButtonRowMouseover");
	});
	$(".job_table .ButtonRow").mouseout(function(){
        $(this).removeClass("jobButtonRowMouseover");
	});
    
    /* Job List: Help */
	$(".job_info_content").hide();
    $(".job_info_show_hide").click(function(){
        $ThisButton = $(this);
        $(".job_info_content").slideToggle("fast", function(){
                $ThisButton.toggleClass("job_info_show_hideToggle");
            }
        );
    });
    
     /* Job List: Print a job (milPrint.css) */
    $(".JobDetails .PrintSingleJob").click(function(){
        $("#Column700").addClass('PrintOneJobOnly');
        $(this).parent().parent().parent().parent().addClass('PrintThisJob');
        window.print();
    });
    $(".job_table .ButtonRow").click(function(){
        //remove targetted printing
        $(".PrintOneJobOnly").removeClass('PrintOneJobOnly');
        $("tr.PrintThisJob").removeClass('PrintThisJob');
    });
    
    /* * * * * * * * * * * * * * * */
    /* 17. POSITION LIST PAGE      */
    /* * * * * * * * * * * * * * * */
    $(".PositionDetails").hide(); //(Hides level2)
    
    /* Position List: Handles AutoExpanision of a specific position (is defined by a class called AutoExpand) */
    $(window).load(function() {
        $ThisRow = $(".vakanser_table .AutoExpand");
        if($ThisRow.length > 0){
           $TargetDetails = $ThisRow.next("tr.Details").children(":first").children(":first").children(":first");
            // show details
            $TargetDetails.slideToggle("fast", function(){
            
                // bg colour
                $ThisRow.toggleClass("PositionListButtonToggleTR");
                // arrow icon
                $ThisRow.children(":first").toggleClass("PositionListButtonToggleTD");
                
                // close other details
                $ThisRow.parent().parent().parent().siblings(".Details").each(function(){
                    $ThisRow.children(":first").children(":first").children(":first").slideUp("fast");
                });
            })
            // reset other button's down arrows
            $ThisRow.siblings(".ButtonRow").each(function(){
                $ThisRow.removeClass("PositionListButtonToggleTR");
                $ThisRow.children().removeClass("PositionListButtonToggleTD");
            });
            window.scroll(0, $ThisRow.offset().top);
        }
    });
        
    /* Position List: Main Recruitment List */
    $(".vakanser_table .ButtonRow").click(function(){
        $ThisButton = $(this);
        $TargetDetails = $(this).next("tr.Details").children(":first").children(":first").children(":first");
        
        // show details
        $TargetDetails.slideToggle("fast", function(){
        
            // bg colour
            $ThisButton.toggleClass("PositionListButtonToggleTR");
            // arrow icon
            $ThisButton.children(":first").toggleClass("PositionListButtonToggleTD");
            
            // close other details
            $(this).parent().parent().parent().siblings(".Details").each(function(){
                $(this).children(":first").children(":first").children(":first").slideUp("fast");
            });
        })
        // reset other button's down arrows
        $(this).siblings(".ButtonRow").each(function(){
            $(this).removeClass("PositionListButtonToggleTR");
            $(this).children().removeClass("PositionListButtonToggleTD");
        });
	});

	/* Position List: Main Recruitment List, extra detail close button */
	$(".PositionDetails .Close").click(function(){
	    $ThisButton = $(this);
        $ThisButton.parent().parent().slideToggle('fast');
        /* Reset the original row button's appearance */
        $ButtonRowTarget = $ThisButton.parent().parent().parent().parent().parent().prev('.ButtonRow');
        $ButtonRowTarget.toggleClass("PositionListButtonToggleTR");
        $ButtonRowTarget.children(":first").toggleClass("PositionListButtonToggleTD");
        $BasketButtonRowTarget = $ThisButton.parent().parent().parent().parent().children(":first");
        $BasketButtonRowTarget.toggleClass("PositionListBasketButtonToggle");
	});
	
	/* Position List: Main Recruitment List Row Mouseovers (CSS wouldn't work for IE6)*/
	$(".vakanser_table .ButtonRow").mouseover(function(){
        $(this).addClass("vakanserButtonRowMouseover");
	});
	$(".vakanser_table .ButtonRow").mouseout(function(){
        $(this).removeClass("vakanserButtonRowMouseover");
	});
	
    /* Position List: Job Basket */
    $(".job_basket_warp li span").click(function(){
        $ThisButton = $(this);
        $BasketDetails = $(this).siblings(".PositionDetailsWrap").children(":first");

        // show details
        $BasketDetails.slideToggle("fast", function(){
            // arrow icon down
            $ThisButton.toggleClass("PositionListBasketButtonToggle");
            
            // close other details
            $(this).parent().parent().siblings().each(function(){
                $(this).children(":last").children().slideUp("fast");
            });
        });
        // reset other button's down arrows
        $ThisButton.parent().siblings().each(function(){
            $(this).children(":first").removeClass("PositionListBasketButtonToggle");
        });
	});
	/* Position List: Help */
	$(".vakanser_info_content").hide();
    $(".vakanser_info_show_hide").click(function(){
        $ThisButton = $(this);
        $(".vakanser_info_content").slideToggle("fast", function(){
                $ThisButton.toggleClass("vakanser_info_show_hideToggle");
            }
        );
    });

    /* Position List: Print a position (milPrint.css) */
    $(".PositionDetails .PrintSinglePosition").click(function(){
        $("#Column700").addClass('PrintOnePositionOnly');
        $(this).parent().parent().parent().parent().addClass('PrintThisPosition');
        window.print();
    });
    $(".vakanser_table .ButtonRow").click(function(){
        //remove targetted printing
        $(".PrintOnePositionOnly").removeClass('PrintOnePositionOnly');
        $("tr.PrintThisPosition").removeClass('PrintThisPosition');
    });

    /* * * * * * * * * * * * * * * */
    /* 18. READWEB ('toolbar')     */
    /* * * * * * * * * * * * * * * */
    $("#A1").click(function(){
        if( $("li#ToolBarSpace").is(":visible")){
            $('#PAFTOOLBAR').hide();//just hides BAR quicker, looks tidier
        }
        if ($('#PAFTOOLBAR').length){//Checking existence
            $("#ToolBarSpace").css({display: 'inline', float: 'none'});
        }
    });
    //Make space for BAR on page load
    //check cookie to see if TOOLBAR will appear
    var c_name = "leseactive";
    var c_value = "";
    if (document.cookie.length>0){
        c_start=document.cookie.indexOf(c_name + '=');
        if (c_start!=-1){
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            c_value = unescape(document.cookie.substring(c_start,c_end));
        }
    }
    if (c_value == "true"){
        $("#ToolBarSpace").css({display: 'inline', float: 'none'});
    }
    // Small 'LYSSNA' link positioning tweak for IE8 only (all other browsers positioned with CSS)
    if($.browser.msie) {
        if($.browser.version == 8) {
            $('#A1 span').css({marginTop:'0px'}); 
        }
    }

    /* * * * * * * * * * * * * * * */
    /* 19. TV THUMBNAILS STYLING   */
    /* * * * * * * * * * * * * * * */
    $(".TVThumbnails .Row").each(function(){
        $(this).children(".ThumbnailItem:eq(0)").css({marginRight: '40px'});
        $(this).children(".ThumbnailItem:eq(1)").css({marginRight: '40px'});
        $(this).children(".ThumbnailItem:eq(2)").css({marginRight: '0px'});
    });
    $(".TVThumbnails").children(".Row:last").children(".ThumbnailItem").css({border: 'none', marginBottom: '0px'});
    
    /* * * * * * * * * * * * * * * * */
    /* 20. BLOCKQUOTE (right quote)  */
    /* * * * * * * * * * * * * * * * */
    $("blockquote").append('<span class="BqEnd">&nbsp;</span>');
    
    /* * * * * * * * * * * * * * * * * * * * * * * */
    /* 21. MEDIA IMAGES: PLAY & PROMPT show/hide   */
    /* * * * * * * * * * * * * * * * * * * * * * * */
    $(".FilmItem220 .Prompt, .FilmPromoItem220 .Prompt, .FilmItem200 .Prompt").hide();
    $(".FilmItem220 a, .FilmPromoItem220 a, .FilmItem200 a").hover(
        function () {
            $(this).children(".Prompt").show();
        }, 
        function () {
            $(this).children(".Prompt").hide();
        }
    );
    
    /* * * * * * * * * * * * * * * * * */
    /* 22. COLLAPSING LEFT COL BOXES   */
    /* * * * * * * * * * * * * * * * * */
    $(".CollapsingWrap.StartCollapsed").hide(0, function(){
        $(this).prev().toggleClass("LeftColBoxCollapseToggle");
	});
	$(".CollapsingWrap.StartExpanded").show(function(){
        $(this).prev().toggleClass("LeftColBoxCollapseToggle");
	});
    $(".CollapseBox h3, .Families h3, .RoyalGuard h3, .FutureDefense h3").click(function(){
        if ($('#leftarea').is('.StartPage')) {
            //cannot open/close on startpage
        }else{
            $(this).toggleClass("LeftColBoxCollapseToggle");
            $(this).next('.CollapsingWrap').slideToggle();
        }
    });
    
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    /* 23. ADDING OPTGROUP-ELEMENTS TO DROPDOWNS ON RECRUITMENT-PAGE */
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    var ddlFunctions = $('.ddlFunctions');
    if(ddlFunctions != null)
    {
        var opt;
        var i = 0;
        $('option', ddlFunctions).each(function(i) { 
            opt = $(this);
            if(opt.val() == opt.text())
            {
                opt.before('<optgroup label="' + opt.val() + '">');
                opt.remove();
            }
            i = i+1;
        });
    }
    var ddlProfessions = $('.ddlProfessions');
    if(ddlProfessions != null)
    {
        var opt;
        var i = 0;
        $('option', ddlProfessions).each(function(i) { 
            opt = $(this);
            if(opt.val() == opt.text())
            {
                opt.before('<optgroup label="' + opt.val() + '">');
                opt.remove();
            }
            i = i+1;
        });
    }
    
	// RESULTAREABOXES
	$('#resultAreaBoxes div:odd').css('margin-left', '10px'); // HIDE ALL ANSWERS
	
	// RECRUIT ACCORDION
	
	$('.recruit_work_faq_title').click(function(e) {
			$(this).toggleClass('selected');
			$(this).next().toggle('slow');
			
			$(this).next().find(".tab:first").each(function(index) {
			    if (index == 0)
			    {
			        SetTabHeight($(this));
			    }
			});
    });
	
	$(".recruit_questions").each(function(){
	    var firstTab = $(this).find(".tab:first");
	    SetTabHeight(firstTab);
	});
	
	$(".tabTitle").click(function(){
	    SetTabHeight($(this).parent());
	});
	
	function SetTabHeight(tab)
	{
		var parentUl = tab.parent(); //hämta parentUl som alla tabbar bor i
		
	    parentUl.find(".tabBody").each(function(){
		    $(this).fadeOut(200);
		});
		
		var minHeight = 0;
		
		parentUl.find(".tabTitle").each(function(){
	        minHeight +=$(this).height();
	        $(this).removeClass('active');
		});
		
		var body = tab.find(".tabBody"); //hämta vår body text som ska visas
		var title = tab.find(".tabTitle"); //hämta vår body text som ska visas
		title.addClass('active');
		
		var bodyPad = 0;
		var bodyHeight = body.height();
		
		//kolla så att vi inte har för lite body
		if(bodyHeight < minHeight)
		{
			bodyHeight = minHeight;
			body.height(bodyHeight);
		}
		
		if(bodyHeight > minHeight)
		{
		    bodyPad = parseInt(body.css("padding-top").replace("px", "")) + parseInt(body.css("padding-bottom").replace("px", ""));
		    bodyHeight = bodyHeight + bodyPad;
		    body.height(bodyHeight);
		}
		
		//Animera rutan till den nya höjden
		parentUl.animate({"height": bodyHeight + "px"}, 200);
		
		//visa vår body/tabinnehåll
		body.fadeIn(200);
	}
	
	
}


//for some reason the galleria object needs to be initialized before popups with gallerias can be shown
//this inits the Galleria object without adding any unnecessary markup to the DOM
function loadGalleriaTheme() {
    Galleria.loadTheme('/Javascript/galleria.classic.js');
}

function initGalleriaObject() {
    loadGalleriaTheme();
    var gallery = new Galleria({target:$('<div></div>')});
}

//galleriaobj : The object that should be transformed into a galleria
//galleriaPopupTarget : The object matching galleriaobj's images. This object will be cloned when opening a popup galleria
function loadGalleria(galleriaobj, galleriaPopupTarget) {
    galleriaobj = $(galleriaobj);
    galleriaPopupTarget = $(galleriaPopupTarget);
    // Load the classic theme
    loadGalleriaTheme();
    
    // Initialize Galleria
    galleriaobj.galleria({
        extend: function(options) {
            //if not removed then clicking on the info-text will hide it
            $('div.galleria-info-text', galleriaobj).unbind();  
            
            //center the thumbnails carousel if less wide than container
            var thumbs = $('.galleria-thumbnails', galleriaobj);
            var thumbswidth = thumbs.outerWidth();
            var galleriawidth = $(galleriaobj.get(0)).outerWidth();
            
            if(thumbswidth < galleriawidth){
                thumbs.css('margin-left', (galleriawidth - thumbswidth) / 2 + 'px');
            }else{
                thumbs.css('margin-left', '0');
            }
            
            //bind click-event to main image of gallery. Opens popup with identical gallery, initialized to showing same image as was clicked
            this.bind(Galleria.IMAGE, 
                function(e) {
                    $(e.imageTarget).click(
	                    this.proxy(function() {
		                    openGalleriaPopup(galleriaPopupTarget, e.index);
	                    })	
                    )
                }    
           )
           
           updateGalleriaBehaviour();
        }
    });
}


//Opens a popup with a galleria
//galleriaPopupTarget : the object that should be cloned and initialized as a galleria in the popup
//showindex : default 0. What image index in the carousel should be shown once galleria is initialized
function openGalleriaPopup(galleriaPopupTarget, showindex) {
    galleriaPopupTarget = $(galleriaPopupTarget);
    
    if(!showindex || showindex < 0) showindex = 0;
    
    //display overlay
    $('.modalBackground').remove();
    $('<div class="modalBackground" />').css({
        'position': 'fixed',
        'z-index': '10000'
    }).appendTo('#aspnetForm');
    
    //remove old popup if it exists
    $('.jpopup').remove();
    
    //clone galleria base so that we can open the same popup galleria twice
    var popupGalleria = galleriaPopupTarget.clone();
    
    //Create modal window and attach form to it
    $('#aspnetForm')
        .append(
            $('<div class="jpopup galleria-popup" />').css(
                {
                    'position': 'fixed',
                    'visibility': 'hidden', //can't use display:none because that will screw up dimension return values
                    'z-index': '100001'
                }
            )
        .append('<div class="base"><div class="close"></div></div><div class="shadow"></div>')
        .append(popupGalleria)
    );
    
    //init galleria
    popupGalleria.galleria({
        extend: function(opts) {
                $('div.galleria-info-text', popupGalleria).unbind(); //if not removed then clicking on the info-text will hide it
                updateGalleriaBehaviour();
            },
        show: showindex
    }).show();
    
    $('.jpopup.galleria-popup').css({
        'top' : ($(window).height() - popupGalleria.outerHeight()) / 2 + 'px',
        'left' : ($(window).width() - popupGalleria.outerWidth()) / 2 + 'px',
        'visibility' : 'visible'
    });
    
    //center the thumbnails carousel if possible
    var thumbs = $('.galleria-thumbnails', popupGalleria);
    var thumbswidth = thumbs.outerWidth();
    var galleriawidth = popupGalleria.outerWidth();
    
    if(thumbswidth < galleriawidth){
        thumbs.css('margin-left', (galleriawidth - thumbswidth) / 2 + 'px');
    }else{
        thumbs.css('margin-left', '0');
    }
    
    //bind click to remove modal
    $('.modalBackground, .jpopup.galleria-popup div.base div.close').css('display','block').click(
        function() {
            $('.modalBackground, .galleria-popup').remove();
        }
    );
}

function updateGalleriaBehaviour() {
    //we don't want to show the nav controls when hovering over the whole .galleria-container
    //only when hovering over the main image 
    $('.galleria-container').unbind('mouseenter mouseleave');
    
    $('.galleria-image-nav div').removeAttr('style'); 
/*
    $('.galleria-image img')
    .click(
        function(){
            var img = $(this);
            var title = img.closest('.galleria-thumbnails-container.galleria-carousel').siblings('.galleria-info').find('.galleria-info-title');
            
            if(img.attr('title') && img.attr('title') != '') {
                //title.text(img.attr('info')).show();
            }else{
                //title.hide();
            }
        }
    );
    */
}


$(document).ready(function(){
    initJQueryFunctions();
    
     // IMAGE SLIDER
    $("div.controller").jFlow({
            slides: ".slides",
            width: "660px",
            height: "150px"
     });
     $(".imageSlider").find("img").each(function(){
		$(this).show();
	});
    // FOOTER IMAGE SLIDER
    $("div.footercontroller").jFlowFooter({
        slides: ".footerslides",
        width: "660px",
        height: "150px"
    });
    
    $(".jFlowControl").live('click', function(){
	    var elm = $(this);
	});
	
	//make #footer_bg show exactly behind #footer
	var intervalTimerCounter = 1,
	    intervalTimer = setInterval(
	        function(){
	            intervalTimerCounter = ++intervalTimerCounter;
	            if(intervalTimerCounter >=10) clearInterval(intervalTimer);
	            
	            var footer_height = $('#footer').outerHeight() + 'px';
    	
	            $('#footer_bg').css({
	                'height' : footer_height,
	                'margin-top' : '-' + footer_height
	            });
	        }, 
	        250
        );
});

