﻿$(document).ready(function () {

    // ----------TOGGLE----------

    $(".toggle .answer").hide();
    $(".toggle .question").click(function () {
        $(this).next(".answer").slideToggle(500);
        $(this).toggleClass("open");
    });

    // ----------SLIDER----------

    //Show the paging and activate its first link
    $(".paging").show();
    $(".paging a:first").addClass("active");

    //  Center paging
    var popupmargin = (($('.main_view .window').width() - $('.paging').width()) / 2);
    $('.paging').css({
        'margin-left': popupmargin
    });

    //Get size of the image, how many images there are, then determin the size of the image reel.
    var imageWidth = $(".window").width();
    var imageSum = $(".image_reel img").size();
    var imageReelWidth = imageWidth * imageSum;

    //Adjust the image reel to its new size
    $(".image_reel").css({ 'width': imageReelWidth });

    //Paging  and Slider Function
    rotate = function () {
        var triggerID = $active.attr("rel") - 1; //Get number of times to slide
        var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

        $(".paging a").removeClass('active'); //Remove all active class
        $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

        //Slider Animation
        $(".image_reel").animate({
            left: -image_reelPosition
        }, 500);

    };

    //Rotation  and Timing Event
    rotateSwitch = function () {
        play = setInterval(function () { //Set timer - this will repeat itself every 7 seconds
            $active = $('.paging a.active').next(); //Move to the next paging
            if ($active.length === 0) { //If paging reaches the end...
                $active = $('.paging a:first'); //go back to first
            }
            rotate(); //Trigger the paging and slider function
        }, 6000); //Timer speed in milliseconds (7 seconds)
    };

    rotateSwitch(); //Run function on launch

    //On Hover
    $(".image_reel a").hover(function () {
        clearInterval(play); //Stop the rotation
    }, function () {
        rotateSwitch(); //Resume rotation timer
    });

    //On Click
    $(".paging a").click(function () {
        $active = $(this); //Activate the clicked paging
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(); // Resume rotation timer
        return false; //Prevent browser jump to link anchor
    });

    // ----------RATING----------
    var smallscalewidth = 167;
    var largescalewidth = 353;
    var halfarrowwidth = 27;

    $(".rating-current").each(function () {

        if ($(this).parent().is('.popupbox')) {
            var scale = largescalewidth;
        } else {
            scale = smallscalewidth;
        }
        var textrating = $(this).text().replace(',', '.');
        var floatrating = Math.round(parseFloat(textrating) / 10 * scale - halfarrowwidth);
        $(this).css({ 'margin-left': floatrating });
    });
    // ----------POPUP
    // Shows confirmation that the message was sent
    if ($('.popupbox div.sfSuccess:contains(" ")').length > 0) {
        //$('body').append('<div class="formsuccess">' + $('div.sfSuccess').text() + '</div>');
        $('body').append('<div class="formsuccess"><h1>Tack för ditt meddelande!</h1><p>Vi kontaktar dig inom kort!</p><p>Med vänlig hälsning<br />Business Check AB</div>');
        $('.formsuccess').prepend('<a class="close">Stäng</a>');
        var popupleftmargin = ($('.formsuccess').width() + 10) / 2;
        $('.formsuccess').css({
            //     'margin-top': -popuptopmargin,
            'margin-left': -popupleftmargin
        });
        $('.formsuccess').fadeIn();
    }
	
    // Reopens popup if it has error messages
    //if ($('.popupbox div.sfError:contains(" ")').length > 0) {

    //    var classList = $('.sfError').parents('.popupbox').attr('class').split(/\s+/);
    //    var popupid = classList[classList.length - 1]; // It is always the last class that is the unique popup identifier
    //    openPopup(popupid);
    //}
    // If the url contains an anchor, open the popup with corresponding classname/id
    var pageUrl = document.location.toString();
    if (pageUrl.match('#')) {
        var currentAnchor = pageUrl.split('#')[1];
        openPopup(currentAnchor);
    }
    
    var category1 = pageUrl.split('/')[3];
    var category2 = pageUrl.split('/')[4];

//    $('a[href*=../' + category1 + ']').addClass('rtsSelected');
//    $('a[href*=../' + category2 + ']').addClass('rtsSelected');

    $('a.popup').click(function () {
        if ($(this).attr('rel')) {
            var popupid = $(this).attr('rel');
            openPopup(popupid);
            return false;
        }
        else if ($(this).attr('href').indexOf('#')) {
            var popupid = $(this).attr('href').split('#')[1];
            if (pageUrl.match($(this).attr('href').split('#')[0])) {
                openPopup(popupid);
            }
        }

    });
     //Close when faded area is clicked
    $('a.close').live('click', function () {
            $('#fade , .popupbox , .formsuccess').fadeOut(function () {
                $('#fade , .formsuccess , a.close').remove();
           });
       return false;
    });
	
    function openPopup(popupid) {
        $('.' + popupid).prepend('<a class="close" title="Stäng">Stäng</a>');

        if ($('window').height() < ($('.' + popupid).height() + 10)) {
            $('.' + popupid).css({ 'top': '10px' });
        }

        $('html, body').animate({ scrollTop: 0 }, 'slow');

        // Fades in popup
        $('.' + popupid).fadeIn();

        // Add div to body
        $('body').append('<div id="fade"></div>');
        $('#fade').css({ 'filter': 'alpha(opacity=0)' }).fadeIn();

        //  Center popup
        //var popuptopmargin = ($('.' + popupid).height() + 10) / 2;
        var popupleftmargin = ($('.' + popupid).width() + 10) / 2;
        $('.' + popupid).css({
            //     'margin-top': -popuptopmargin,
            'margin-left': -popupleftmargin
        });
    }

});
/*
$(window).bind('beforeunload', function () {
    $('.popupbox div.sfError').text();
}
);*/
