﻿function initScrollbar() {
    var elemWidth = $('.product_list_column').width();
    var elemCount = $('.product_list_column').length;
    var scrollContentWidth = (elemWidth * elemCount);
    
    $('#product_list_container').css('width', scrollContentWidth);
    // this initialises the demo scollpanes on the page.
    $('#product_list_scrollcontent').jScrollPane({ showArrows: true, horizontalArrowPositions: 'after', horizontalDragMaxWidth: 600});
    
    addMouseOverAndOutForScrollbar();
    
    //$('.jScrollPaneTrack').css('left', 0);



   //$('.jScrollArrowLeft').attr("style", "width: 20px; height: 20px;");
   //$('.jScrollArrowRight').attr("style", "width: 20px; height: 20px;");

    //width: 20px; height: 20px; position: absolute; top: 0pt; left: 920px;
    //$('.jScrollPaneTrack').css('width', 900);
    //$('.jScrollPaneTrack').append('<div class="scrollPaneMini">&nbsp;</div>');

   /* $('.jScrollArrowLeft').css("position", "absolute");
    $('.jScrollArrowLeft').css("width", 20);
    $('.jScrollArrowLeft').css("height", 20);
    $('.jScrollArrowLeft').css("top", 0);
    $('.jScrollArrowLeft').css("left", 900);
    */

    //width: 20px;height:15px; position: absolute; z-index: 88888; top: 0px; left: 750px;

    //jScrollPaneTrack
}

function addMouseOverAndOutForScrollbar() {
    $('.jspTrack').bind("mouseover", function () {
        $('.jspDrag').addClass("over");
    });

    $('.jspTrack').bind("mouseout", function () {
        $('.jspDrag').removeClass("over");
    });
}

var open = false;
function initSelectBox() {
    /*$('#' + elemId).selectbox();
    
    var imagePadding = $('.selectbox').css('padding-right');
    var wrapperWidth = $('div.selectbox-wrapper').css('width');

    $('div.selectbox-wrapper').css('width', parseInt(wrapperWidth) + parseInt(imagePadding));*/

    $('#sel_designer').bind("click", function () {
        if (!open) {
            $("#designer_selected").css("display", "block");
            open = true;
        } else { 
         $("#designer_selected").css("display", "none");
        open = false;
        }
    });

    $('#designer_carousel li').bind("click", function () {
        var name = this.innerHTML;
        var id = this.id.replace("designer_", "");

        $("#designer-uid").val(id);
        $("#sel_designer").html(name);
        $("#designer_selected").css("display", "none");

        $("#designer-select-form").submit();
    });
}

function initDetailPage(detailId, numThumbs) {
    // We only want these styles applied when javascript is enabled
    //$('div.navigation').css({ 'width': '300px', 'float': 'left' });
    $('div.content').css('display', 'block');
    $('div.content').css('width', 'auto');

    // Initially set opacity on thumbs and add
    // additional styling for hover effect on thumbs
    var onMouseOutOpacity = 0.67;
    $('#thumbs ul.thumbs li').opacityrollover({
        mouseOutOpacity: onMouseOutOpacity,
        mouseOverOpacity: 1.0,
        fadeSpeed: 'fast',
        exemptionSelector: '.selected'
    });

    // Initialize Advanced Galleriffic Gallery
    var gallery = $('#thumbs').galleriffic({
        delay: 2500,
        enableKeyboardNavigation: false,
        numThumbs: (numThumbs > 1) ? numThumbs : 0,
        preloadAhead: 10,
        enableTopPager: false,
        enableBottomPager: false,
        maxPagesToShow: 1,
        imageContainerSel: '#slideshow',
        controlsContainerSel: '#controls',
        captionContainerSel: '#caption',
        loadingContainerSel: '#loading',
        renderSSControls: false,
        renderNavControls: false,
        enableHistory: false,
        autoStart: false,
        syncTransitions: true,
        defaultTransitionDuration: 900,
        onSlideChange: function (prevIndex, nextIndex) {
            // 'this' refers to the gallery, which is an extension of $('#thumbs')
            this.find('ul.thumbs').children()
							.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
							.eq(nextIndex).fadeTo('fast', 1.0);
        },
        onPageTransitionOut: function (callback) {
            this.fadeTo('fast', 0.0, callback);
        },
        onPageTransitionIn: function () {
            this.fadeTo('fast', 1.0);
        }
    });

    var allElems = $('ul.thumbs li img');
    for (var i = 0; i < allElems.length; i++) {
        var thisElem = allElems[i];
        thisElem.src = 'fileadmin/system/images/gallery_bullet.gif';
        thisElem.width = '15';
        thisElem.height = '15';
    }

    //added Links
    var toggleIsOpen = false;
    $('#technical-details').click(function () {
        $('#technical-details-entry').slideToggle('slow', function () {
            toggleIsOpen = !toggleIsOpen;

            if (toggleIsOpen) {
                $('#product_technical').attr("class", "open");
            } else {
                $('#product_technical').attr("class", "close");
            }
        });

        return false;
    });

    $("#product_remember").click(function () {
        var data = "eID=ajax_ctrl&view=remember&act=add&detailId=" + detailId;
        $("#remember-call-out-box").css("display", "none");
        ajaxCall(getCurrentLocation(), "GET", "#item-pane", "html", data, productRememberHelperWithCallOutBox, null);

        return false;
    });
}

var isProductAdded = false;
var outBoxMsg;
function productRememberHelperWithCallOutBox(data, resultId) {
    pushData(data, resultId);
    $("#call-out-box-msg").html(outBoxMsg);
    $("#remember-call-out-box").fadeIn("slow");
    window.setTimeout("$('#remember-call-out-box').fadeOut('slow')", 4000);
}

function ajaxCall(address, type, resultID, dataType, data, successAction, errorAction) {
    if (address != null && address != "" && $(resultID) != "" && (type == "POST" || type == "GET")) {
        var contentUid = $("#tt-content-uid-field").val();

        if (contentUid != "" && contentUid != null) {
            data += "&ttUid=" + contentUid;
        }

        $.ajax(
         {
             type: type,
             url: address,
             cache: false,
             dataType: dataType,
             data: data,
             beforeSend: function () {
                 showLoadingContainer(resultID);
             },
             success: function (result) {
                 hideLoadingContainer(resultID);

                 if (successAction != null) {
                     successAction(result, resultID);
                 }
             },
             error: function (xhr, status, thrownError) {
                 hideLoadingContainer(resultID);

                 if (errorAction != null) {
                     errorAction(xhr, status, thrownError);
                 }
             }
         });
    }
 }

 function hideLoadingContainer(elemId) {
     var el = $(elemId);

     if (el.length == 1) {
         el.html("");
     }
 }

 function showLoadingContainer(elemId) {
     var el = $(elemId);

     if (el.length == 1) {
         el.html('<div id="ajax-preloader-img">&nbsp;</div>');
     }
 }

 function loadDetails(detailId, resultId, act, category, designer) {
     var data = "eID=ajax_ctrl&view=detail&detailId=" + detailId;

     if (act != null) {
         data += "&act=" + act;
     }

     if (category != null && category != "") {
         data += "&category=" + category;
     }

     if (designer != null && designer != "") {
         data += "&designer=" + designer;
     }
     
     ajaxCall(getCurrentLocation(), "GET", resultId, "html", data, pushData, null);
 }

 function detailLoaded(curDetailId, resultId, itemFound, category, designer) {
     if (!itemFound) {
         $("#product_detail_navigation").css("display", "none");

         return;
     }

     initNavigationFields(curDetailId, resultId, loadDetails, category, designer);

     $("#product_detail_navigation").css("display", "block");
 }

 function loadDesignerProduct(curId, resultId, act) {
     var data = "eID=ajax_ctrl&view=designer";
     
     if (curId != null) {
         data += "&curId=" + curId;
     }

     if (act != null) {
         data += "&act=" + act;
     }

     ajaxCall(getCurrentLocation(), "GET", "#products_topten_dynamic_content", "html", data, pushDesignerProductData, null);
 }

 function pushDesignerProductData(data, elemId) {
     if (data != null && data != "") {
         pushData(data, elemId);
         $("#products_topten_navigation").css("display", "block");
         $("#products_topten").css("display", "block");
     } else {
         $("#products_topten").css("display", "none");
     }
 }

 function initNavigationFields(curId, resultId, loadFunction, category, designer) {
     var prev = $("#previous-link");
     var next = $("#next-link");
     
     if (prev.length > 0) {
         prev.unbind();
         prev.bind("click", function () {
             if (loadFunction != null)
                 loadFunction(curId, resultId, "prev", category, designer);
         });
     }

     if (next.length > 0) {
         next.unbind();
         next.bind("click", function () {
             if (loadFunction != null)
                 loadFunction(curId, resultId, "next", category, designer);
         });
     }

    $(document).unbind();
    $(document).bind("keydown", function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        switch (key) {
            case 37: // left arrow
                loadFunction(curId, resultId, "prev", category, designer);
                e.preventDefault();
                break;
            case 39: // right arrow
                loadFunction(curId, resultId, "next", category, designer);
                e.preventDefault();
                break;
        }
    });
 }

 function pushData(data, elemId) {
    $(elemId).html(data);
 }

 function getCurrentLocation() {
     var loc = String(window.location);

     loc = loc.substr(0, loc.lastIndexOf("/") + 1);
     loc += 'index.php';

     return loc;
 }

 function initContactForm() {
     $.each($("#contact-form input[type='text'], #contact-form textarea"), function (index, elem) {
         $(elem).unbind();
         $(elem).bind("focus", function () {
             $("#contact-form p").removeClass("selected");
             $(elem).parent().addClass("selected");

             if (elem.tagName.toLowerCase() == "textarea") {
                 if ($(elem).val() == "Your Message") {
                     $(elem).val("");
                 }
             }
         });
     });
 }

 function makeMyProductsRemovable() {
     var elemArray = new Array("#item-pane", "#myproducts_entries_contact");

     $.each(elemArray, function (ind, parentContainer) {
         $.each($(parentContainer + ' div.myproducts_item .recycler a'), function (index, elem) {
             var el = $(elem);
             var id = el.attr("id").replace("uid-", "");
             
             el.unbind();
             el.bind("click", function () {
                 var data = "eID=ajax_ctrl&view=remember&act=remove&detailId=" + id;

                 if (parentContainer == "#myproducts_entries_contact") {
                     data += "&overview=1";
                 }
                 $("#remember-call-out-box").css("display", "none");
                 ajaxCall(getCurrentLocation(), "GET", parentContainer, "html", data, pushData, null);

                 return false;
             });
         });
     });
 }

 var myProductsToogleIsOpen = false;

 function initMyProducts() {
    var elemWidth = $('.myproducts_item').width() + 20;
     var elemCount = $('.myproducts_item').length;
     var scrollContentWidth = (elemWidth * elemCount);

     scrollContentWidth = (scrollContentWidth == 0) ? "auto" : scrollContentWidth;
     
     $('#item-pane').css('width', scrollContentWidth);

     if (myProductsToogleIsOpen) {
        $("#entry-container").jScrollPane();

         //doppelte Linie in myProducts entfernen
         if ($("#myproducts_entries .jScrollPaneTrack").length > 0) {
             $("#myproducts_entries .jScrollPaneContainer").css("background", "none");
         } else {
             $("#myproducts_entries .jScrollPaneContainer").css("background","");
         }

         addMouseOverAndOutForScrollbar();
     }

     makeMyProductsRemovable();
     if (!myProductsToogleIsOpen) {
         $('#myproducts_entries').hide();
     }

     $("#my_products").unbind();
     $("#my_products").bind("click", function () {

        $("#item-pane").html("");
        $("#footer").css("top", $("#footer").offset().top);
        $("#page").css("padding-bottom", 280);

        
        $('#myproducts_entries').slideToggle('slow', function () {
            myProductsToogleIsOpen = !myProductsToogleIsOpen;

            if (myProductsToogleIsOpen) {
                window.setTimeout("loadMyProducts()", 100);
            }

            if (myProductsToogleIsOpen) {
                $('#my_products').attr("class", "open");
                $("#myproducts_wrap").attr("class", "open");
                scrollTo(0, 10000000);
            } else {
                $("#myproducts_entries .jScrollPaneTrack").css("display", "none");
                $('#my_products').attr("class", "close");
                $("#myproducts_wrap").attr("class", "close");
                $("#page").css("padding-bottom", 120);
                $("#footer").css("top", "");
                scrollTo(0, 0);
            }
        });

        return false;
    });
   
  }

function loadMyProducts() {
    var data = "eID=ajax_ctrl&view=remember";
    ajaxCall(getCurrentLocation(), "GET", "#item-pane", "html", data, producsToogleHelper, null);
}

function producsToogleHelper(data, elemId) {
    $(".jScrollPaneTrack").css("display", "block");
    
    pushData(data, elemId);
}

jQuery.fn.onImagesLoaded = function (_cb) {
    return this.each(function () {

        var $imgs = (this.tagName.toLowerCase() === 'img') ? $(this) : $('img', this),
        _cont = this,
            i = 0,
    _done = function () {
        if (typeof _cb === 'function') _cb(_cont);
    };

        if ($imgs.length) {
            $imgs.each(function () {
                var _img = this,
        _checki = function (e) {
            if ((_img.complete) || (_img.readyState == 'complete' && e.type == 'readystatechange')) {
                if (++i === $imgs.length) _done();
            }
            else if (_img.readyState === undefined) // dont for IE
            {
                $(_img).attr('src', $(_img).attr('src')); // re-fire load event
            }
        }; // _checki \\

                $(_img).bind('load readystatechange', function (e) { _checki(e); });
                _checki({ type: 'readystatechange' }); // bind to 'load' event...
            });
        } else _done();
    });
};


function linkToDetailPage(uri) {
    location.href = uri;
}
