jq(document).ready(function() {
    var currentImg = 0;

    function formatTitle(title, currentArray, currentIndex, currentOpts) {
        currentImg = currentIndex;
        return jq('.fancybox-title').html();
    }

    jq('.super-attribute-select').live('change', function(){ initConfigurableButtons(jq(this));} ); // Init configurable inputs as buttons
    jq('#container-color-configurable a').live('mouseup', function(){ initConfigurableButtons(jq(this));} ); // Init configurable inputs as buttons
    jq('.carouselRel').live('click', function() {jq.fancybox.pos(jq(this).attr("rel")); });
    jq('.more-photos').click(function(){ jq(".fancy-popup").attr('rel', 'gallery').click(); });
    jq('.fancy-popup').fancybox({
        cyclic: true,
        titlePosition: 'inside',
        changeFade: 'fast',
        titleFormat: formatTitle,
        onComplete: function() {
            var imgCount = jq(".product-img-views a=[rel='gallery']").length;
            if (imgCount > 1 && imgCount < 7) {
                jq("#fancybox-title #cr_next, #fancybox-title #cr_prev").css("display", "none");
                jq("#fancybox-title .carousel").jCarouselLite({
                    circular: false,
                    visible: imgCount-1
                });
            } else if (imgCount > 6) {
                jq("#fancybox-title .carousel").jCarouselLite({
                    circular: true,
                    visible: 6,
                    start: currentImg-2,
                    btnNext: "#fancybox-title #cr_next",
                    btnPrev: "#fancybox-title #cr_prev"
                });
            }
            jq(".carousel").css("width", "86%");
            jq(".carousel img=[rel]").css("border", "0px")
                .css("opacity", "0.5");
            if (jq(".carousel img=[rel='"+currentImg+"']").html() == null) {
                currentImg = 0;
            }

            jq(".carousel img=[rel='"+currentImg+"']").css("border", "2px solid black")
                .css("opacity", "1");
        }
    });
    jq('.write-review').fancybox({
        'padding': 0,
        'autoDimensions': true
    });
    jq('.overall-link').click(function(e){
        e.preventDefault();
        Tabs.selectTab($('reviews_tab'));
    });
    jq('.unfold').click(function(e){
        e.preventDefault();
        var filter = jq(this).parent().parent();
        if (jq(this).text() == 'Show less...') {
            jq('li.unfolded', filter).fadeOut().removeClass('unfolded');
            jq(this).text('Show more...');
        } else {
            jq('li.folded', filter).fadeIn().addClass('unfolded');
            jq(this).text('Show less...');
        }
    });
    controlCartButton('0');
    handleConfigurableButtons();
    checkSingleAttributes();

    jq('.product-pdf-popup').click(function(){
        var offset = jq('.product-pdf-popup').position();
        jq('.download-pdf').css("left", (offset.left - 40)+"px");
        jq('.download-pdf').animate({
                height: 'toggle'
            }, 400, function() {
        });
    });
});

//var grayedButtons = new Array();
var attributesCount = 0;

function colorSwatch(id, value)
{
    var attributeSelector = jq('#' + id);
    attributeSelector.val(value);
    jq('.inlineBox').removeClass('selected');
    jq('#color' + value).addClass('selected');
    spConfig.configureElement($(id));
    initStyleChange(true);
}

function initConfigurableButtons(optionInput)
{
   var order = 0;
   if (optionInput.is('select')) {
       order = parseInt(optionInput.attr('order'), 10);
   }
   jq('.super-attribute-select').each(function(){
       var currentOrder = parseInt(jq(this).attr('order'), 10);
       if (currentOrder > order) {
          jq('.configurable-buttons[order="'+currentOrder+'"] div').attr('class', 'configurable-button-disabled');
       }
       if (currentOrder == (order + 1)) {
           drawConfigurableButtons(currentOrder);
       }
       attributesCount = currentOrder;
   });
}

function drawConfigurableButtons(order)
{
    var buttonsContainer = jq('.configurable-buttons[order="'+order+'"]');
    var optionsInputMain = jq('.super-attribute-select[order="'+order+'"]');
    var optionsInput = jq('.complete-conf-options[order="'+order+'"]');
    optionsInput.find('option').each(function(){
        var value = jq(this).val();
        var label = jq(this).text();
        if (value.length > 0) {
            if (optionsInputMain.find('option[value="'+value+'"]').length > 0) {
                jq('div:contains("'+label+'")', buttonsContainer).attr('class', 'configurable-button');
            } else {
                jq('div:contains("'+label+'")', buttonsContainer).attr('class', 'configurable-button-disabled');
            }
        }
    });
}

function handleConfigurableButtons()
{
   jq('.configurable-buttons div').live('click', function(){
       if (!jq(this).hasClass('configurable-button-disabled')) {
           var order = jq(this).parent().attr('order');
           order = parseInt(order, 10);
           var configurableInput = jq('.super-attribute-select[order="'+order+'"]');
           configurableInput.val(jq(this).attr('point'));
           spConfig.configureElement($(configurableInput.attr('id')));
           configurableInput.change();
           jq(this).parent().find('div').removeClass('selected');
           jq(this).addClass('selected');
           handleNextAttribute(order);
       }
   });
}

function initStyleChange(colorOnly)
{
    var styleBody = '';
    var optionOrder = 0;
    var selectedValue;
    controlCartButton('0');
    jq('label.required').each(function(){
        if (optionOrder == 0) {
            selectedValue = jq('#container-color-configurable').find('.selected');
            if (selectedValue.length > 0) {
                styleBody += ' <span class="container-head">' + jq('.required[order="'+optionOrder+'"]').html() + '</span> ' + selectedValue.find('img').attr('title');
            }
            if (colorOnly) {
                return false;
            }
       } else {
            optionOrder = parseInt(jq(this).attr('order'), 10);
            selectedValue = jq('.configurable-buttons[order="'+optionOrder+'"]').find('.selected');
            if (selectedValue.length > 0) {
                styleBody += ' <span class="container-head">' + jq('.required[order="'+optionOrder+'"]').html() + '</span> ' + selectedValue.html();
                if (optionOrder == attributesCount) {
                    controlCartButton('1');
                }
            }
       }
       optionOrder++;
    });
    jq('#var_style_block').html(styleBody);
}

function checkSingleAttributes()
{
    var colorSwatch = jq('#container-color-configurable a.colorSwatch');
    if (colorSwatch.length == 1) {
        if (!jq('#container-color-configurable a.colorSwatch.selected').length) {
            colorSwatch.first().mouseup();
            handleNextAttribute(0);
        }
    }
}

function handleNextAttribute(order)
{
    var attribute = jq('.configurable-buttons[order="'+(order+1)+'"] div:not(.configurable-button-disabled):not(.selected)');
    if (attribute.length == 1) {
        attribute.first().click();
    } else {
        initStyleChange(false);
    }
}

//function initAllOptions()
//{
//    grayedButtons[0] = '';
//    jq('.complete-conf-options').each(function(){
//        var currentOrder = parseInt(jq(this).attr('order'), 10);
//        grayedButtons[currentOrder] = '';
//        jq(this).find('option').each(function(){
//            if (jq(this).val() != '') {
//                grayedButtons[currentOrder] += '<div class="configurable-button-disabled">'+jq(this).text()+'</div>';
//            }
//        })
//    });
//    drawAllOptions();
//}

//function drawAllOptions()
//{
//    if (grayedButtons.length > 0) {
//        jq('.configurable-buttons').each(function(){
//            var currentOrder = parseInt(jq(this).attr('order'), 10);
//            jq(this).html(grayedButtons[currentOrder]);
//        });
//    }
//}

function controlCartButton(status)
{
    if (status == '0') {
        jq('.btn-cart').attr('disabled', '1');
        jq('.btn-cart').animate({
            opacity: 0.25
         }, 25);
        jq('.addcart-locker').css('z-index', '10');
    } else {
        jq('.btn-cart').removeAttr('disabled');
        jq('.btn-cart').animate({
            opacity: 1
        }, 100);
        jq('.addcart-locker').css('z-index', '-10');
    }
}
