(function($) {
	//execute right now
	//execute when document's ready
	$(function() {
// Guide Of Arrival
        var targetMail = $("form.guideOfArrival input:text");
        var targetItem = $(".guideOfArrivalItem a");
        var alertBox = $("#guideOfArrivalAlert");
        var defMsg = "メールアドレスを入力してください";
        var trim = new RegExp("(^\\s+|\\s+$)", "g");
        var regMail = new RegExp("^(?:(?:(?:(?:[a-zA-Z0-9_!#\\$\\%&'*+/=?\\^`{}~|\\-]+)(?:\\.(?:[a-zA-Z0-9_!#\\$\\%&'*+/=?\\^`{}~|\\-]+))*)|(?:\"(?:\\\\[^\\r\\n]|[^\\\\\"])*\")))\\@(?:(?:(?:(?:[a-zA-Z0-9_!#\\$\\%&'*+/=?\\^`{}~|\\-]+)(?:\\.(?:[a-zA-Z0-9_!#\\$\\%&'*+/=?\\^`{}~|\\-]+))*)|(?:\\[(?:\\\\\\S|[\\x21-\\x5a\\x5e-\\x7e])*\\])))$");
        var timeOutChecker;
        if (!targetMail.val()) targetMail.val(defMsg);

		targetMail.focus(function(){
            if ($(this).val() == defMsg) $(this).val("");
        });

		targetMail.change(function(){
			var mail = $(this).val().replace(trim, "");
            if (!mail.match(regMail)) {
                if (!mail.length) $(this).val(defMsg);
            } else {
                var data = {"mail":mail};
                guideOfArrivalSend($, "setMail", data);
            }
        });

		targetMail.blur(function(){
			var mail = $(this).val().replace(trim, "");
            if (!mail.match(regMail)) {
                if (!mail.length) $(this).val(defMsg);
            }
        });

        $("form.guideOfArrival").submit(function(){
            return false;
        });
        
        // send data
        targetItem.click(function(event){
            $(this).blur();
			var mail = targetMail.val().replace(trim, "");
            clearTimeout(timeOutChecker);
            timeOutChecker = setTimeout(function() {
                if (alertBox.css("display") != "none") {
                    alertBox.css({display: "none"});
                    targetMail.focus();
                }
            },10000);
            
            if (mail.match(regMail)) {
                var item_id = $(this).attr("item_id");
                var isbn_jan = $(this).parent().attr("class");
                var type = $(this).attr("type") - 0;
                
                var brinkE = $(".guideOfArrivalItem ." + isbn_jan).css({"display":"none"});

                data = {"mail"    : mail
                      , "item_id" : item_id
                      , "isbn_jan": isbn_jan
                      , "type"    : type
                       }
                guideOfArrivalSend($, "setItem", data, isbn_jan, brinkE);
            } else {
                $(targetMail).parent().css({"display":"block"});
                var alertMsg = mail != defMsg ? "<p>メールアドレスが正しく入力されていません<br /><br />入力したメールアドレスをご確認ください<br />" : "<p>「入荷お知らせメール送信アドレス」を入力した後に<br />「登録する/削除する/再登録する」をクリックしてください</p><p>※「登録する/削除する/再登録する」をクリックして登録完了となります</p>";

                alertBox.find("div").html(alertMsg);
                var windowHeight = window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight); 
                var targetTop = targetMail.position().top;
                var y = (windowHeight/2 > targetTop) ? (windowHeight/2) - targetTop : targetTop - (windowHeight/2);
                window.scrollTo(0, y)

                var windowWidth = window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth); 
                alertBoxX = alertBox.width() / 2;
                var x = (windowWidth/2 > alertBoxX) ? (windowWidth/2) - alertBoxX : 0;
                var y = targetMail.position().top - alertBox.height();

                alertBox.css({top: y, left: x, display: "block"}).find("p.closeBtn").click(function() {
                    $(this).parent().css({display: "none"});
                    targetMail.focus();
                    clearTimeout(timeOutChecker);
                });
            }
            return false;
        });
	});


})(jQuery);

function guideOfArrivalSend($, type, data, isbn_jan, brinkE) {
    var headerLabel = Array("新品・中古", "新品", "中古");
    var clickLabel = Array("登録する", "解除する");
    var statusLabel = Array("解除済","登録済");
    var headFlg;
    $.ajax({url  : '/guideOfArrival/' + type
         , "data" : data
         , timeout : 10000
	     , success: function(msg){
             try {
                 var response = eval("(" + msg + ")");
             } catch (e) {
                window.location.href = "";
                return;
             }
             if (response.error) {window.location.href = "";return;}
             response.type = response.type - 0;
             response.status = response.status - 0;
             response.newStockStatus = response.newStockStatus - 0;
             response.usedStockStatus = response.usedStockStatus - 0;
             if (response.type == 0) {
                 if (response.newStockStatus > 40 && response.usedStockStatus > 40) {
                     headerFlg = 0;
                 } else if (response.newStockStatus > 40) {
                     headerFlg = 1;
                 } else if (response.usedStockStatus > 40) {
                     headerFlg = 2;
                 } else {
                     window.location.href = "";
                     return;
                 }
             } else {
                 if (response.status == 0) {
                     headerFlg = 0;
                 } else if (response.status == 1) {
                     headerFlg = 2;
                 } else if (response.status == 2) {
                     headerFlg = 1;
                 } else {
                     window.location.href = "";
                     return;
                 }
             }
             setTimeout(function() {
                 brinkE.css({"display":"block"});
                 $(".guideOfArrivalItem div." + isbn_jan + " a").each(function(){
                     $(this).attr("type", (response.type + 1) % clickLabel.length).text(clickLabel[response.type]);
                     $(this).parent().find("span").text(statusLabel[response.type]);
                     $(this).parent().parent().find("legend").text(headerLabel[headerFlg] + "入荷お知らせメール");
                 });
             },400);
	     }
         , error : function() {
            window.location.href = "";
         }
    });
}
