var comics;
if (!comics) comics = {};

comics.tips2Init = function() {
    // 投票按鈕
    $('#voting').jqm({modal: true});
    $('a[name="btnVote"]').click(function() {
        if (confirm('一人一天限投一票\n確定要投他嗎？')) {
            $('#voting').jqmShow();
            var id = $(this).attr('id');
            $.ajax({
                url: 'ajax_comics_vote.php',
                cache: false,
                type: 'post',
                data: {id: id},
                success: function(data) {
                    switch ($.trim(data)) {
                        case 'notLogin':
                            alert('請先登入會員！');
                            window.location = 'login.php';
                            break;
                        case 'noid':
                            alert('請勿修改參數！');
                            break;
                        case 'done':
                            alert('感謝你投我一票！');
                            break;
                        case 'doubleVote':
                            alert('您今天已經投過票了！')
                            break;
                    }
                    $('#voting').jqmHide();
                },
                error: function() {
                    $('#voting').jqmHide();
                }
            });
        }
        return false;
    });
    
	$('#btnArea').click(function() {
		window.location = 'tips.php?area=' + $('#area').val();
		return false;
	});
	
	$('#areaSelect').click(function() {
		$(this).find('.pop').toggle();
	});
	
	$('#ulArea > li').each(function() {
		$(this).click(function() {
			$('#area').val($(this).attr('id'));
			$('#spanArea').text($(this).text());
		});
	});
	
	$('#btnSearch').click(function() {
		window.location = 'tips.php?keyword=' + $('#keyword').val();
		return false;
	});
	$('#keyword').click(function() {
		if ($(this).val() == '搜尋挑戰者暱稱或景點') {
			$(this).val('');
		}
	});
	$('#btnUp').click(function() {
		window.history.back();
		return false;
	});
}

/**
* membership forget2 page initial
*/
comics.membershipForget2Init = function() {
	// modal initial
	$('#processModal').jqm({modal: true});
	
	// next button
	$('#btnNext').css('cursor', 'pointer').click(function() {
		if($('#year option:selected').val() == '') {
			alert('請選擇年份');
			return false;
		}
		if($('#month option:selected').val() == '') {
			alert('請選擇月份');
			return false;
		}
		if($('#day option:selected').val() == '') {
			alert('請選擇日期');
			return false;
		}
		if ($('#zip').val() == '') {
			alert('請填寫郵遞區號');
			return false;
		}
		
		$('#processModal').jqmShow();
		$.ajax({
			url: 'ajax_request_password2.php',
			cache: false,
			type: 'post',
			data: {year: $('#year option:selected').val(), month: $('#month option:selected').val(), day: $('#day option:selected').val(), zip: $('#zip').val()},
			success:function(data) {
				alert(data);
				$('#processModal').jqmHide();
			},
			error: function() {
				$('#processModal').jqmHide();
			}
		});
		
		return false;
	});
}

/**
* membership forget1 page initial
*/
comics.membershipForget1Init = function() {
	// modal initial
	$('#processModal').jqm({modal: true});
	
	// next button
	$('#btnNext').css('cursor', 'pointer').click(function() {
		switch ($('[name="way"]:checked').val()) {
			case '1':
				if ($('#usn').val() == '') {
					alert('請輸入帳號');
					$('#usn').focus();
				} else {
					$('#processModal').jqmShow();
					$.ajax({
						url: 'ajax_request_password.php',
						type: 'post',
						cache: false,
						data: {usn: $('#usn').val()},
						success: function(data) {
							alert(data);
							$('#processModal').jqmHide();
						},
						error: function() {
							$('#processModal').jqmHide();
						}
					});
				}
				break;
			case '2':
				window.location = 'membership_forget2.php';
				break;
			default: alert('請選擇方式');
		}
		return false;
	});
}

comics.tipsInit = function() {
	$('#btnArea').click(function() {
		window.location = 'tips.php?area=' + $('#area').val();
		return false;
	});
	
	$('#areaSelect').click(function() {
		$(this).find('.pop').toggle();
	});
	
	$('#ulArea > li').each(function() {
		$(this).click(function() {
			$('#area').val($(this).attr('id'));
			$('#spanArea').text($(this).text());
		});
	});
	
	$('#btnSearch').click(function() {
		window.location = '?keyword=' + $('#keyword').val();
		return false;
	});
	$('#keyword').click(function() {
		if ($(this).val() == '搜尋挑戰者暱稱或景點') {
			$(this).val('');
		}
	});
}

comics.memberInit = function() {
	// modal initial
	$('#memberModal, #saving').jqm({modal: true});
	
	$('#zip').click(function() {
		if ($(this).val() == '郵遞區號') {
			$(this).val('');
		}
	});
    
	// preview button
	$('#btnPreview').click(function() {
		if ($('#usn').val() == '') {
			alert('請填寫帳號');
			$('#usn').focus();
			return false;
		}
		if ($('#pwd').val() == '') {
			alert('請填寫密碼');
			$('#pwd').focus();
			return false;
		}
		if ($('#confirm').val() == '') {
			alert('請填寫確認密碼');
			$('#confirm').focus();
			return false;
		}
		if ($('#pwd').val() != $('#confirm').val()) {
			alert('密碼不相同');
			return false;
		}
		if ($('#nickname').val() == '') {
			alert('請填寫暱稱');
			$('#nickname').focus();
			return false;
		}
		if ($('#email').val() == '') {
			alert('請填寫email');
			$('#email').focus();
			return false;
		}
		if ($('#zip').val() == '' || $('#zip').val() == '郵遞區號') {
			alert('請填寫郵遞區號');
			$('#zip').focus();
			return false;
		}
		if ($('#address').val() == '') {
			alert('請填寫地址');
			$('#address').focus();
			return false;
		}
		if ($('#name').val() == '') {
			alert('請填寫姓名');
			$('#name').focus();
			return false;
		}
		if ($('#cell').val() == '') {
			alert('請填寫行動電話');
			$('#cell').focus();
			return false;
		}
		if ($('#birthYear').val() == '') {
			alert('請選擇生日（年）');
			$('#birthYear').focus();
			return false;
		}
		if ($('#birthMonth').val() == '') {
			alert('請選擇生日（月）');
			$('#birthMonth').focus();
			return false;
		}
		if ($('#birthDay').val() == '') {
			alert('請選擇生日（日）');
			$('#birthDay').focus();
			return false;
		}
		if ($('#agree').attr('checked') == false) {
			alert('您尚未勾選同意約定條款');
			return false;
		}

		$('#mUsn').text($('#usn').val());
		$('#mNickname').text($('#nickname').val());
		$('#mEmail').text($('#email').val());
		$('#mZip').text($('#zip').val());
		$('#mAddress').text($('#address').val());
		$('#mCompany').text($('#company').val());
		$('#mName').text($('#name').val());
		$('#mTel').text($('#tel').val());
		$('#mCell').text($('#cell').val());
		$('#mBirthYear').text($('#birthYear').val());
		$('#mBirthMonth').text($('#birthMonth').val());
		$('#mBirthDay').text($('#birthDay').val());
		$('[name="gender"]:checked').val() == 1 ? $('#mGender').text('男') : $('#mGender').text('女');
		$('#memberModal').jqmShow();
		return false;
	});
	
	// submit button
	$('#btnSubmit').click(function() {
		$('#memberModal').jqmHide();
		$('#saving').jqmShow();
		$.ajax({
			url: 'ajax_member_register.php',
			cache: false,
			type: 'post',
			data: {usn: $('#usn').val(), pwd: $('#pwd').val(), nickname: $('#nickname').val(), email: $('#email').val(), zip: $('#zip').val(), address: $('#address').val(), company: $('#company').val(), name: $('#name').val(), tel: $('#tel').val(), cell: $('#cell').val(), year: $('#birthYear').val(), month: $('#birthMonth').val(), day: $('#birthDay').val(), edm: $('[name="epaper"]:checked').val()},
			success: function(data) {
				if ($.trim(data) == '加入會員成功') {
					alert(data);
                    $.ajax({
                        url: 'login.php',
                        type: 'post',
                        data: {login: 1, usn: $('#usn').val(), pwd: $('#pwd').val()},
                        success: function() {
                            window.location = 'cover.php';
                        }
                    });
				} else {
					alert(data);
				}

				$('#saving').jqmHide();
			},
			error: function() {
				$('#saving').jqmHide();
			}
		});
		return false;
	});
	
	// date pick
	$('ul#year > li').each(function() {
		$(this).click(function() {
			$('span#spanYear').text($(this).text());
			$('#birthYear').val($.trim($(this).text()));
		});
	});
	
	$('ul#month > li').each(function() {
		$(this).click(function() {
			$('span#spanMonth').text($(this).text());
			$('#birthMonth').val($.trim($(this).text()));
		});
	});
	
	$('ul#day > li').each(function() {
		$(this).click(function() {
			$('span#spanDay').text($(this).text());
			$('#birthDay').val($.trim($(this).text()));
		});
	});
	
	// date popup
	$('div.select').each(function() {
		$(this).click(function() {
			$(this).find('div.pop').toggle();
		});
	});
}

/**
* link page initial
*/
comics.linkInit = function() {
	// link select
	$('[name="link"]').each(function() {
		$(this).click(function() {
			$(this).select();
		});
	});
	
	// copy button
	$('[name="btnCopy"]').each(function() {
		$(this)
			.css('cursor', 'pointer')
			.click(function() {
				$('[name="link"]').eq($('[name="btnCopy"]').index(this)).select();
				$.copy($('[name="link"]').eq($('[name="btnCopy"]').index(this)).val());
			});
	});
}

/**
* membership2 page initial
*/
comics.membership2Init = function() {
	// link select
	$('#link').click(function() {
		$(this).select();
	});
	
	// copy button
	$('#btnCopy')
		.css('cursor', 'pointer')
		.click(function() {
			$('#link').select();
			$.copy($('#link').val());
		});
}

/**
* everyone page initial
*/
comics.everyoneInit = function() {
	// link select
	$('#link').click(function() {
		$(this).select();
	});
	
	// copy button
	$('#btnCopy')
		.css('cursor', 'pointer')
		.click(function() {
			$('#link').select();
			$.copy($('#link').val());
		});
}

/**
* membership page initial
*/
comics.membershipInit = function() {
	// textarea select
	$('#link').click(function() {
		$(this).select();
	});
	
	// copy button
	$('#btnCopy')
		.css('cursor', 'pointer')
		.click(function() {
			$('#link').select();
			$.copy($('#link').val());
		});
}

/**
* login page initial
*/
comics.loginInit = function() {
	$('#usn').focus();
	$('br.clearfixplain').remove();
}

/**
* member page initial
*/
comics.memeberInit = function() {
	//alert();
}

/**
* choose page initial
*/
comics.chooseInit = function() {
    // modal initial
    $('div#modalHowToPlay').jqm({modal: true});
    
   /* $('#btnHowToPlay').click(function() {
        $('div#modalHowToPlay').jqmShow();
        return false;
    });*/
    
	// button next
	$('#btnNext').click(function() {
		if ($(this).parent().attr('href') == '#') {
			alert('尚未選擇樣式');
		} else {
			window.location = $(this).parent().attr('href');
		}
		return false;
	});
	// image pick
	var crtStyle = '';
	urlArr = ['creation_six2.php', 'creation_six3.php', 'creation_six.php', 'creation_six4.php', 'creation2.php', 'creation3.php', 'creation.php', 'creation4.php'];
	$('[name="chooseImg"]').each(function(i) {
		$(this)
			.css('cursor', 'pointer')
			.data('go', {on: $(this).attr('src').replace('_', '_over_'), out: $(this).attr('src'), url: urlArr[i]})
			.click(function() {
				if (crtStyle != '') crtStyle.attr('src', crtStyle.data('go').out);
				$(this).attr('src', $(this).data('go').on);
				crtStyle  =$(this);
				$('#btnNext').parent().attr('href', $(this).data('go').url);
			});
	});
}

/**
* creation page initial
*/
comics.creationInit = function() {
    // modal initial
    $('div#loading, div#saving, div#popup_bg, div#modalHowToPlay').jqm({modal: true});
    
    /*$('#btnHowToPlay').click(function() {
        $('div#modalHowToPlay').jqmShow();
        return false;
    });*/
    
    $('div#popup_bg').jqmShow();
    
    // float controler
    setInterval(function() {
        $('#right_go_bg').animate({top: $(window).scrollTop()+50}, 200);
    }, 500);
    
    // add path
    $('#btnPathAdd')
        .data('max', 4)
        .click(function() {
            if ($(this).data('max') < 8) {
                $('.road_bg').eq($(this).data('max')).fadeIn('fast');
                $('img[name="arrowImg"]').eq($(this).data('max')-1).fadeIn('fast');
                $(this).data('max', $(this).data('max')+1);
            } else {
                alert('已達上限');
            }
            return false;
        });
    
    // color picker
    $('#color')
        .css('cursor', 'pointer')
        .click(function() {
            $(this).find('#color_choose').toggle();
        });
    
    colorArr = new Array('#000', '#fff', '#2CA376', '#253E99', '#FF8500', '#75367A', '#F7D900', '#E30000', '#009900');
    $('#color_choose td').each(function() {
        $(this).click(function() {
            $('#color_down').css('backgroundColor', colorArr[$('#color_choose td').index(this)]);
        });
    });

    // butto save
    $('#btnSave').click(function() {
        $.ajax({
                url: 'ajax_check_member.php',
                cache: false,
                success: function(data) {
                    if ($.trim(data) == '0') {
                        alert('編輯時間超過一小時，因安全性緣故，系統將自動登出，\n你可以「另開視窗」，重新登入後就可以再繼續編輯你的漫畫喔！﹝未完成的作品將會自動保留，請放心﹞');
                    } else {
                        if ($.trim($('#money').val()) == '') {
                            alert('請填寫使用金額');
                            $('#money').focus();
                        } else {
                            var re = /^\d+$/;
                            if (!re.test($.trim($('#money').val()))) {
                                alert('金額欄位請填寫正整數');
                            } else {
                                if ($.trim($('#good').val()) == '') {
                                    alert('請填寫短旅行哪裡好！');
                                    $('#good').focus();
                                } else {
                                    var pathCheck = false;
                                    $('input[name="path"]').each(function() {
                                        if ($.trim($(this).val()) != '') {
                                            pathCheck = true;
                                        }
                                    });
                                    if (!pathCheck) {
                                        alert('請至少填寫一項路線！');
                                    } else {
                                        if (confirm('按下發布後，就不能再修改漫畫內容囉！\n﹝一位會員只有一次發布的機會喔，確定要發布嗎？﹞')) {
                                            var ul = $('#comicsUl');
                                            pathArr = new Array()
                                            $('input[name="path"]').each(function() {
                                                if ($.trim($(this).val()) != '') {
                                                    pathArr.push($(this).val());    
                                                }
                                            });
                                            pathStr = pathArr.join(',');                               

                                             $('#saving').jqmShow();
                                            $.ajax({
                                                url: 'ajax_detail_insert.php',
                                                cache: false,
                                                type: 'post',
                                                data: {type: $('#frameType').val(), money: $('#money').val(), more: $('#more').val(), li1: $('li:eq(0)', ul).html(), li2: $('li:eq(1)', ul).html(), li3: $('li:eq(2)', ul).html(), li4: $('li:eq(3)', ul).html(), li5: $('li:eq(4)', ul).html(), li6: $('li:eq(5)', ul).html(), li7: $('li:eq(6)', ul).html(), li8: $('li:eq(7)', ul).html(), path: pathStr, good: $('#good').val()},
                                                success: function(data) {
                                                    switch($.trim(data)) {
                                                        case '1':
                                                            window.location = 'everyone.php';
                                                            break;
                                                        case '2':
                                                            alert('編輯時間超過一小時，因安全性緣故，系統將自動登出，\n你可以「另開視窗」，重新登入後就可以再繼續編輯你的漫畫喔！﹝未完成的作品將會自動保留，請放心﹞');
                                                            $('#saving').jqmHide();
                                                            break;
                                                        case '3':
                                                            alert('尚未製作封面');
                                                            $('#saving').jqmHide();
                                                            break;
                                                        case '4':
                                                            alert('儲存過程發生錯誤');
                                                            $('#saving').jqmHide();
                                                            break;
                                                        case '5':
                                                            alert('您已經建立過漫畫');
                                                            $('#saving').jqmHide();
                                                            break;
                                                    }
                                                }
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
       
        
        return false;
    });
    
    crtFrame = '';
    crtObj = '';
    
    // text select
    $('#fontSize > li').each(function() {
        $(this).click(function() {
            $('#textValue').text($(this).text());
        });
    });
    
    // insert text
    $('#btnTextInput').click(function() {
        // check text
        if ($.trim($('#text').val()) == '') {
            alert('請先輸入文字');
            $('#text').focus();
        } else {
            if (crtFrame == '') {
                alert('小提醒：請先在你想要編輯的圖框上點一下喔！');
            } else {
                var theTool = 'tools2';
                var zIndex = 2;
                var fontSize = $('#textValue').text();
                if (isNaN(fontSize)) {
                    fontSize = 12;
                } else {
                    fontSize = parseInt(fontSize);
                }

                // 找高的z-index
                $('img[status="img"], div[status="txt"]', crtFrame).each(function() {
                    if ($(this).css('z-index') >= zIndex) {
                        zIndex = parseInt($(this).css('z-index'))+1;
                    }
                });
                
                $('<div>')
                    .attr({status: 'txt'})
                    .css({zIndex: zIndex, fontSize: fontSize, left: 80, top: 60, position: 'absolute', color    : $('#color_down').css('backgroundColor')})
                    .html($('#text').val().replace(/\n/g, '<br>'))
                    .appendTo(crtFrame)
                    .contextMenu({menu: theTool}, function(act, ele, pos) {
                        switch (act) {
                            case 'up':
                                var z = parseInt(ele.css('z-index'));
                                ele.css('z-index', z+1);
                                break;
                            case 'down':
                                var z = parseInt(ele.css('z-index'));
                                if (z-1 >= 2) {
                                    ele.css('z-index', z-1);
                                }
                                break;
                            case 'flip':
                                if (ele.attr('flip') == 1) {
                                    ele.attr('src', ele.attr('ssrc').replace('_h', '_b'));
                                    ele.attr('flip', 0);
                                } else {
                                    ele.attr('src', ele.attr('ssrc').replace('_b', '_h'));
                                    ele.attr('flip', 1);
                                }
                                break;
                        }
                    })
                    .draggable({
                        start: function() {
                            $('img[status="img"], div[status="txt"]').removeClass('addBorder');
                            $(this).addClass('addBorder')
                            crtObj = $(this);
                        }
                    })
                    .click(function() {
                        $('img[status="img"], div[status="txt"]').removeClass('addBorder');
                        $(this).addClass('addBorder')
                        crtObj = $(this);
                    });
            }
        }
        return false;
    });
    
    // insert icon
    $('div[rel="face"] img').each(function() {
        $(this).click(function() {
            if (crtFrame == '') {
                alert('小提醒：請先在你想要編輯的圖框上點一下喔！');
            } else {
                var src = $(this).attr('ssrc').replace('_s', '_b');
                var ssrc = $(this).attr('ssrc').replace('_s', '_b');
                var w = $(this).attr('w') + 'px';
                var h = $(this).attr('h') + 'px';
                var theTool = '';
                var zIndex = 2;
                if ($(this).attr('verticle') == 'yes') theTool = 'tools'; else theTool = 'tools2';
            
                // 找高的z-index
                $('img[status="img, div[status="txt"]"]', crtFrame).each(function() {
                    if ($(this).css('z-index') >= zIndex) {
                        zIndex = parseInt($(this).css('z-index'))+1;
                    }
                });
                
                $('<img>')
                    .attr({src: src, status: 'img', flip: 0, w: w, h: h, ssrc: ssrc})
                    .data('c', 0)
                    .css({zIndex: zIndex, width: w, height: h, left: 80, top: 60, position: 'absolute'})
                    .appendTo(crtFrame)
                    .contextMenu({menu: theTool}, function(act, ele, pos) {
                        switch (act) {
                            case 'up':
                                var z = parseInt(ele.css('z-index'));
                                ele.css('z-index', z+1);
                                break;
                            case 'down':
                                var z = parseInt(ele.css('z-index'));
                                if (z-1 >= 2) {
                                    ele.css('z-index', z-1);
                                }
                                break;
                            case 'flip':
                                if (ele.attr('flip') == 1) {
                                    ele.attr('src', ele.attr('ssrc').replace('_h', '_b'));
                                    ele.attr('flip', 0);
                                } else {
                                    ele.attr('src', ele.attr('ssrc').replace('_b', '_h'));
                                    ele.attr('flip', 1);
                                }
                                break;
                        }
                    })
                    .draggable({
                        start: function() {
                            $('img[status="img"], div[status="txt"]').removeClass('addBorder');
                            $(this).addClass('addBorder')
                            crtObj = $(this);
                        }
                    })
                    .click(function() {
                        $('img[status="img"], div[status="txt"]').removeClass('addBorder');
                        $(this).addClass('addBorder')
                        crtObj = $(this);
                    });
            }
        });
    });    
    
    // 大圖框加上外框
    $('#comicsUl li').each(function() {
        $(this).click(function() {
            crtFrame = $(this);
            var bc = '3px solid ' + borderColor;
            $(this)
                .css('border', bc)
                .siblings().css('border', '3px solid black');
        });
    });
    
    $('div.liImg').draggable();
	 
    // font size module
    comics.fontSizeModule();
    
    // tool module
    comics.toolModule();

    // face module
    comics.faceModule();
    
    // folder upload initial
    comics.folderUploadInit();
}
/**
* folder upload initial
*/
comics.folderUploadInit = function() {
	$('#file').fileUpload ({
		'uploader': 'uploader.swf',
		'script': 'upload_cover.php',
		'cancelImg': 'images/cancel.png',
		'buttonImg': 'images/icon3_2.png',
		'auto': false,
		'width': 50,
		'height': 40,
		'wmode': 'transparent',
		'sizeLimit': 1500000,
		'fileExt': '*.jpg',
		'fileDesc': true,
		'rollover': true,
		'onSelect': function() {
			if (crtFrame == '') {
				alert('小提醒：請先在你想要編輯的圖框上點一下喔！');
			} else {
				$('input#file').fileUploadStart();
			}
			return false;
		},
		'onProgress': function() {
			$('div#loading').jqmShow();
		},
		'onComplete': function(a, b, c, d, e) {
			$('div#loading').jqmHide();
			$('div.liImg', crtFrame)
				.animate({left: 0, top: 0}, 0)
				.html(d)
				.find('img')
                .data('c', 0)
				.click(function() {
					crtObj = $(this);
				});
		},
		'onError': function(a, b, c, d) {
			$('div#loading').jqmHide();
			if(d.type == 'File Size') {
				alert('檔案大小超過1.5MB限制。')
			} else {
				alert('上傳發生錯誤');
			}
		}
	});
}

/**
* cover page initial
*/
comics.coverInit = function() {
    // 檢查瀏覽器版本
    $.each($.browser, function(i, v) {
        if (v == true) {
            $('#browser').val(i + ' ' + $.browser.version);
        }
    });
    
    // modal initial
    $('div#modalHowToPlay').jqm({modal: true});
    
    /*$('#btnHowToPlay').click(function() {
        $('div#modalHowToPlay').jqmShow();
        return false;
    });*/
    
    // area select
    $('#ulArea li').each(function(i) {
        $(this).click(function() {
            $('#spanArea').text($(this).text());
            $('#ecc_area').val(i+1);
        });
    });
    
    // next button
    $('#btnNext').click(function() {
        // check login
        $.ajax({
            url: 'ajax_check_member.php',
            cache: false,
            success: function(data) {
                if ($.trim(data) == 0) {
                    alert('請先登入會員');
                } else {
                    // check contents
                    if ($.trim($('#subject').val()) == '') {
                        alert('請填寫標題');
                        return false;
                    }
                    
                    if ($('#ecc_year').val() == '' || $('#ecc_month').val() == '' || $('#ecc_day').val() == '') {
                        alert('請選擇出遊日');
                        return false;
                    }
                    
                    if ($('#ecc_area').val() == '') {
                        alert('請選擇旅行地區');
                        return false;
                    }
                    
                    if ($.trim($('#book_pic').html()) == '') {
                        alert('請上傳圖片');
                        return false;
                    }
                    
                    // start saving
                    $('#saving').jqmShow();
                    
                    var json = [];
                    var imgDiv = $('#book_pic');
                    var bk = '"bk": {"src": "' + imgDiv.find('img').attr('src') + '", "w": "' + imgDiv.find('img').width() + '", "h": "' + imgDiv.find('img').height() + '", "l": "' + imgDiv.position().left +'", "t": "' + imgDiv.position().top + '"}';
                    var imgArr = [];
                    $('img[status="img"]').each(function() {
                        imgArr.push('{"z": "' + $(this).css('z-index') + '", "src": "' + $(this).attr('ssrc') + '", "w": "' + $(this).width() + '", "h": "' + $(this).height() + '", "l": "' + $(this).position().left + '", "t": "' + $(this).position().top + '", "f": "' + $(this).attr('flip') + '", "ow": "' + $(this).attr('ow') + '", "oh": "' + $(this).attr('oh') + '"}');
                    });
                    
                    json.push(bk);
                    json.push('"img": [' + imgArr.join(', ') + ']');
                    json = '{' + json.join(', ') + '}';
                    
                    $.ajax({
                        url: 'ajax_cover_insert.php',
                        cache: false,
                        type: 'post',
                        data: {subject: $('#subject').val(), year: $('#ecc_year').val(), month: $('#ecc_month').val(), day: $('#ecc_day').val(), nickname: $('#nickname').val(), place: $('#place').val(),area: $('#ecc_area').val(), json: json, browser:  $('#browser').val()},
                        success: function(data) {
                            if ($.trim(data) == 'ok') {
                               window.location = 'choose.php';
                            } else {
                                alert('發生錯誤');
                                setTimeout(function() {
                                    $('#saving').jqmHide();
                                }, 1500);
                            }
                        }
                    });
                }
            }
        });
        
        return false;
    });
    
    // reset button
    $('#btnReset').click(function() {
        $('#book_img img[status="img"]').remove();
        return false;
    });
    
    //圖片點選效果
    crtObj = '';
    $('div[rel="face"] img').each(function() {
        $(this).click(function() {
            var src = $(this).attr('ssrc').replace('_s', '_b');
            var ssrc = $(this).attr('ssrc').replace('_s', '_b');
            var theTool = '';
            var zIndex = 2;
            var w = $(this).attr('w') + 'px';
            var h = $(this).attr('h') + 'px';
            var ow = $(this).attr('ow');
            var oh = $(this).attr('oh');
            
            // 找高的z-index
            $('img[status="img"]', $('div#book_img')).each(function() {
                if ($(this).css('z-index') >= zIndex) {
                    zIndex = parseInt($(this).css('z-index'))+1;
                }
            });
            
            if ($(this).attr('verticle') == 'yes') theTool = 'tools'; else theTool = 'tools2';
            $('<img>')
                .attr({src: src, status: 'img', flip: 0, ow: ow, oh: oh, w: w, h: h, ssrc: ssrc})
                .data('c', 0)
                .css({zIndex: zIndex, width: w, height: h, left: 70, top: 110, position: 'absolute'})
                .appendTo($('div#book_img'))
                .contextMenu({menu: theTool}, function(act, ele, pos) {
                    switch (act) {
                        case 'up':
                            var z = parseInt(ele.css('z-index'));
                            ele.css('z-index', z+1);
                            break;
                        case 'down':
                            var z = parseInt(ele.css('z-index'));
                            if (z-1 >= 2) {
                                ele.css('z-index', z-1);
                            }
                            break;
                        case 'flip':
                            if (ele.attr('flip') == 1) {
                                ele.attr('src', ele.attr('ssrc').replace('_h', '_b'));
                                ele.attr('flip', 0);
                            } else {
                                ele.attr('src', ele.attr('ssrc').replace('_b', '_h'));
                                ele.attr('flip', 1);
                            }
                            break;
                    }
                })
                .draggable({
                    start: function() {
                        $(this)
                            .addClass('addBorder')
                            .siblings('img[status="img"]')
                            .removeClass('addBorder');
                        crtObj = $(this);
                    }
                })
                .click(function() {
                    $(this)
                        .addClass('addBorder')
                        .siblings('img[status="img"]')
                        .removeClass('addBorder');
                    crtObj = $(this);
                });
        });
    });
    
    // picture initail
    $('div#book_pic').draggable();
    
    // date value
    var date = new Date();
    var y = date.getFullYear();
    var m = '';
    var d = '';
    var fromDate = y-50;
    var yStr = '';
    for (i = y; i >= fromDate; i--) {
        yStr += '<li>' + i + '</li>';
    }
    for (i = 1; i <= 12; i++) {
        m += '<li>' + i + '</li>';
    }
    for (i = 1; i <= 31; i++) {
        d += '<li>' + i + '</li>';
    }    
    $('ul#year').html(yStr);
    $('ul#month').html(m);
    $('ul#day').html(d);
    
    // date pick
    $('ul#year > li').each(function() {
        $(this).click(function() {
            $('span#spanYear').text($(this).text());
            $('#ecc_year').val($.trim($(this).text()));
        });
    });
    
    $('ul#month > li').each(function() {
        $(this).click(function() {
            $('span#spanMonth').text($(this).text());
            $('#ecc_month').val($.trim($(this).text()));
        });
    });
    
    $('ul#day > li').each(function() {
        $(this).click(function() {
            $('span#spanDay').text($(this).text());
            $('#ecc_day').val($.trim($(this).text()));
        });
    });
    
    // date popup
    $('div.select').each(function() {
        $(this).click(function() {
            $(this).find('div.pop').toggle();
        });
    });
    
    // face module
    comics.faceModule();
    
    // tool madule
    comics.toolModule();
    
    // submit button define
    $('a#btnSubmit').click(function() {
        $('#file').fileUploadStart();
        return false;
    });

    // modal initial
    $('div#loading, div#saving').jqm({modal: true});
        
    // upload button define
    $('#file').fileUpload ({
        'uploader': 'uploader.swf',
        'script': 'upload_cover.php',
        'cancelImg': 'images/cancel.png',
        'buttonImg': 'images/icon3_2.png',
        'auto': true,
        'width': 50,
        'height': 40,
        'sizeLimit': 1500000,
        'wmode': 'transparent',
        'fileExt': '*.jpg',
        'fileDesc': true,
        'rollover': true,
        onSelect: function() {
            return false;
        },
        'onProgress': function() {
            $('div#loading').jqmShow();
        },
        'onComplete': function(a, b, c, d, e) {
            $('div#loading').jqmHide();
            $('div#book_pic')
                .animate({left: '0', top: '0'}, 0)
                .html(d)
                .find('img')
                .data('c', 0)
                .click(function() {
                    crtObj = $(this);
                });
        },
        'onError': function(a, b, c, d) {
            $('div#loading').jqmHide();
            if(d.type == 'File Size') {
                alert('檔案大小超過1.5MB限制。')
            } else {
                alert('上傳發生錯誤');
            }
        }
    });
}

/**
* tool module
*/
comics.toolModule = function() {
	// enlarge button
	moveSize = 4;
	moveInterval = '';
	$('a[name="btnEnlarge"]')
		.mousedown(function() {
			moveInterval = setInterval('comics.enlargeImg()', 100);
		})
		.mouseout(function() {
			clearInterval(moveInterval)
		})
		.mouseup(function() {
			clearInterval(moveInterval)
		})
		.click(function() {
			comics.enlargeImg();
			return false;
		});
	
	$('a[name="btnReduce"]')
		.mousedown(function() {
			moveInterval = setInterval('comics.decreaseImg()', 100);
		})
		.mouseout(function() {
			clearInterval(moveInterval)
		})
		.mouseup(function() {
			clearInterval(moveInterval)
		})
		.click(function() {
			comics.decreaseImg();
			return false;
		});
	
	$('a[name="btnDel"]').click(function() {
		if (crtObj == '') {
			alert('尚未選擇物件');
		} else {
			if (confirm('確定要移除嗎？')) {
				crtObj.remove();
				crtObj = '';
			};
		}
		return false;
	});
}

/**
* check login
*/
comics.checkLogin = function() {
	$.ajax({
		url: 'ajax_check_member.php',
		cache: false,
		success: function(data) {
			var res = $.trim(data);
			return res;
		}
	});
}

/**
* face module
*/
comics.faceModule = function() {
	var moveCount = 1;
	var moveRound = 7;
	
	$('div#tab_top a').each(function() {
		$(this).click(function() {
			if ($(this).attr('status') != 'no') {
				var index = $('div#tab_top a').index(this);
				$('div[rel="face"]').hide().eq(index).find('ul').animate({'left': 0}, 0).end().show();
				moveRound = $('div[rel="face"]:visible').attr('round');
				moveCount = 1;
			}
			return false;
		});
	});
	
	// go right
	$('a#goRight').click(function() {
		if (moveCount <= moveRound && moveRound != 0) {
			var ul = $('div.item div[rel="face"]:visible ul');
			ul.animate({left: '-=345'}, 'fast');
			moveCount++;
		}
		return false;
	});
	
	// go left
	$('a#goLeft').click(function() {
		if (moveCount-1 != 0 && moveRound != 0) {
			var ul = $('div.item div[rel="face"]:visible ul');
			ul.animate({left: '+=345'}, 'fast');
			moveCount--;
		}
		return false;
	});
}

/**
* font size module
*/
comics.fontSizeModule = function() {
	$('div.select').click(function() {
		$(this).find('div.pop').toggle();
	});
}

comics.enlargeImg = function() {
	if (crtObj == '') {
		alert('尚未選擇物件');
	} else {
		switch (crtObj.attr('status')) {
			case 'txt':
				var size = parseInt(crtObj.css('font-size').replace('px', ''));
				crtObj.css('font-size', size+1);
				break;
			case 'img':
			case 'background':
				crtObj.data('c', crtObj.data('c')+1);
				var w = parseInt(crtObj.attr('w'))+(crtObj.data('c')*moveSize);
				var h = parseInt(parseInt(crtObj.attr('h'))*w/parseInt(crtObj.attr('w')));
				crtObj.animate({width: w, height: h}, 0);
				break;
		}
	}
   
}

comics.decreaseImg = function() {
	if (crtObj == '') {
		alert('尚未選擇物件');
	} else {
		switch (crtObj.attr('status')) {
			case 'txt':
				var size = parseInt(crtObj.css('font-size').replace('px', ''));
				if (size-1 != 0) {
					crtObj.css('font-size', size-1);
				}
				break;
			case 'img':
			case 'background':
				crtObj.data('c', crtObj.data('c')-1);
				var w = parseInt(crtObj.attr('w'))+(crtObj.data('c')*moveSize);
				var h = parseInt(parseInt(crtObj.attr('h'))*w/parseInt(crtObj.attr('w')));
				crtObj.animate({width: w, height: h}, 0);
				break;
		}
	}
}
