(function(){
	var rs = window['rimohsalon'] = {};
    jQuery.fn.extend({
        effectButton: function(){
            return $(this).each(function(){
                $(this).addClass('ui-state-default').hover(
                    function(){
                        $(this).addClass('ui-state-hover').removeClass('ui-state-default');
                    },
                    function(){
                        $(this).addClass('ui-state-default').removeClass('ui-state-hover');
                    }
                );
            });
        },
        createButton: function(callback) {
            return $(this).each(function(){
                $(this).bindFunc('click', callback).effectButton();
            });
        },
        bindFunc: function(evt, callback) {
            return $(this).each(function(){
                var func = function(){
                    callback.apply(this, arguments);
                    return false;
                };
                $(this)[evt](func);
            });
        }
    });
    jQuery.extend({
    	numFormat: function(n){
	    	var a = n.toString().split('').reverse(), b = [], i = 0;
	    	for (i = 0; i < a.length; i++) {
	    		if (i != 0 && i % 3 == 0) b.push(',');
	    		b.push(a[i]);
	    	}
	    	return b.reverse().join('');
	    }
    });
	jQuery.extend(rs, {
		showDialog: function(obj){
	        $('<div id="rimohsalon-dialog"></div>').html(obj.html).dialog({
	            title:obj.title,
	            modal:true,
	            bgiframe:true,
	            drag:obj.drag?obj.drag:function(){},
	            resize:obj.resize?obj.resize:function(){},
	            resizable:obj.resizable!=undefined?obj.resizable:true,
	            open:obj.open?obj.open:function(){},
	            close:obj.close?obj.close:function(){},
	            width:obj.width?obj.width:400,
	            buttons:obj.buttons
	        });
	        $('#rimohsalon-dialog').bind('dialogclose', function(){
	            $('#rimohsalon-dialog').dialog('destory').empty().remove();
	        });
		},
		closeDialog: function(){
	        $('#rimohsalon-dialog').dialog('close');
	    }
	});
	jQuery(function($){
		$('#header-main').insertBefore('#footer .main-navigations');
		$.getJSON('/gateway/is_campaign', function(json){
			if (!$('body').is('.campaign-page') && (json.campaign || location.search.match(/check/))) {
				$('#header .main-navigations #salon-link').replaceWith('<li id="campaign-link" ><a href="/campaign" title="普及キャンペーン指定サロン">普及キャンペーン指定サロン</a></li>');
				$('#footer .main-navigations #footer-salon-link').replaceWith('<li id="footer-campaign-link" ><a href="/campaign" title="普及キャンペーン指定サロン">普及キャンペーン指定サロン</a></li>');
			}
		});
		$('a.popup').click(function(){
			var that = this;
			function showform(){
				$('#form-pane').load($(that).attr('href'), function(){
                    var formsetup = function(){
                    	var calcTotal = function(){
                    		var sum = 0, sendFee = 420;
                    		$('#form-application-of-purchase .charges').each(function(){
                    			var p = parseInt($(this).text().replace(/￥|,/g, ''));
                    			sum += isNaN(p) ? 0 : p;
                    		});
                    		sendFee = sum >= 5250 ? 0 : 420;
                    		$('#price-total').text('￥'+$.numFormat(sum));
                    		$('#send-fee').text('￥'+sendFee);
                    		$('#grand-total').text('￥'+$.numFormat(sum ? sum+sendFee : 0));
                    	};
                        $('#accept_date').datepicker({
                            dateFormat:'yy-mm-dd',
                            yearText:'年',
                            minDate: 5,
                            beforeShow: function(input, obj){
                                obj.dpDiv.css('z-index', parseInt($('#rimohsalon-dialog').parents('.ui-dialog').css('z-index'))+10);
                            }
                        });
                        $('#btn-getaddress').createButton(function(){
                        	var zipcode = $('#zipcode').val().replace(/[^0-9]/g, '');
                        	var getAddress = function(json){
                        		if (json.address) {
                        			$('#address').val(json.address.prefecture+json.address.city+json.address.town);
                        		}
                        		if (json.result) {
                        			var results = $('<ul id="address-list" class="ui-widget-content"/>');
                        			$.each(json.result, function(i, result){
                        				results.append('<li><a href="#" class="zip-address-list-item" rel="'+i+'">'+result.address+'</a></li>');
                        			});
                        			$('#address-list').remove();
                        			$('#zipcode-cell').append(results);
                        			$('#zipcode-cell .zip-address-list-item').createButton(function(){
                        				var res = json.result[$(this).attr('rel')];
                        				$('#zipcode').val(res.zipcode);
                        				$('#address').val(res.address);
                        				$('#zipcode-cell #address-list').remove();
                        			});
                        		}
                        	};
                        	$.ajax({
                        		dataType: 'jsonp',
                        		data: {count: 100},
                        		url: 'http://zip.ricollab.jp/'+zipcode+'.json',
                        		success: getAddress
                        	});
                        });
                        $('.item-amounts').change(function(){
                        	$(this).val($(this).val().replace(/([Ａ-Ｚａ-ｚ０-９＿])/g, function(mc){ return String.fromCharCode(mc.charCodeAt(0) - 65248); }));
                        	var p = parseInt($(this).parent().prev().text().replace(/￥|,/g, ''));
                       		$(this).parent().next().text($(this).val() ? '￥'+$.numFormat(p * parseInt($(this).val())) : '');
                        	calcTotal();
                        });
                        $('#submit-form-button').createButton(function(){
                            $(this).attr('disabled', true);
                            $(this).parents('form').ajaxSubmit({
                                dataType: 'json',
                                success: function(json){
                                    if (json.posted) {
                                        rs.closeDialog();
                                        rs.showDialog({
                                            title:'フォーム内容を送信しました。',
                                            html: '<p>確認用のメールが届きますので、お申し込みの内容をお確かめ下さい。<br/>ご利用ありがとうございました。</p>',
                                            buttons: {
                                                'OK': rs.closeDialog
                                            }
                                        });
                                    }
                                    else {
                                        $('#form-pane').replaceWith(json.form);
                                        formsetup();
                                    }
                                }
                            });
                        });
                        $('#reset-form-button').effectButton();
                    };
                    formsetup();
                });
			}
			rs.showDialog({
				title: '商品購入申し込みフォーム',
				html:'<div id="form-pane" style="height:580px;"/>',
				width:750,
				open: showform,
				buttons:{
					'閉じる':rs.closeDialog
				}
			});
			return false;
		});
		$('#product-information a.commentform-popup').live('click', function(e){
			var that = this;
			e.preventDefault();
			$.nyroModalManual({
				url: $(that).attr('href'),
				endShowContent: function(elm){
					var setform = function(){
						$('#form-product-comment button').click(function(){
				    		$(this).parents('form').ajaxSubmit({
				    			dataType: 'json',
				    			success:function(json){
					    			if (json) {
					    				$('#nyroModalContent').html(json.form);
					    				setform();
					    			}
					    		}
				    		}).end().attr('disabled', true);
						});
					}
					setform();
				}
			});
		});
	});
})();

