var ajaxRequestActive     = false;
var disableHeaderEvents   = false;
var headerMenueActive     = false;
var scrollingActive       = false;
var teaserFlag            = false;

$(document).ready(function()
{
    // Update the body
    $('body').addClass('javascriptEnabled');

    // Assign arrow functionality
    $('#ownTeaserArrowsScrollLeft').click(function()  { scrollTeaser(false); });
    $('#ownTeaserArrowsScrollRight').click(function() { scrollTeaser(true);  });
    
    //start stop button for teaser
    $('#ownTeaserNumberList .buttonControl').click(function(){
        if($(this).hasClass('stop'))
        {
            $(this).removeClass('stop');
            teaserFlag = true;
            var teaserBox = $('#ownTeaserBox');
            teaserBox.stopTime('fade');
        }
        else
        {
            $(this).addClass('stop');
            teaserFlag = false;
            startTeaserTimer();
        }
    });
    
    // Assign number button functionality
    $('#ownTeaserNumberList>li').filter(function(index){
        return index !== 0;
    }).click(function() {
        // Get the new position
        var newPosition = (parseInt($(this).text()) - 1) * 985 * -1;
        
        // Scroll
        scrollTeaserToPosition(newPosition);
    });
    
    // Register the accound edit buttons
    $('.actionButtons span').click(function()
    {
        // Get the button
        var button = $(this);
        
        // Get the button cotainer
        var buttonContainer = button.parent();
        
        // Change the class
        buttonContainer
            .removeClass('state1')
            .addClass('state2');
        
        // Get the form container
        var formContainer = buttonContainer.parent();
        
        // Enable all controls
        var disabledDropDowns = formContainer.find('select:disabled');
        formContainer.find(':disabled').removeAttr('disabled');
        disabledDropDowns.trigger('redraw');
        
    });    
    
    // Start the fade timer
    startTeaserTimer();
    
    // Set up main menue events
    $('#ownMenueContent li a').click(function(e) { return mainMenueLinkClicked(e, this); });

    // Check whether events are required
    if (window.location.href.indexOf('noHeaderMenueEvents') == -1)
    {    
        // Set up the top navigation effect
        $('#ownHeaderContent .right > ul > li:first-child').mouseenter(function()
        {
            headerMenueActive = true;
        
            // Check whether no animation is running
            if (!disableHeaderEvents)
            {
                if ($.browser.msie() && $.browser.version.number() < 8)
                {
                    $('#ownHeader').css('position', 'relative');
                }
                
                // Stop the teaser
                stopTeaserTimer();
            
                // Get the div container
                var div = $(this).find('div');
                
                // Get the list
                var ul = div.find('> ul');
                
                // Start the animation
                div.parent().addClass('open');
				div.find('.facebooklinkHeader').show();
				div.show();
                ul.height(0);
                ul.animate({
                    height: 270
                }, 100);
                
                if(!$.browser.msie)
                {
                    div.animate({opacity: 1}, 100);
                }
                else
                {
                    div.show();
                }
				
                div
                    .css({
                        height: 0,
                        paddingBottom: 0
                    })
                    .animate({
                        height: 310,
                        paddingBottom: 12
                    }, 250, function()
                    {
                        ul.animate({
                            height: 258
                        }, 100);
                        div.animate({
                            height: 298
                        }, 100);
                    });
            }
        });
        $('#ownHeaderContent .right > ul > li:first-child').mouseleave(function()
        {    
            headerMenueActive = false;
            disableHeaderEvents = true;
            
            // Start the teaser
            startTeaserTimer();
            
            // Get the div container
            var div = $(this).find('div.navigation');
            
            // Get the list
            var ul = div.find('> ul');
            
            // Start the animation
			div.find('.facebooklinkHeader').hide();
            ul.animate({
                height: 270
            }, 100);
            div.animate({
                height: 310
            }, 100, function()
            {
                ul.animate({
                    height: 0
                }, 250);
             
                div.animate({
                    height: 0,
                    paddingBottom: 0
                }, 250, function()
                {
                    div
                        .parent().removeClass('open');
                        div.hide();
                        //div.css('opacity', 0);
                        disableHeaderEvents = false;
                        
                        if ($.browser.msie() && $.browser.version.number() < 8)
                        {
                            $('#ownHeader').css('position', 'static');
                        }
                        
                        if (headerMenueActive)
                        {
                            //$('#ownHeaderContent .right > ul > li:first-child').mouseenter();
                        }
                });
            });   
        });
    }
    
    // Check whether the basket is opened
    if ($('#basketItems').length != 0)
    {
        // Append the delete functionallity
        $('.basketItem li.delete').click(function()
        {
            // Get the button
            var button = $(this);
            
            // Change the checkbox name and check it
            $('#deleteCheckbox')
                .attr('name', button.text())
                .attr('checked', true);
        
            // Submit the hidden remove button
            $('#test_basket_Remove').click();
        });
    }
    
    // Set up the gui
    setUpGui();
    
    
    // Set up the cart print event
    $('.basketItem .print').click(function()
    {
        // Initialize the query string
        var queryString = [];
        
        // Get the button
        var button = $(this);
        
        // Get the basket item
        var basketItem = button.parent().parent().parent();
        
        // Append the product information
        queryString.push('item[Produkt:]=' + encodeURI($.trim(basketItem.find('.picture').text()) + '__'));

        
        
        queryString.push('title=Angebot%20(' + encodeURI($.trim(basketItem.find('.header .productName').text()) + ')'));
        
        
        // Append the description
        basketItem.find('.description li > span').each(function(i, element)
        {
            // Get the current item
            var currentItem = $(this);
        
            // Get the value
            var value = currentItem.text().replace(currentItem.find('span').text(), '');
        
            // Append the key value pair
            queryString.push('item[' + encodeURI($.trim(currentItem.find('span').text())) + ']=' + encodeURI($.trim(value)));
        });
        
        // Append the prices
        basketItem.find('.pricing dd').each(function(i, element)
        {
            // Get the current item
            var currentItem = $(this);
        
            // Append the key value pair
            queryString.push('price' + (i + 1) + '=' +encodeURI( $.trim(currentItem.text())));
        });
        
        // Append the rest
        queryString.push('salutation=' + encodeURI(($.trim($('#printField5').text()) == 'MR' ? 'Herr' : 'Frau')));
        queryString.push('name=' + encodeURI($.trim($('#printField1').text())));
        queryString.push('street=' + encodeURI($.trim($('#printField2').text())));
        queryString.push('postalcode=' + encodeURI($.trim($('#printField4').text())));
        queryString.push('city=' + encodeURI($.trim($('#printField3').text())));

        // Build the final url
        var finalUrl = $.trim(button.text()) + 'views/basketprint.php?' + queryString.join('&');

        // Open a new window
        window.open(finalUrl, 'offer');
    });
    
    // Register error box events
    registerErrorBoxEvents();

    // Fix some internet explorer bugs...
    fixSenselessInternetExplorerBugsWithAlsoSenselessCommands();
});

// Show a error
var customError = function(errors)
{
    // Remove old errors and overlays
    $('#popupError,#blackOverlay').remove();
  
    // Create the error list
    var errorList = $('<ul></ul>');
    
    // Add all errors
    $.each(
        errors,
        function(index, value)
        {
            // Add the error
            errorList.append(
                $('<li></li>')
                    .text(value)            
            );
        }
    );

    // Append the html code
    $('#content')
        .append(
            $('<div></div>')
                .attr('id', 'popupError')
                .css('z-index', 35252532)
                .append(
                    $('<div></div>')
                        .addClass('top')
                        .append(
                            $('<div></div>')
                                .addClass('bottom')
                                .append(
                                    $('<div></div>')
                                        .addClass('content')
                                        .append(
                                            $('<div></div>')
                                                .addClass('error')
                                                .append(
                                                    $('<span></span>')
                                                        .addClass('close')
                                                        .text('Schließen')
                                                )
                                                .append(
                                                    errorList
                                                )
                                        )
                                        .append(
                                            $('<div></div>')
                                                .addClass('gray')
                                                .append(
                                                    $('<span></span>')
                                                        .addClass('closeButton')
                                                        .text('Zurück')                                            
                                                )
                                        )
                                )
                        )
                )
        )
        .append(
            $('<div></div>')
                .attr('id', 'blackOverlay')        
        );
        
    // Register the error events
    registerErrorBoxEvents();
}

// Fix senseless internet explorer bugs
var fixSenselessInternetExplorerBugsWithAlsoSenselessCommands = function ()
{
    $('#basketItemList').hide().show();
}

// Filter the content
var getContent = function (source)
{
    // Try to match the content
    var source = source.substring(source.indexOf('<!-- CONTENT START -->'), source.indexOf('<!-- CONTENT END -->'));

    // Return the source
    return source;
}

// Filter the footer
var getFooter = function (source)
{
    // Try to match the content
    var source = source.substring(source.indexOf('<!-- FOOTER START -->'), source.indexOf('<!-- FOOTER END -->'));

    // Return the source
    return source;
}

// Main menue link got clicked
var mainMenueLinkClicked = function (e, link) 
{
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();


    // Get all required elements
    var link               = $(link);
    var ownMenue           = $('#ownMenue');
    var ownBackground      = $('#ownBackground');
    var ownMenueContent    = $('#ownMenueContent');
    var ownMenueContentUl  = ownMenueContent.find('ul');
    var ownTeaserAnimation = $('#ownTeaserAnimation');
    
    // Check whether there is something to close
    if (!ownMenue.hasClass('closed'))
    {
        // Stop the teaser timer
        stopTeaserTimer();
               
        // Debug
        var debug = 0;
       
        // Start the animation
        ownBackground.animate({height: 600}, 180 + debug, function()
        {
            // Fix the background position
            ownMenueContent.css('marginTop', -13);
            ownMenueContentUl.css('marginTop', -45);
            ownMenueContent.addClass('animation');
            ownBackground.addClass('animation');
            
            // Close the teaser
            ownMenueContent.animate({marginTop: 0}, 500 + debug);
            ownTeaserAnimation.animate({height: 0, opacity: 0}, 500 + debug, function()
            {
                // Hide the timer
                ownTeaserAnimation.hide();
                
                // Remove the high background
                ownBackground.css('background', 'none');
                
                // Flag the teaser as closed
                ownMenue.addClass('closed');
            });    
            ownBackground.animate({height: 202}, 500 + debug);
            
            // Move the background to prevent some ugly effects
            ownBackground.animate({backgroundPosition: '0 -700px'}, 250 + debug);
        });
    }
    
    // Check whether no ajax request is running
    if (!ajaxRequestActive)
    {
        // Update the indicator
        ajaxRequestActive = true;
    
        // Get the content element
        var content = $('#content');
    
        // Remove all highlights
        ownMenueContentUl.find('li.active').removeClass('active');
        
        // Highlight the clicked section
        link.parent().addClass('active');

        // Fade out the content
        content.animate({opacity: 0}, 250, function()
        {
            // Get the link target
            var linkTarget = link.attr('href');
                        
            // Check whether we have to use ssl
            if (location.href.indexOf('https://') != -1)
            {
                // Fix the url
                linkTarget = linkTarget.replace('http://', 'https://');
            }

            //Handle different domains: replace the default url with the current host url
            var currentHost = window.location.hostname;
            //linkTarget = linkTarget.replace('www.eversfrankdirekt.de', currentHost);
            //linkTarget = linkTarget.replace(currentHost + '/', '');
            //console.log(linkTarget);
            
            
            $.get(linkTarget, function(data)
            // Load the page
            {
                // Filter the content
                var contentData = getContent(data);
				

                // Append the new data
                content.html(contentData);
				initCalculculateButton();
				var title = data.substring(data.indexOf('<title>'), data.indexOf('</title>')).replace('<title>', '');
                document.title = title;
                
                // Check whether the footer is required
                if ($('#footer').length == 0)
                {
                    // Get the footer source
                    var footer = getFooter(data);
                    
                    // Append the footer
                    $('#contentTop').append(footer);                    
                }
                                
                // Update priceings
                productInit();
                
                // Set up the gui
                setUpGui();    
                
                // Remove some start classes
                $('#contentTop').removeClass('noBackground');
                
                // Update the body classes
                $('body').removeClass().addClass('currentPage_details javascriptEnabled');
                
                // Fade the content in again
                content.animate({opacity: 1}, 250);
                
                //fix ie8 bug mouse over
                if(!$('#test_toBasket').hasClass('disabled'))
                {
                    $('#test_toBasket').mouseover(function(){$(this).css('background-position', '0 -114px')});
                    $('#test_toBasket').mouseout(function(){$(this).css('background-position', '0 -76px')});
                    //$(document).stopTime('ajaxRequestTimer');
                }
    
            });  
            //$(document).everyTime(1500, 'ajaxRequestTimer', function(){window.location.href = linkTarget;});

                
        });

        // Update the indicator
        ajaxRequestActive = false;
    }
    
    return false;
}

// Register the error box events
var registerErrorBoxEvents = function()
{
    $('#popupError .close,#popupError .closeButton').click(function()
    {
        $('#blackOverlay,#popupError').remove();
    });
}

// Scroll the teaser
var scrollTeaser = function (toTheRight)
{
    // Get the teaser box
    var teaserBox = $('#ownTeaserBox');
    
    // Get the number of teaser elements
    var teaserElementCount = teaserBox.find('.ownTeaserItem').length;

    // Get the current direction
    var currentDirection = parseInt(teaserBox.css('marginLeft'));
    if (!currentDirection)
    {
        currentDirection = 0;
    }

    // Get the next scroll position
    var nextScrollPosition = currentDirection + (985 * (toTheRight ? -1 : 1));

    // Check whether we are not out of bounds
    if (nextScrollPosition <= 0 && nextScrollPosition >= ((teaserElementCount * 985) - 985) * -1)
    {
        // Scroll
        scrollTeaserToPosition(nextScrollPosition);
    }
    // We reached the end
    else
    {
        // Check whether we reached the left end
        if (currentDirection == 0)
        {
            // Scroll to the right
            scrollTeaserToPosition(((teaserElementCount * 985) - 985) * -1, 2000);
        }
        // We reached the right end
        else
        {
            // Scroll to the left
            scrollTeaserToPosition(0, 2000);
        }
    }
}

// Scroll the teaser
var scrollTeaserToPosition = function (position, speed)
{
    
    // Check wheter a special speed is given
    if (!speed)
    {
        speed = 500;
    }

    // Check whether no animation is running
    if (!scrollingActive)
    {
        // Update the indicator
        scrollingActive = true;

        // Get the teaser box
        var teaserBox = $('#ownTeaserBox');
        
        // Scroll
        teaserBox.animate({'marginLeft': position}, speed, function()
        {
            
            if (!isNaN(position)) {
               
              
                // Unselect all buttons
                $('#ownTeaserNumberList li.selected').removeClass('selected');
                
                // Select the current button
                $('#ownTeaserNumberList li.button' + (Math.abs((position / 985)) + 1)).addClass('selected');
                
            }

            // Update the indicator
            scrollingActive = false;
            
            // Restart the fade timer            
            startTeaserTimer();
            
           
        });
    }
}

// Set up the gui
var setUpGui = function ()
{
    // Set up the gui
    $('.customCheckBox').socialbitUIRegisterCheckBoxes();
    
    $('.environmentCheckBox').socialbitUIRegisterCheckBoxes(
    {
        'checked': function ()
        {
         
            $('#environmentSelects select:eq(0) option:eq(1)').attr('selected', 'selected').trigger('change');   
            
            $('#environmentSelects .socialbitUIDropDown:eq(0) .socialbitUIDropDownItem.first').addClass('selected');
            
            $('#environmentHidden').css('display', 'block');
        },
        'unchecked': function ()
        {
            $('#environmentSelects select')
                .find('option:selected').removeAttr('selected')
            .end()
                .find('option:eq(0)').attr('selected', 'selected');
                
            $('#environmentSelects select:eq(0)').trigger('change');
                
            $('#environmentSelects .socialbitUIDropDown:eq(0) .selected').removeClass('selected');
            
            
            $('#environmentHidden').css('display', 'none');
        }    
    });
    
    
    
    // Check whether we are on a product page
    if ($('#test_product_name').length != 0)
    {
        $('.customDropDown').socialbitUIRegisterDropDowns(
        {
            'change': function(item)
            {
                if (item.parent().parent().parent().parent().hasClass('opened'))
                {
                    item.parent().parent().parent().parent().parent().find('select:eq(0)').change();
                }
            },
            'filter': function(value, text)
            {
                if (value == '0' && text == 'kein Zusatz')
                {
                    return false;
                }
                
                return true;
            }
        });
    }
    // No product page
    else
    {
        $('.customDropDown').socialbitUIRegisterDropDowns();
    }
        
    // Add some tooltip effects
    $('.tooltip').mouseenter(function()
    {
        $(this).find('.tooltipTop').stop().css({'opacity': '0', 'display': 'block'}).animate({opacity: 1}, 250);
    });
    $('.tooltip').mouseleave(function()
    {        
        
        var tooltip = $(this).find('.tooltipTop');
        tooltip.stop().css('display','none'); //animate({opacity: 0}, 250, function() { tooltip.css('display', 'none'); });
    });
    
    //Add some tooltip for big version
    if ($.browser.msie())
    {
        $('.tooltipBig').mouseenter(function()
        {
            $(this).find('.tooltipTop').stop().css({'opacity': '0', 'display': 'block', 'filter':"alpha(Opacity=100)"}).animate({opacity: 1}, 250);
        });
        $('.tooltipBig').mouseleave(function()
        {
            
            var tooltip = $(this).find('.tooltipTop');
            tooltip.stop().animate({opacity: 0}, 250, function() { tooltip.css('display', 'none'); });
        });
    }
    
    // Add 
    $('.customRadioBox').socialbitUIRegisterRadioBoxes(
    {
        'change': function(customRadioBox)
        {
            // Get the container
            var container = customRadioBox.parent();
            
            // Get the list item
            var listItem = container.parent();
            
            // Get the real radiobox
            var realRadioBox = container.find($.socialbitUI.selectors.radioBox);
            
            // Get the form
            var form = listItem.find('.form');
     
            // Check whether the real radiobox is checked
            if (realRadioBox.is(':checked'))
            {
                form.slideDown(250);
            }
            // The real radiobox is not checked
            else
            {
                form.slideUp(250);
            }
        }  
    });
}

// Start the teaser timer
var startTeaserTimer = function ()
{
    // Get the teaser box
    var teaserBox = $('#ownTeaserBox');

    // Stop all current timers
    teaserBox.stopTime('fade');

    // Start the timer again
    if(teaserFlag == false)
    {
        teaserBox.everyTime(7000, 'fade', function () { scrollTeaser(true); });
    }
}

// Stop the teaser timer
var stopTeaserTimer = function ()
{
    // Get the teaser box
    var teaserBox = $('#ownTeaserBox');

    // Stop all current timers
    teaserBox.stopTime('fade');
}

var submitShippingAddr = function () {
    var disabledDropDowns = $(document.order).find('select:disabled');
    $(document.order).find(':disabled').removeAttr('disabled');
    disabledDropDowns.trigger('redraw');
    
    document.order.submit();
}

