//this file contains all member js functions
$(document).ready(function(){
	
	if ($('div.family_start_page').length) {
		$('input#nickname_input').focus(function(){
			if ($(this).val() == '自分の好きなニックネーム') {
				$('input#nickname_input').val('');
				$('input#nickname_input').css({color: '#000'});
			}
			});
	}
	
	$('a#close_notification_button').click(function(){
		//pass the rel to an ajax script
		$('div.news_notification').hide();
		$.post('/ajax/hide_news', { item: $(this).attr('rel') }, function(json){
			if (json.success) {
				//hide the div
			}
		}, 'json');			
		});

	if ($('a.fancybox').length) {
		$('a.fancybox').fancybox({
			width: 500,
			height: 303,
			overlayOpacity: 0.5,
			hideOnContentClick: false,
            autoDimensions:false,
            onStart:function(){
                $($(this).attr('href').substring($(this).attr('href').indexOf('#'))).show();
            },
            onClosed:function(){
                $($(this).attr('href').substring($(this).attr('href').indexOf('#'))).hide();
            }
        });
	}

	if ($('a#mail_to_friend_link').length) {
		$('a#mail_to_friend_link').fancybox({
			width: 500,
			height: 303,
            autoDimensions:false,
			overlayOpacity: 0.5,
			hideOnContentClick: false,
			onStart:function(){
				$($(this).attr('href').substring($(this).attr('href').indexOf('#'))).show();
				//js for mail sending
				$('form#send_product_mail_form').ajaxForm({
	        		dataType:  'json', 
	       			success:   processJson
	        		});
	        	function processJson(data) {
	        		if (data.error) {
	        			$('div#send_product_mail_ajax_response').html(data.error);
						$('form#send_product_mail_form p.submit').show();
						$('form#send_product_mail_form p.indicator').hide();
	        		} else {
	        			//success and fade out
						$('form#send_product_mail_form p.indicator').hide();
	        			$('div#send_product_mail_ajax_response').html(data.success);
	        			setTimeout("parent.$.fn.fancybox.close()", 1000);
	        		}
	        	}
				$('form#send_product_mail_form').submit(function(){
					//show progress
					$('div#send_product_mail_ajax_response').html('');
					$('form#send_product_mail_form p.submit').hide();
					$('form#send_product_mail_form p.indicator').show();
				});
			},
            onClosed:function(){
                $($(this).attr('href').substring($(this).attr('href').indexOf('#'))).hide();
            }
		});
	}
	
	if ($('ul.recent_orders').length) {
		$("ul.recent_orders").simplyScroll({
			autoMode: 'loop',
			speed: 1
		});		
	}

	if ($('ul#sale_slider').length) {
		if ($('ul#sale_slider').hasClass('noslide')) {
			return;	
		}
		$('ul#sale_slider').cycle({
		    fx:     'scrollLeft', 
		    delay:  2000, 
	    	speed:  1500, 
	    	easing: 'easeInOutExpo', 
	    	pause:  1,
	    	timeout:  8000
			});
	}
	
	if ($('div.checkout_buttons a.button').length) {
		//always center the big checkout button
		var button_width = $('div.checkout_buttons a.button').width();
		var offset = ($('div.checkout_buttons').width() - button_width - 60) / 2;
		$('div.checkout_buttons a.button').css('margin-left', offset + 'px');
	}
	
	$('a.delete_address').click(function(){
		if (confirm('このお届け先を削除しますか？')){ 
			return true;
		} else {
			return false;	
		}
		});
	
	if ($('div.success_container').length) {
		if (!$('div.success_container').hasClass('nofade')) {
			setTimeout(function() { $('div.success_container').fadeOut(); }, 5000);
		}
	}

	$('input[name=zipcode]').keyup(function(e) {
		//except IE 6 and 7
		//if ($.browser.msie && ($.browser.version == '6.0' || $.browser.version == '7.0')) return;
		//translate postcode
		translate_postcode($('input[name=zipcode]').val());
	});
	
	function translate_postcode(zipcode)
	{
		$.get('/ajax/convert_zipcode/' + zipcode, function(json){
			if (json.city) {
				//populate form fields
				//$('input#zipcode').val(json.zipcode);
				$('input[name=city]').val(json.city + ' ' + json.street);
				$('select[name=area] option[value='+ json.areas_id +']').attr('selected', 'selected');
			}
		}, 'json');			
	}
	
	//always make twin panels same height
	if ($('div.static_panel_a').length) {
		var a_height = $('div.static_panel_a').height();	
		var b_height = $('div.static_panel_b').height();
		if (a_height > b_height) {
			$('div.static_panel_b').css('height', a_height + 'px')
		} else {
			$('div.static_panel_a').css('height', b_height + 'px')
		}
	}

	$('a.submit_button').click(function(){
		$('form.submit_form').submit();
		return false;
		});
	
	if ($('a.brand_info').length) {
		$('a.brand_info').fancybox({
			frameWidth: 780,
			frameHeight: 600,
			overlayOpacity: 0.5,
			hideOnContentClick: false
			});
		if (window.location.hash == '#play_video') {
			$('a.brand_info').click();
		}
	}

    $('#cancal_form a.button').click(function(){
        if (confirm('本当にこのご注文をキャンセルしますか？')) {
    		$(this).toggle();
    		$('div#cancel_activity').show();
            $('#cancal_form').submit();
        }
    });

	if ($('a.tour_video').length) {
		$('a.tour_video').fancybox({
			frameWidth: 700,
			frameHeight: 415,
			overlayOpacity: 0.5,
			hideOnContentClick: false
			});
	}
		
	//common behaviour for all dropdowns
	$('ul.dropdown li a').click(function(){
		$(this).parents('ul.submenu').children('li').children('a').removeClass('selected');
		$(this).addClass('selected');
		$(this).parents('li.dropdown_display').children('a').html($(this).html());
		$(this).parents('ul.submenu').hide();
		});

	//order select
	$('ul.order_select li a').click(function(){
		var current_order = $('ul.order_select ul.submenu li a.selected').attr('rel');
		if (current_order == 'price') {
			$('ul.product_list li').tsort('span.product_price_plain');
		} else {
			$('ul.product_list li').tsort('span.original_order');
		}
		});

	//category select
	$('ul.category_select li a').click(function(){
		$('ul.product_list li').show();
		filter_categories($(this).attr('rel'));
		if ($('ul.attribute_select').length) {
			filter_attributes($('ul.attribute_select a.selected').attr('rel'));
		}
		});

	function filter_categories(category)
	{
		if (category == 'all') {
			//do nothing
		} else {
			$('ul.product_list li').not('.category_' + category).hide();			
		}
	}
	
	//attribute select
	$('ul.attribute_select li a').click(function(){
		$('ul.product_list li').show();
		if ($('ul.category_select').length) {
			filter_categories($('ul.category_select a.selected').attr('rel'));
		}
		filter_attributes($(this).attr('rel'));
		});

	function filter_attributes(attribute)
	{
		if (attribute == 'all') {
			//do nothing
		} else {
			$('ul.product_list li').not('.attribute_' + attribute).hide();			
		}
		//this always happens last so we do a bunch of stuff here
		//$('ul.product_list img').lazyload({
    		//effect : 'fadeIn',
    		//placeholder: '/public/images/UI/lazyload_placeholder.gif'
			//});	
		//show "no items" if there are no items
		var num = $('ul.product_list li').filter(':visible').size();
		if (num == 0) {
			$('div.no_products').show();	
		} else {
			$('div.no_products').hide();	
		}
		var main_container_height = $('div.main_container').height();
		var window_height = $(window).height();
		var footer_height = $('div.footer').height();
		if (main_container_height < (window_height + (footer_height - 50))) {
			$('div.main_container').css({height: (window_height - footer_height)});
		}	
	}

	//brand drop down
	$('ul.dropdown li').hover(
		function () {
			//show its submenu
			$('ul', this).slideDown(100);

		}, 
		function () {
			//hide its submenu
			$('ul', this).slideUp(100);			
		}
	);
	
	$('a.add_to_cart').click(function(){
		$('a.add_to_cart').hide();
		$('#add_to_cart_progress').show();
		$.ajax({
			type	: 'POST',
			cache	: false,
			url		: '/members/cart/ajax',
			data	: $('form#add_to_cart').serializeArray(),
			error	: function() { alert('エラーが発生しました。ページを更新してからもう一度やってみて下さい。'); return false; },
			success	: function(data) {
				$('a.add_to_cart').show();
				$('#add_to_cart_progress').hide();
				//increase tab display
				if ($('#cart_num').html() != '') {
					var current_cart_num = parseInt($('#cart_num').html().replace('(','').replace(')',''));
				} else {
					var current_cart_num = 0;	
				}
				var new_quantity = parseInt($('select[name=quantity]:visible').val());
				$('#cart_num').html('('+(current_cart_num + new_quantity)+')');
				$.fancybox({
					width: 720,
					height: 480,
					overlayOpacity: 0.5,
					hideOnContentClick: false,
		            autoDimensions: false,
					content:data,
					onClosed: function(){
						location.reload();
					}
				});
			}
		});
		//$('form#add_to_cart').submit();
		return false; //prevent page refreshing
	});
	
	//dynamic stock level change for different product attributes
	if ($('span.attribute_quantity').length) {
		switch_attribute_quantity();
	}
		
	$('select[name=size]').change(function(){
		switch_attribute_quantity();
		});

	function switch_attribute_quantity()
	{
		$('select.attribute_quantity_select').attr('disabled', 'disabled');
		$('span.attribute_quantity').hide();
		//show the first one that is selected
		var first_available = $('select[name=size]').val();
		$('span.attribute_quantity.attribute_' + first_available).show();		
		$('span.attribute_quantity.attribute_' + first_available + ' select.attribute_quantity_select').removeAttr('disabled');		
	}

	if ($('#product_images').length) {
		$('#product_images li').hide();
		$('#product_images li:first').show();
		$('#product_images').cycle({
			timeout: 5000
			//before: highlight_next_thumbail,
			});
		//$('div.slideshow_container').hover(function(){
			//$('#product_images').cycle('stop');
			//});
		$('.zoom').jqzoom({
			zoomWidth: 400,
		    zoomHeight: 500,
		    lens: false,
		    showEffect: 'fadein',
		    hideEffect: 'fadeout',
		    preloadText: 'ロード中'
			});

	}
	
	function highlight_next_thumbail()
	{
		var current = $('ul.thumbnail_images img.current');
		$('ul.thumbnail_images img').removeClass('current');
		if (!current.length) {
			$('ul.thumbnail_images li:first img').addClass('current');	
		} else {
			if (current.parents('a').parents('li').next().length) {
				current.parents('a').parents('li').next().children('a').children('img').addClass('current');				
			} else {
				$('ul.thumbnail_images li:first img').addClass('current');
			}
		}
	}
	
	$('ul.thumbnail_images a').hover(function(){
		$('ul.thumbnail_images img').removeClass('current');
			$(this).children('img').addClass('current');
		},function(){
			$('ul.thumbnail_images img').removeClass('current');
			});
	
	$('ul.thumbnail_images a').click(function(){
		//stop cycle
		//$('#product_images').cycle('pause');
		//$('#product_images li').css('opacity', 1);
		//$('ul.thumbnail_images img').removeClass('current');
		//$(this).children('img').addClass('current');
		//var image_id = $(this).attr('rel');
		//$('#product_images li').hide();
		//$('li#' + image_id).show();
		});
	
	//highlight fade on cart add item
	if (window.location.hash == '#added') {
		//$('table tr.item:last td').highlightFade({
			//color: '#ffff99',
			//speed: 1000
			//});
	}
    
    if ($('a.display_large_image').length) {
    	
	    $('a.display_large_image').fancybox({
	    	cyclic: true,
	        overlayOpacity: 0.5,
	        hideOnContentClick: false,
	        onStart:function(){
	            $('#product_images').cycle('pause');
	        },
	        onClosed:function(){
	            $('#product_images').cycle('resume');
	        }
	    });
    }
});