$(function() {
    var prev = 0;
    var uri = window.location.toString();
    $('[class="rtg_link"]').each(function(i) {
	  var target_div = $(this).attr('rel');
	  var li = $(this).parent();var cls = $(li).attr('class');
	  if(!document.getElementById(target_div)) {
	    $(li).remove();return;
	  }
	  
	  if(prev == 0) { 
	    cls = 'step1';
	  } else { 
	    cls = 'eachDisible'+prev;
	  }
	  $(li).removeClass();$(li).addClass(cls);
	  $(this).click(function(){show(target_div);return false;});
      prev++;
	});
	$('#confirm_addr_book').hide();
	$('#add_address_submit').click(function() {
	  $('#saveAddr').click();
	});
	/* payment selective option */
	$('#radio').click(function(){toggle_payment('bank_account');});
	$('#radio2').click(function(){toggle_payment('post_account');});
	$('#radio3').click(function(){toggle_payment('pay_on_arrived');});
	$('#radio,#radio2,#radio3').each(function() {if($(this).attr('checked')) $(this).click();});
	
	/* if all divs haven been showed, then submit the form and shows the layer ask whether user want to save this address */
	$('#checkout_frm').submit(function(){
	  if(show(':next')) {
	    return false;
	  } else {
		if($('#confirm_addr_book').css('display') != 'none') {
		  return true;	
		} else {
		  if(!$('#saveAddr').attr('checked')) {
		    $('#normal_submit_table').hide('slow');
		    $('#confirm_addr_book').show('slow');
	        return false;
		  } else {
			return true;
		  }
		}
	  }
	});
	$('[rel="rtg"]').hide();$('[rel="rtg"]:first').show();

	if(uri.match(/section=(\w+)/)) {
	  var section = uri.match(/section=(\w+)/)[1];
	  show(section);
	}
});

function toggle_payment(id) {
	$('#bank_account,#pay_on_arrived,#post_account').each(function() {
      ($(this).attr('id') == id) ? $(this).show() : $(this).hide();
    });
}

function show(id) {
	if(id == ':next' || id == ':prev') {
		var ar = $('[rel="rtg"]');var rt;
		ar.each(function(i){
			if($(this).css('display') != 'none') {
				var n = (id == ':next') ? i+1 : i-1;//alert($(ar[n]).attr('id'));
				if(ar[n]) {
					rt = show($(ar[n]).attr('id'));return false;
				}
			}
	    }); return rt;
	} else if(id == ':all') {
		$('[rel="rtg"]').show();
	} else {
		$('[rel="rtg"]:visible').hide();var prev;
		toggle_number(id);
	    if(document.getElementById(id)) {
	      $('#'+id).show();return true;
	    } else {
	      return false;
	    }
	}
}

function toggle_number(id) {
  $('[class="rtg_link"]').each(function(i) {
	 var li = $(this).parent();
	 var cls = $(li).attr('class');
	 prev = cls.match(/\d+/)[0];
	 if($(this).attr('rel') == id) {
	  (cls.match(/eachDisible/)) ? prev++ : prev; 
	  cls = 'step'+prev;
	 } else {
	  (cls.match(/step/)) ? prev-- : prev;
	  cls = 'eachDisible'+prev;
	 }
	 $(li).removeClass();$(li).addClass(cls);
  });
}
