var SHOP_PATH = parent.location.protocol + '//www.kiebel.de/';

$(document).ready(function() {

    /* general highslide settings */

    hs.Expander.prototype.onShowLoading = function () {
        $("body").css({'cursor' : 'wait'});
        $("body a").css({'cursor' : 'wait'});
        $("body input").css({'cursor' : 'wait'});
        $("body select").css({'cursor' : 'wait'});
        return false;
    }

    hs.Expander.prototype.onHideLoading = function () {
        $("body").css({'cursor' : ''});
        $("body a").css({'cursor' : ''});
        $("body input").css({'cursor' : ''});
        $("body select").css({'cursor' : ''});
    }

    hs.minWidth = 385;
    hs.showCredits = false;
    hs.preserveContent = false;
    hs.expandDuration = 150;
    hs.restoreDuration = 0;
    hs.outlineType = 'rounded-white';
    hs.wrapperClassName = 'draggable-header';
    hs.graphicsDir = SHOP_PATH+'out/basic/src/hs/';


    $("#slider-container").easySlider({
            auto: true,
            continuous: true,
            pause: 5000,
            speed: 500
    });

    var position = 0;
    var cases = $('#caseSlider li').size();

    $("#caseSlider").parent().addClass('scroll-gallery');

    updateArrows = function() {
        if ((position + 4) >= cases) {
            $("#arrowRight").css('visibility', 'hidden');
        } else {
            $("#arrowRight").css('visibility', 'visible');
        }

        if (position <= 0) {
            $("#arrowLeft").css('visibility', 'hidden');
        } else {
            $("#arrowLeft").css('visibility', 'visible');
        }
    };

    updateArrows();

    $("#arrowRight").click(function(event) {
      if ((position + 4) >= cases) return
      $('#caseSlider li').animate({
        left: '-=154'
      });
      position++;
      updateArrows();
    });

    $("#arrowLeft").click(function(event) {
      if (position <= 0) return;
       $('#caseSlider li').animate({
        left: '+=154'
      });
      position--;
      updateArrows();
    });

    $("a.popup-plain").click(function(event) {
        hs.src = $(this).attr('href') + '?plain=1';
        hs.htmlExpand(this, { objectType: 'iframe' , width: 625 , minWidth: 500 , headingText: this.innerHTML});
        event.preventDefault();
    });

    $("a.zoom").click(function(event) {
        var src = $('.product-image:first', $(this).parent()).attr('src');
        src = src.replace(/\/pictures\//g, "/pictures/z");

        hs.expand(this, {
            outlineType: 'rounded-white',
            src: src
        });
        event.preventDefault();
    });

    $(".morepics a").click(function(event) {
        $("a.zoom", $(this).parent().parent()).trigger('click');
    });

    $(".teasysconf .footer li a").click(function(event) {
        $(".teasysconf .teaserContent").hide();
        $("#"+this.id.replace(/Tab/g, "Content")).show();
    });

    $(".details div.picture div, .teasysconf div.picture div").click(function(event) {
        $("a.zoom", $(this).parent()).trigger('click');
    });

    /* w3c zoomfix */

    $("#zoom #zoom_img").load(function() {
        oxid.popup.resize('zoom', this.width + 4, this.height + 32);
    });

    /* topnav subnav handler */

    $("#mainnav ul li").hoverIntent(function() {
        if ($(this).attr('id') == 'logo') return;
        var element = $(this).attr('id').replace(/main/g, "tab");
        $("#subnav ul.active").removeClass('active');
        $("#subnav ul").hide();
        $('#' + element).show();
    }, function() {});

    /* tabmenu handler */

    $('.tabmenu li a').click(function() {
        if ($(this).parent().hasClass('active')) return;
        $('#body .tabcontent').addClass('hide');
        $('#body .tabmenu li').removeClass('active');
        $(this).parent().addClass('active');
        $('#' + $(this).attr('rel')).removeClass('hide');
    });

    /* list view toggle */

    $("#viewGallery").click(function() {
        $("#body .product").removeClass('thin');
        $("#body .product").addClass('gallery');
        $("#viewThin").removeClass('active');
        $("#viewGallery").addClass('active');
        /*
        $("#body .product img").each(function() {
                var src = this.src;
                src = src.replace(/icon/g, "0");
                src = src.replace(/_ico/g, "_th");
                this.src = src;
        });
        */
        $.ajax({ url: (document.URL.indexOf('?') >= 0 ? '&' : '?') + 'ajax=updateview&view=gallery', dataType: 'text' });
    });

    $("#viewThin").click(function() {
        $("#body .product").removeClass('gallery');
        $("#body .product").addClass('thin');
        $("#viewGallery").removeClass('active');
        $("#viewThin").addClass('active');
        /*
        $("#body .product img").each(function() {
                var src = this.src;
                src = src.replace(/\/0/g, "/icon");
                src = src.replace(/_th/g, "_ico");
                this.src = src;
        });
        */
        $.ajax({ url: (document.URL.indexOf('?') >= 0 ? '&' : '?') + 'ajax=updateview&view=thin', dataType: 'text' });
    });

    /* left mini tabmenu */

    $("#tabsearch").click(function() {
        $('#left .tabcontent').removeClass('active');
        $("#tabnav").css('backgroundPosition', '0 ' + (-49 * 0) + 'px');
        $.ajax({ url: (document.URL.indexOf('?') >= 0 ? '&' : '?') + 'ajax=updatetab&tab=searchform', dataType: 'text' });
        $('#' + $(this).attr('rel')).addClass('active');
    });

    $("#tabbasket").click(function() {
        $('#left .tabcontent').removeClass('active');
        $("#tabnav").css('backgroundPosition', '0 ' + (-49 * 1) + 'px');
        $.ajax({ url: (document.URL.indexOf('?') >= 0 ? '&' : '?') + 'ajax=updatetab&tab=minibasket', dataType: 'text' });
        $('#' + $(this).attr('rel')).addClass('active');
    });

    $("#tabnoticelist").click(function() {
        $('#left .tabcontent').removeClass('active');
        $('#tabnav').css('backgroundPosition', '0 ' + (-49 * 2) + 'px');
        $.ajax({ url: (document.URL.indexOf('?') >= 0 ? '&' : '?') + 'ajax=updatetab&tab=mininoticelist', dataType: 'text' });
        $('#' + $(this).attr('rel')).addClass('active');
    });

    /* sysconf accessories handler */

    $("#accessories input:checkbox").click(function() {
        var bIsChecked = $(this).is(':checked');
        var element = $('.price big', $(this).parent().get(0));
        var text = element.text();
        var result = /([-\+]) ([,\.0-9]+) .*/.exec(text);

        if (result && result[1] && result[2]) {
            text = result[1] + result[2];
            result = parseFloat(text.replace((/,/g), "."));
            var value = parseFloat($('#price span.data').text());

            if (!bIsChecked) result = 0 - result;
            value += result;

            $('#price span.data').text(value);
            $('#price big').html(formatPrice(value));

            if (bIsChecked) {
                $(this).closest('.product').addClass('selected');
            }
            else {
                $(this).closest('.product').removeClass('selected');
            }
            
        }
    });

    /* sysconf inline info handler */

    $("#overview .content a").click (function(event)	{
        hs.src = $(this).attr('href') + '?ajax=longdesc';
        hs.htmlExpand(this, { objectType: 'iframe' , width: 385, headingText: $(this).text()});
        event.preventDefault();
    });


    $("#accessories .product .details .h3 a").click (function(event)	{
        hs.src = $(this).attr('href') + '?ajax=longdesc';
        hs.htmlExpand(this, { objectType: 'iframe' , width: 385, headingText: $(this).text()});
        event.preventDefault();
    });

    $("#accessories .product a.picture").click (function(event)	{
        $(".details .h3 a", $(this).parent()).trigger('click');
        event.preventDefault();
    });

    $(".bysysconf .product a.picture").click (function(event)	{
        $(".details .h3 a", $(this).parent()).trigger('click');
        event.preventDefault();
    });

    $(".product.accessories").hover(function() {
        $(this).addClass("hover");
        $(this).css('cursor', 'pointer');
    }, function() {
        $(this).removeClass("hover");
        $(this).css('cursor', 'auto');
    });

    $("#accessories .product.accessories").click (function(event) {
        var bIsChecked = $('input', this).is(':checked');

        if ($(event.target).is('a')) {
            if (!$(event.target).parent().hasClass('actions')) return;
            $("strong.h3 a", this).trigger('click');
            event.preventDefault();
            return;
        }
        else if ($(event.target).is('input')) {
            return;
        }
        else if ($(event.target).is('div')) {
            if ($('a.picture', event.target).length == 0 && $('img', event.target).length > 0) return;
        }
        else if ($(event.target).is('img')) {
            return;
        }

        $('input', this).attr('checked', !bIsChecked)
        $('input', this).trigger('click');
        $('input', this).attr('checked', !bIsChecked);
        event.preventDefault();
    });

   $("#servicepacks .product.accessories").click (function(event) {
        if ($(event.target).is('input')) return;
        
        $('#servicepacks .product.accessories input').attr('checked', false);
        $('#servicepacks .product.accessories').removeClass('selected');

        $('input', this).attr('checked', true);
        $('input', this).trigger('click');
        
        event.preventDefault();
    });

    /* adding running clock */

    window.date	= new Date();
    window.date.setTime(parseInt($("#clock #timestamp").text()) * 1000);

    window.setInterval(function() {
            $("#clock").text(''
                    + addZero(window.date.getDate()) + '.'
                    + addZero(window.date.getMonth() + 1) + '.'
                    + window.date.getFullYear() + ' '
                    + addZero(window.date.getHours()) + ':'
                    + addZero(window.date.getMinutes()) + ':'
                    + addZero(window.date.getSeconds())
            );
            window.date.setTime(window.date.getTime() + 1000);
    }, 1000);

    $("#body .morepics").click (function(event) {
        event.preventDefault();
    });

    /* sysconf price update routines */
    
    $("#servicepacks .product input").click (function()	{
        $("#servicepacks .product").removeClass('selected');
        $(this).parent().parent().addClass('selected');
        
        var parent = $(this).parent().parent().parent().get(0);

        if (typeof parent._diff == 'undefined') parent._diff = 0;

        var text = $('.price big', $(this).parent().get(0)).text();
        var result = /([-\+]) ([,\.0-9]+) .*/.exec(text);
        var value = 0.0, diff = 0.0;

        if (result && result[1] && result[2]) {
            text = result[1] + result[2];
            diff = parseFloat(text.replace((/,/g), "."));
            value = parseFloat($('#price span.data').text()) - parent._diff + diff;
            parent._diff = diff;
        }
        else {
            value = parseFloat($('#price span.data').text()) - parent._diff;
            parent._diff = 0;
        }

        $('#price span.data').text(value);
        $('#price big').html(formatPrice(value));
    });
    
    $(".bxsysconf .group-gallery a").click (function()	{
        $(".bxsysconf .group-gallery a").removeClass('selected');
        $(this).addClass('selected');
        var parent = $(this).parent().parent().get(0);
        if (!this.id) return;

        $('input', this).attr('checked', 'checked');

        $('.teasysconf img.picture').hide();
        $('#'+this.id.replace((/articleGallerySelector/g), "articleTeaserPicture")).show();


        if (typeof parent._diff == 'undefined') parent._diff = 0;

        var text = $('span', this).text();
        var result = /\[([-\+]) ([,\.0-9]+) .*\]/.exec(text);
        var value = 0.0, diff = 0.0, url = '';
        
        if (result && result[1] && result[2]) {
            text = result[1] + result[2];
            diff = parseFloat(text.replace((/,/g), "."));
            value = parseFloat($('#price span.data').text()) - parent._diff + diff;
            parent._diff = diff;
        }
        else {
            value = parseFloat($('#price span.data').text()) - parent._diff;
            parent._diff = 0;
        }

        $("#teaserGalleryContent div.header").hide();
        $("#"+this.id.replace((/articleGallerySelector/g), "productGallery")).show();

        $('#price span.data').text(value);
        $('#price big').html(formatPrice(value));

        var image = $('img:first', this).attr('src');

        image = image.replace((/\/0\//g), "/1/");
        image = image.replace((/_th./g), ".");

        $('#product_img').attr('src', image);
    });

    $(".bxsysconf div.group select").change(function() {
        var element = $('option:selected', this);

        SysConf.updateShortDesc(element.attr('value'), 'info_' + $(this).attr('id'));

        if (parseInt(element.attr('value')) > 0)
            $(".moreinfo", $(this).parent()).show();
        else
            $(".moreinfo", $(this).parent()).hide();

        if (typeof this._diff == 'undefined') this._diff = 0;

        var result = /\[([-\+]) ([,\.0-9]+) .*\]/.exec(element.text());
        var value = 0.0, diff = 0.0, url = '';

        if (result && result[1] && result[2]) {
            text = result[1] + result[2];
            diff = parseFloat(text.replace((/,/g), "."));
            value = parseFloat($('#price span.data').text()) - this._diff + diff;
            this._diff = diff;
        }
        else {
            value = parseFloat($('#price span.data').text()) - this._diff;
            this._diff = 0;
        }

        $('#price span.data').text(value);
        $('#price big').html(formatPrice(value));
    });

    /* some sysconf init */
    
    $(".bxsysconf .group-gallery input").hide();

    $(".bxsysconf .moreinfo").each(function() {
        $(this).attr('href', 'javascript:void(0);')
        if (parseInt($('select option:selected', $(this).parent().parent()).attr('value')) > 0) $(this).css('display', 'inline-block');
    });

    $(".bxsysconf .moreinfo").click (function(event) {
        var element = $('select option:selected', $(this).parent().parent());
        if (!element) return;
        var title = /(.*) \[(.*)\]/.exec(element.text());
        title = title && title[1] ? title[1] : element.text();
        var oxarticle = element.attr('value');
        hs.src = SHOP_PATH+'index.php?cl=details&anid='+oxarticle+'&ajax=longdesc&searchparam=dummy';
        hs.htmlExpand(element.get(0), { objectType: 'iframe' , width: 385, headingText: title});
        event.preventDefault();
    });

    SysConf.addAutoScrolling('.bxsysconf .pricebox');

    if (document.getElementById("map_canvas") && GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(48.480342, 7.92434), 13);
        map.addOverlay(new GMarker(new GLatLng(48.486882, 7.92404)));
        map.addControl(new GSmallMapControl());
    }

    $("a.calcpopup").click (function(event) {
        hs.src = this.href;
        event.preventDefault();
        hs.htmlExpand(this, { objectType: 'iframe' , height: 410 , width: 445 , headingText : 'Rechenmodul' });
    });

    $(".actions a").click (function(event) {
        var element = $('#logo').get(0);
        hs.close();
        var aid = parseInt(getGETParameter(this.href, "aid"));
        if (this.href.indexOf('&addcompare=1') >= 0 && aid) {
            hs.src = SHOP_PATH+'index.php?cl=compare&popup=1&addcompare=1&fnc=tocomparelist&aid='+aid;
            this.href = this.href.replace((/addcompare=1/g), "removecompare=1");
            this.innerHTML = 'aus Vergl. entfernen';
            event.preventDefault();
            hs.htmlExpand(element, { objectType: 'iframe' , width: 600 , headingText : 'Vergleich' });
        }
        else if (this.href.indexOf('&removecompare=1') >= 0 && aid) {
            hs.src = SHOP_PATH+'index.php?cl=compare&popup=1&removecompare=1&fnc=tocomparelist&aid='+aid;
            this.href = this.href.replace((/removecompare=1/g), "addcompare=1");
            this.innerHTML = 'vergleichen';
            event.preventDefault();
            hs.htmlExpand(element, { objectType: 'iframe' , width: 600 , headingText : 'Vergleich' });
        }
        
    });

});

/* help routines */

function addZero(num) {
	return num < 10 ? '0' + num : num;
}

function getGETParameter(url, name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp("[\\?&]"+name+"=([^&#]*)");
    var results = regex.exec(url);
    if(results == null) return "";
    return results[1];
}

function formatPrice(price) {
    price = price.toFixed(2);
    price = price.replace(/\./,",");
    while(price.match(/^(\d+)(\d{3}\b)/)) {
        price = price.replace(/^(\d+)(\d{3}\b)/, RegExp.$1 + '.' + RegExp.$2);
    }
    return price + ' EUR';
}

/* sysconf help routines */

var SysConf = function() {};

SysConf.gotoStep = function(step) {
    $("form input[name='next']").each(function() {
        $(this).val(step);
    });

    $("form input[name='fnc']").each(function() {
        $(this).val('sysconf_switch');
    });

    document.forms.sysconf_.submit();
}

SysConf.updateShortDesc = function(oxarticle, elementID) {
    var container = $('#'+elementID);

    if (oxarticle == '0') {
        if (!container.is(":hidden")) container.slideUp("fast");
        return;
    }

    $.ajax({ url : SHOP_PATH+'modules/kcs_sysconf/kcs_sysconf__tooltips.php?oxarticle=' + oxarticle, dataType: 'text', success: function(result) {
        if (result == '') {
            if (!container.is(":hidden")) container.slideUp("fast");
            return;
        }

        $('div', container).html(result);
        if (container.is(":hidden")) container.slideDown("fast");
    }});
}

SysConf.addAutoScrolling = function(element) {
    var box = $(element);
    var pos = box.position();
    if (!box || !pos) return;
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) return;
    var autoScroll = false;

    var scrollFunc = function() {
        
        if ($(document).scrollTop() > pos.top) {
            if (autoScroll) return;
            box.css({
                'position' : 'fixed',
                'margin-left' : '553px',
                'top' : '0'
            });
            autoScroll = true;
        }
        else if (autoScroll) {
            box.css({
                'position' : 'relative',
                'margin-left' : '5px'
            });
            autoScroll = false;
        }
    };

    $(window).scroll(scrollFunc);
    scrollFunc(); /* call first time manually */
}


toggleZoomPicture = function(element, image) {
    $('.product-image', $(element).parent().parent()).attr('src', image);
    return false;
}