var Class = {
 create: function(){return function (){this.extend=function(a){var b=function(){this.initialize.apply(this, arguments)};for(var p in this)b.prototype[p] = this[p];for(var p in a)b.prototype[p] = a[p];return b;};this.initialize.apply(this, arguments);};},
 register:function(a,d){a=a.split(".");for(var b=window,c=0,f=a.length;c<f;c++){if(typeof b[a[c]]=="undefined")b[a[c]]={};b=b[a[c]]}for(var e in d)b[e]=d[e]}
};

Nicopon = {};
Nicopon.countDownTimer = Class.create();
Nicopon.countDownTimer.prototype = {
  initialize: function(remain, options){
    for (var i in options) this[i] = options[i];
    this.limitTime = new Date().getTime() + remain*1000;
    this.timerElement = $(document.createElement("div"));
    this.update();
    var self = this;
    setInterval(function(){self.update()},250);
    return this;
  },
  getElement: function(){
    return this.timerElement;
  },
  update: function(remain){
    var remain = ~~((this.limitTime - new Date().getTime())/1000);
    switch (true) {
      case (remain>=3600):
        this.timerElement.html(["<span class=\"red\">", Math.floor(remain/3600),"</span>時間 <span class=\"red\">", Math.floor(remain%3600/60), "</span>分 <span class=\"red\">", remain%3600%60,"</span>秒"].join(""));
        break;
      case (remain>=60):
        this.timerElement.html(["<span class=\"red\">", Math.floor(remain/60), "</span>分 <span class=\"red\">", remain%60,"</span>秒"].join(""));
        break;
      case (remain>=0):
        this.timerElement.html(["<span class=\"red\">", Math.floor(remain),"</span>秒"].join(""));
        break;
      default:
        this.timerElement.html(["完売しました"].join(""));
        break;
    }
  } 
}
Nicopon.countDownTimerMini = Class.create();
Nicopon.countDownTimerMini.prototype = {
  initialize: function(remain, options){
    for (var i in options) this[i] = options[i];
    this.limitTime = new Date().getTime() + remain*1000;
    this.timerElement = $(document.createElement("span"));
    this.update();
    var self = this;
    setInterval(function(){self.update()},250);
    return this;
  },
  getElement: function(){
    return this.timerElement;
  },
  update: function(remain){
    var remain = ~~((this.limitTime - new Date().getTime())/1000);
    switch (true) {
      case (remain>=86400):
        this.timerElement.html(["残り: <span class=\"red\">", Math.floor(remain/86400),"</span>日"].join(""));
        break;
      case (remain>=3600):
        this.timerElement.html(["残り: <span class=\"red\">", Math.floor(remain/3600),"</span>時間"].join(""));
        break;
      case (remain>=60):
        this.timerElement.html(["残り: <span class=\"red\">", Math.floor(remain/60), "</span>分"].join(""));
        break;
      case (remain>=0):
        this.timerElement.html(["残り: <span class=\"red\">", Math.floor(remain),"</span>秒"].join(""));
        break;
      default:
        this.timerElement.html(["完売しました"].join(""));
        break;
    }
  } 
}
Nicopon.locationDetector = Class.create();
Nicopon.locationDetector.prototype = {
  initialize: function(_options){
    this.debug = false;
    
    for (var i in _options) this[i] = _options[i];
    
    if (!navigator.geolocation) {
      if (!!this.debug) window.alert("geolocation element can not find");
      return false;
    }
    navigator.geolocation.getCurrentPosition(this.onFound, this.onError);
  },
  onFound: function(position){
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
window.alert("/api/rev_geocoder.json?lat="+lat+"&lng="+lng);
    jQuery.getJSON("/api/rev_geocoder.json?lat="+lat+"&lng="+lng, function(data){
      var rawdata = data;
      window.alert(rawdata);
      if (!!rawdata && rawdata.status=="OK"){
        var results = rawdata.results[0].address_components;
        for (var i = 0, len=results.length; i<len; i++){
          if (results[i].types[0] == "administrative_area_level_1") {
            window.alert(results[i].short_name);
          }
        }
      } else {
        window.alert("住所を検索できませんでした")
      }
    });
  
    window.alert(["lat:", lat, ", lng:", lng].join(""));
  },
  onError: function(position){
    window.alert("error, can not find location");
  }
}

Nicopon.LoginForm = {
    closeAllSections: function(){
      $('.input_form_area').each(function(){
        $(this).addClass("hidden");
      });
    },
    openLoginForm: function(){
      $('.input_form_area').each(function(){
        $(this).addClass("hidden");
      })
      var target_element = $("#"+$("input[name=signin]:checked").val());
      target_element.removeClass("hidden");
    } 
}
Nicopon.OrderForm = {
  closeAllSections: function(){
    $('.section_wrapper').each(function(){
      $(this).css("min-height", "");
      $(this).addClass("hidden");
    });
  },
  openSection: function(target_element, close_other_sections){
    close_other_sections = close_other_sections || true;

    /* close unneeded summaries */
    $('.summary').each(function(){
      if ($(this).html() == "") {
//        $(this).addClass("hidden");
        $(this).next().addClass("hidden");
      } else {
        $(this).removeClass("hidden");
        $(this).next().removeClass("hidden");        
      }
    })

    if (close_other_sections) {
      $('.section_wrapper').each(function(){
        $(this).css("min-height", "");
        $(this).addClass("hidden");
      })
    } else {
      $('.section_wrapper').each(function(){
        $(this).css("min-height", "");
      })      
    }
    /* calculate min height */
    var displayHeight = window.innerHeight;
    $('.section_header').each(function(){
      displayHeight -= $(this).outerHeight(true);
    })
    displayHeight -= $('#footer').outerHeight(true);
//    $(target_element).find('.section_wrapper').css("min-height", displayHeight+"px");
    $(target_element).find('.section_wrapper').removeClass("hidden");
  },
  updateAmount: function(){
    var totalPrice = Nicopon.OrderSession.unitPrice * $('#order_quantity').val();
    $('#subtotal_price').html(String(totalPrice).addDelimiter() + "円");
  },
  reEdit: function(target_element){
    $(target_element).find('.section_wrapper').removeClass("hidden");
    $(target_element).find('.summary').addClass("hidden");
    $(target_element).find('.summary').next().addClass("hidden");
  },
  reviewCouponRules: function(){
    $('#order_agreed_to_coupon').attr('checked',true);
    $('#price_calculator').find('.summary').html([$('#coupon_name').html().substr(0,15), "... を ", $('#order_quantity').val(), "枚購入"].join(""));
    if (!!Nicopon.OrderForm.alreadyLoggedIn) {
      Nicopon.OrderForm.openSection("#orderPaymentMethodForm",true);
      $.scrollTo($('#orderPaymentMethodForm'), 0);        
    } else {
      Nicopon.OrderForm.openSection("#userRegistOrLoginForm",true);
      $.scrollTo($('#userRegistOrLoginForm'), 0);      
    }
  },
  openLoginForm: function(target_element){
    $('#userRegistOrLoginForm').find('.input_form_area').each(function(){
      $(this).hide();
    })
    $(target_element).show();
  },
  loginWithIdPass: function(id, pass){
    $('#userRegistOrLoginForm').find('.summary').html("");        
    $('#userRegistOrLoginForm').find('.error_message').html("");        

    jQuery.post("/session_create.json", {login: id, password: pass}, function(data){
      if (!!data['login']) {
        $('#userRegistOrLoginForm').find('.summary').html(data['login'] + "でログインしています。"); 
        $('#session_escape_button').attr('value','ログアウト');
        $('#session_escape_button').bind('click',function(){
          Nicopon.OrderForm.logout();
        })
        Nicopon.OrderForm.openSection("#orderPaymentMethodForm",true);

      } else {
        $('#userRegistOrLoginForm').find('.error_message').html("ログインできませんでした。");        
      }
    }, "json");
  },
  logout: function(){
    window.location="/logout";
/*    $('#userRegistOrLoginForm').find('.summary').html("");
    $('#login').val("");
    $('#password').val("");
    Nicopon.OrderForm.reEdit($('#userRegistOrLoginForm'));*/
  },
  openPaymentMethod: function(target_element){
    $('.each_block').each(function(){
      $(this).hide();
    })
    $(target_element).slideToggle();    
  },
  closeAllPaymentMethods: function(){
    $('.each_block').each(function(){
      $(this).hide();
    })  
  },
  preAccountRegistration: function(){
    if (!!Nicopon.OrderForm.mailAddressConfirm($('#order_user_attributes_email').val())){
      $('#order_review_site_rules').attr('checked',true);
      $('#session_escape_button').attr('value','キャンセル');
      $('#session_escape_button').bind('click',function(){
        Nicopon.OrderForm.reEdit($('#userRegistOrLoginForm'));
      });
      Nicopon.OrderForm.openSection('#orderPaymentMethodForm',true);    
    } 
  },
  attachSmartHint: function(){/*
//    $('#order_user_attributes_login').focus(function() {
    $('#signupFormLoginNotes').addClass("form_notes");
    $('#signupFormLoginNotes').html("英数字[a-z,A-Z,0-9]と下線[_]が使えます");

    $('#order_user_attributes_login').blur(function() { 
      if ($('#order_user_attributes_login')[0].value.length!=0) {
        
      }
    });
//    $('#order_user_attributes_login').blur(function() { $('#signupFormLoginNotes').html("")});

//    $('#order_user_password').focus(function() {
    $('#signupFormPasswordNotes').html("パスワードは英数記号6文字以上で決めてください");
//      });
    $('#order_user_attributes_password').blur(function() {
      if ($('#order_user_attributes_password')[0].value.length!=0 && $('#order_user_attributes_password')[0].value.length<6) {
        $('#signupFormPasswordNotes').html("");
        $('#signupFormPasswordErrs').html("パスワードは6文字以上である必要があります");       
      } else {
        $('#signupFormPasswordNotes').html("パスワードは英数記号6文字以上で決めてください");
        $('#signupFormPasswordErrs').html("");
      }
//      $('#signupFormPasswordNotes').html("")
    });

    //$('#order_user_attributes_password_confirmation').focus(function() { 
      $('#signupFormPassConfirmNotes').html("上に入れたパスワードをもう一度");
    //});
    $('#order_user_attributes_password_confirmation').blur(function() {
      if ($('#order_user_attributes_password_confirmation')[0].value.length!=0 && $('#order_user_attributes_password_confirmation')[0].value != $('#order_user_attributes_password')[0].value) {
        $('#signupFormPassConfirmNotes').html("");
        $('#signupFormPassConfirmErrs').html("上に入力したパスワードと一致していません");       
      } else {
        $('#signupFormPassConfirmNotes').html("上に入れたパスワードをもう一度");
        $('#signupFormPassConfirmErrs').html("");
      }
//      $('#signupFormPassConfirmNotes').html("")
    });

    //$('#order_user_attributes_email').focus(function() {
       $('#signupFormEmailNotes').html("購入されたクーポンはメールでお届けします");
    //});
    /*.blur(function(){
/*      self.email_name_regex  = '[\w\.%\+\-]+'.freeze
      self.domain_head_regex = '(?:[A-Z0-9\-]+\.)+'.freeze
      self.domain_tld_regex  = '(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|jobs|museum)'.freeze
      self.email_regex       = /\A#{email_name_regex}@#{domain_head_regex}#{domain_tld_regex}\z/i
      
    })*/
    
    //$('#order_user_attributes_email').blur(function() { $('#signupFormEmailNotes').html("")});*/
  },
  mailAddressConfirm: function(_val){
    var reenter = window.prompt("確認のため、もう一度メールアドレスを入力してください", "");
    if (reenter == "") return false;
    if (reenter != _val) {
      $('#userRegistOrLoginForm').find('.error_message').html("確認の入力が一致していません。");
      return false;
    }
    $('#userRegistOrLoginForm').find('.error_message').html("");
    $('#userRegistOrLoginForm').find('.summary').html("決済時に新規アカウント登録を行います。");
    return true;
  }
}

window.setTimeout("window.scrollTo(0, 1)", 500);


String.prototype.addDelimiter = function() {
  var val = String(this), tmp;
  while (val != (tmp = val.replace(/^([+-]?\d+)(\d\d\d)/, "$1,$2"))) {
    val = tmp;
  }
  return val;
}

function switch_tab(prefix, index){
    $("div#shopinfo ul li[class^="+ prefix +"] a").each(function() {
        $(this).removeClass('on');
    });
	$("div#shopinfo ul li." + prefix + index + " a").addClass('on');
	
    $("div[id^="+ prefix +"]").each(function() {
        $(this).hide();
    });
    $("#"+prefix + index).show();
}
(function($){
	$(document).ready(function() {
	  // the element in which we will observe all clicks and capture
	  // ones originating from pagination links
    $("div.pagination.ajax a").live("click", function() {
       show_loading($(this));
       $.get(this.href, null, hide_loading, "script");
       return false;
    });


    $('a[rel=lightbox]').each(function(){
      $(this).click(function(){
        var cover = $(document.createElement("div"));
        cover.addClass("screen_cover");
        cover.css('height',document.height+"px")
        cover.appendTo(document.body);


        event.preventDefault();

        cover.css('-webkit-transition','opacity 0.5s linear');
        cover.addClass("dark");

        var picture_box = $(document.createElement('div'));
        picture_box.addClass("large_picture")
        var image = $(document.createElement('img'));
        image.attr("src",$(this).attr("href"));
        image.appendTo(picture_box);
        var close_button = $(document.createElement('div'));
        close_button.html("閉じる");
        close_button.addClass("close_button");
        close_button.appendTo(picture_box);
        
        var top_margin = (window.orientation % 180 == 0) ? 80 : 25; 
        
        picture_box.appendTo(document.body);
        picture_box.css('left', (document.width-window.scrollX-290)/2 + "px").css('top', window.scrollY+ top_margin + "px").css('-webkit-transition','opacity 0.5s linear').show();
        picture_box.addClass("show");
        picture_box.click(function(){
/*          cover.css('-webkit-transition','');
          cover.removeClass("dark");*/
          picture_box.remove();
          cover.remove();
        });
        
      });
    });



/*    $(".pic").click(function(){
      cover.css('-webkit-transition','opacity 0.5s linear');
      cover.addClass("dark");
      var large_pic = $(this).next();
      large_pic.css('left', (document.width-window.scrollX-280)/2 + "px").css('top', window.scrollY+20 + "px").css('-webkit-transition','opacity 0.5s linear').show();
      large_pic.addClass("show");
      large_pic.click(function(){
        large_pic.css('-webkit-transition','');
        cover.css('-webkit-transition','');
        cover.removeClass("dark");
        $(this).removeClass("show");
        $(this).hide();
      });
    });*/
	
	})
})(jQuery);

function show_loading(obj){
   if ($('div#cho-progress').length == 0){
       $('<div id="cho-progress" style="display:none;">Loading...</div>').appendTo('body');
   }
   
   var current_pos = obj.offset();
   var left_pos;
   if (current_pos.left < 150) {
   		left_pos = 50;
   } else {
   		left_pos = current_pos.left - 100;
   }
   $('div#cho-progress').css('left', left_pos).css('top', current_pos.top - 40).show();
}

function hide_loading(){
	$('div#cho-progress').remove();
}

function scroll_comment_top(){
	var new_position = $('div#messages').offset();
	window.scrollTo(new_position.left,new_position.top);
}

