var iContentTextSize = 11;
var sVoucherFormTpl = '';

// hilfsfunktionen
function cW (winurl, winname, winbreite, winhoehe, resize)
{
    var scroll="yes";
    var resize = "yes";
    if (winurl.indexOf('?') != -1)
    {
        winurl += '&media=popup';
    }
    else
    {
        winurl += '?media=popup';
    }
    
    if(!winbreite) winbreite = 780;
    if(!winhoehe) winhoehe = 500;    
    if(winbreite<150) winbreite=150;

    var winseite = Math.round((screen.availWidth - winbreite) / 2);
    var winoben = Math.round((screen.availHeight - winhoehe) / 3);
    var parameter = ('width='+ winbreite +',height='+ winhoehe +',left='+ winseite +',top='+ winoben +',scrollbars='+ scroll +',resizable='+ resize +',status=yes');
    var winname = window.open(winurl,winname,parameter);
    winname.focus();
}


formatPrice = function(iIn)
{
    return numberFormat(iIn, 2, ',', ' ');
}

function numberFormat( number, laenge, sep, th_sep )
{
    number = Math.round( number * Math.pow(10, laenge) ) / Math.pow(10, laenge);
    str_number = number+"";
    arr_int = str_number.split(".");
    if(!arr_int[0]) arr_int[0] = "0";
    if(!arr_int[1]) arr_int[1] = "";
    if(arr_int[1].length < laenge)
    {
        nachkomma = arr_int[1];
        for(i=arr_int[1].length+1; i <= laenge; i++){   nachkomma += "0";   }
        arr_int[1] = nachkomma;
    }
    if(th_sep != "" && arr_int[0].length > 3)
    {
        Begriff = arr_int[0];
        arr_int[0] = "";
        for(j = 3; j < Begriff.length ; j+=3)
        {
            Extrakt = Begriff.slice(Begriff.length - j, Begriff.length - j + 3);
            arr_int[0] = th_sep + Extrakt + arr_int[0] + "";
        }
        str_first = Begriff.substr(0, (Begriff.length % 3 == 0)?3:(Begriff.length % 3));
        arr_int[0] = str_first + arr_int[0];
    }
    return arr_int[0]+sep+arr_int[1];
}

toggleDiv = function(sElementId, checkBox, hideOthers)
{
    checked = (!checkBox) ? $('#' + sElementId).css('display') == 'none' : checked = checkBox.checked || !checkBox;    
    if(checked)
    {
        $('#' + sElementId).slideDown(200);
    }
    else
    {
        $('#' + sElementId).slideUp(200);
    }
}


// product detail
var sOldSize = '';
updateImage = function(sImage)
{
    $('.thumbList a').each(function()
    {
        sImg = this + '';
        if(sImg.substr(sImg.lastIndexOf('/') + 1) == sImage)
        {
            doImageTransition(this);
        }
    });
}

updateColor = function(oCurrentImg)
{
    sColor = $('#color').val();
    sSize = $('#size').val() || 0;

    oCurrentImg = oCurrentImg + '';
    sCurrentImg = oCurrentImg.substr(oCurrentImg.lastIndexOf('/') + 1);
    sFirstMatchingSize = '';
    bUpdated = false;
    if(sCurrentImg != aColors[sColor]['aSizes'][sSize]['sImageName'])
    {
        for(var sCurrentColor in aColors)
        {
            for(var sCurrentSize in aColors[sCurrentColor]['aSizes'])
            {
                if(aColors[sCurrentColor]['aSizes'][sCurrentSize]['sImageName'] == sCurrentImg)
                {
                    $('#color').val(sCurrentColor);
                    $('#colorSelector ul li').removeClass('active');
                    $('#color_' + sCurrentColor).addClass('active').parent().parent().find('div span').text($('#color_' + sCurrentColor).find('span').text());

                    if(sFirstMatchingSize == '')
                    {
                        sFirstMatchingSize = sCurrentSize;
                    }
                    if(aColors[sCurrentColor]['aSizes'][sCurrentSize]['iDeliverable'] > 0)
                    {
                        updateSize(sCurrentColor, sCurrentSize);
                        bUpdated = true;
                        break;
                    }
                }
            }
            if(sFirstMatchingSize != '' && bUpdated == false)
            {
                updateSize(sCurrentColor, sFirstMatchingSize);
                break;
            }
        }
    }
}

updateSize = function(sColor, sSize)
{
    sCurrentSizeCleanString = $('#size').val();
    if(sCurrentSizeCleanString)
    {        
        $('#sizeSelector ul').empty();
        for(iCount = 0; iCount < aColors[sColor]['aSizesCleanStrings'].length; iCount ++)
        {
            sText = unescape(decodeURI(aColors[sColor]['aSizes'][aColors[sColor]['aSizesCleanStrings'][iCount]]['sSize']));
            $oNewLi = $('<li></li>')
                .attr('id', 'size_' + aColors[sColor]['aSizesCleanStrings'][iCount])
                .text(sText)
                .addClass('delivery' + aColors[sColor]['aSizes'][aColors[sColor]['aSizesCleanStrings'][iCount]]['iDeliverable'])
                .attr('title', sText + aDeliveryHints[aColors[sColor]['aSizes'][aColors[sColor]['aSizesCleanStrings'][iCount]]['iDeliverable']])
                .wrapInner('<span></span>')
                .bind('click', selectLiClick);
            $('#sizeSelector ul').append($oNewLi);
        }
        
        if(typeof(sSize) != 'undefined')
        {
            sCurrentSizeCleanString = sSize;
        }
        else if($.inArray(sCurrentSizeCleanString, aColors[sColor]['aSizesCleanStrings']) == -1)
        {
            sCurrentSizeCleanString = aColors[sColor]['aSizesCleanStrings'][0];
        }
        $('#size').val(sCurrentSizeCleanString);
        $('#size_' + sCurrentSizeCleanString).addClass('active');
        
        // update
        $('#sizeSelector').find('div span').text(unescape(decodeURI(aColors[sColor]['aSizes'][sCurrentSizeCleanString]['sSize'])));
        initVoucherForm();
        
        // todo !!
        if(aColors[sColor]['aSizesCleanStrings'].length == 1)
        {
            $('#sizeSelector').unbind('click').find('div').addClass('inactive');
        }
        else
        {
            $('#sizeSelector').bind('click', selectClick).find('div').removeClass('inactive').end().find('ul').hide().find('li').bind('click', selectLiClick);        
        }
    }
    updateParams();
}

updateParams = function()
{
    sSize = $('#size').val() || '0';
    aCurrentSize = aColors[$('#color').val()]['aSizes'][sSize];
    
    $('#basketForm input[name=id]').val(aCurrentSize['iId']);
    $('#price').text(formatPrice(aCurrentSize['fPrice']) + ' €');
    $('#basePrice').text(decodeURI(aCurrentSize['sBasePrice']));
    
    if(document.getElementById('oldPrice'))
    {
        if(aCurrentSize['fOldPrice'])
        {
            $('#oldPrice').text(formatPrice(aCurrentSize['fOldPrice']) + ' €');
            $('#price').addClass('detailPriceSale').removeClass('detailPrice');
        }
        else
        {
            $('#oldPrice').text('');
            $('#price').addClass('detailPrice').removeClass('detailPriceSale');
        }
    }
    
    $('#artnum').text(aCurrentSize['sArtNum']);
    $('#basketButton').attr('class', 'status' + aCurrentSize['iDeliverable']);
    
    if(aCurrentSize['iDeliverable'] < 2)
    {
        $('#basketButton').attr('disabled', 'disabled').addClass('disabled');
    }
    else
    {
        $('#basketButton').removeAttr('disabled').removeClass('disabled');
    }
}

var aCosts = new Object();
updateCheckoutPrice = function()
{
    if($('#totalPrice').length == 0)
    {
        return;
    }

    var aPreselectedValues = new Object();
    $(".inputradio").each(function()
    {
        if(this.checked)
        {
            aPreselectedValues[this.name] = this.value;
        }
        else
        {
            aCosts[this.name] = 0;
            $('#' + this.name + 'Price').text(formatPrice(aCosts[this.name]));
        }
        
        if(!this.onclick)
        {
            oldOnClick = this.onclick;
            this.onclick = function()
            {
                if(aIncompatible[this.value])
                {
                    var iDeliveryId = this.value;
                    $('input:radio[name="payment"]').each(function()
                    {
                        if($.inArray(this.value, aIncompatible[iDeliveryId]) > -1)
                        {
                            $(this).attr('disabled', 'disabled').val([]).parent().addClass('disabled');
                        }
                        else
                        {
                            $(this).removeAttr('disabled').parent().removeClass('disabled');
                        }
                    });
                }
                
                aCosts[this.name] = numberFormat( eval(fProductsPrice + ' ' + aCalculations[this.name][this.value]), 2, '.', '' ) - fProductsPrice;
                $('#' + this.name + 'Price').text(formatPrice( aCosts[this.name] ));
                                
                // adjust price
                fTotalPrice = aCosts['delivery'] + aCosts['payment'] + fProductsPrice;
                if(typeof fVoucherValueTapir == 'number' && fVoucherValueTapir !== null)
                {
                    fTotalPrice -= fVoucherValueTapir;
                }
                if(typeof fVoucherValue == 'number' && fVoucherValue !== null)
                {
                    fTotalPrice -= fVoucherValue;
                }
                if(fCreditFromAccount > 0)
                {
                    fTotalPrice -= fCreditFromAccount;
                }
                if(fTotalPrice <= 0)
                {
                    $('input[name=payment]').attr('disabled', 'disabled').val([]).parent().addClass('disabled');
                }
                if(fTotalPrice < 0)
                {
                    $('#creditToAccount').css({display: 'table-row'}).find('td:nth-child(2)').text(formatPrice(fTotalPrice) + ' €');
                    fTotalPrice = 0;
                }
                else
                {
                    $('#creditToAccount').css({display: 'none'});
                }
                $('#totalPrice').text(formatPrice(fTotalPrice));
            }
        }
    });
    
    for(var sNodeName in aPreselectedValues)
    {
        aCosts[sNodeName] = eval(fProductsPrice + ' ' + aCalculations[sNodeName][aPreselectedValues[sNodeName]]) - fProductsPrice;
        $('#' + sNodeName + 'Price').text(formatPrice(aCosts[sNodeName]));
    }
    
    // adjust price
    fTotalPrice = aCosts['delivery'] + aCosts['payment'] + fProductsPrice;
    if(typeof fVoucherValueTapir == 'number' && fVoucherValueTapir !== null)
    {
        fTotalPrice -= fVoucherValueTapir;
    }
    if(typeof fVoucherValue == 'number' && fVoucherValue !== null)
    {
        fTotalPrice -= fVoucherValue;
    }
    if(fCreditFromAccount > 0)
    {
        fTotalPrice -= fCreditFromAccount;
    }
    if(fTotalPrice <= 0)
    {
        $('input[name=payment]').attr('disabled', 'disabled').val([]).parent().addClass('disabled');
    }
    if(fTotalPrice < 0)
    {
        $('#creditToAccount').css({display: 'table-row'}).find('td:nth-child(2)').text(formatPrice(-fTotalPrice) + ' €');
        fTotalPrice = 0;
    }
    else
    {
        $('#creditToAccount').css({display: 'none'});
    }
    $('#totalPrice').text(formatPrice(fTotalPrice));
}

selectClick = function()
{
    $('.selectBox ul, .naviSelectBox ul').hide();
    $(this).unbind().find('ul').show(20, function()
    {
        $('body').bind('click', function()
        {
            if($('#fancy_div').is(':visible'))
            {
                return false;
            }
            
            $('.selectBox, .naviSelectBox').not(":has(div[class*='inactive'])").bind('click', selectClick).find('ul').hide().find('li').not(':has(a)').bind('click', selectLiClick);
            $(this).unbind('click');
        });
    });
}

selectLiClick = function()
{
    $(this).parent().hide().find('li').removeClass('active');
    $(this).addClass('active').parent().parent().find('div span').text($(this).find('span').text());
    
    if(this.id.indexOf('color_') == 0)
    {
        sColorCleanString = this.id.replace('color_', '');
        $('#color').val(sColorCleanString);
        updateSize(sColorCleanString);
        updateImage(aCurrentSize['sImageName']);
    }
    else if(this.id.indexOf('size_') == 0)
    {
        sSizeCleanString = this.id.replace('size_', '');
        $('#size').val(sSizeCleanString);
        updateParams();
        updateImage(aCurrentSize['sImageName']);
    }
}

// allgemeiner start
startApp = function()
{
    // forms
    $('form').bind('submit', function()
    {
        if (this.bSubmitted)
        {
            return false;
        }
        else
        {
            this.bSubmitted = true;
            $(this).find(":submit,:image").addClass('disabled');
            return true;
        }
    });
    
    // imgload // safari
    $('<img />').attr('src', ("https:" == document.location.protocol ? sSslBaseUrl : sBaseUrl) + 'images/bgButtonsBlueDisabled.gif');
    $('<img />').attr('src', ("https:" == document.location.protocol ? sSslBaseUrl : sBaseUrl) + 'images/bgButtonsDisabled.gif');
    
        
    // navi over
    $('#nav li:not(#nav li li)')
        .mouseover(function(){$(this).addClass("over");})
        .mouseout(function(){$(this).removeClass("over");});   
        
    // buttons
    $('button').wrapInner('<span><span></span></span>');
    $('a.button').wrapInner("<span></span>");
   
    // links ohne rahmen
    $('a').focus(function(){if(this.blur)this.blur();});
    
    // external
    $('a.blank').click(function(){window.open(this.href); return false;});
   
    // selectboxen
    $('.selectBox, .naviSelectBox').not(":has(div[class*='inactive'])").bind('click', selectClick).find('ul li').not(':has(a)').bind('click', selectLiClick);
    
    // voucher value form
    if(sVoucherFormTpl)
    {
        $(sVoucherFormTpl).appendTo('body');
        initVoucherForm();
    }
    
    // suche initialisieren
    if(sSearchAjaxUrl)
    {
        $('#searchbox').autocomplete(sSearchAjaxUrl.replace(/&amp;/g, '&'));
    }

    // produktdetails toggle
    sToggleName = '';
    if($('#productDescription').length)
    {
        sToggleName = 'product';
    }
    else if($('#categoryDescription').length)
    {
        sToggleName = 'category';
    }
    if(sToggleName)
    {
        var fHeight = 162 / iContentTextSize;
        var sTextDown = '';//'Details einblenden';
        var sTextUp = '';//'Details ausblenden';
        var sClassNameDn = 'blindDn';
        var sClassNameUp = 'blindUp';
        
        var fTextHeight = $('#' + sToggleName + 'Description').height() / iContentTextSize;
        var bDown = false;
        
        if(fTextHeight > fHeight)
        {
            if((($('#' + sToggleName + 'Description .' + sToggleName + 'Text').height()) / iContentTextSize) < fHeight)
            {
                $('#' + sToggleName + 'Description .' + sToggleName + 'Text').height((fHeight - 1) + 'em');
            }

            var fTextHeight = ($('#' + sToggleName + 'Description').height() / iContentTextSize) + 3;
            var fDownPercentage = fTextHeight / fHeight * 100;
            var fUpPercentage = fHeight / fTextHeight * 100;
            
            $('#' + sToggleName + 'DescriptionToggler').css({display: 'block'}).click(function ()
            {
                if(bDown == false)
                {
                    $('#' + sToggleName + 'Description').animate(
                        {height: (fTextHeight * iContentTextSize)}, 
                        400, '', 
                        function(){$('#' + sToggleName + 'Description').height(fTextHeight + 'em');}
                    );
                    $(this).text(sTextUp).removeClass(sClassNameDn).addClass(sClassNameUp);
                    bDown = true;
                }
                else
                {
                    $('#' + sToggleName + 'Description').animate(
                        {height: (fHeight * iContentTextSize)}, 
                        400, '', 
                        function(){$('#' + sToggleName + 'Description').height(fHeight + 'em');}
                    );
                    $(this).text(sTextDown).removeClass(sClassNameUp).addClass(sClassNameDn);
                    bDown = false;
                }
            });            
            $('#' + sToggleName + 'DescriptionToggler').text(sTextDown).removeClass(sClassNameUp).addClass(sClassNameDn);
        }
        $('#' + sToggleName + 'Description').height(fHeight + 'em');
    }
    
    // tabnavi product detail
    $("#detailNavi").glider({});

    // blogticker startseite
    $('#blogTicker').each(function()
    {
        $oTicker = $(this);
        $oTickerContent = $oTicker.find('.scrollContent');
        var iWidth = $oTicker.innerWidth() - $oTicker.find('h2').outerWidth(true) - $oTicker.find('a.blogLink').outerWidth(true);
        //var iWidth = $oTicker.innerWidth(true);
        //var iCountNews = $oTickerContent.width(iWidth).find('li').width(iWidth).length - 1;
        var iCountNews = $oTickerContent.width(iWidth).find('li').css({opacity: 0.01}).width(iWidth).length - 1;
        var bAnimationRunning = false;
        var iAnimationSpeed = 1000;
        var iCurrentPosition = 0
        $oTickerContent.find('li:nth-child(' + (iCurrentPosition + 1) + ')').fadeTo(iAnimationSpeed, 1);
        function next()
        {
            if(bAnimationRunning)
            {
                return;
            }
            
            iCurrentPosition ++;
            bAnimationRunning = true;
            if(iCurrentPosition > iCountNews)
            {
                iCurrentPosition = 0;
            }
            $oTickerContent.animate(
                { left: (-iCurrentPosition * iWidth) + 'px' }, 
                iAnimationSpeed, 
                "easeInOutCirc",
                function()
                {
                    bAnimationRunning = false;
                }
            );
            $oTickerContent.find('li:nth-child(' + iCurrentPosition + ')').fadeTo(iAnimationSpeed, 0.01);
            $oTickerContent.find('li:nth-child(' + (iCurrentPosition + 1) + ')').fadeTo(iAnimationSpeed, 1);
        }
        setInterval(next, 3000);
        
        return $oTicker;
    });


    // blog team table
    $('.team table').prepend($('<tr></tr>').prepend($('<th></th>').attr({colSpan: 2}).text($('.team h1').text())));
    
    // nice checkboxes / radios
    $('.inputcheckboxes label, .inputradios label').not('.inputcheckboxes.none label').each(function()
    {
        $(this).contents().filter(function(){ return this.nodeType != 1 || this.nodeName == 'A'; }).wrap("<span/>")
    });
    
    
    /*
    // sifr
    $.sifr({path: sBaseUrl + 'swf'});
    $('#content h1').sifr({font: 'tapir', offsetTop: 10});
    $('h2, h3').sifr({font: 'tapir'});
    $('#nav li.mainLi a:not(#nav li ul a)').sifr({font: 'tapir'});
    */
}

initVoucherForm = function()
{
    $('#size_anderer_betrag').wrapInner('<a id="voucherCustomValue" href="#voucherCustomValueFormDiv"></a>');
    $('#voucherCustomValue').css({padding: 0}).fancybox(
    {
        frameWidth: 600,
        frameHeight: 250,
        onLoad: function()
        {
            $('#customValue').focus().bind('keyup', function(event)
            {
                sValue = this.value;
                if (!event) event = window.event
                var key = event.keyCode || event.which;

                if(key == 37 || key == 39)
                {
                    return;
                }
                else if(key == 13)
                {
                    $('#voucherCustomValueForm a.button').trigger('click');
                }
                else if(key == 190 && sValue.indexOf('.') == sValue.lastIndexOf('.'))
                {
                    return;
                }
                else if(key == 188 && sValue.indexOf(',') == sValue.lastIndexOf(','))
                {
                    return;
                }

                sValue = sValue.replace(',', '.');
                sValue = sValue.replace(/[^0-9.]/gi, '');
                sValue = parseFloat(sValue);
                if(isNaN(sValue)) sValue = 0;
                sValue = sValue + '';
                sValue = sValue.replace('.', ',');
                this.value = sValue;
            }); 
            $('#voucherCustomValueForm a.button').click(function(event)
            {
                fValue = parseFloat($('#customValue').val().replace(',', '.'));
                if(fValue > 0 && !isNaN(fValue))
                {
                    aColors['none']['aSizes']['anderer_betrag']['fPrice'] = fValue;
                    $('#basketForm input[name=customVoucherValue]').val(fValue);
                    $.fn.fancybox.close();
                    $('#size_anderer_betrag').trigger('click');
                    $('#sizeSelector').trigger('click');
                }
                
                event.preventDefault();
            });
        },
        onClose: function()
        {
            
        },
        zoomSpeedIn: 300, zoomSpeedOut: 200, 
        overlayShow: true, overlayOpacity: 0.05, zoomOpacity: true, 'easingIn': 'easeOutQuad', 'easingOut': 'easeOutQuad'
    });
}

// runde ecken (box & select) und dropshadow
roundCorners = function ()
{
    // selectboxes
    $('#nav .lastLi, .naviSelectBox .lastLi, .selectBox .lastLi').each(function()
    {
        var oNewLi = document.createElement("li");
        oNewLi.className = "navBottom";
        var oNewDiv = document.createElement("div");
        oNewLi.appendChild(oNewDiv);
        $(this).after(oNewLi);
    });

    $('#nav .navBottom').each(function()
    {
        $(this).width($(this).parent().width());
    });

    // roundedBox
    $('.roundedBox').each(function()
    {        
        // duplicate 
        var oNewElement = this.cloneNode(true);
        
        // wrapper
        var roundCorner = document.createElement('div');
        roundCorner.className = this.className;
        this.className = '';
        
        roundCorner.style.width = this.style.width;
        oNewElement.style.width = '';
        roundCorner.style.margin = this.style.margin;
        oNewElement.style.margin = '';
        
        // top
        var top = document.createElement('div');
        top.className = 'top';
        var topDiv = document.createElement('div');
        top.appendChild(topDiv);
        
        // content
        var content = document.createElement('div');
        content.className = 'content autoclear';
        content.appendChild(oNewElement);
        
        // bottom
        var bottom = document.createElement('div');
        bottom.className = 'bottom';
        var bottomDiv = document.createElement('div');
        bottom.appendChild(bottomDiv);
                
        // appending
        roundCorner.appendChild(top);
        roundCorner.appendChild(content);
        roundCorner.appendChild(bottom);

        // replace
        this.parentNode.replaceChild(roundCorner, this);
    });
}

applyDropShadows = function ()
{
    $('.dropShadowContainer').each(function()
    {
        // duplicate
        var oNewElement = this.cloneNode(true);
        
        // wrapper
        var dropShadow = document.createElement('div');
        dropShadow.className = 'dropShadow';
        
        // top
        var top = document.createElement('div');
        top.className = 'top';
        var topDiv = document.createElement('div');
        topDiv.style.width = ($(this).width());
        top.appendChild(topDiv);
        
        // content
        var content = document.createElement('div');
        content.className = 'content';
        content.appendChild(oNewElement);
        
        // bottom
        var bottom = document.createElement('div');
        bottom.className = 'bottom';
        
        // shadow
        dropShadow.appendChild(top);
        dropShadow.appendChild(content);
        dropShadow.appendChild(bottom);

        // replace
        this.parentNode.replaceChild(dropShadow, this);
    
    });
}

// img runde ecken
roundImgCorners = function ()
{
    $('.popupImg').addClass('roundCornersContainer').addClass('autoclear');
    $('.roundCornersContainer').wrap('<span class="roundCorners"><span class="leftTop"></span></span>');
    $('.roundCorners')
        .append('<span class="rightTop"></span><span class="leftBottom"></span>')
        .each(function()
        {
            $(this).addClass($(this).find('.roundCornersContainer').attr('class')).removeClass('popupImg');
        }
    );

    $('.roundCorners img').removeAttr('align').css({'float': 'none'});    
}

// carousels
var carousel = null;
loadCarousels = function ()
{
    $("#carouselContainer1 .container").jCarouselLite(
    {
        btnNext: "#carouselContainer1 .next_button",
        btnPrev: "#carouselContainer1 .previous_button",
        easing: "easeInOutQuint",
        speed: 800,
        circular: false,
        visible: 4,
        scroll: 4
    });

    $("#carouselContainer2 .container").jCarouselLite(
    {
        btnNext: "#carouselContainer2 .next_button",
        btnPrev: "#carouselContainer2 .previous_button",
        easing: "easeInOutQuint",
        speed: 800,
        circular: false,
        visible: 4,
        scroll: 4
    });

    $("#carouselContainer3 .container").jCarouselLite(
    {
        btnNext: "#carouselContainer3 .next_button",
        btnPrev: "#carouselContainer3 .previous_button",
        easing: "easeInOutQuint",
        speed: 800,
        circular: false,
        visible: 4,
        scroll: 4
    });
}

var oFancyBoxOptions = {hideOnContentClick: true, zoomSpeedIn: 400, zoomSpeedOut: 400, overlayShow: true, overlayOpacity: 0.01, zoomOpacity: true, 'easingIn': 'easeOutQuad', 'easingOut': 'easeOutQuad'};
var oFancyBoxLensOptions = {hideOnContentClick: true, zoomSpeedIn: 400, zoomSpeedOut: 400, overlayShow: true, overlayOpacity: 0.01, zoomOpacity: true, 'easingIn': 'easeOutQuad', 'easingOut': 'easeOutQuad', el: "#zoomImageLink"};

initFancyBox = function ()
{
    $('.thumbList a:visible').click(function()
    {
        updateColor(this);
        doImageTransition(this);
        return false;
    });

    $(".popupImg").fancybox(oFancyBoxOptions);
    $("#zoomImageLink").fancybox(oFancyBoxOptions);
    $("#zoomImageLens").fancybox(oFancyBoxLensOptions);
 
    $("#orderForm button").fancybox({
        zoomSpeedIn: 400, zoomSpeedOut: 300, frameWidth: 600, frameHeight: 420, overlayShow: true, overlayOpacity: 0.9, 'easingIn': 'easeOutQuad', 'easingOut': 'easeOutQuad'
    });
    $('.popupLink').each(function()
    {
        if (this.href.indexOf('?') != -1)
        {
            this.href += '&media=popup';
        }
        else
        {
            this.href += '?media=popup';
        }    
    }).fancybox({ zoomSpeedIn: 400, zoomSpeedOut: 300, frameWidth: 800, frameHeight: 540, overlayShow: true, overlayOpacity: 0.01, 'easingIn': 'easeOutQuad', 'easingOut': 'easeOutQuad' });
}

var sImage = '';
doImageTransition = function (oCurrentThumbnail)
{
    var sImage = $(oCurrentThumbnail).attr('href');

    if($('#zoomImg').attr('src') == sImage)
    {
        return false;
    }
    
    var sTransition = /^transition\[(.+)\]$/.exec( $(oCurrentThumbnail).attr('rel') )[1];

    aRelArray = sTransition.split(",");
    iXSize = aRelArray[0];
    iYSize = aRelArray[1];
    zoomLink = aRelArray[2];
    if(iXSize)
    {
        iHXSize = $('#zoomImageLink').width()/16;
        iXMargin = numberFormat(((iHXSize - iXSize) / 2), 4, '.', '');
    }
    else
    {
        iXPos = 0;
    }
    if(iYSize)
    {
        iHYSize = $('#zoomImageLink').height()/16;
        iYMargin = numberFormat(((iHYSize - iYSize) / 2), 4, '.', '');
    }
    else
    {
        iYPos = 0;
    }
    
    if(iXMargin < 0) iXMargin = 0;
    if(iYMargin < 0) iYMargin = 0;
    
    if(zoomLink) 
    {
        $("#zoomImageLink").attr('href', zoomLink).fancybox(oFancyBoxOptions);
        $('#zoomImageLens').show().fancybox(oFancyBoxLensOptions);
    }
    else
    {
        $('#zoomImageLink').unbind('click').click(function(){return false;});
        $('#zoomImageLens').hide();
    }
    
    var eImage = document.createElement( 'img' );
    $('#zoomImg').fadeOut(100, function(){$(eImage).attr('src', sImage);});
    eImage.onload = function()
    {
        $('#zoomImg').css( 
        { 
            width: iXSize + 'em', 
            height: iYSize + 'em', 
            paddingTop: iYMargin + 'em', 
            paddingBottom: iYMargin + 'em',
            paddingLeft: iXMargin + 'em', 
            paddingRight: iXMargin + 'em'
        }).attr('src', sImage).fadeIn(500);
    }
}

if (top != self && window.location.search.indexOf('popup') == -1)
{
    top.location = self.location;
}

$(document).ready(function(){
    loadCarousels();
    roundCorners();
    roundImgCorners();
    if(!($.browser.msie)) applyDropShadows();
    initFancyBox();
    if($.browser.msie) applyDropShadows();
    startApp();
    updateCheckoutPrice();
    if ($.fn.pngFix) $(document).pngFix({blankgif: ("https:" == document.location.protocol ? sSslBaseUrl : sBaseUrl) + 'images/blank.gif'});
});

