﻿var showError = function(errorCode) {
    var errorMessages = [];
    errorMessages['TECHNICAL_ERROR'] = {};
    errorMessages['TECHNICAL_ERROR'].title = escape('Tekniskt fel');
    errorMessages['TECHNICAL_ERROR'].description = escape('Ett tekniskt fel uppstod. Försök senare'); 
    $('body').initLB('LBError', {
            closeElement: '.close',
            openTrigger: 'none'
        }, { onLoad: function(){
            initButtons();
            initCufon();
        }
    });
    LB.load('LBError', '/foretag/lightbox_message.html?title=' + errorMessages[errorCode].title + '&description=' + errorMessages[errorCode].description);
    LB.open('LBError');
};
function initButtons(optionalContextSelector) {
    var $btns;
    if (optionalContextSelector) {
        optionalContextSelector = $(optionalContextSelector);
        $btns = $('a[class^=BTNbtn]', optionalContextSelector);
    } else {
        $btns = $('a[class^=BTNbtn]');
    }
    $btns.each(function() {
        var $this = $(this);
        var hasImg = '';
        if ($this.children('img').length > 0) {
            hasImg = ' btnHasImg';
        }
        $this.wrap('<span class="' + $this.attr('class').substr(3) + hasImg + '"></span>')
        .after('<span class="right"></span>')
        .removeAttr('class');
    });
    // Cufon for buttons
    Cufon.replace('.btnGreyPlain a, .btnGrey a, .btnGreySmall a, .btnGreyPlainSmall a, .btnGreyMedium a, .btnGreyPlainTiny a', {
        fontFamily: 'boton',
        textShadow: '1px 1px #ffffff',
        hover: true
    });
    Cufon.replace('.btnBlackBig a, .btnBlack a, .btnBlackHalf a, .btnBlackOversized a, .btnBlackPlainBig a', {
        fontFamily: 'boton',
        textShadow: '1px 1px #444444'
    });
    Cufon.replace('.btnGreen a, .btnGreenSmall a, .btnGreenPlainSmall a, .btnGreenMedium a, .btnGreenBig a, .btnGreenPlainBig a, .btnGreenPlain a', {
        fontFamily: 'boton',
        textShadow: '1px 1px #05540a'
    });
}
function initCufon(contextID) {
    if (!contextID) {
        contextID = '';
    } else {
        contextID = $(contextID).attr('id');
        contextID = '#' + contextID + ' ';
    }
    Cufon.replace(contextID + '.footer h4,' + contextID + '.t1000Carousel .menu a', { fontFamily: 'boton', hover: true });
    Cufon.replace(contextID + 'h1[class!=noCufon],' + contextID + 'h2[class!=noCufon],' + contextID + 'h3[class!=noCufon],' + contextID + 'h4[class!=noCufon],' + contextID + 'h5[class!=noCufon]', { fontFamily: 'boton' });
    Cufon.replace(contextID + '.navigationDetails a,' + contextID + '.navigationMenu a,' + contextID + '.navigationSubMenu a,' + contextID + '.mainContentTopTabbs ul li h5', { fontFamily: 'botonRegular', hover: true });
    Cufon.replace(contextID + '.botonRegular', { fontFamily: 'botonRegular' });
    Cufon.replace(contextID + '.size1,' + contextID + '.size2,' + contextID + '.size3,' + contextID + '.size4,' + contextID + '.size5,' + contextID + '.size6,' + contextID + '.size7', { fontFamily: 'boton', hover: true });
    Cufon.replace(contextID + '.navigationTop a', { fontFamily: 'botonRegular', hover: true });
    Cufon.replace('#headerNavigationTop a, #M105 .links a', { fontFamily: 'boton', hover: true });
    Cufon.replace('#M105 .box .title', { fontFamily: 'boton' });
}
/* +++ GENERAL +++ */
$(document).ready(function() {
    // Replace links with buttons and init Cufon
    initButtons();
    initCufon();
    AddThis();
    pdfLinks();
    Cufon.replace('.actionOption', {hover:true });
    actionNavigation();

    $('.disconnect-link').click(function(event) {
        event.preventDefault();
    });        
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };
    /* +++ DROP-DOWN-MENU +++ */
    var closeDropDownTimeOut;
    var closeDropDownWaitCount = 0;
    var closeDropDownWaitCountMax = 8;
    var navigationHeight = 64;
    var delay = 140; // e.g. 200 ms * 10 = 2 sec
    var cS = { isHoveringSomething: 0, isHoveringDropDown: 1, isHoveringNothing: 2 };
    var cursorStatus = cS.isHoveringNothing;
    var dropDown = $('#navigationDropDown');
    $('#headerNavigationSub a').hover(function() {
        cursorStatus = cS.isHoveringSomething;
        openDropDown(this);
    }, function() {
        cursorStatus = cS.isHoveringNothing;
        closeDropDown();
    });
    dropDown.hover(function() {
        cursorStatus = cS.isHoveringSomething;
    }, function() {
        cursorStatus = cS.isHoveringNothing;
        closeDropDown();
    });
    var openDropDown = function(obj) {
        var $obj = $(obj);
        var newLeft = $obj.offset().left - $('#M105').offset().left - 1;
        if (dropDown.css('top') != (navigationHeight + 'px') || dropDown.css('left') != newLeft) {
            var arr = $obj.attr('class').split(' '), foundClass;
            for (var i = 0; i < arr.length; i++) {
                if (arr[i].match('navigationSubMenuItem') == 'navigationSubMenuItem') {
                    foundClass = arr[i];
                    break;
                }
            }
            $('.navigationDropDownContent:visible', dropDown).hide();
            $('.' + foundClass + ':last', dropDown).show();
            dropDown.queue([]).stop()
            .css({ 'left': newLeft, 'top': '-' + dropDown.height() })
            .animate({
                top: navigationHeight
            }, 300, 'easeOutExpo');
            $('#navigationDropDownArrow').css({
                left: newLeft + ($obj.width() / 2),
                top: navigationHeight - 3
            });
        }
    };
    var closeDropDown = function() {
        if (cursorStatus != cS.isHoveringSomething) {
            clearTimeout(closeDropDownTimeOut);
            if (closeDropDownWaitCount >= closeDropDownWaitCountMax) {
                closeDropDownWaitCount = 0;
                closeDropDownDefinitely();
            }
            else if (closeDropDownWaitCount > 0) {
                closeDropDownWaitCount++;
                closeDropDownTimeOut = setTimeout(closeDropDown, delay);
            }
            else {
                closeDropDownWaitCount++;
                closeDropDownTimeOut = setTimeout(closeDropDown, delay);
            }
        }
    };
    var closeDropDownDefinitely = function() {
        dropDown.queue([]).stop().animate({
            top: '-' + (dropDown.height() + 15) + 'px'
        }, 300, 'easeInExpo', function() {
            $('#navigationDropDownArrow').css('top', -20);
        });
    };
    $('.navigationDropDownContent:visible', dropDown).hide();
    /* --- DROP-DOWN-MENU --- */
    // Text boxes and textfields
    $("input[type!='submit'], textarea").focus(function() {
        if (this.value == this.defaultValue) {
            this.value = '';
        }
    }).blur(function() {
        if (this.value.trim() == '') {
            this.value = this.defaultValue;
        }
    });
    // Select boxes
    if ($.fn.selectBox && !($.browser.msie && parseInt($.browser.version) < 7)) {
        $('.select').selectBox();
        $('.selectSmall').selectBox({
            newClass: 'selectSmall'
        });
    }
    // Checkboxes and radio buttons
    if ($.fn.checkbox) {
        $('input:checkbox').checkbox({
            empty: '/system_images/empty.png'
        });
        $('input:radio').checkbox({
            empty: '/system_images/empty.png',
            cls: 'jquery-radiobutton'
        });
    }
/* using static links implement later
    $('#headerUserControls .login').click(function() {
        obj = $(this);
        if (obj.hasClass('loggedOn') && !obj.hasClass('open')) {
            $('#headerUserControls').find('.open').removeClass('open');
            $('#headerUserControls .box').hide();
            $('#headerLoggedOnBox').show();
            obj.addClass('open');
        } else if (!obj.hasClass('open')) {
            $('#headerUserControls').find('.open').removeClass('open');
            $('#headerUserControls .box').hide();
            $('#headerLoginBox').show();
            obj.addClass('open');
        } else {
            $('#headerUserControls').find('.open').removeClass('open');
            $('#headerUserControls .box').hide();
        }
        return false;
    });
    $('#headerLoginBox .btnGreyPlain').click(function() {
        $(this).parent().submit();
        return false;
    });
    $('#headerUserControls .language').click(function() {
        obj = $(this);
        if (obj.hasClass('open')) {
            $('#headerLanguageBox').hide();
            obj.removeClass('open');
        } else {
            $('#headerUserControls').find('.open').removeClass('open');
            $('#headerUserControls .box').hide();
            $('#headerLanguageBox').show();
            obj.addClass('open');
        }
        return false;
    });
*/
});
var ranAddThis = false;
// AddThis
var AddThis = function(force) {
    if(!force && ranAddThis === true) return;
    ranAddThis = true;
    $('.addThis').each(function(counter) {
        var obj = $(this);
        var objUrl = "http://www.tele2.se"+obj.attr('href');
        if (!objUrl) {
            objUrl = "http://www.tele2.se"+obj.find('a.addThisUrl').attr('href');
            if (!objUrl) {
                objUrl = "http://www.tele2.se"+obj.find('a').attr('href');
            }
        }
        $('body').append('<div class="M120" id="addThisID' + counter + '" style="display:none;"><div class="M120top"></div><div class="M120content"><h2>Dela med dig</h2><div class="addthis_toolbox addthis_default_style" addthis:url="' + objUrl + '" addthis:title="' + objUrl + '"><div class="M120left"><a class="addthis_button_facebook facebookimg">Facebook</a><a class="addthis_button_twitter twitterimg">Twitter</a><a class="addthis_button_email emailimg">Email</a></div><div class="M120right"><a class="addthis_button_delicious deliciousimg">Delicious</a><a class="addthis_button_myspace googleimg">MySpace</a><a class="moreimg addthis_button_expanded moreAddThisImg">Fler...</a></div><div class="clear"></div></div><a class="close"><img src="/system_images/0-btn-close.png" alt="Stäng" text="Stäng" /></a></div><div class="M120bottom"></div>');
        var X = 0,Y = 0;
        var pos = function(){
            X = obj.offset().left;
            Y = obj.offset().top;
            $('#addThisID' + counter).css({
                'left': X - 108 + (obj.width() / 2),
                'top': Y - $('#addThisID' + counter).height() + 5
            });
        };
        obj.click(function() {
             pos();
            if (obj.hasClass("active")) {
                if ($.browser.msie) {
                    obj.removeClass("active");
                    $('#addThisID' + counter).hide();
                } else {
                    obj.removeClass("active");
                    $('#addThisID' + counter).fadeOut();
                }
                $(window).unbind('resize',pos);
            }
            else {
                $(window).bind('resize',pos);
                if ($.browser.msie) {
                    $('.addThis').removeClass('active');
                    $('.M120').hide();
                    obj.addClass("active");
                    $('#addThisID' + counter).show();
                } else {
                    $('.addThis').removeClass('active');
                    $('.M120').fadeOut();
                    obj.addClass("active");
                    $('#addThisID' + counter).fadeIn();
                }
            }
            return false;
        });
        $('#addThisID' + counter).find('.close').click(function() {
            obj.trigger('click');
        });
    }).before('<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4b4c8aad6a977627"></script>');
};
var pdfLinks = function() {
    $("a[href$='.pdf']").attr("target", "_blank");
};
//general function for setting up button onclick event to open up shop flow with preconfigured offering, phone, etc
/*
function bindBuyOfferingButton(buttonId, ContractOfferingId, PhoneId, PhoneColor, BindingTimeDuration, Installment);
parameters: 
            - buttonId(String): Id of an HTML-element.   
            - ContractOfferingId (String): offeringId.
            - PhoneId(String): articleId.
            - PhoneColor(String): variant color
            - BindingTimeDuration(String) : month duration ex. 12 månader -> "12"
            - Installment(String) : förhöjd månadsavgift ex. 120 kr -> "12000"            
side-effects: shop flow opens on click of HTML-element with buttonId as id, shop flow is preconfigured with the given inputs (contract).
*/
function bindBuyOfferingButton(buttonId, ContractOfferingId, PhoneId, PhoneColor, BindingTimeDuration, Installment)
{    
    $('#'+buttonId).unbind('click'); //unbind click functionality
    $('#'+buttonId).click(function(){ //function that opens up shop flow lightbox
        // LOADING SPINNER
        $.fn.initLB('load', {
            URL: '',
            openTrigger: 'none',
            'closeOnClickOutside': false
        });
        // Get selected phone data
        var selectedContractOfferingId = ContractOfferingId;
        var selectedPhoneId = PhoneId;
        var selectedColor = PhoneColor;
        var selectedBindingTimeDuration = BindingTimeDuration;
        var selectedInstallment = Installment;
        
        $.getJSON('/foretag/ajax/phone.html', {
             offeringId: selectedContractOfferingId,
             chosenPhone: selectedPhoneId,
             chosenColor: selectedColor,
             chosenBindingTimeDuration: selectedBindingTimeDuration,
             chosenInstallment: selectedInstallment,
             rootEntity: 'ARTICLE'
        }, function(data) {
             if(data.status == 'OK') {
                 $.fn.initLB('LBshopFlow', {
                     URL: '/foretag/lightbox_selection_configure.html?hideBackButton=true',
                     closeElement: '.close',
                     openTrigger: 'none',
                     'closeOnClickOutside': false
                 },
                 {
                    'onBeforeLoad': function(){
                        // CLOSE LOADING SPINNER
                        LB.close('load');                                        
                    }
                    ,
                     'onLoad': function() {
                        var lb = $('#LightBoxFlow');
                        $('.select', lb).selectBox();
                        $(".stangBtn").html(htmlDecode($(".close").html()));
                        initCufon();
                        initButtons();
                        $('.scrollable', lb).scrollable({
                            size: 4,
                            clickable: false,
                            easing: 'easeOutCirc',
                            speed: 700,
                            keyboard: false
                        });
                        $('.lightBoxItemList', lb).scrollable({
                            size: 2,
                            clickable: false,
                            easing: 'easeOutCirc',
                            speed: 700,
                            keyboard: false
                        });
                        $('.scrollList', lb).jScrollPane({
                            'showArrows': true,
                            'scrollbarWidth': 20,
                            'scrollbarMargin': 0,
                            'arrowSize': 7,
                            'dragMaxHeight': 100,
                            'dragMinHeight': 100
                        });
                        //New number
                        $('#nyttnr').initLB('trycknytt', {
                            'URL': '/foretag/lightbox_new_number.html',
                            'closeElement': '.close',
                            'backLayer': false
                        }, {
                            'onLoad': function() {
                                initButtons();
                                initCufon();
                                $('.select', '#loadInToMetrycknytt').selectBox();
                            }
                        });
                        //Move number
                        $('#flyttnr').initLB('tryckflytta', {
                            'URL': '/foretag/lightbox_move_to_tele2.html',
                            'closeElement': '.close',
                            'backLayer': false
                        }, {
                            'onLoad': function() {
                                initButtons();
                                initCufon();
                            }
                        });
                        // Keep number
                        $('#befintnr').initLB('tryckbehall', {
                            'URL': '/foretag/lightbox_prolong_number.html',
                            'closeElement': '.close',
                            'backLayer': false
                        }, {
                            'onLoad': function() {
                                initButtons();
                                initCufon();
                            }
                        });
                    } // Ends onLoad callback
                    
                }); // End initLB
             } // End if data status ok
             else {
                 showError('TECHNICAL_ERROR');
             }
        }); // End getJSON
        return false;
    });
}
/* --- GENERAL --- */
/* +++ MODULES +++ */
var M102 = function() {
    var cufonSelector = '.M102 .center span';
    Cufon.replace(cufonSelector, { fontFamily: 'boton' });
    $('.M102').each(function() {
        var $this = $(this);
        var $bottom = $('.M102-bottom', $this);
        var animationSpeed = { up: 100, down: 200 };
        var isAnimating = false;
        $('.M102-content > div', $this).hide();
        $bottom.hide();
        $('.M102-top a', $this).click(function() {
            var $thisC = $(this);
            var $correspondingContent = $($thisC.attr('href'), $this);
            var allContentDivs = $correspondingContent.parent().parent().find('.M102-content > div');
            var i = 1;
            if (!$bottom.is(':visible')) {
                if ($.browser.msie && parseInt($.browser.version) < 8)
                    $bottom.show();
                else
                    $bottom.slideDown(animationSpeed.down);
            }
            if (!$correspondingContent.is(':visible') & !isAnimating) {
                // Close all tabs and then open the corresponding tab
                $thisC.parent().find('a').removeClass('active');
                $thisC.addClass('active');
                Cufon.refresh(cufonSelector);
                isAnimating = true;
                allContentDivs.slideUp(animationSpeed.up, function() {
                    if (i == allContentDivs.length) {
                        $correspondingContent.slideDown(animationSpeed.down, function() {
                            isAnimating = false;
                        });
                    }
                    i++;
                });
            } else if (!isAnimating) {
                // Close all tabs
                $thisC.parent().find('a').removeClass('active');
                Cufon.refresh(cufonSelector);
                isAnimating = true;
                allContentDivs.slideUp(animationSpeed.up, function() {
                    if (i == allContentDivs.length) {
                        if ($.browser.msie && parseInt($.browser.version) < 8) {
                            $bottom.hide();
                            isAnimating = false;
                        } else {
                            $bottom.slideUp(animationSpeed.up, function() {
                                isAnimating = false;
                            });
                        }
                    }
                    i++;
                });
            }
            return false;
        });
    });
};
//M102 end
var M103 = function() {
    $('.M103').each(function() {
        var $this = $(this);
        $('.scrollable', $this).scrollable({
            size: 4,
            clickable: false,
            easing: 'easeOutCirc',
            speed: 700,
            keyboard: false
        });
        $('.nextPage, .prevPage', $this).click(function() {
            return false;
        });
        $('.thumbs a', $this).click(function() {
            var obj = $(this);
            if (!obj.hasClass('active')) {
                var activeObj = obj.parent().find('.active');
                var imageSource = obj.attr('href');
                var preview = obj.parent().prev();
                activeObj.removeClass('active');
                preview.fadeOut(200, function() {
                    preview.attr('src', imageSource);
                    preview.fadeIn(100);
                });
                obj.addClass('active');
            }
            return false;
        });
        $('span.bindingTime div div ul.sb-list li[class^="sb-li"]', $this).click(function() {
            var articleId = $(this).closest('div.column').find('.bindingTime select').attr('rel');
            var bindingTime = $(this).attr('thevalue');
            $(this).closest('div.column').find('span.increasedMonthlyFee div div ul.sb-list').filterInstallments(articleId, bindingTime);

            var installment = $(this).closest('div.column').find("span.increasedMonthlyFee select.select option[title='"+$(this).closest('div.column').find('span.increasedMonthlyFee span.sb-disp').text()+"']").val();

            $(this).closest('div.column').find('span.increasedMonthlyFee div div ul.sb-list').setPhonePrice(bindingTime, installment);
        });
        $('span.increasedMonthlyFee div div ul.sb-list li[class^="sb-li"]', $this).click(function() {
            var installment = $(this).attr('thevalue');
            var bindingTime = parseInt($(this).closest('div.column').find('span.bindingTime span.sb-disp').text());
            $(this).closest('div.column').find('span.increasedMonthlyFee div div ul.sb-list').setPhonePrice(bindingTime, installment);
        });
        $('.btnBlackBig a', $this).click(function() {
            $('#phoneRemove').click();
        });
        //$('.info', $this).initLB('hardwareLightbox', {
        //    closeElement: '.close'
        //});
        $('.info', $this).click(function() {
            $(this).showPhoneInfo();
            return false;
        });
    });
    
    var $trigger = $('#LBnoElementsTrigger'); 
    if ($trigger.length < 1)
        $trigger = $('<div id="LBnoElementsTrigger" />').appendTo('body'); 
    $trigger.lb({
        name: 'hardwareLightbox'
    });

    $.fn.showPhoneInfo = function () {
        var $t = $(this);
        var infooffering = $t.closest('.column').data('contracts');
        var currentbindingtime = $t.parent().find("span.bindingTime select.select option[title='"+$t.parent().find('span.bindingTime div div span.sb-disp').text()+"']").val();
        var currentinstallment = $t.parent().find("span.increasedMonthlyFee select.select option[title='"+$t.parent().find('span.increasedMonthlyFee div div span.sb-disp').text()+"']").val();
        var articleIdMatch = $t.attr('href').match(/[\d]+$/);
        var articleId = articleIdMatch[0];
        if(articleId == null || articleId == '')
            articleId = $t.attr('href');
        var offeringIds = infooffering[currentbindingtime]['offeringIds'];
        var offeringId = offeringIds[currentinstallment];
        var newHref = '/foretag/lightbox_article_info.html?offeringId=' + offeringId + '&articleId=' + articleId;

        //LB.load('hardwareLightbox', newHref);
        //LB.open('hardwareLightbox');

        $.fn.initLB('detailsLB', {
            'URL': newHref,
            'openTrigger': 'none',
            'closeElement': '.close'
            }, {'onLoad':function(){
                $('#centerBoxdetailsLB').css('z-index','1008');
            }}
        ); 

    };
    $.fn.setPhonePrice = function(bindingTimeParam, installment) {
        var $t = $(this);
        var closestColumn = $t.closest('.column');
        var btimearticle = $t.closest('.column').data('contracts');
        for(var o in btimearticle[bindingTimeParam]['prices']) {
            if(o != null) {
                if(o == installment) {
                    var seekval = btimearticle[bindingTimeParam]['prices'][o];
                    closestColumn.find('.price').text(seekval);
                    Cufon.refresh();
                    break;
                }
            }
        }
    };
    $.fn.filterInstallments = function(articleIdParam, bindingTimeParam) {
        $(this).find('li').hide();
        var btimearticle = $(this).parentsUntil('div.column').parent().data('contracts');
        for(var o in btimearticle[bindingTimeParam]['installments']) {
            if(o != null) {
                var seekval = btimearticle[bindingTimeParam]['installments'][o];
                $(this).find('li[thevalue='+seekval+']').show();
            }
        }
        $(this).parent().parent().find('span.sb-disp').text($(this).find('li:first').text());
    };
};
//M103 end
var M104 = function() {
    /*
    $('#startCart, #headerCart a').initLB('MiniCart', {
        'URL': '/foretag/2176.html',
        'closeElement': '#miniCartLB .close',
        'closeOnClickOutside': false
    }, {
        'onLoad': function() {
            var context = $('#miniCartLB')[0];
            initButtons(context);
            initCufon(context);
            $('.select', context).change(function() {
                var val = $(this).val();
                LB.load('MiniCart', '/foretag/2176.html?package=' + val);
            }).selectBox();
            $('.lightBoxItemList', context).scrollable({
                size: 2,
                clickable: false,
                easing: 'easeOutCirc',
                speed: 700,
                keyboard: false
            });
            $('.scrollList', context).jScrollPane({
                'showArrows': true,
                'scrollbarWidth': 20,
                'scrollbarMargin': 0,
                'arrowSize': 7,
                'dragMaxHeight': 100,
                'dragMinHeight': 100
            });
            $('.nextPage, .prevPage', context).click(function() {
                return false;
            });
        }
    });
    */
};
//M104 end
var M108 = function() {
    var topSort = $('#topSort'); //context
    var inputs = $('.sortPart li label input', topSort);
    var str = '';
    var countSpan = $('#amountPhones');
    var counter = 0;
    var selectionHasChanged = false;
    var ajaxRequest = null;
    var showingSpinner = false;
    var timer = null;

    
    countSpan.html(counter);
    // phone update end
    var getPhones = function(append, para) {

        if (!selectionHasChanged)
            return;
        else {
            selectionHasChanged = false;
        }

        if(ajaxRequest)
            ajaxRequest.abort();



        str = '';

        inputs.each(function() {
            var $this = $(this);
            if ($this[0].checked == 1) {
                str += $this.attr('name').trim() + '=' + $this.val().trim() + '&';
            }
        });

        ajaxRequest = $.ajax({
                'url': '/foretag/ajax/sortPhone.html',
                'type': 'get',
                'data': str,
                'cache': false,
                'dataType': 'json',
                'error': function() { 
                    $("#loadingSpinner").hide(); 
                    LB.close('loadPhones'); 
                },
                'success': function(data) {
                    LB.close('loadPhones');
                    $("#loadingSpinner").hide();
                    showingSpinner = false;
                    if(data.status == 'ERROR' && data.errorCode != 'NO_MATCH')
                    {
                         $('body').initLB('LBError', {
                                           closeElement: '.close',
                                           openTrigger: 'none'
                                         }, { onLoad: function(){
                                                      initButtons();
                                                      initCufon();
                                         }
                          });
                          LB.load('LBError', '?title='+escape('Teknisk fel')+'&description='+escape('Ett okänt fel uppstog, kontakta admin.'));
                          LB.open('LBError');
                    }
                    else
                    {
                        var jsonLen = data.results.length;
                        var appendStr = '';
                        for (var i = 0; i < jsonLen; i++) { // removed criteria i < 12 because we don't use paging
                            appendStr += '<div class="phonePart">';
                            appendStr += '<h3>' + data.results[i].title + '</h3>';
 
                            var uspsLen = data.results[i].usps.length;
                            
                            for (var k = 0; k < uspsLen; k++) {
                                data.results[i].usps[k] = data.results[i].usps[k].replace('<ul>','<ul class=list>');
                                appendStr += data.results[i].usps[k];
                            
                            }
                            if(data.results[i].image != "/produktbilder/")
                            {
                                appendStr += '<img src="' + data.results[i].image + '" class="preview" alt="' + data.results[i].title + '" />';
                            }


                            appendStr += '<span class="thumbs">';
                            var colorsLen = data.results[i].colors.length;
                            for (var k = 0; k < colorsLen; k++) {
                                appendStr += '<a>'; 
                                appendStr += '<img src="' + data.results[i].colors[k].color +'" /></a>';
                            }
                            appendStr += '</span>';

                            appendStr += '<hr /><h4>Från</h4>';
                            appendStr += '<h2>' + data.results[i].from + '</h2>';
                            appendStr += '<a href="' + data.results[i].readmore + '" class="BTNbtnGreyPlain">Läs mer</a>';
                            appendStr += '</div>';
                        }
                        if (append === true) {
                            counter += jsonLen;
                            $('#catchPhoneParts').append(appendStr);
                                countSpan.html('<h3 style="display:inline;">'+counter+'</h3>');
                        } else {
                                counter = jsonLen;
                                $('#catchPhoneParts').html(appendStr);
                                countSpan.html('<h3 style="display:inline;">'+jsonLen+'</h3>');
                        }
                        initCufon($('#catchPhoneParts'));
                        initCufon($('#amountPhones'));
                        initButtons($('#catchPhoneParts'));
                    }
                }
            });
        //} // end of if
    };

/*
    $('.thumbs a', '#catchPhoneParts').live('click', function() {
        var obj = $(this);
        if (!obj.hasClass('active')) {
            var activeObj = obj.parent().find('.active');
            var imageSource = obj.attr('href');
            var preview = obj.parent().prev();
            activeObj.removeClass('active');
            preview.fadeOut(200, function() {
                preview.attr('src', imageSource);
                preview.fadeIn(100);
            });
            obj.addClass('active');
        }
        return false;
    });

*/
    
    timer = setInterval(getPhones, 300);

    inputs.bind('click', function() {
        selectionHasChanged = true;
        if(!showingSpinner)
        {
            $.fn.initLB('loadPhones', {
                URL: '',
                openTrigger: 'none',
                'closeOnClickOutside': false
            //backLayer: null
            });
            showingSpinner= true;
        }

    });

    
    $(".sortPart li label input:not(:checked)",topSort).click();

    selectionHasChanged = true;

    if(!showingSpinner)
        {
            $.fn.initLB('loadPhones', {
                URL: '',
                openTrigger: 'none',
                'closeOnClickOutside': false
            //backLayer: null
            });
            showingSpinner= true;
    }

    getPhones();

    
};
//M108 end
var M109_113 = function() {
    Cufon.replace('.thumbs p, .badge p', { fontFamily: 'boton' });
    $('.M109-113').each(function() {

        var obj = $(this);

        $('.info', obj).not('.not-lightbox').click(function() {
            $(this).initLB('heroLightbox', {
                closeElement: '.close',
                openTrigger: null
            });
            LB.load('heroLightbox', $(this).attr('href'));
            LB.open('heroLightbox');
            return false;
        });
        $('.color a', obj).click(function() {
            var $this = $(this);
            if (!$this.hasClass('active')) {
                var activeObj = $this.parent().find('.active');
                var imageSource = $this.attr('href');
                var preview = $this.parent().prev();
                activeObj.removeClass('active');
                preview.fadeOut(200, function() {
                    preview.attr('src', imageSource);
                    preview.fadeIn(100);
                });
                $this.addClass('active');
            }
            return false;
        });

        var collectGETprocessJSON = function($context, URL, success) {
            var GET = {}, i = 0; // i++ makes all POST variables unique
            $('select', $context).each(function() {
                GET[i++ + $(this).attr('name')] = $(this).val();
            });
            $('.thumbs a', $context).each(function() {
                if ($(this).hasClass('active'))
                    GET[i++ + 'color'] = $(this).find('img').attr('src');
            });
            $.ajax({
                'url': URL,
                'type': 'get',
                'data': GET,
                'cache': false,
                'dataType': 'json',
                'success': success
            });
        }; //end collect

    });
};
//M109_113 definition end
var getSelectedOptionFromSelectBox = function(selectBoxId, generatedSelectBoxId) {
    var selectedItem = $('#'+generatedSelectBoxId);
    var selectedName = selectedItem.text().trim();

    var expr = '#' + selectBoxId + " option[title='" + selectedName  + "']" + '';
    var selectedValue = $(expr).val();

    return {
        name: selectedName, 
        value: selectedValue
    };        
};

var M109 = function() {
   
    M109_113();
    
    window.LBGeneric = function(clickedElement, lightBoxUrl){
        $(clickedElement).click(function() {
            var theTrigger = $(this);
            var lightboxId = theTrigger.attr('id') + 'LB';
            
            $('body').initLB(lightboxId, {
                    closeElement: '.close',
                    openTrigger: 'none'
                }, { onLoad: function(){
                   $(window).resize(function() {
                       if(parseFloat($('#centerBox' + lightboxId).css('top'),10) < 0) 
                       {
                           $('#centerBox' + lightboxId).css('top', '0');
                           $('#centerBox' + lightboxId).css('position', 'absolute');
                       }
                       else {
                           $('#centerBox' + lightboxId).css('position', 'fixed'); 
                       } 
                   });    
                   if(parseFloat($('#centerBox' + lightboxId).css('top'),10) < 0) {
                       $('#centerBox' + lightboxId).css('top', '0');
                       $('#centerBox' + lightboxId).css('position', 'absolute');
                   }
                }
            });
            LB.load(lightboxId, lightBoxUrl);
            LB.open(lightboxId);
        });
    };

    /*
    $('div.subscription ul li.sb-li1').click(function() {
        var selectedContractOffering = $(this).text().trim();
        $.fn.filterBindingTimeAndInstallment(selectedContractOffering);
    });
    */

    $('div.subscription ul li.sb-li1').click(function() {
            var selectedContractOffering = $(this).text().trim();
            $.fn.filterBindingTimeAndInstallment(selectedContractOffering);
    
            if(typeof(contract)!="undefined")
            {
                var lightboxUrl = '/foretag/lightbox_article_info.html';
                
                var selectedOfferingName = selectedContractOffering; 
                
                var selectedBT = $('#sb-dispSelctboxnr2').text();
                var selectedBTVal = $("#selectedBindingTime option[title='"+selectedBT +"']").val();
    
                var selectedInst = $('#sb-dispSelctboxnr3').text();
                var selectedInstVal = $("#selectedInstallment option[title='"+selectedInst+"']").val();
                
                var selectedOfferingId = contract[selectedOfferingName][selectedBTVal]['offeringIds'][selectedInstVal];
                var selectedArticleId = contract[selectedOfferingName][selectedBTVal]['contractarticleid'][selectedInstVal];
                
                var infoButton = $('.configContent .info');
                infoButton.attr('href', lightboxUrl + '?articleId=' + selectedArticleId  + '&offeringId=' + selectedOfferingId);
            }
    });

    if(typeof(contract)!="undefined")
    { // inits subscription info button
            var lightboxUrl = '/foretag/lightbox_article_info.html';
                
            var selectedOfferingName = $('#sb-dispSelctboxnr1').text().trim();
                
            var selectedBT = $('#sb-dispSelctboxnr2').text();
            var selectedBTVal = $("#selectedBindingTime option[title='"+selectedBT +"']").val();
    
            var selectedInst = $('#sb-dispSelctboxnr3').text();
            var selectedInstVal = $("#selectedInstallment option[title='"+selectedInst+"']").val();
                
            var selectedOfferingId = contract[selectedOfferingName][selectedBTVal]['offeringIds'][selectedInstVal];
            var selectedArticleId = contract[selectedOfferingName][selectedBTVal]['contractarticleid'][selectedInstVal];
                
            var infoButton = $('.configContent .info');
            infoButton.attr('href', lightboxUrl + '?articleId=' + selectedArticleId  + '&offeringId=' + selectedOfferingId);
    }
    

    $('div.column1 ul.selectSmall-list li').click(function() {
        $(this).filterInstallments();
    });

    $('div.column2 ul.selectSmall-list li').click(function() {
        $.fn.updatePrices();
    });

    $('div.color a').click($.fn.setVariantColorImage);

    $('#btnSkickaBig').click(function() {
        $('#hero_module_form').submit();
    });

    $('#start-config-phone').click(function(){
        // LOADING SPINNER
        $.fn.initLB('load', {
            URL: '',
            openTrigger: 'none',
            'closeOnClickOutside': false
        });

        // Get selected phone data
        var selectedContractOfferingId = getSelectedOptionFromSelectBox('selectedSubscription', 'sb-dispSelctboxnr1').value;
        var selectedPhoneId = $(this).attr('rel');
        var selectedColor = $("#color a.active").attr('rel');
        var selectedBindingTimeDuration = getSelectedOptionFromSelectBox('selectedBindingTime', 'sb-dispSelctboxnr2').value;
        var selectedInstallment = getSelectedOptionFromSelectBox('selectedInstallment', 'sb-dispSelctboxnr3').value;
        $.getJSON('/foretag/ajax/phone.html', {
             offeringId: selectedContractOfferingId,
             chosenPhone: selectedPhoneId,
             chosenColor: selectedColor,
             chosenBindingTimeDuration: selectedBindingTimeDuration,
             chosenInstallment: selectedInstallment,
             rootEntity: 'ARTICLE'
        }, function(data) {
             if(data.status == 'OK') {
                 $.fn.initLB('LBshopFlow', {
                     URL: '/foretag/lightbox_selection_configure.html?hideBackButton=true',
                     closeElement: '.close',
                     openTrigger: 'none',
                     'closeOnClickOutside': false
                 },
                 {
                    'onBeforeLoad': function(){
                        // CLOSE LOADING SPINNER
                        LB.close('load');                                        
                    }
                    ,
                     'onLoad': function() {
                        var lb = $('#LightBoxFlow');
                        $('.select', lb).selectBox();
                        $(".stangBtn").html(htmlDecode($(".close").html()));
                        initCufon();
                        initButtons();
                        $('.scrollable', lb).scrollable({
                            size: 4,
                            clickable: false,
                            easing: 'easeOutCirc',
                            speed: 700,
                            keyboard: false
                        });
                        $('.lightBoxItemList', lb).scrollable({
                            size: 2,
                            clickable: false,
                            easing: 'easeOutCirc',
                            speed: 700,
                            keyboard: false
                        });
                        $('.scrollList', lb).jScrollPane({
                            'showArrows': true,
                            'scrollbarWidth': 20,
                            'scrollbarMargin': 0,
                            'arrowSize': 7,
                            'dragMaxHeight': 100,
                            'dragMinHeight': 100
                        });
                        //New number
                        $('#nyttnr').initLB('trycknytt', {
                            'URL': '/foretag/lightbox_new_number.html',
                            'closeElement': '.close',
                            'backLayer': false
                        }, {
                            'onLoad': function() {
                                initButtons();
                                initCufon();
                                $('.select', '#loadInToMetrycknytt').selectBox();
                            }
                        });
                        //Move number
                        $('#flyttnr').initLB('tryckflytta', {
                            'URL': '/foretag/lightbox_move_to_tele2.html',
                            'closeElement': '.close',
                            'backLayer': false
                        }, {
                            'onLoad': function() {
                                initButtons();
                                initCufon();
                            }
                        });
                        // Keep number
                        $('#befintnr').initLB('tryckbehall', {
                            'URL': '/foretag/lightbox_prolong_number.html',
                            'closeElement': '.close',
                            'backLayer': false
                        }, {
                            'onLoad': function() {
                                initButtons();
                                initCufon();
                            }
                        });
                    } // Ends onLoad callback
                    
                }); // End initLB
             } // End if data status ok
             else {
                 showError('TECHNICAL_ERROR');
             }
        }); // End getJSON
        return false;
    }); // End click
};
//M109 end
/* THIS IS M110 */
var M110 = function() {

    M109_113();

    var bundleCall = function(context) {
        $('.select', context).selectBox();
        initCufon(context);
        initButtons(context);
        M103();
        $('.lightBoxItemList', context).scrollable({
            size: 2,
            clickable: false,
            easing: 'easeOutCirc',
            speed: 700,
            keyboard: false
        });
        $('.scrollList', context).jScrollPane({
            'showArrows': true,
            'scrollbarWidth': 20,
            'scrollbarMargin': 0,
            'arrowSize': 7,
            'dragMaxHeight': 100,
            'dragMinHeight': 100
        });
        $('.nextPage, .prevPage', context).click(function() {
            return false;
        });
    };

    // Start the config flow with a subscription



    var start_config_subscription = function()
    {    
            
        $('#start-config-subscription').unbind('click');
        $('#start-config-subscription').initLB('LBshopFlow', {
            // Changed 2010-01-04 to pass the bundle id
            'URL': '/foretag/lightbox_selection_phone.html?id=' + $('#start-config-subscription').attr('rel') + '&isFirstStep=true',       
            'closeElement': '.lightBoxBackgroundImage .close',
            'closeTrigger': 'click',
            'closeOnClickOutside': false
        }, {
            'onLoad': function() {
                 var lb = $('#LightBoxFlow')[0];
bundleCall(lb);
// Add buttons
var changeButtons = function(context, toGreen) {
    $(toGreen ? '.btnGreyPlain' : '.btnGreenPlain', context)
    .removeClass(toGreen ? 'btnGreyPlain' : 'btnGreenPlain')
    .addClass(toGreen ? 'btnGreenPlain' : 'btnGreyPlain');
    if (!toGreen) {
        $(context).find('.btnGreyPlain a').each(function() {
            Cufon.replace(this, {
                color: '#aaa',
                fontFamily: 'boton',
                textShadow: '1px 1px #fff'
            });
        });
        $('.M103 .btnGreyPlain a', lb).unbind(); // disable all event handlers
        $('.M103 .btnGreyPlain a', lb).click(function() {return false;}); // register "empty" click event handler
    } else {
        $(context).find('.btnGreenPlain a').each(function() {
            Cufon.replace(this, {
                fontFamily: 'boton',
                textShadow: '1px 1px #05540a'
            });
        });
        $('.M103 .btnGreenPlain a', lb).unbind(); // disable all event handlers
        $('.M103 .btnGreenPlain a', lb).click(btnAddClick); // register default click event handler
    }
};
var clickAdd = function($this, doAdd) {
    var id = $this.attr('href');
    id = id.split("/");
    id = id[(id.length)-1];
    var offeringid = $this.attr('rel');
    var color = $this.parent().parent().find('span.thumbs').find('a.active').attr('rel');
    var bindingtime = parseInt($this.parent().parent().find('span.bindingTime').find('span.sb-disp').text());
    //var installment = parseInt($this.parent().parent().find('span.increasedMonthlyFee').find('span.sb-disp').text());
    var installment = $this.parent().parent().find("span.increasedMonthlyFee select.select option[title='"+$this.parent().parent().find('span.increasedMonthlyFee span.sb-disp').text()+"']").attr('value');
    if (id.trim() != '' && id.trim() != '#') {
        if (doAdd) {
            changeButtons($('.M103'), !doAdd);
            $.ajax({
                type: "POST",
                url: "/foretag/ajax/phone.html",
                dataType: "json",               
                data: {
                    offeringId: offeringid, 
                    chosenPhone:  id,
                    chosenColor: color,
                    chosenBindingTimeDuration: bindingtime,
                    chosenInstallment: installment
                },
                success: function(data) {
                    if(data.status !== 'ERROR') {
                        $('.btnBlackBig a').bind("click", phoneRemoveNext);
                        $('.btnBlackBig').show();
                        $("#nextStep").bind("click", nextLightBoxEvent);
                        $(".scrollable .btnGreenPlainBig").show();
                        $('#jsonTotalPrice').html(data.totalPrice);
                        $('#jsonMonthlyPrice').html(data.monthlyPrice);
                        $('#jsonPhoneInfo').html(data.phoneInfo);
                        $('#scenePhone').attr('src', data.phoneImageURL);
                        $('#scenePhone').css('visibility', 'visible');
                        $('#phoneRemove').css('visibility', 'visible');
                        $('#monthlyFeeText').html(',&nbsp;'+data.monthlyFee);
                        var months = $this.parent().parent().find(".bindingTime .sb-disp").html();
                        var increasedMonthlyFee = $this.parent().parent().find(".increasedMonthlyFee .sb-disp").html();
                        if($("#bindingTimeDurationText").size() == 1)
                        {
                            $("#bindingTimeDurationText").html(",&nbsp;" + months);
                        }
                        else
                        {
                            $('<strong id="bindingTimeDurationText"></strong>').insertAfter($('#jsonSubscriptionInfo p strong').eq(0));
                            $("#bindingTimeDurationText").html(",&nbsp;" + months);
                        }
                        if(increasedMonthlyFee != "0 kr" && months != "0 mån")
                        {
                            
                            $("#installmentFeeText").html(",&nbsp;" + increasedMonthlyFee + " förhöjd månadsavgift");
                        }
                    }
                    else {
                        showError('TECHNICAL_ERROR');
                        changeButtons($('.M103'), true);
                        $("#nextStep").bind("click", nextLightBoxEvent);
                        $(".scrollable .btnGreenPlainBig").show();
                        $('.btnBlackBig a').bind("click", phoneRemoveNext);
                        $('.btnBlackBig').show();    

                        $('.increasedMonthlyFee, .bindingTime').each(function(){  
                                $(this)[0].style.display = "";
                            }
                        );

                    }
                },
                error:function(xhr, status, errorThrown) {
                    // TODO: remove in prod
                    alert(errorThrown+'\n'+status+'\n'+xhr.statusText);
                    $("#nextStep").bind("click", nextLightBoxEvent);
                    $(".scrollable .btnGreenPlainBig").show();
                    $('.btnBlackBig a').bind("click", phoneRemoveNext);
                    $('.btnBlackBig').show();

                    $('.increasedMonthlyFee, .bindingTime').each(function(){  
                            $(this)[0].style.display = "";
                        }
                    );


                }
            });            
        }
        else {
            $.ajax({
                dataType: 'json',
                url:'/foretag/ajax/phone.html',
                data: {
                    offeringId: offeringid,
                    removedPhone: id
                },
                success: function(data) {
                    $('#jsonTotalPrice').html(data.totalPrice);
                    $('#monthlyFeeText').html(', '+data.monthlyPrice);
                    $('#jsonMonthlyPrice').html(data.monthlyPrice);
                    $("#bindingTimeDurationText").html(",&nbsp;" + data.bindingTimeDuration);
                    $('#jsonPhoneInfo').html(data.phoneInfo);
                    $('#scenePhone').css('visibility', 'hidden');
                    $('#phoneRemove').css('visibility', 'hidden');
                    $("#installmentFeeText").html("");
                    $("#nextStep").bind("click", nextLightBoxEvent);
                    $(".scrollable .btnGreenPlainBig").show();
                    $('.btnBlackBig a').bind("click", phoneRemoveNext);
                    $('.btnBlackBig').show();
                    changeButtons($('.M103'), !doAdd);

                    $('.increasedMonthlyFee, .bindingTime').each(function(){  
                            $(this)[0].style.display = "";
                        }
                    );

                },
                error:function(){
                    $("#nextStep").bind("click", nextLightBoxEvent);
                    $(".scrollable .btnGreenPlainBig").show();
                    $('.btnBlackBig a').bind("click", phoneRemoveNext);
                    $('.btnBlackBig').show();
                    changeButtons($('.M103'), !doAdd);
                }
            });
        }
    }
};
var btnAddClick = function() {
    var $this = $(this);
    if($("#nextStep").size() > 0)
    {
        $("#nextStep").unbind("click", nextLightBoxEvent);
        $(".scrollable .btnGreenPlainBig").hide();
        $('.btnBlackBig a').unbind("click", phoneRemoveNext);
        $('.btnBlackBig').hide();

        $('.increasedMonthlyFee, .bindingTime').each(function(){  
                $(this)[0].style.display = "none";
            }
        );

    }
    clickAdd($this, true);
    $this.unbind('click');
    $this.click(function() { return false; });
    $('body').data('selectedPhone', $this);
    return false;
};
$('.M103 .btnGreenPlain a', lb).click(btnAddClick);
var phoneRemoveNext = function() {
    if($("#nextStep").size() > 0)
    {
        $("#nextStep").unbind("click", nextLightBoxEvent);
        $(".scrollable .btnGreenPlainBig").hide();

        $('.btnBlackBig a').unbind("click", phoneRemoveNext);
        $('.btnBlackBig').hide();

    }
    clickAdd($('body').data('selectedPhone'), false);
    return false;
};
$('#phoneRemove').click(phoneRemoveNext);
if($('#phoneRemove').css('visibility') === 'visible') {
    changeButtons($('.M103'), false);    
}
            }
        });
    }

    start_config_subscription();

    if($('#start-config-subscription').size() > 0)
    {
        $.data($('#start-config-subscription')[0],'updateStartConfig', start_config_subscription);
    }

};
//M110 end
var M111 = function() {
    M109_113();
};
var M112 = function() {
    M109_113();
};
var M113 = function() {
    
    M109_113();


    $('#start-config-mobileinternet').click(function() {
        $.fn.initLB('LBshopFlow', {
            'URL': '?id=' + $('#start-config-mobileinternet').attr('rel') + '&isFirstStep=true',
            'closeElement': '.close',
            'closeOnClickOutside': false,
            'openTrigger': 'none'
        }
        ,
        { 
             'onLoad': function() {
                //#LightBoxFlow
                var lb = $('#loadInToMeLBshopFlow');
                $('.select', lb).selectBox();
                initCufon();
                initButtons();
                //$(".stangBtn").html(htmlDecode($(".close").html()));
                $('.scrollable', lb).scrollable({
                    size: 4,
                    clickable: false,
                    easing: 'easeOutCirc',
                    speed: 700,
                    keyboard: false
                });
                $('.lightBoxItemList', lb).scrollable({
                    size: 2,
                    clickable: false,
                    easing: 'easeOutCirc',
                    speed: 700,
                    keyboard: false
                });
                $('.scrollList', lb).jScrollPane({
                    'showArrows': true,
                    'scrollbarWidth': 20,
                    'scrollbarMargin': 0,
                    'arrowSize': 7,
                    'dragMaxHeight': 100,
                    'dragMinHeight': 100
                });
            } // Ends onLoad callback
        }); // End initLB

        return false;
    });


    

};
//M113 end
var M115 = function() {
    // Körs redan i Herosidornas load
    //M109_113();

    window.LBGeneric = function(clickedElement, lightBoxUrl){
        $(clickedElement).click(function() {
            var theTrigger = $(this);
            var lightboxId = theTrigger.attr('id') + 'LB';
            
            $('body').initLB(lightboxId, {
                    closeElement: '.close',
                    openTrigger: 'none'
                }, { onLoad: function(){
                   $(window).resize(function() {
                       if(parseFloat($('#centerBox' + lightboxId).css('top'),10) < 0) 
                       {
                           $('#centerBox' + lightboxId).css('top', '0');
                           $('#centerBox' + lightboxId).css('position', 'absolute');
                       }
                       else {
                           $('#centerBox' + lightboxId).css('position', 'fixed'); 
                       } 
                   });    
                   if(parseFloat($('#centerBox' + lightboxId).css('top'),10) < 0) {
                       $('#centerBox' + lightboxId).css('top', '0');
                       $('#centerBox' + lightboxId).css('position', 'absolute');
                   }
                }
            });
            LB.load(lightboxId, lightBoxUrl);
            LB.open(lightboxId);
        });
    };


    $('#displayRelatedProductImagesRoll').initLB('relatedProductImagesRoll', {
        'URL': '/foretag/con_module_lightbox_toolbar_related_product_images_roll.html?id=' + $('#displayRelatedProductImagesRoll').attr('rel'),
        'closeElement': '#M115LB2 .close',
        'backLayer': false
    }, {
        'onLoad': function() {
            $('.scrollable', '#M115LB2').scrollable({
                size: 6,
                clickable: false,
                easing: 'easeOutCirc',
                speed: 700,
                keyboard: false
            });
            
            $('.prevPage, .nextPage', '#M115LB2').click(function() { return false; });
            var moveImgContainer = $('#JScontentFeed2');
            var itemLinks = $('.items a', '#M115LB2');
            var insertMoveImg = function(that) {
                var href = that.attr('href');
                moveImgContainer.html('<img src="' + href + '" />');
            };
            itemLinks.click(function() {
                itemLinks.removeClass('selected');
                insertMoveImg($(this).addClass('selected'));
                return false;
            });
            itemLinks.filter(':first').addClass('selected');
            //itemLinks.filter(':first').click();        
        }
    });

    $('#displayVariantProductImagesRoll').initLB('variantProductImagesRoll', {
        'URL': '/foretag/con_module_lightbox_toolbar_variant_product_images_roll.html?id=' + $('#displayVariantProductImagesRoll').attr('rel'),
        'closeElement': '#M115LB .close',
        'backLayer': false
    }, {
        'onLoad': function() {
            $('.scrollable', '#M115LB').scrollable({
                size: 6,
                clickable: false,
                easing: 'easeOutCirc',
                speed: 700,
                keyboard: false
            });
            $('.prevPage, .nextPage', '#M115LB').click(function() { return false; });
            var moveImgContainer = $('#JScontentFeed');
            var itemLinks = $('.items a', '#M115LB');
            var insertMoveImg = function(that) {
                var href = that.attr('href');
                moveImgContainer.html('<img src="' + href + '" />');
            };
            itemLinks.click(function() {
                itemLinks.removeClass('selected');
                insertMoveImg($(this).addClass('selected'));
                return false;
            });
            itemLinks.filter(':first').addClass('selected');
            //itemLinks.filter(':first').click();
        }
    });


    $('#displayImageVideoRoll').initLB('imageVideoRoll', {
        'URL': '/foretag/lightbox_image_video_roll.html',
        'closeElement': '#M115LB .close',
        'backLayer': false
    }, {
        'onLoad': function() {
            $('.scrollable', '#M115LB').scrollable({
                size: 6,
                clickable: false,
                easing: 'easeOutCirc',
                speed: 700,
                keyboard: false
            });
            $('.prevPage, .nextPage', '#M115LB').click(function() { return false; });
            var moveImgContainer = $('#JScontentFeed');
            var $itemLinks = $('.items a', '#M115LB');
            var regstr = /^\s*(<object)\s*/;
            var youTubeReg = /^\s*(?:http:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v\=){1}([\w&]*)$/i;
            var youTubeTest = /^\s*(?:www\.|http:\/\/www\.|)youtube{1}/im;
            var insertMoveImg = function(that) {
                var href = that.attr('href');
                if (youTubeTest.test(href)) {
                    var link = href.match(youTubeReg);
                    moveImgContainer.html('<object width="630" height="375">' +
                    '<embed src="http://www.youtube.com/v/' + link[1] +
                    '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed>' +
                    '</object>');
                } else {
                    moveImgContainer.html('<img src="' + href + '" />');
                }
            };
            $itemLinks.click(function() {
                $itemLinks.removeClass('selected');
                insertMoveImg($(this).addClass('selected'));
                return false;
            });
            $itemLinks.filter(':first').click();
        }
    });
};
//M115 end
var M116 = function() {
    Cufon.replace('.M116 .separator a', { hover: true });
};
var M117 = function() {
    $('.M117').each(function() {
        var $this = $(this);
        $('.scrollable', $this).scrollable({
            size: 3,
            clickable: false,
            easing: 'easeOutCirc',
            speed: 700,
            keyboard: false
        });
        $('.nextPage, .prevPage', $this).click(function() {
            return false;
        });
        $('.thumbs a', $this).click(function() {
            var obj = $(this);
            if (!obj.hasClass('active')) {
                var activeObj = obj.parent().find('.active');
                var imageSource = obj.attr('href');
                var preview = obj.parent().prev();
                activeObj.removeClass('active');
                preview.fadeOut(200, function() {
                    preview.attr('src', imageSource);
                    preview.fadeIn(100);
                });
                obj.addClass('active');
            }
            return false;
        });
        $('.info', $this).initLB('hardwareLightbox', {
            closeElement: '.M103Lightbox .close'
        });
    });
};
var M119 = function() {
    var htmlStr = '<div id="tool119" class="tool119"><div class="tool119top"></div><div class="tool119mid"><div class="wrapIndent"><div id="imageContainer"><img id="tool119Img" src="" />' +
                     '</div><p id="toolContentText"></p><p id="toolContentPrice"></p></div></div><div class="tool119bottom"></div></div>',
                     toolInn = false, tipContainer, imageContainer, toolContentText, toolContentPrice, ypos2 = 0, xpos, closeTimer, isIE, theImage;
    isIE = $.browser.msie;
    var tipIn = function(that) {
        if (toolInn === false) {
            $('body').append(htmlStr);
            tipContainer = $('#tool119');
            tipContainer.css({ 'left': '-9999em', 'top': '-9999em' });
            imageContainer = $('#imageContainer');
            toolContentText = $('#toolContentText');
            toolContentPrice = $('#toolContentPrice');
            theImage = $('#tool119Img');
            toolInn = true;
            tipContainer.mouseover(function(e) {
                ypos2 = e.pageY;
                positionTip($('#jsTipIt li a'), -10, -136);
            });
            $('#jsTipIt li a').mousemove(function(e) {
                ypos2 = e.pageY;
                positionTip($('#jsTipIt li a'), -10, -136);
            });
        }
        positionTip(that, -10, -136);
        imageContainer.css('background-image', '');
        if (isIE == true) {
            tipContainer.show();
        } else {
            tipContainer.show().css('opacity', 1);
        }
        getInfo(that);
    };
    var positionTip = function(that, x, y) {
        var pos = that.offset(),
            thatHalf = (that.width() / 2);
        var ypos = (ypos2 + y);
        xpos = (pos.left + x);
        tipContainer.css({ 'left': xpos, 'top': ypos });
    };
    var getInfo = function(that) {
        var link = that.attr('rel'),
            shortFix,
            bredText = that.attr('expand');
        bredText = bredText.split('::');
        shortFix = (bredText[0].length <= 12) ? (bredText[0].trim() + ' <br/><br/>') : (bredText[0].trim());
        toolContentText.html(shortFix);
        toolContentPrice.html(bredText[1].trim());
        theImage.attr('src', link.trim());
        theImage.load(function() {
            theImage.show();
            imageContainer.css('background-image', 'none');
        });
    };
    var takeOutInfo = function() {
        toolContentText.html('');
        toolContentPrice.html('');
    };
    var tipOut = function() {
        if (isIE == true) {
            tipContainer.hide();
            tipContainer.css({ 'left': '-9999em', 'top': '-9999em' });
        } else {
            tipContainer.animate({ 'opacity': 0 }, 200, function() {
                tipContainer.css({ 'left': '-9999em', 'top': '-9999em' });
            });
        }
    };
    $('#jsTipIt li a').each(function() {
        var schift = $(this).attr('title');
        $(this).attr('expand', schift).attr('title', '');
    });
    $('#jsTipIt li a').hover(function(){
        tipIn($(this));
        clearTimeout(closeTimer);
    },function(){  
        takeOutInfo();   
        closeTimer = setTimeout(tipOut,200);   
    });
};
//M119 end
var LB10_117 = function() {
    var bundleCall = function(context) {
        $('.select', context).selectBox();
        initCufon(context);
        initButtons(context);
        M117();
        $('.lightBoxItemList', context).scrollable({
            size: 2,
            clickable: false,
            easing: 'easeOutCirc',
            speed: 700,
            keyboard: false
        });
        $('.scrollList', context).jScrollPane({
            'showArrows': true,
            'scrollbarWidth': 20,
            'scrollbarMargin': 0,
            'arrowSize': 7,
            'dragMaxHeight': 100,
            'dragMinHeight': 100
        });
        $('.nextPage, .prevPage', context).click(function() {
            return false;
        });
    };
    //Selection-Phone 117
    $('#start-config-subscription-117').initLB('LBshopFlow2', {
        'URL': '/foretag/3020.html',
        'closeElement': '.lightBoxBackgroundImage .close',
        'closeTrigger': 'click',
        'closeOnClickOutside': false
    }, {
        'onLoad': function() {
            var lb = $('#LightBoxFlow')[0];
            bundleCall(lb);
            $('#findFavorit', lb).initLB('darkLightBox', {
                'closeElement': '.LBdarkBox .close2',
                'URL': '',
                'backLayer': false
            }, {
                'onLoad': function() {
                    bundleCall($('#LBdarkBoxID')[0]);
                }
            });
            // Lägg till-knappar
            var changeButtons = function(context, toGreen) {
                $(toGreen ? '.btnGreyPlain' : '.btnGreenPlain', context)
                .removeClass(toGreen ? 'btnGreyPlain' : 'btnGreenPlain')
                .addClass(toGreen ? 'btnGreenPlain' : 'btnGreyPlain');
                if (!toGreen) {
                    $(context).find('.btnGreyPlain a').each(function() {
                        Cufon.replace(this, {
                            color: '#aaa',
                            fontFamily: 'boton',
                            textShadow: '1px 1px #fff'
                        });
                    });
                } else {
                    $(context).find('.btnGreenPlain a').each(function() {
                        Cufon.replace(this, {
                            fontFamily: 'boton',
                            textShadow: '1px 1px #05540a'
                        });
                    });
                }
            };
            var btnAddClick = function() {
                var $this = $(this);
                clickAdd($this, true);
                $this.unbind();
                $this.click(function() { return false; });
                $('#phoneRemove').data('selectedPhone', $this);
                return false;
            };
            $('.M117 .btnGreenPlain a', lb).click(btnAddClick);
            $('#phoneRemove').click(function() {
                clickAdd($(this).data('selectedPhone'), false);
                $('.M103 .btnGreenPlain a', lb).click(btnAddClick);
                return false;
            });
        }
    });
};
var M121 = function() {
    //Selection-Phone 
    $('#compare-launcher').initLB('CompPrice', {
        'URL': '/foretag/lightbox_compare_priceplan.html',
        'closeElement': '#M121 .lightBoxMiddle .close',
        'closeTrigger': 'click',
        'closeOnClickOutside': true
    }, {
        'onLoad': function() {
            initCufon();
            initButtons();
            if ($('#mainTable table tr').length > 9) {
                $('#M121 .lightBoxMiddle').addClass('scroll').css({ 'padding-right': '0' })
                $('#M121 .infoTableWrap').jScrollPane({
                    'showArrows': true,
                    'scrollbarWidth': 19,
                    'scrollbarMargin': 5,
                    'arrowSize': 7,
                    'dragMaxHeight': 79,
                    'dragMinHeight': 79
                });
                var mainTableWidth = $('#mainTable').css('width');
                $('#M121 .headerTableWrap').css('width', mainTableWidth);
                if ($.browser.msie && parseInt($.browser.version) == 7) {
                    $('#M121 .headerTableWrap').css('margin-left','-23px');
                }
            }
        }
    });
};
function armLightBox(lightboxContent, buttonToArmId) {
    // Compare Priceplan, Residential
    $('#'+buttonToArmId).initLB('CompPrice', {
        'URL': lightboxContent,
        'closeElement': '.close',
        'closeTrigger': 'click',
        'closeOnClickOutside': false
    }, {
        'onLoad': function() {
            initCufon();
            initButtons();
            if ($('#mainTable table tr').length > 9) {
                $('#M121 .lightBoxMiddle').addClass('scroll').css({ 'padding-right': '0' })
                $('#M121 .infoTableWrap').jScrollPane({
                    'showArrows': true,
                    'scrollbarWidth': 19,
                    'scrollbarMargin': 5,
                    'arrowSize': 7,
                    'dragMaxHeight': 79,
                    'dragMinHeight': 79
                });
                var mainTableWidth = $('#mainTable').css('width');
                $('#M121 .headerTableWrap').css('width', mainTableWidth);
                if ($.browser.msie && parseInt($.browser.version) == 7) {
                    $('#M121 .headerTableWrap').css('margin-left','-23px');
                }
            }
        },
        'onClose': function() {
            $('#darkLayer').hide();    
        }
    });
};
var M122 = function() {
    Cufon.replace('.compare a', { fontFamily: 'botonRegular', color: '-linear-gradient(#656565, #000)' });
    
    $('.M122').each(function() {
        obj = $(this);
        $('.fiveColumns ul, .sixColumns ul', obj).wrap('<div class="tooltip"><div class="repeat"></div><div class="bottom"></div></div>');
        $('.fiveColumns img, .sixColumns img').hover(function() {
            if ($.browser.msie)
                $(this).prev().show();
            else
                $(this).prev().fadeIn(200);
        },
        function() {
            if ($.browser.msie)
                $(this).prev().hide();
            else
                $(this).prev().fadeOut(200);
        });
    });
};
var M124 = function() {
    /* Include AddThis functions */
    AddThis();
    $('.M124').each(function() {
        /* Close the slides */
        $('.innerSlide .content', this).slideUp().parent().slideUp();
        /* Open slide from hashtag */
        if (window.location.hash !== null && window.location.hash && window.location.hash !== "" && window.location.hash !== "#") {
            var obj = $(window.location.hash);
            if (obj.hasClass('innerSlide')) {
                obj.parent().addClass('active').children('.innerSlide').slideDown(400);
                obj.addClass('active').children('.content').slideDown(400);
            }
        }
        $('.header a', this).click(function() {
            var obj = $(this).closest('.slide');
            var objActive = obj.parent().children('.slide.active');
            if (obj.hasClass('active'))
                $.data(obj, "active", true);
            objActive.children('.innerSlide').removeClass('active').children('.content').slideUp(400);
            objActive.removeClass('active').children('.innerSlide').slideUp(400);
            //if (!$.data(obj))
            if (!$.data(obj, 'active'))
                obj.addClass('active').children('.innerSlide').slideDown(400);
            Cufon.replace('.dynamic_area h2,.dynamic_area h3', { fontFamily: 'boton', hover: true });
            if ($(this).attr('href') == "#")
                return false;
        });
        $('.subHeader a', this).click(function() {
            var obj = $(this).closest('.innerSlide');
            var objActive = obj.parent().children('.innerSlide.active');
            if (obj.hasClass('active'))
                $.data(obj, "active", true);
            objActive.removeClass('active').children('.content').slideUp(400);
            //if (!$.data(obj))
            if (!$.data(obj, 'active'))
                obj.addClass('active').children('.content').slideDown(400);
            Cufon.replace('.dynamic_area h2,.dynamic_area h3', { fontFamily: 'boton', hover: true });
            if ($(this).attr('href') == "#")
                return false;
        });
    });
};
var M126 = function() {
    var do1 = function() {
        $('.textInputKamm').html('<h3>Välkommen till KST självbetjäning!</h3><p>Ni kommer om några sekunder slussas vidare till vår underleverantör Datametrix Integration självbetjäning.Om ni inte slussas vidare så <a href="http://servicedesk.datametrix.se">klicka här.</a></p>');
        initCufon();
        setTimeout(function(){window.location = 'http://servicedesk.datametrix.se';}, 7000);
    };
    var do2 = function() {
        $('.textInputKamm').empty().html('<h3>Välkommen till KST självbetjäning!</h3><p>Ni kommer om några sekunder slussas vidare till vår underleverantör Spring Mobil självbetjäning. Om ni inte slussas vidare så <a href="https://sjalvbetjaning.springmobil.se/CerillionWebSelfCare/Login/Login.aspx">klicka här.</a></p>');
        initCufon();
        setTimeout(function(){window.location = 'https://sjalvbetjaning.springmobil.se/CerillionWebSelfCare/Login/Login.aspx';}, 7000);
    };
    var valFunc = function() {
        var nr = $.trim($('#Kammarkollegiet input').val()), reg = /^(?:[12]{1}[\d]{0,28})$/i;
        var getit = reg.test(nr), first = nr.substring(0, 1);
        if (getit) {
            if (first == '1') { do1(); } else if (first == '2') { do2(); } else { return false; }
            return true;
        } else {
            return false;
        }
    };
    $('#Kammarkollegiet').validate();
    $('#Kammarkollegiet input[type=text]').validateExpression(valFunc, 'Fel kund ID! Skriv in ditt kund ID igen och tryck på skicka.');
    $('#subKamm').click(function() {
        $('#Kammarkollegiet input').submit();
    });
    $('#Kammarkollegiet').submit(function(){
        return false;
    });
};
var scrollDown = function(idToScrollTo){  
 
     //get the top offset of the target anchor  
     var target_offset = $("#"+idToScrollTo).offset();  
     var target_top = target_offset.top - 165;  
  
     //goto that anchor by setting the body scroll top to anchor top  
     $('html, body').animate({scrollTop:target_top}, 1500);  
 };  


//-------------------------- M127 ---------------------------------------
var M127 = function() {
  // post back object
  var mobiltInternetPost = { 'type': false, 'modem': false, 'month': false };
  //JSON price settings
  var editPrice;
  $.getJSON("/foretag/ajax/127-jsonPrice.html", function(data) {
    editPrice = data;
  });
  // 127 Light box calls
  $('.priceListBTN,.compareTitle').initLB('PrisListor', {
    'closeElement': '.closeLightbox',
    'closeOnClickOutside': true
  }, {
    'onLoad': function() {
      initCufon();
    }
  });
  //127 slide functions
  var tracker = { 'justMove': false, 'large': false, 'medium': false, 'small': false, 'kill':
  function() {
    this.large = false; this.medium = false; this.small = false;
    $('.expandoContent').css('display', 'none');
  }
  }
  tracker.kill('start');
  $('.triggLarge').click(function() {
    $('#large .radioFeild input').val(["1", "18"]);
    if (tracker.large === false && tracker.justMove === false) { tracker.kill(); $('#large').slideDown(300, function() { tracker.large = true; tracker.justMove = true; calcprice(); }); }
    else if (tracker.large === false && tracker.justMove === true) { tracker.kill(); $('#large').css('display', 'block'); tracker.large = true; tracker.justMove = true; }
    else if (tracker.large === true) { $('#large').slideUp(600, function() { tracker.kill(); tracker.justMove = false; }); }
    mobiltInternetPost.type = 'large';
    calcprice();
    scrollDown("large");
    return false;
  });
  $('.triggMedium').click(function() {
    $('#medium .radioFeild input').val(["1", "18"]);
    if (tracker.medium === false && tracker.justMove === false) { tracker.kill(); $('#medium').slideDown(300, function() { tracker.medium = true; tracker.justMove = true; calcprice(); }); }
    else if (tracker.medium === false && tracker.justMove === true) { tracker.kill(); $('#medium').css('display', 'block'); tracker.medium = true; tracker.justMove = true; }
    else if (tracker.medium === true) { $('#medium').slideUp(600, function() { tracker.kill(); tracker.justMove = false; }); }
    mobiltInternetPost.type = 'medium';
    calcprice();
    scrollDown("medium");
    return false;
  });
  $('.triggSmall').click(function() {
    $('#small .radioFeild input').val(["1", "24"]);
    if (tracker.small === false && tracker.justMove === false) { tracker.kill(); $('#small').slideDown(300, function() { tracker.small = true; tracker.justMove = true; calcprice(); }); }
    else if (tracker.small === false && tracker.justMove === true) { tracker.kill(); $('#small').css('display', 'block'); tracker.small = true; tracker.justMove = true; }
    else if (tracker.small === true) { $('#small').slideUp(600, function() { tracker.kill(); tracker.justMove = false; }); }
    mobiltInternetPost.type = 'small';
    calcprice();
    scrollDown("small");
    return false;
  });
  //127 get price matrix
  var getPrice = function(obj) {
    var mod = false, mon = false;
    if (obj.type == 'large') {
      if (obj.modem == '0') {
        $('#large .radioFeild input[name=bindningstid]').val(["0"]);
        $('#modemPrisLarge').html('0 kr');
        $('#large .radioFeild .hider').hide();
        $('#totalPrisLarge').html(editPrice.large.pricemonth + ' kr');
      } else if (obj.modem == '1' && obj.month == '0') {
        $('#modemPrisLarge').html(editPrice.large.pricemodem + ' kr');
        $('#totalPrisLarge').html(editPrice.large.pricemonth + ' kr');
        $('#large .radioFeild .hider').show();
      } else if (obj.modem == '1' && obj.month == '18') {
        $('#modemPrisLarge').html('0 kr');
        $('#totalPrisLarge').html(editPrice.large.pricemonth + ' kr');
        $('#large .radioFeild .hider').show();
      } else {
        $('#modemPrisLarge').html('0 kr');
        $('#totalPrisLarge').html('0 kr');
        $('#large .radioFeild .hider').show();
      }
    } else if (obj.type == 'medium') {
      if (obj.modem == '0') {
        $('#medium .radioFeild input[name=bindningstid]').val(["0"]);
        $('#totalPrisMedium').html(editPrice.medium.pricemonth + ' kr');
        $('#modemPrisMedium').html('0 kr');
        $('#medium .radioFeild .hider').hide();
      } else if (obj.modem == '1' && obj.month == '0') {
        $('#modemPrisMedium').html(editPrice.medium.pricemodem + ' kr');
        $('#totalPrisMedium').html(editPrice.medium.pricemonth + ' kr');
        $('#medium .radioFeild .hider').show();
      } else if (obj.modem == '1' && obj.month == '18') {
        $('#modemPrisMedium').html('0 kr');
        $('#totalPrisMedium').html(editPrice.medium.pricemonth + ' kr');
        $('#medium .radioFeild .hider').show();
      } else {
        $('#modemPrisMedium').html('0 kr');
        $('#totalPrisMedium').html('0 kr');
        $('#medium .radioFeild .hider').show();
      }
    } else if (obj.type == 'small') {
      if (obj.modem == '0') {
        $('#small .radioFeild input[name=bindningstid]').val(["0"]);
        $('#modemPrisSmall').html('0 kr');
        $('#small .radioFeild .hider').hide();
      } else if (obj.modem == '1' && obj.month == '18') {
        $('#modemPrisSmall').html('0 kr'); //Pierre: was 295 kr
        $('#totalPrisSmall').html('89 kr');
        $('#small .radioFeild .hider').show();



      } else if (obj.modem == '1' && obj.month == '0') {
        $('#modemPrisSmall').html('595 kr');
        $('#totalPrisSmall').html('89 kr');
        $('#small .radioFeild .hider').show();




      } else if (obj.modem == '1' && obj.month == '24') {
        $('#modemPrisSmall').html('0 kr');
        $('#totalPrisSmall').html('89 kr');
        $('#small .radioFeild .hider').show();
      } else {
        $('#modemPrisSmall').html('0 kr');
        $('#totalPrisSmall').html('0 kr');
        $('#small .radioFeild .hider').show();
      }
    } else { }
    mobiltInternetPost = { 'type': obj.type, 'modem': obj.modem, 'month': obj.month }
  };

  var calcprice = function() {
    if (tracker.large == true) {
      getPrice({ 'type': 'large', 'modem': $('#large input[name=modem]:checked').val(), 'month': $('#large input[name=bindningstid]:checked').val() });
    } else if (tracker.medium == true) {
      getPrice({ 'type': 'medium', 'modem': $('#medium input[name=modem]:checked').val(), 'month': $('#medium input[name=bindningstid]:checked').val() });
    } else if (tracker.small == true) {
      getPrice({ 'type': 'small', 'modem': $('#small input[name=modem]:checked').val(), 'month': $('#small input[name=bindningstid]:checked').val() });
    }
  };

smallUrls = {
    '0' : { 
            '0' : 'https://webbutiken.tele2.se/p-order/buy.asp?mode=addpackage&PackageId=796&SubscriptionId=146&rContractMonth=9',
            '1' : 'https://webbutiken.tele2.se/p-order/buy.asp?mode=addpackage&PackageId=797&SubscriptionId=146&rContractMonth=9'
            },
    '18' : { '1' : 'https://webbutiken.tele2.se/p-order/buy.asp?mode=addpackage&PackageId=798&SubscriptionId=146&rContractMonth=5' },
    '24' : { '1' : 'https://webbutiken.tele2.se/p-order/buy.asp?mode=addpackage&PackageId=799&SubscriptionId=146&rContractMonth=7' }
};
$('.smallBuyBtn').unbind('click');
$('.smallBuyBtn').click(
    function(){
        var hasModem = $('#small input[name=modem]:checked').val();
        var bindingTime = $('#small input[name=bindningstid]:checked').val();
        var url = smallUrls[bindingTime][hasModem];
        //alert(url);
        window.location = url;
        return false;
    }
);
  
mediumUrls = {
    '0' : { 
            '0' : 'https://webbutiken.tele2.se/p-order/buy.asp?mode=addpackage&PackageId=804&SubscriptionId=147&rContractMonth=9',
            '1' : 'https://webbutiken.tele2.se/p-order/buy.asp?mode=addpackage&PackageId=805&SubscriptionId=147&rContractMonth=9'
            },
    '18' : { '1' : 'https://webbutiken.tele2.se/p-order/buy.asp?mode=addpackage&PackageId=806&amp;SubscriptionId=147&rContractMonth=5' }
};
$('.mediumBuyBtn').unbind('click');
$('.mediumBuyBtn').click(
    function(){
        var hasModem = $('#medium input[name=modem]:checked').val();
        var bindingTime = $('#medium input[name=bindningstid]:checked').val();
        var url = mediumUrls[bindingTime][hasModem];
        //alert(url);
        window.location = url;
        return false;
    }
); 
  
largeUrls = {
    '0' : { 
            '0' : 'https://webbutiken.tele2.se/p-order/buy.asp?mode=addpackage&PackageId=811&SubscriptionId=148&rContractMonth=9',
            '1' : 'https://webbutiken.tele2.se/p-order/buy.asp?mode=addpackage&PackageId=812&SubscriptionId=148&rContractMonth=9'
            },
    '18' : { '1' : 'https://webbutiken.tele2.se/p-order/buy.asp?mode=addpackage&PackageId=813&SubscriptionId=148&rContractMonth=5' }
};
$('.largeBuyBtn').unbind('click');
$('.largeBuyBtn').click(
    function(){
        var hasModem = $('#large input[name=modem]:checked').val();
        var bindingTime = $('#large input[name=bindningstid]:checked').val();
        var url = largeUrls[bindingTime][hasModem];
        //alert(url);
        window.location = url;
        return false;
    }
);

  //$('.largeBuyBtn, .mediumBuyBtn, .smallBuyBtn').click(function() {
    //example ajax post values
    // alert('abonnemang:'+mobiltInternetPost.type+' modem:'+mobiltInternetPost.modem+' month:'+mobiltInternetPost.month);
  //});

  $('.radioFeild .jquery-radiobutton,.radioFeild label').click(function() { calcprice(); });

};    //M127 end
var M133 = function() {
    /* Include AddThis functions */
    AddThis();
    $('.M133').each(function() {
        /* Close the slides */
        $('.innerSlide', this).slideUp();
        /* Open slide from hashtag */
        if (window.location.hash) {
            var obj = $(window.location.hash);
            if (obj.hasClass('innerSlide'))
                obj = obj.parent();
            obj.addClass('active').children('.innerSlide').slideDown(400);
        }
        $('.header a', this).click(function() {
            var obj = $(this).closest('.slide');
            var objActive = obj.parent().children('.slide.active');
            if (obj.hasClass('active'))
                $.data(obj, "active", true);
            objActive.children('.innerSlide').removeClass('active');
            objActive.removeClass('active').children('.innerSlide').slideUp(400);
            if (!$.data(obj, "active"))
                obj.addClass('active').children('.innerSlide').slideDown(400);
            Cufon.replace('h2, h3', { fontFamily: 'boton', hover: true });
            if ($(this).attr('href') == "#") {
                return false;
            }
        });
    });
};
/* --- MODULES --- */
/* +++ TEMPLATES +++ */
var accordianBound = false;
var initializedModules = new Array();
var t1000Generic = function() {
    if(initializedModules["t1000Generic"] != true)
    {
        /* Cufon Start */
        Cufon.replace('.accordion .links a, .accordion .remove, #navigationTop a, #navigationRightTop a', { fontFamily: 'boton', hover: true });
        Cufon.replace('#topText p, .summary p[class!=small], .sumBig, #paymentMethod .title, #print a', { fontFamily: 'boton' });
        Cufon.replace('.accordion .header h2 span, .row h3 span', { fontFamily: 'botonRegular' });
        Cufon.replace('#linksBottom .btnBack', { fontFamily: 'boton', color: '-linear-gradient(#656565, #000)' });
        /* Cufon End */
    
        /* Accoridion Start */
        if(!accordianBound)
        {
        
            var accordion = $('.accordion');
            $('.header', accordion).bind('click', function(e) {
                var obj = $(this);
                var objAccordion = obj.parent();
                var objContainer = obj.next();
                if (objAccordion.hasClass('closed')) {
                    objContainer.slideDown(200);
                    objAccordion.removeClass('closed');
                }
                else {
                    objContainer.slideUp(200);
                    objAccordion.addClass('closed');
                }
                return false;
            });
            
            /* Close Acordion At Bottom */
            $('.bottom', accordion).bind('click', function(e) {
                var obj = $(this);
                var objContainer = obj.parent();
                var objAccordion = objContainer.parent();
                objContainer.slideUp(200);
                objAccordion.addClass('closed');
                return false;
            });
            
            /* Close all accordion except first one */
            // I was told that everyhing should be closed
            /*var counter = 0;
            $('.header', accordion).each(function() {
                if (counter == 0) {
                    $(this).trigger('click');
                }
                counter++;
            });*/
            accordianBound = true;
        }
        /* Accoridion End */
    
        /* Phone Specification Lightbox Start */
        $('.specification').each(function() {
                $(this).initLB('specificationLightbox'+$(this).attr('rel'), {
                closeElement: '.close'
                });
        });
        /* Phone Specification Lightbox Start */
        /* Slide effect on shipment info Start */
        $("#cartShipmentInfo").click(function() {
            $("#cartShipmentInfo").toggleClass('down');
            $("#slideCartShipmentInfo").slideToggle(200);
        });        
        /* Set module as initialized */
        initializedModules["t1000Generic"] = true;
    }
};
var hideMiniCart = function()
{
    $("#headerCart").removeClass("open");
    $("#headerCart").hide();
};
var t1000 = function() {
    t1000Generic();
    /* Get Json Start */
    $('.remove').click(function() {
        var obj = $(this);
        var objContainer = obj.parent();
        var objAccordion = objContainer.parent().parent();
        var objId = objContainer.attr('id');
        var packageId = obj.attr('rel');
        /* ?????? 
        if (objId == 'summary') {
            objId = 'package';
        }*/
        if(objContainer.hasClass('summary')){
            objId = 'package';
        }
        $.getJSON('/foretag/ajax/json_cart.html', { remove: packageId }, function(data) {
            $('#cart .jsonDelivery').html(data.delivery);
            $('#cart .jsonPerMonth').html(data.perMonth);
            $('#cart .jsonShipping').html(data.shipping);
            $('#cart .jsonActivate').html(data.activate);
            $('#cart .jsonDiscount').html(data.discount);
            $('#cart .jsonBindingTime').html(data.bindingTime);
            $('#cart .jsonTotal').html(data.total);
            if(data.nrOfPackages > 0)
            {
                $("#headerCart").find("a span").eq(0).html(data.nrOfPackages);
                $("#headerCart").find("a span").eq(2).html(data.nrOfArticles);
                   
            }
            else
            {
                hideMiniCart();
            }
               if (objId != 'package') {
                objContainer.slideUp();
            }
            else {
                objAccordion.remove();
                if($('.accordion').length == 0)
                {
                    $('.btnGreenPlain, .btnGreenPlainBig, #totalPackagesAndProducts').hide();
                    $('#emptyCartText').show();
                } else {
                    $('.header:first').click();
                    $('#numberOfTotalPackages').html( $('.accordion').length );
                    $('#numberOfTotalProducts').html( $('.accordion .row').length );
                }
            }
            Cufon.replace('#summary p[class!=small], .sumBig, #totalPackagesAndProducts span', { fontFamily: 'boton' });
        });
        return false;
    });
    /* Get Json End */    /* Get Json Start */
    $('.removePackage').click(function() {
        var obj = $(this);
        var objContainer = obj.parent().next();
        var objId = objContainer.attr('id');
        $.getJSON("/foretag/ajax/json_cart.html", { remove: objId }, function(data) {
            $('.jsonDelivery').html(data.delivery);
            $('.jsonPerMonth').html(data.perMonth);
            $('.jsonShipping').html(data.shipping);
            $('.jsonActivate').html(data.activate);
            $('.jsonDiscount').html(data.discount);
            $('.jsonBindingTime').html(data.bindingTime);
            $('.jsonTotal').html(data.total);
            objContainer.slideUp().next().slideUp();
            Cufon.replace('.summary p[class!=small], .sumBig', { fontFamily: 'boton' });
        });
        return false;
    });
    /* Get Json End */
};
var t1001 = function() {
    t1000Generic();
    /* Validate Function Start */
    $('#theForm').validate();
    $('#theForm input[type=text]').validateRequired('Felmeddelande!');
    /* Validate Function End */
    $('#btnSubmitFormTop, #btnSubmitFormBottom, #btnSubmitForm').click(function() {
        $('.validateErrorBox').remove(); //remove all errorbox (this is fix because cordovan validationboxes is not properly removed)
        $('#theForm').submit();
        return false;
    });
};
var t1002 = function() {
    t1000Generic();
    var submitPayment = function(){
        $('#theForm').submit();
        return false;
    };
    /* Payment Method Function Start */
    $('.selectedPayment .jquery-radiobutton').click(function() {
        var obj = $(this);
        var objId = obj.prev().attr('id');
        var objBg = obj.parent().parent();
        $('#linksBottom span, .topRightButton span').hide();
        $.ajax({
            type: 'POST',
            url: '/foretag/ajax/select_payment_method.html',
            dataType: 'json',
            data: { paymentMethod: objId },
            beforeSend: function(xhr) {
                if(xhr && xhr.overrideMimeType) {
                    xhr.overrideMimeType('application/j-son;charset=UTF-8');
                }
            },
            success: function(data) {
                objBg.parent().find('> div').removeClass('active');
                objBg.addClass('active');
                $('.jsonDelivery').html(data.delivery);
                $('.jsonPerMonth').html(data.perMonth);
                $('.jsonShipping').html(data.shipping);
                $('.jsonActivate').html(data.activate);
                $('.jsonDiscount').html(data.discount);
                $('.jsonBindingTime').html(data.bindingTime);
                $('.jsonTotal').html(data.total);
                
                if(data.paymentMethodFee)
                {
                    $('.paymentMethodFee2 span').html(data.paymentMethodFee);
                    $('#paymentMethodFee').show();
                    $('.paymentMethodFee2 span').show();
                    $('.paymentMethodFee2').next().show().next().show();
                }
                else
                {
                    $('#paymentMethodFee').hide();
                    $('.paymentMethodFee2 span').hide();
                    $('.paymentMethodFee2').next().hide().next().hide();
                }
                
                Cufon.replace('.sumBig', { fontFamily: 'boton' });
                $('#linksBottom span, .topRightButton span').show();
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#linksBottom span, .topRightButton span').show();
                alert('fel uppstod');
                initCufon();
            }
        });
        return false;
    });
    /* Payment Method Function End */
    $('#linksBottom .btnGreenPlainBig, #topText .btnGreenPlain').click(submitPayment);
};
var t1003 = function() {
    t1000Generic();
    Cufon.replace('.t1000Generic .accordion .summary p', { fontFamily: 'boton', hover: true });
};
/* --- General Fixes --- */
//fix loadingspinner so that it's got a very high zIndex.
$(document).ready(function(){
    setTimeout(function(){
        $('#loadingSpinner').each(function(){this.style.zIndex=99999;})
    },200);
});
/* --- TEMPLATES --- */
/* +++ TESTS +++ */
var M = function() {
    $('#theForm').validate();
    $('#theForm input[type=text]').validateRequired('Felmeddelande!');
    $('#theForm input[type=password]').validateMatch();
};
var LBI = function() {
    $('#trigger').initLB('grwewr', {
        URL: '/foretag/lightbox_article_info.html',
        closeElement: '.close'
    });
};
/* --- TESTS --- */
/* +++ AJAX FORMS +++ */
var businessContactFormSender = function() {
    console.log("FormSenderInit");
    var formObject = $("#hero_module_form");         
        var formData = {
            lead_interest: escape($("#lead_interest").val()),
            lead_source: escape($("#lead_source").val()),
            oid: escape($("#oid").val()),
            retURL: escape($("#retURL").val()),
            description: escape($("#description").val()),
            lead1_companyname: escape($("#lead1_companyname").val()),
            lead1_org: escape($("#lead1_org").val()),
            leads1_nbr_empl: escape($("#leads1_nbr_emp1").val()),
            first_name: escape($("#first_name").val()),
            leads1_contact_email: escape($("#leads1_contact_email").val()),
            leads1_contact_number: escape($("#leads1_contact_number").val())
        };
        var randomnumber=Math.floor(Math.random()*99999);
        console.log(formData);
        $.ajax({
            url: formObject.attr('action'),
            data: formData,
            type: "GET",
            error: function(result){
                formObject.hide().after('<h3>Ett fel inträffade tyvärr med formuläret. Skicka ditt ärende via kundservice istället tills vi lagar felet.</h3><br /><br />');
            }
        });
};
/* --- AJAX FORMS --- */
 
/* +++ HTML ACTION DRIVEN NAV +++ */
                actionNavigation = function(){
            
                var menuSelector = $('#actionNavMenu ul li');
            
                menuSelector.hover(function(){
                        $(this).animate({
                            marginLeft:'4px'
                        }, 50 );
                    }, 
                    function () {
                        $(this).animate({
                            marginLeft:'0'
                        }, 200 );
                    });
                
                };
/* --- HTML ACTION RIVEN NAV --- */