$(function() {
    var numberFormat = function(num){
        return num.toString().replace(/([\d]+?)(?=(?:\d{3})+$)/g, function(t){return t + ',';});
    }


    //カラー選択時のクラス切替
    var changeClass = function () {
        $('.selectcolor')
            .find('.sum_selected')
            .removeClass()
            .addClass('sum_unselected')
            .end()
            .find('input[name=color]:checked')
            .parents('div.sum_unselected')
            .attr('class', 'sum_selected');
    }

    //XML取得
    var StockAjax = function (stock_flag) {
        $('.thumbs').empty();

        //$.ajaxTimeout(5000);
        $.post("/Products/Stock/",
        {
            products_id : products_id,
            color : $('input[name=color]:checked').val(),
            stock_flag : stock_flag
        },
        function(xml) {
            if ($('ProductInfo>Response>Result', xml).text() == 'TRUE') {
                var MainImage = $('ProductInfo>MainImage', xml).text();
                $('.MainImage').attr('src', MainImage);
                
                $('.thumbs').html('');
                $('ProductInfo', xml).find('ThumbImage').each(function(){
                    $$ = $(this);
                    var number  = $$.attr('number');
                    var LThumbImage = $('LThumbImage[number=' + number +']', $$.parent()).text();
                    $('.thumbs').append('<a href="' + LThumbImage + '" rel="syncLightpop"><img src="' + $(this).text() + '" /></a>');
                });

                //色の在庫情報取得
                var stock_zero_flag = false;
                $('ProductInfo', xml).find('ColorStock').each(function(){
                    $$ = $(this);
                    var color_name  = $$.attr('color');
                    var stock = $('ColorStock[color=' + color_name +']', $$.parent()).text();
                    if (stock == 0) {
                        $('#' + color_name + '_radio').parents('.radio').prev('.sumwrap').append('<div class="front"><img src="/img/soldout_front.png" class="alphafilter"></div>');
                        stock_zero_flag = true;
                    }
                });

                if (stock_zero_flag) {
                    $('.front').click(imageRadioClick);
                }

                //thumbにイベント付与
                $("a[rel='syncLightpop']").colorbox({transition:"none"});
                
                $('#size').empty();
                $('.amountinputbx').empty();
                var innerHTML = '';
                var stock = 0;
                var color_comment = '';
                var defaultSize;
                if ($('ProductInfo>StockInfo>Result', xml).text() == 'TRUE') {
                    var count = $('ProductInfo>StockInfo', xml).find('Stock').size();
                    var sizeSerial = 0;
                    $('ProductInfo>StockInfo', xml).find('Stock').each(function(){
                        stock += Number($(this).attr('quantity'));
                        color_comment = $(this).text();
                        defaultSize = $(this).attr('size');
                        if (Number($(this).attr('quantity')) > 0) {
                            if (count == 1) {
                                innerHTML += '&nbsp;' + $(this).attr('size') + '<input name="size" type="hidden" id="' + $(this).attr('size') + '_radio" value="' + $(this).attr('size') + '" checked="checked" />';
                            } else {
                                innerHTML += '<div class="lef"><label for="' + $(this).attr('size') + '_radio">';
                                if (size == $(this).attr('size')) {
                                    innerHTML += '<input name="size" type="radio" id="' + $(this).attr('size') + '_radio" value="' + $(this).attr('size') + '" checked="checked" />';
                                    size = '';
                                } else {
                                    //サイズ選択がされていないかつ、一巡目の時
                                    if (size == '' && sizeSerial == 0) {
                                        innerHTML += '<input name="size" type="radio" id="' + $(this).attr('size') + '_radio" value="' + $(this).attr('size') + '" checked="checked" />';
                                    } else {
                                        innerHTML += '<input name="size" type="radio" id="' + $(this).attr('size') + '_radio" value="' + $(this).attr('size') + '" />';
                                    }
                                }
                                innerHTML += '&nbsp;' + $(this).attr('size') + '</label></div>';
                            }
                        } else {
                            innerHTML += '&nbsp;' + $(this).attr('size') + '<input name="size" type="hidden" id="' + $(this).attr('size') + '_radio" value="' + $(this).attr('size') + '" checked="checked" />';
                        }
                        sizeSerial++;
                    });

                    $('#cartin').unbind('click').unbind('mouseover').unbind('mouseout').removeAttr('style');
                    $('#recomein').unbind('click').unbind('mouseover').unbind('mouseout').removeAttr('style');
                    $('.colordetail div.lef').html('<strong>color</strong>' + $('input[name=color]:checked').val() + ':');
                    $('.colordetail div.rig').html(color_comment);
                    $('#size').append(innerHTML);

                    var sizeVal = $('input[name=size][checked]').val();
                    if (sizeVal == undefined) sizeVal = defaultSize;

                    if (wish_flag == '-1') {
                        $('.wishlistbtn a').attr('href', wishurl + 'size/' + encodeURI(sizeVal) + '/color/' + $('input[name=color]:checked').val() + '/');
                    }

                    //在庫あるとき
                    if (stock > 0) {
                        var quantity_html = '<select id="quantity" name="quantity">';
                        for (var i=1; i <= stock; i++) {
                            quantity_html += '<option value="' + i + '">' + i + '</option>';
                        }
                        quantity_html += '</select>';
                        $('.amountinputbx').html(quantity_html);
                        $('.amounttitle img').attr('src', '/img/itemdetail_title_number.gif');
                        if (reserve_flag == 1) {
                            //$('.cartbtn').html('<img src="/img/itemdetail_rsvbtn.gif" alt="予約購入する" ref="over" id="cartin" />');
                            $('.cartbtn').html('<img src="/img/itemdetail_btn_cart.gif" alt="カートに入れる" ref="over" id="cartin" />');
                        } else {
                            $('.cartbtn').html('<img src="/img/itemdetail_btn_cart.gif" alt="カートに入れる" ref="over" id="cartin" />');
                        }
                        $('#cartin').bind('click', function(){
                            $('form[name=products_form]').submit();
                        }).mouseover(function () {
                            this.src = this.src.replace(/^(.+)(\.[a-z]+)$/, "$1_over$2");
                        }).mouseout(function () {
                            this.src = this.src.replace(/^(.+)_over(\.[a-z]+)$/, "$1$2");
                        }).css({cursor: 'pointer'});
                    //在庫ないとき
                    } else {
                        $('.amounttitle img').attr('src', '/img/itmselect_noitem.gif');
                        if (products_recomein_flag == '1') {
                            if (wish_flag == '-1' || wish_flag == '0') {
                                $('.cartbtn').html('<a href="' + wishurl + 'recomein/1/size/' + encodeURI(sizeVal) + '/color/' + $('input[name=color][checked]').val() + '/' + '"><img src="/img/itemdetail_btn_infomail.gif" alt="再入荷お知らせメール" id="recomein"></a>');
                                $('#recomein').mouseover(function () {
                                    this.src = this.src.replace(/^(.+)(\.[a-z]+)$/, "$1_over$2");
                                }).mouseout(function () {
                                    this.src = this.src.replace(/^(.+)_over(\.[a-z]+)$/, "$1$2");
                                }).css({cursor: 'pointer'});
                            } else {
                                $('.cartbtn').html('<img src="/img/itemdetail_btn_mail_done.gif" alt="再入荷お知らせメール登録済">');
                            }
                        } else {
                            if (reserve_flag == 1) {
                                //$('.cartbtn').html('<img src="/img/itemdetail_rsvbtn.gif" alt="予約購入する" ref="over" id="cartin" />');
                                $('.cartbtn').html('<img src="/img/itemdetail_btn_cart.gif" alt="カートに入れる" ref="over" id="cartin" />');
                            } else {
                                $('.cartbtn').html('<img src="/img/itemdetail_btn_cart.gif" alt="カートに入れる" ref="over" id="cartin" />');
                            }
                            $('#cartin').fadeTo('fast', 0.3);
                        }
                    }
                } else {

                }
            } else {
                //error
            }
        });
    }

    //カラーレンズ選択で小計加算
    function setPrice(){
        var selectedObj = $('#option_lens_color_id').children('option[selected]');
        var quantity = Number($('#quantity').val());
        if (selectedObj.val() == 0 || products_category_id != 1) {
            $('.price div.rig').html(numberFormat(Number(price)*quantity) + '円');
        } else {
            $('.price div.rig').html(numberFormat((Number(price) + 2000)*quantity) + '円');
        }
    }

    $('#option_lens_color_id').change(function(){
        setPrice();
    });

    $('#quantity').change(function(){
        setPrice();
    });

    setPrice();
    
    $('input[name=color]').click(function(){
        changeClass();
        StockAjax(0);
    });
    
   var imageRadioClick = function () {
        $(this).parents('.sumwrap').next().children('input').attr('checked', 'checked');
        changeClass();
        StockAjax(0);
    };

    //IE用で
    $('.imageradio').click(imageRadioClick);

    changeClass();
    StockAjax(1);
});