$(function(){

    $(".click").live('click',function(event){
         var elemName = event.target.nodeName.toLowerCase();
         if (elemName == "a" || elemName == "input")
             return;
         window.location=$(this).find("a").attr("href");
         return false;
    });
    $(".popin_fan_description").prettyPopin({width: 400});
    $(".popup_login").prettyPopin({width: 500});
    $(".popin_staff, .popin_contest").prettyPopin({width: 600});

    // 完了メッセージは自動で非表示
    setTimeout(function(){
        $("div.success_box").fadeOut("slow");
    },5000);

    var focusInput;
    focusInput  = " body.login #account";
    focusInput += ",body.signup #account";
    focusInput += ",body#create #title";
    focusInput += ",body.write_new #title";

    $(focusInput).focus();

});

/* -------------------------
    Scroll top
------------------------- */
function slowdownScroll() {
    if(navigator.appName == "Microsoft Internet Explorer" && document.compatMode == "CSS1Compat") {
        sctop = document.body.parentNode.scrollTop;
    }else if(window.pageYOffset){
        sctop = window.pageYOffset;
        } else {
        sctop = document.body.scrollTop;
    }
    if(sctop){
        scup = Math.ceil(sctop*.2);
        scrollBy(0,-scup);
        if (sctop-scup) setTimeout("slowdownScroll()",15);
    }
}

/* -------------------------
    Textarea resize
------------------------- */
function resize_textarea(ev){
    var textarea = ev.target || ev.srcElement;
    var value = textarea.value;
    var lines = 3;
    for (var i = 0, l = value.length; i < l; i++){
        if (value.charAt(i) == '\n') lines++;
    }
    textarea.setAttribute("rows", lines);
}


/* -------------------------
    指定サイズでウィンドウを開き、センターに表示
------------------------- */
function gf_OpenNewWindow(pURL,pName,pSize){

    var wWidth,wHeight;
    var wSize,wFeatures;
    var wLeft,wTop,PositionX,PositionY;

    wWidth = window.screen.availWidth/2;
    wHeight = window.screen.availHeight/2;
    wSize = pSize.split(":");
    wLeft = wSize[0].split("=");
    wTop = wSize[1].split("=");
    PositionX = wWidth-wLeft[1]/2;
    PositionY = wHeight-wTop[1]/2;
    
    wFeatures = wSize+",left="+PositionX+",top="+PositionY;
    wWindow = window.open(pURL,pName,wFeatures+",scrollbars=yes,status=yes,resizable=yes");
    wWindow.focus();
}

/* -------------------------
   バイト数チェック
------------------------- */
function gf_GetLength(value){
    var i,nCnt=0;
    for(i=0; i<value.length; i++){
        if(escape(value.charAt(i)).length >= 4 ) nCnt+=2;
        else nCnt++;
    }
    return nCnt;
}

/* -------------------------
 全角数字を半角数字に
------------------------- */
function gf_ZenToHanNum(pVal) {
    return pVal.replace(/([０-９])/g,
    function ($0) {
        return String.fromCharCode($0.charCodeAt(0) - 65248);
    });
}

/* -------------------------
 全角を半角に
------------------------- */
function gf_ZenToHan(pVal) {
    return pVal.replace(/([０-９ａ-ｚＡ-Ｚ―＿])/g,
    function ($0) {
        return String.fromCharCode($0.charCodeAt(0) - 65248);
    });
}


//*********************************
// 読者になる
//*********************************
function addFan(id){

    $('.fan_'+id).find('a.button_fan_add').hide();
    $('.fan_'+id).append('<div class="fan_loading"><img src="/image/loading.gif" /></div>');

    $.post('/fan/add/'+id+'/', {fan_user_id:id}, function(data){
        if (data=='ok') {
            $('.fan_'+id).find('.fan_loading').remove();
            $('.fan_'+id).find('a.button_fan_del').show();
            return false;
        } else {
            alert('読者登録時にエラーが発生しました');
            return false;
        }
    });

}

//*********************************
// 読者をやめる
//*********************************
function delFan(id){

   // if(!confirm("読者登録を解除してもよろしいですか？")) return false;
    $.post('/fan/del/'+id+'/', {}, function(data){
        if (data=='ok') {
            $('.fan_'+id).find('a.button_fan_del').hide()
                         .end()
                         .find('a.button_fan_add').show();
            $('#b_close').click();
            return false;
        } else {
            alert('読者登録の解除時にエラーが発生しました');
            return false;
        }
    });

}

//*********************************
// IEのバージョンを調べる
//*********************************
function ieVersion() {
    var ie = (function(){
        var undef, v = 3, div = document.createElement('div');
        while (
            div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->',
            div.getElementsByTagName('i')[0]
        );
        return v> 4 ? v : undef;
    }());
    return ie;
}


/* ------------------------- 
     help colse 
------------------------- */
function helpClose() {
    $(".err_box").fadeOut("slow");
    return false;
} 

//*********************************
// Androidアプリでダウンロードや購入用のボタンを出す
//*********************************
function loadDownloadLink(index) {
    var $this = $(this);
    var uri = $this.attr("href");
    $.get(uri, function(data) {
        $this.removeClass("loading");
        if (data["link"]) {
            $this.after($(data["link"]));
            $this.remove();
        } else {
            $this.after("エラーが発生しました");
            $this.remove();
        }
    });
    return true;
}

//*********************************
// Androidアプリでのワンクリック購入
//*********************************
function purchase(event) {
    event.preventDefault();
    if (! confirm("購入してもよろしいですか？"))
        return false;

    var $form = $(event.currentTarget);
    var $loadingMessage = $("<div class=\"loading\">購入手続き中…</div>"); 
    var fadeOuting = true;
    var blink = function() {
        fadeOuting = ! fadeOuting;
        $loadingMessage.fadeTo(700, fadeOuting ? 0.9 : 0.2, blink);
    }
    blink();
    $("input[type=\"submit\"]", $form).hide();
    $loadingMessage.appendTo($form).show();
    var callback = function(data) {
        $loadingMessage.remove();
        if (data["result"] == "ok") {
            $form.after($(data["link"]));
            $form.remove();
            alert("購入手続きが終了しました。\n本をダウンロードできます。");
        } else if (data["result"] == "ng") {
            $("input[type=\"submit\"]", $form).show();
            alert(data["message"]);
        } else {
            $("input[type=\"submit\"]", $form).show();
            alert("予期せぬエラーが発生しました。");
        }
    };
    $.post($form.attr("action"), {}, callback);
}

/* -------------------------
 カテゴリ選択（create.jsとedit.jsで使用）
------------------------- */
category = {};

category.showSubcategoryInitially = function() {
	var $categorySelect = $('#category');
	var catId = $categorySelect.val();
	var $subcategoryArea = $('div.subcategory_area');

	$('select.subcategory').hide();
	if (catId != '') {
	    $('select.subcategory_' + catId).show();
	    $subcategoryArea.show();
	} else {
	    $subcategoryArea.hide();
	}
};

category.showSubcategory = function(event) {
	var catId = $('#category').val();
	var $subcategorySelect = $('select.subcategory');
	var $subcategoryArea = $('div.subcategory_area');

	$('select.subcategory').hide();
	if (catId != '') {
        $('select.subcategory_' + catId).show();
        $subcategoryArea.show();
	} else {
        $subcategoryArea.hide();
	}
};

category.removeExcessSelects = function() {
	var catId = $('#category').val();
	$('select.subcategory').not('.subcategory_' + catId).remove();
}

