/****************************
Global variables
****************************/
var axflow = {}

/****************************
Startup script
****************************/
/**
Write style to hide content
*/
axflow.writeStyleForJavaScritpEnabledBrowsers = function() {
    var str = "";
    str = "<style type=\"text/css\">";
    //	str += ".productTabContent {"
    //	str += "    display: none;"
    //	str += "}"
    //	str += ".ProductImages li {"
    //	str += "    display: none";
    //	str += "}"
    str += "</style>"
    document.write(str);
}

axflow.writeStyleForJavaScritpEnabledBrowsers();


axflow.startup = function() {
    /*var productTabView = new axflow.TabView('productTabView');
    var tabView = new axflow.TabView('tabView');*/

    /*    axflow.initEventRotator();*/
    //axflow.initPageRelatedTools();
    axflow.initFileUploads();
    /*axflow.initProductListItems();
    axflow.initProductImages();
    axflow.initTopNavigationList();*/
    // Add dialogwindow to Fluidity Nonstop logotype in the footer
    /*axflow.dialogWindowForFooterLogo();
    //axflow.stretchZoneA3();
    /*axflow.formBrandModelLogic();*/


    if ($('#newsRotator').length) {
        axflow.initNewsRotator();
    }
    if ($('.zoneA2').length && $('.zoneB2').length) {
        axflow.setZoneHeight($('.zoneA2'), $('.zoneB2'));
    }
    if ($('.zoneC2').length && $('.zoneD2').length) {
        axflow.setZoneHeight($('.zoneC2'), $('.zoneD2'));
    }
    if ($('.zoneE2').length && $('.zoneF2').length) {
        axflow.setZoneHeight($('.zoneE2'), $('.zoneF2'));
    }

    
    // #7587
    //axflow.setFooterLinkList();

    axflow.setLinkListHeight('#bottominformation .column_inner');

    $('#fluidityNonstopText').insertAfter($('#root'));

    $('#fluidityNonstopLogotypeContainer').hover(function() {
        $('#fluidityNonstopText').fadeIn();

    }, function() {
        $('#fluidityNonstopText').fadeOut();
    });

    $('#fluidityNonstopLogotypeContainer').mousemove(function(e) {
        $('#fluidityNonstopText').css('top', (e.pageY - $('#fluidityNonstopText').height() - 10) + 'px');
        $('#fluidityNonstopText').css('left', (e.pageX - 25) + 'px');
    });

    $('.tabs a').each(function(i, item) {
        $('.productTabView .productTabContent .name').hide();

        if (!$(item).parents('li').hasClass('active')) {
            $('.productTabView .productTabContent:eq(' + i + ')').hide();
        }
    });

    $('.tabs a').click(function() {
        if (!$(this).parents('li').hasClass('active')) {
            var i = $(this).parents('li').index();
            $('.tabs a').parents('li').removeClass('active');
            $('.productTabView .productTabContent').hide();

            $(this).parents('li').addClass('active');
            $('.productTabView .productTabContent:eq(' + i + ')').show();
        }
    });

    $('a.readmore').click(function() {
        $('#readmore').toggle(400);
        return false;
    });
}

axflow.tabView = function() {

}

axflow.setZoneHeight = function(zone1, zone2) {
    if (zone1.height() < zone2.height()) {
        zone1.css('height', zone2.height() + 'px');
    }
}

axflow.setLinkListHeight = function(objects) {
    var listHeight = 0;
    $(objects).each(function() {
        if ($(this).height() > listHeight) {
            listHeight = $(this).height();
        }
    });
    $(objects).height(listHeight);
}



axflow.setFooterLinkList = function() {
    var maxHeight = 0;
    var minHeight = 0;
    var wrapperMaxHeight = 0;

    wrapperMaxHeight = $('#footerlinks').height();

    $('.footerlinks_inner').each(function() {
        if ($(this).height() > maxHeight) {
            maxHeight = $(this).height();
        }
    });

    if ($('.footerlinks_inner li').length > 6) {

        $('.footerlinks_inner').each(function() {
            var itemHeights = 0;
            for (var i = 1; i < 7; i++) {
                itemHeights = itemHeights + $(this).find('li:nth-child(' + i + ')').height();
            }
            if (itemHeights > minHeight) {
                minHeight = itemHeights;
            }
        });
        minHeight = 15 + minHeight;
        maxHeight = 15 + maxHeight;

        $('#footerlinks').append('<a class="expandLink col1" href="#">Visa mer</a><a class="expandLink col2" href="#">Visa mer</a><a class="expandLink col3" href="#">Visa mer</a><a class="expandLink col4" href="#">Visa mer</a>');

        $('.expandLink').toggle(function() {
            $('#footerlinks').animate({ height: maxHeight + 'px' });
            $('.expandLink').text('Visa mindre');
            return false;
        },
        function() {
            $('#footerlinks').animate({ height: minHeight + 'px' });
            $('.expandLink').text('Visa mer');
            return false;
        });

    }
    $('.footerlinks_inner').height(maxHeight);

    $('#footerlinks').height(minHeight);
}

axflow.initNewsRotator = function() {
    $("#newsRotator").jcarousel({
        scroll: 1,
        size: 4,
        wrap: 'both',
        buttonNextHTML: null,
        buttonPrevHTML: null,
        auto: 10,
        itemVisibleInCallback: {
            onAfterAnimation: function(c, o, i, s) {
                $('.jcarousel-control a').removeClass('selected');
                $('.jcarousel-control a:eq(' + (i - 1) + ')').addClass('selected');
            }
        },
        initCallback: axflow.newsRotator_initCallback
    });
}
axflow.newsRotator_initCallback = function(carousel) {
    $('#newsRotator .jcarousel-control a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });

    $('#newsRotator .jcarousel-scroll select').bind('change', function() {
        carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value);
        return false;
    });

    $('#newsRotator-next').bind('click', function() {
        carousel.next();
        return false;
    });

    $('#newsRotator-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

$(document).ready(function() {
    axflow.startup();

    var products = 0;
    var service = 0;
    var systems = 0;

    $(function() {
        //scrollpane parts
        var scrollPane = $('.scroll-pane');
        var scrollContent = $('.scroll-content');

        //build slider
        var scrollbar = $(".scroll-bar").slider({
            slide: function(e, ui) {
                if (scrollContent.width() > scrollPane.width()) {
                    scrollContent.css('margin-left', Math.round(ui.value / 100 * (scrollPane.width() - scrollContent.width())) + 'px');
                }
                else { scrollContent.css('margin-left', 0); }
            },
            change: function(e, ui) {
                if (scrollContent.width() > scrollPane.width()) { scrollContent.animate({ 'margin-left': Math.round(ui.value / 100 * (scrollPane.width() - scrollContent.width())) + 'px' }, 1000); }
                else { scrollContent.css('margin-left', 0); }
            },
            animate: 1000
        });

        function posScrollButtons() {
            var total = $('.scroll-content-item').length;

            $('.scroll-content').css('width', total * 135 + 'px');

            var indexOfProducts = $('.scroll-content').find('.products').index();
            var indexOfService = $('.scroll-content').find('.service').index();
            var indexOfSystems = $('.scroll-content').find('.systems').index();

            var productsLeftPos = (indexOfProducts / total) * 100;
            var serviceLeftPos = (indexOfService / total) * 100;
            var systemsLeftPos = (indexOfSystems / total) * 100;

            products = productsLeftPos;
            service = serviceLeftPos;
            systems = systemsLeftPos;

            if (indexOfService > 0) {
                if (service < 95) {
                    $('#serviceScroll').css('left', serviceLeftPos + '%');
                }
                else {
                    $('#serviceScroll').css('left', '95%');
                }
            }
            else {
                $('#serviceScroll').css('display', 'none');
            }

            if (indexOfSystems > 0) {
                if (systems < 95) {
                    $('#systemsScroll').css('left', systemsLeftPos + '%');
                }
                else {
                    $('#systemsScroll').css('left', '95%');
                }
            }
            else {
                $('#systemsScroll').css('display', 'none');
            }
        }


        //append icon to handle
        var handleHelper = scrollbar.find('.ui-slider-handle')
		.mousedown(function() {
		    scrollbar.width(handleHelper.width());
		})
		.mouseup(function() {
		    scrollbar.width('100%');
		})
		.append('<span class="ui-icon ui-icon-grip-dotted-vertical"></span>')
		.wrap('<div class="ui-handle-helper-parent"></div>').parent();

        //change overflow to hidden now that slider handles the scrolling
        scrollPane.css('overflow', 'hidden');

        //size scrollbar and handle proportionally to scroll distance
        function sizeScrollbar() {
            var remainder = scrollContent.width() - scrollPane.width();
            // Check if the content is larger than the container
            if (remainder > 0) {
                // If it is, resize the scroll handler
                var proportion = remainder / scrollContent.width();
                var handleSize = scrollPane.width() - (proportion * scrollPane.width());
                scrollbar.find('.ui-slider-handle').css({
                    width: handleSize,
                    'margin-left': -handleSize / 2
                });
                handleHelper.width('').width(scrollbar.width() - handleSize);
            }
            else {
                // If not, disable the slider
                scrollbar.slider({ disabled: true });
                $(".scrollRight").unbind('click');
                $(".leftRight").unbind('click');
                scrollbar.find('.ui-slider-handle').css({
                    width: "100%"
                });
            }
        }

        //reset slider value based on scroll content position
        function resetValue() {
            var remainder = scrollPane.width() - scrollContent.width();
            var leftVal = scrollContent.css('margin-left') == 'auto' ? 0 : parseInt(scrollContent.css('margin-left'));
            var percentage = Math.round(leftVal / remainder * 100);
            scrollbar.slider("value", percentage);
        }
        //if the slider is 100% and window gets larger, reveal content
        function reflowContent() {
            var showing = scrollContent.width() + parseInt(scrollContent.css('margin-left'));
            var gap = scrollPane.width() - showing;
            if (gap > 0) {
                scrollContent.css('margin-left', parseInt(scrollContent.css('margin-left')) + gap);
            }
        }

        $('.scrollRight').click(function() {
            var remainder = scrollPane.width() - scrollContent.width();
            var leftVal = scrollContent.css('margin-left') == 'auto' ? 0 : parseInt(scrollContent.css('margin-left'));
            var percentage = Math.round(leftVal / remainder * 100);
            var plusScroll = Math.round((1 / $('.scroll-content-item').length) * 100);
            scrollbar.slider("value", Math.round(percentage + plusScroll));
            return false;
        });
        $('.scrollLeft').click(function() {
            var remainder = scrollPane.width() - scrollContent.width();
            var leftVal = scrollContent.css('margin-left') == 'auto' ? 0 : parseInt(scrollContent.css('margin-left'));
            var percentage = Math.round(leftVal / remainder * 100);
            var plusScroll = Math.round((1 / $('.scroll-content-item').length) * 100);
            scrollbar.slider("value", Math.round(percentage - plusScroll));
            return false;
        });

        //$('#pumpScroll').click(function() {
        //    scrollbar.slider("value", Math.round(pump));
        //    return false;
        //});

        $('#serviceScroll').click(function() {
            //var indexOfService = $('#mycarousel').find('.service').index();
            scrollbar.slider("value", Math.round(service));
            return false;
        });

        $('#systemsScroll').click(function() {
            scrollbar.slider("value", Math.round(systems));
            return false;
        });

        $('#productsScroll').click(function() {
            scrollbar.slider("value", Math.round(products));
            return false;
        });

        posScrollButtons();
        //change handle position on window resize
        $(window)
		.resize(function() {
		    resetValue();
		    sizeScrollbar();
		    reflowContent();
		});
        //init scrollbar size
        setTimeout(sizeScrollbar, 10); //safari wants a timeout
    });

    if ($('#imageGallery').length) {
        var numItems = $('#imageGallery ul li').length;
        var activeItem = 0;
        $('.ProductImages ul li:eq(' + activeItem + ')').show();
        $('.ProductImages').append('<div class="buttons"><img class="prev" src="/images/prevButton.gif"><span>' + (activeItem + 1) + '/' + numItems + '</span><img class="next" src="/images/nextButton.gif"></div>');
        $('.buttons .prev').click(function() {
            activeItem--;
            $('#imageGallery ul li').hide();
            if (activeItem >= 0) {
                $('#imageGallery ul li:eq(' + activeItem + ')').show();
                $('.buttons span').html((activeItem + 1) + ' / ' + numItems);
            }
            else {
                activeItem = numItems - 1;
                $('#imageGallery ul li:eq(' + activeItem + ')').show();
                $('.buttons span').html((activeItem + 1) + ' / ' + numItems);
            }
        });
        $('.buttons .next').click(function() {
            activeItem++;
            $('#imageGallery ul li').hide();
            if (numItems > activeItem) {
                $('#imageGallery ul li:eq(' + activeItem + ')').show();
                $('.buttons span').html((activeItem + 1) + ' / ' + numItems);
            }
            else {
                activeItem = 0;
                $('#imageGallery ul li:eq(' + activeItem + ')').show();
                $('.buttons span').html((activeItem + 1) + ' / ' + numItems);
            }
        });
    }
});


axflow.initProductImages = function() {
    if ($defined($('imageGallery'))) axflow.imageGallery = new axflow.ImageGallery2($('imageGallery'));
}

axflow.initTopNavigationList = function() {
    $$("#topnav li").each(function(item) {
        item.addEvent('mouseenter', function() {
            item.addClass('over');
            item.setStyle('height', item.getSize().y + 'px');
        });
        item.addEvent('mouseleave', function() {
            item.removeClass('over');
        });
    });
}

axflow.initProductListItems = function() {
    $$('.ProductListItem').each(function(item) {
        item.addClass('clickable');
        item.addEvent('click', function() {
            document.location.href = item.getElement("a").href;
        });
    });
}

axflow.initFileUploads = function() {
    var W3CDOM = (document.createElement && document.getElementsByTagName);
    if (!W3CDOM) return;
    var fakeFileUpload = document.createElement('div');
    fakeFileUpload.className = 'fakefile';
    fakeFileUpload.appendChild(document.createElement('input'));
    var image = document.createElement('img');
    image.src = '/images/back/btnDarkGreyBg.gif';
    fakeFileUpload.appendChild(image);
    var x = document.getElementsByTagName('input');
    for (var i = 0; i < x.length; i++) {
        if (x[i].type != 'file') continue;
        if (x[i].parentNode.className != 'uploadField') continue;
        x[i].className = 'file';
        var clone = fakeFileUpload.cloneNode(true);
        x[i].parentNode.appendChild(clone);
        x[i].relatedElement = clone.getElementsByTagName('input')[0];
        x[i].onchange = x[i].onmouseout = function() {
            this.relatedElement.value = this.value;
        }
        x[i].onkeyup = function() {
            this.relatedElement.value = this.value;
        }
        x[i].onkeydown = function() {
            this.relatedElement.value = this.value;
        }
    }
}

var imgArr = null;

// Add events to page related tools
axflow.initPageRelatedTools = function() {
    $('#printPage').click(function() {
        axflow.printPage();
    });
}

axflow.printPage = function() {
    if (window.print) window.print();
}


axflow.initImageScroller = function() {

    //<div class="buttons"><img src="/images/prevButton.gif"><span>1/4</span><img src="/images/nextButton.gif"></div>
}

axflow.footerLinkStretch = function() {

}



function getSelectString(elementID, className, elementName, optionsHTML, label) {
    return '<label for="' + elementID + '">' + label + '</label><select id="' + elementID + '" class="' + className + '" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xforms="http://www.w3.org/2002/xforms" name="' + elementName + '">' + optionsHTML + '</select>';
}

// FORMS dynamic brand/model selector
axflow.formBrandModelLogic = function() {

    // Get content language from page
    var contentLanguage = $('contentLanguage');

    if (contentLanguage == null)
        return;

    var language = contentLanguage.innerHTML;

    // For every brand
    var brands = $$('select.brands').each(function(item, index) {

        // Try to find this brands model
        var models = $$('select.models');

        // Hide hide all models
        models.each(function(item, index) {
            item.getParent().setStyle('display', 'none');
        });

        // Get models and fill the list with javascript
        // This could be done from code behind if you could set the value of the options individually
        var request = new Request.HTML({ method: 'get', url: '/AjaxProxies/GetAllModelsHandler.ashx' });
        request.addEvents({
            'onSuccess': function(responseTree, responseElements, responseHTML, responseJavaScript) {

                // Replace current select box
                var parent = item.getParent();
                parent.set('html', getSelectString(item.id, item.className, item.name, responseHTML, item.getParent().getFirst('label').get('text')));

                // Add the onChange event
                parent.getFirst('select').addEvents({
                    'change': function() {

                        // Get brand ID from selected value
                        var BrandID_re = /\d+(?=\])/
                        var BrandID = BrandID_re.exec(this.get('value'));

                        // Get models by brand
                        var request = new Request.HTML({ method: 'get', url: '/AjaxProxies/ModelsByBrandHandler.ashx' });
                        request.addEvents({
                            'onSuccess': function(responseTree, responseElements, responseHTML, responseJavaScript) {

                                // Get model
                                var models = $$('select.models');

                                // If this brands drop down list controls several models drop down lists
                                models.each(function(item, index) {
                                    item.getParent().setStyle('display', 'inline');
                                    item.getParent().set('html', getSelectString(item.id, item.className, item.name, responseHTML, item.getParent().getFirst('label').get('text')));
                                });
                            }
                        });

                        request.send('BrandID=' + BrandID + '&Language=' + language);

                    }
                });
            }
        });

        request.send('Language=' + language);
    });
}


