var lightBoxConfig = {
    overlayBgColor: '#FFF',
    overlayOpacity: 0.6,
    imageBlank: BASE_URL + 'templates/images/jquery.lightbox/lightbox-blank.gif',
    imageLoading: BASE_URL + 'templates/images/jquery.lightbox/lightbox-ico-loading.gif',
    imageBtnClose: BASE_URL + 'templates/images/jquery.lightbox/lightbox-btn-close.gif',
    imageBtnPrev: BASE_URL + 'templates/images/jquery.lightbox/lightbox-btn-prev.gif',
    imageBtnNext: BASE_URL + 'templates/images/jquery.lightbox/lightbox-btn-next.gif',
    containerResizeSpeed: 350,
    txtImage: 'Imagine',
    txtOf: 'din'
};
jQuery(document).ready(function($j) {
    if (window.console === undefined) {
        console = {
            log : function() {
                args = arguments;
                $j.each(args, function(key, arg) {
                    if (typeof(arg) == "object") {
                        mess = new Array;
                        for (prop in arg) {
                            if (typeof(prop) != "function") {
                                mess.push('"' + prop + '": "' + arg[prop] + '"');
                            }
                        }
                        //alert('(' + mess.join(', ') + ')');
                    } else {
                        //alert(arg);
                    }
                });
            }
        }
    }
    String.prototype.ucFirst = function() {
        return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
    }

    /*$j('.product_img img').each(function(i) {
        eval('elem' + i + ' = jQuery(this);');
        setTimeout('elem' + i + '.css({\'margin-top\': (140 - parseInt(elem' + i + '.height())) / 2})', 200);
    });*/

    $j.metadata.setType("attr", "data-validate");
    
    $j.validator.setDefaults({
        //debug: true,
        onsubmit: true,
        onfocusout: false,
        onkeyup: false,
        onclick: false,
        focusInvalid: false,
        errorPlacement: function(error, elem) {
            error.appendTo('#app_messages').before('<span class="error"></span>').after('<br class="clear" />');
        },
        invalidHandler: function(form, validator) {
            $j('#app_messages').dialog('open');
        }
    });

    $j('form.validate').validate();

    $j('#app_messages').dialog({
        autoOpen: false,
        autoResize: true,
        buttons: {
            Ok: function() {
                $j('#app_messages').dialog('close');
            }
        },
        close: function() {
            $j('#app_messages').html('');
        },
        draggable: false,
        modal: true,
        resizable: false,
        width: 350
    });

    if ($j('#app_messages').html() != '') {
        $j('#app_messages').dialog('open');
    }

    if ($j('#product_img img').length && !$j('body').hasClass('premium')) {
        $j('#product_img img').draggable({
            containment: [$j('#product_img').position().left + 131, $j('#product_img').position().top + 20, $j('#product_img').position().left + 131, $j('#product_img').position().top + 20],
            cursor: 'move'
        });
    }

    if ($j.cookie('reset_pag')) {
        $j.cookie('reset_pag', null);
    }

    $j('#categories li a, #header_menu li a').live('click', function() {
        $j.cookie('reset_pag', 1, {'path': '/'});
    });
    
    $j.slide_zoom = function(event, ui) {
        $j.change_zoom(event, ui);
    }

    $j.change_zoom = function(event, ui) {
        var offset = 300 * (ui.value - 1);
        var zoom_img = $j('#product_img img');
        var img_size = 300 * ui.value;
        var img_pos = zoom_img.position();
        zoom_img.draggable('option', 'containment', [$j('#product_img').position().left + 131 - offset, $j('#product_img').position().top + 20 - offset, $j('#product_img').position().left + 131, $j('#product_img').position().top + 20]);
        zoom_img.width(img_size)/*.height(img_size)*/.css({'left': 0 - offset / 2, 'top': 0 - offset / 2});
    };

    $j('#zoom_slider').slider({
        min: 1,
        max: 2.07,
        value: 1,
        step: 0.0107,
        slide: $j.slide_zoom,
        change: $j.change_zoom
    });

    $j('#zoom_plus').live('click', function() {
        var curr_val = $j('#zoom_slider').slider('option', 'value');
        $j('#zoom_slider').slider('value', curr_val + 0.107);
    });

    $j('#zoom_minus').live('click', function() {
        var curr_val = $j('#zoom_slider').slider('option', 'value');
        $j('#zoom_slider').slider('value', curr_val - 0.107);
    });

    $j('#zoom_reset').live('click', function() {
        $j.reset_slide = true;
        $j('#zoom_slider').slider('value', 1);
    });

    $j('#do_login').live('click', function() {
        $j.post(BASE_URL, {login: 1, user_email: $j('#user_email').val(), user_password: $j('#user_password').val(), remember: $j('#remember').get(0).checked ? 1 : 0}, function(response) {
            if (response.search(/<\?xml/) == -1) {
                $j('#app_messages').append('<span class="error"></span><label>' + response + '</label><br class="clear" />').dialog('open');
            } else {
                $j('#left_header').html($j(response).find('#left_header').html());
            }
        });
        return false;
    });
    
    $j('#categories li a').live('click', function() {
        _this = $j(this);
        setTimeout('window.location = _this.attr(\'href\')', 600);
        return false;
    });

    $j('#categories > ul').treeview({'animated': '500', 'persist': 'cookie', 'unique': true, 'collapsed': true});

    $j('.order_slider').live('click', function() {
        if ($j(this).parents('tr').next('.order_slide:visible').length == 1)
        {
            $j(this).parents('tr').next().slideUp();
        } else {
            slide_tr = $j(this).parents('tr').next();
            slide_tr.slideDown();
            setTimeout('slide_tr.css(\'display\', \'table-row\');', 500);
        }
        return false;
    });

     $j('#imgs_down').live('click', function() {
        var prod_count = $j('#product_imgs div').children('a').length;
        if ($j('#product_imgs div').children('a:visible').eq(2).next().length != 0 && !inAnimation && prod_count > 3)
        {
            inAnimation = true;
            var toHide = $j('#product_imgs div').children('a:visible:first');
            var toShow = $j('#product_imgs div').children('a:visible').eq(2).next().show();
            var firstProd = $j('#product_imgs div').children('a:first');//.appendTo('#product_imgs div');
            if (prod_count == 3)
            {
                firstProd.show();
            }
            $j('#product_imgs div')
                .children('a:visible')
                .css('position', 'relative')
                .animate(
                    {'top': -toHide.height()},
                    'slow',
                    'linear',
                    function() {
                        toHide.hide();
                        //firstProd.appendTo('#product_imgs div');
                        $j(this).css({'position': 'static', 'top': 0});
                        inAnimation = false;
                    }
                );
        }
        return false;
    });

    $j('#imgs_up').live('click', function() {
        if ($j('#product_imgs div').children('a:visible').eq(0).prev().length != 0 && !inAnimation && $j('#product_imgs div').children('a').length > 3)
        {
            //goUp = true;
            inAnimation = true;
            var toHide = $j('#product_imgs div').children('a:visible:last');
            var toShow = $j('#product_imgs div').children('a:visible').eq(0).prev().show();
            var toShowHeight = toShow.height();
            var lastProd = $j('#product_imgs div').children('a:last');
            $j('#product_imgs div')
                .children('a:visible')
                .css({'position': 'relative', 'top': -toShowHeight})
                .animate(
                    {'top': '+=' + toHide.height()},
                    'slow',
                    'linear',
                    function() {
                        toHide.hide();
                        //lastProd.prependTo('#product_imgs div');
                        $j(this).css({'position': 'static', 'top': 0});
                        inAnimation = false;
                    }
                );
        }
        return false;
        /*var lastProd = $j('#right_thumbs').children('.product:last');
        var toHide = $j('#right_thumbs').children('.product:visible:last');
        var toShow = $j('#right_thumbs').children('.product:visible:first').prev();
        lastProd.prependTo('#right_thumbs');
        toHide.slideUp('slow', 'easeOutQuad');
        toShow.slideDown('slow', 'easeOutQuad');*/
    });

    $j('#pay_method').change(function() {
        var terms = $j(this).children('option:selected').attr('data-terms');
        if (terms != null && terms != '') {
            $j('#app_messages').append('<span class="success"></span><label>' + terms + '</label><br class="clear" />').dialog('open');
        }
    });

    $j('#continue_shop').live('click', function() {
        window.location.href = BASE_URL;
    });

    $j.update_quant = function() {
        quant = $j(this).val();
        prod_id = $j(this).attr('id').replace('product_quantity_', '');
        $j('.cart').load(BASE_URL + 'cart.php?set_quantity=' + quant + '&product_id=' + prod_id + ' .cart > *', function() {
            $j('[id^="product_quantity_"]').change($j.update_quant);
        })
    };
    $j('[id^="product_quantity_"]').change($j.update_quant);

    $j('[class^="jcarousel-skin-"]').each(function() {
        $j(this).jcarousel({scroll: 1, visible: 4});
        var lis = $j('li.jcarousel-item a', this);
        var maxVisible = $j('body').hasClass('premium') ? 4 : 4;
        lis.lightBox(lightBoxConfig);
        if (lis.length < maxVisible) {
            $j('.jcarousel-next, .jcarousel-prev', $j(this).parents('.jcarousel-container')).attr('disabled', 'true').hide();
        }
    });

    $j('.tabs').tabs({selected: 1});

    $j.banner_slide = function() {
        var l = $j('#right_header li:first').width();
        $j('#right_header ul').css('position', 'relative').animate({'left': '-=' + l}, 3000, function() {
            var first_li = $j('#right_header li:eq(0)');
            var last_li = $j('#right_header li:last');
            first_li.insertAfter(last_li);
            $j('#right_header ul').css({'left': 0});
        });
    };

    $j('.light_imgs:not(:eq(1))').lightBox(lightBoxConfig);

    $j('#product_imgs div a').unbind('click').live('click', function() {
        selectedImg = $j(this).prevAll('a').length;
        
        var new_src = $j(this).attr('href');
        $j('#product_img img').attr('src', new_src);
        $j('#product_img a').attr('href', new_src);
        return false;
    });

    // $j('#product_accordion').accordion({
//     });

    setInterval('jQuery.banner_slide()', 3200);

    $j('#product_variant').change(function() {
        if ($j(this).val() != '') {
            window.location.href = $j(this).val();
        }
    });

    $j('#search_term').keypress(function(e) {
        if (e.which == 13) {
            $j('#do_search').click();
        }
    });

    $j('#do_search').live('click', function() {
        window.location.href = BASE_URL + 'search/' + escape($j('#search_term').val()) + '/';
        return false;
    });

});

