﻿$('html').addClass('js');

var slideSpeed = 6000;
var run;
var delayedRun;
var autoplay = true;
var timeOuts = new Array();
var intervals = new Array();

$(document).ready(function() {
    backgroundSlides();
    frontPageTabs();
    hoverImages();
    submitHover();
    articleListHover();
    articleListItemClick();
    menuActions();
    initSlides();
    initToolTips();
    fixArticleBlockQuotes();
    adjustTextAreas();
    $("#printerfriendly").click(function(e) {
        window.print();
        e.preventDefault();
    });
    ensureEqualHeightCustomBoxes();
    $("a[rel^='prettyPhoto']").prettyPhoto({
        default_width: 620,
        default_height: 350,
        theme: 'light_square'
    });
    footerLogosHover();
    initDdls();


    $(".giver:not(.contribution) input:image").click(function(e) {
        var amount = $(this).siblings(":text").val();
        if (amount.length) {
            if (amount < 150) {
                alert("Minimumsbeløp er kr 150,-");
                e.preventDefault();
            }
        } else {
            alert("Minimumsbeløp er kr 150,-");
            e.preventDefault();
        }
    });

    $("#WAFBlogPostCommentFormCaptchaInput input").wrap('<span class="rb-text" />');
    $("input:checkbox, input:radio").customInput();
});

function footerLogosHover() {
    $('#sponsor-wrapper a img').hover(function() {
        var obj = $(this);
        obj.attr('src', obj.attr('src').replace('.gif', '_farge.png'));
    }, function() {
        var obj = $(this);
        obj.attr('src', obj.attr('src').replace('_farge.png', '.gif'));
    });
}

function initDdls() {
    $("select").not("select.custom-ddl").each(function() {
        $(this).sexyCombo();
        var pSexy = $(this).parent("div.sexy");
        var w;
        if ($(this).hasClass("ddl-member")) {
            w = 240;
        } else {
            w = $(this).siblings(".list-wrapper li").css("visibility", "hidden").end().outerWidth(true);
            $(pSexy).css("margin-right", "40px");
        }
        
        
        $(this).next("input").width(w);
        $(pSexy).width(w + 25);
        $(pSexy).children("div.icon").css("left", w + 20 + "px");
        $(pSexy).children("div.list-wrapper").width(w + 20);
    });
}

function adjustTextAreas() {
    $(".rb-textarea-wrapper textarea").each(function() {
        $(this).css("width", $(this).width() -20);    
    });
}

function ensureEqualHeightCustomBoxes() {
    var tallest = 0;

    // loop through columns and find the tallest
    $('#custom-list li').each(function() {
        if ($(this).height() > tallest)
            tallest = $(this).height();
    });

    // loop through columns and adjust height as necessary
    $('#custom-list li').each(function() {
        if ($(this).height() < tallest) {
            $(this).height(tallest);
        }
    });
}

function fixArticleBlockQuotes() {
    $("#article-content blockquote:has(p[class])").each(function() {
        var p = $(this).find("p[class]:first");        
        $(this).attr('class', p.attr('class'));
        p.removeAttr('class');
    });
}

function rotate(reverse) {    
    //clear any autoplays initiated by setTimeout
    clearTimeouts();
    //Get the first image
    var current = ($('ul#slides li.active') ? $('ul#slides li.active') : $('ul#slides li:first'));
    var next;
    //check if the 'prev' button is clicked and get the next image, if it's the last image, get the first
    if (!reverse) {
        next = ((current.next().length) ? ((current.next().hasClass('active')) ? $('ul#slides li:first') : current.next()) : $('ul#slides li:first'));
    } else {
        next = ((current.prev().length) ? ((current.prev().hasClass('active')) ? $('ul#slides li:last') : current.prev()) : $('ul#slides li:last'));
    }

    //fade in next image, activate class puts it on top of stack
    next.css({ opacity: 0.4 }).addClass('active').stop().animate({ opacity: 1.0 }, 500).find(".description, .next, .prev").css('display', 'block');
    current.stop().removeClass('active').find(".description, .next, .prev").css('display', 'none'); //Hide current image
    //current.stop().animate({ opacity: 0.0 }, 1000).removeClass('active').find(".description, .next, .prev").css('display', 'none'); //Hide current image
    $("#main-content-wrapper .tabs").css("opacity", "1");
};

function clearTimeouts() {
    for (key in timeOuts) {
        clearTimeout(timeOuts[key]);
    }
}
function clearIntervals() {
    for (key in intervals) {
        clearInterval(intervals[key]);
    }
}

function initSlides() {    
    if ($('ul#slides li').length < 2) {
        autoplay = false;
        $('ul#slides li .next, ul#slides li .prev').hide();
    }
    $('ul#slides li').css({ opacity: 0.0 });
    //Get the first image and display it (gets set to full opacity)
    $('ul#slides li:first').css({ opacity: 1.0 });

    $('#slides li a').click(    //prevent bubbling
        function(event) {
            event.cancelBubble = true;
            if (event.stopPropagation) event.stopPropagation();
        }
    );

    $("ul#slides li").has("a.read-quote").each(function() {
        $(this).css("cursor", "pointer");
        $(this).not("blockquote a").click(function() {
            window.location.href = $(this).find("a.read-quote").attr("href");
        });
    });

    //Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds
    if (autoplay) {
        intervals["init"] = setInterval('rotate()', slideSpeed);
    }

    $('#slides').hover(
        function() {
            if (autoplay) {
                clearTimeouts();
                clearIntervals();
            }
        }, function() {
            if (autoplay) intervals["hover"] = setInterval('rotate()', slideSpeed);
        }
    );

        $("#slides .next").click(function(e) {
            if (autoplay) {
                clearTimeouts();
                clearIntervals();
            }
            rotate(); //show next slide
            if (autoplay) {
                timeOuts["next"] = setTimeout(function() {
                    intervals["next"] = setInterval('rotate()', slideSpeed);
                }, 5000); //activate autoplay
            }
            e.preventDefault();
        });
    
    $("#slides .prev").click(function(e) {
        if (autoplay) {
            clearTimeouts();
            clearIntervals();
        }
        rotate(true); //show next slide
        if (autoplay) {
            timeOuts["prev"] = setTimeout(function() {
                intervals["prev"] = setInterval('rotate()', slideSpeed);
            }, 5000); //activate autoplay
        }
        e.preventDefault();
    });
}

function backgroundSlides() {
    $("ul#slides li").each(function() {
        var imageSrc = $(this).find("img").attr('src');
        $(this).css({ backgroundImage: "url(" + imageSrc + ")" });
    });
}

function frontPageTabs() {
    $(".tab-content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab-content:first").show(); //Show first tab content

    $("ul.tabs li").children("a").click(function() {        
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).parent().addClass("active"); //Add "active" class to selected tab
        $(".tab-content").hide(); //Hide all tab content
        var activeTab = $(this).parent().children("a").attr("href"); //Find the href attribute value to identify the active tab + content
        $(activeTab).show(); //Fade in the active ID content
        return false;
    });    
}

function submitHover() {
    $("#sidebar .giver .btn-submit, #header-promo .giver .btn-submit, .productlist-item-orderbutton").hover(function () {
            var src = $(this).attr("src").match(/[^\.]+/) + "_on.gif";
            $(this).attr("src", src);
        }, function() {
            var src = $(this).attr("src").replace("_on", "");
            $(this).attr("src", src);
        });    
}

function openLevel2() {
    $("#sitenav li.active").find('ul').hide().end().removeClass('active').children("a.active").removeClass("active");    //close any open items
    if ($(this).hasClass("has-children")) {
        $(this).find("a:first").addClass("active");
        var ul = $(this).find('ul:first');
        ul.css({ visibility: "visible", display: "block" }).show(100).end().addClass('active');
        setHeaderHeight(ul.height() + 3);
    }
}

function closeLevel2() {
    $(this).parent().find("a:first").removeClass("active");    //remove active class from top-level
}

function openLevel3() {
    if ($(this).hasClass("has-children")) {
        $(this).find("a:first").addClass("active");
        child = $(this).find('ul:first');
        var h = child.height() + $(this).height();

        if (child.length) h = h + 20;
        else h = h + 3;

        child.css({ visibility: "visible", display: "block" }).show(100);
        child.parent().addClass("active");

        var menuOffsetLeft = $("#sitenav").offset().left;
        var menuRight = menuOffsetLeft + $("#sitenav").width();

        var offsetLeft = $(child).offset().left;
        var subMenuRight = offsetLeft + $(child).width();
        if (subMenuRight > menuRight) {
            $(child).css("right", 0);
        }

        setHeaderHeight(h);
    } else {        
        setHeaderHeight($(this).parent().height());        
    }
}
function closeLevel3() {
    $("#sitenav li.lvl-2").find('ul').hide().end().removeClass('active');    //close any open items
    $(this).find("a.active").removeClass("active");    
}

function menuActions() {
    $('#sitenav > li').hoverIntent({   //lvl-1
        over: openLevel2,
        sensitivity: 8,
        interval: 140,
        out: closeLevel2
    });

    $('#sitenav li.lvl-2').hoverIntent( {   //lvl-2
        over: openLevel3,
        sensitivity: 7,
        interval: 250,
        timeout: 240,
        out: closeLevel3
    });    

    $('#header-wrapper-inner').hoverIntent({   //lvl-2
        over: headerWrapperInnerOver,
        sensitivity: 5,
        interval: 500,
        timeout: 450,
        out: headerWrapperInnerOut
    });
}

function headerWrapperInnerOver() {
    var a = "a";
}

function headerWrapperInnerOut() {
    $(this).find("ul:gt(0)").hide();
    $("#sitenav li a.active").removeClass("active");    //close any open items
    setHeaderHeight(0);
}

function hoverImages() {
    $('#main-content-wrapper .content-items img, #campaign-boxes img').hover(function() {
            $(this).stop().animate({ opacity: 0.5 }, 0);
        }, function() {
            $(this).stop().animate({ opacity: 1.0 }, 0);
        });    
}

function articleListHover() {
    $('.item-list li:not(li.member-box, li.member-box li)', $("#body-content")).hover(function() {
            $(this).addClass('active').css("cursor", "pointer");
        }, function() {
            $(this).removeClass('active');
        });
    }

function articleListItemClick() {
    $('.item-list li:not(li.member-box, li.member-box li)', $("#body-content")).click(function() {
        var firstLink = $("a", $(this)).eq(0); 
        if ($(firstLink).length) {
            window.location.href = firstLink.attr("href");
        }
    });
}

function setHeaderHeight(elHeight) {
    var header = $("#header-wrapper-inner");
    var totalHeight = $("#header-wrapper").height() + elHeight;
    header.stop().animate({ height: (totalHeight) }, 275);
}

function initToolTips() {
    //tooltip  start
    var tipContainer;
    var tip;
    $(".tip_trigger").hover(function() {
        tip = $(this).find('.tip');
        $(this).data("tip", tip);
        tipContainer = $('<div>');
        tipContainer.addClass("tip-container");
        $('<div class="tip-container-top"></div>').appendTo(tipContainer);
        $('<p class="content"></p>').append(tip.show()).append("<span class='tip-connector'></span>").appendTo(tipContainer);
        $('<div class="tip-container-bottom"></div>').appendTo(tipContainer);
        $('body').append(tipContainer);
        tipContainer.show(); //Show tooltip
    }, function() {
        $(this).append($(this).data("tip"));
        tipContainer.hide(); //Hide and remove tooltip appended to the body                
        $(this).find('.tip').hide(); //Hide tooltip
    }).mousemove(function(e) {
     if (typeof(tip) != "undefined") {
        var mousex = e.pageX; //Get X coodrinates
        //var mousey = e.pageY + 20; //Get Y coordinates
        var mousey = e.pageY; //Get Y coordinates
        var tipWidth = 360; //Find width of tooltip
        var tipHeight = tipContainer.height(); //Find height of tooltip

        //Distance of element from the right edge of viewport
        var tipVisX = $(window).width() - (mousex + tipWidth);
        //Distance of element from the bottom of viewport
        var tipVisY = $(window).height() - (mousey + tipHeight);

        if (tipVisX < 20) { //If tooltip exceeds the X coordinate of viewport
            mousex = e.pageX - tipWidth - 20;
        } if (tipVisY < 20) { //If tooltip exceeds the Y coordinate of viewport
            mousey = e.pageY - tipHeight - 20;
        }
        //var newMousey = mousey + (tipHeight / 2);
        var newMousey = e.pageY - (tipHeight /2) - 20;
        
        
        //Absolute position the tooltip according to mouse position
        tipContainer.css({ top: newMousey, left: mousex + 15 });
        }
    }).click(function(e) {
        e.preventDefault();
    });
}
