$(function(){
        $('#contenttabs').tabs({
        selected:0
    });
        $('#form_add').submit(function(){
        return false;
    });
        $('#img_search').click(function(){
        $('#form_search').submit();
    });
	$('#img_search_sub').click(function(){
        $('#form_search_sub').submit();
    });
        $('#search').keydown(function(e){
        if(e.keyCode==13)$('#form_search').submit();
    });
    /** 排序點擊, 自動選取文字 (1)由小變大 (2)由大變小 (3)不變 **/
    $(document).on('click', '.enter_type1', function(event){
        $(this).select();
    }).on('keyup', '.enter_type1', function(event){
        if(parseInt($(this).attr('data-sort')) != parseInt($(this).val())){
            $('input[data-sort-name="'+$(this).attr('name')+'"]').val((parseInt($(this).val())+0.5));
        }else{
            $('input[data-sort-name="'+$(this).attr('name')+'"]').val(parseInt($(this).val()));
        }
    });
        $('td[data-location]').click(function(){
        location.replace($(this).attr('data-location'));
    });
    	$(document).on('click', 'table[class="main_list"] tr:gt(0)', function(event){
		$checkbox = $(this).find(':checkbox');
		//$checkbox.attr('checked', !$checkbox.attr('checked'));
		if($checkbox.size()*1>0){
			if($checkbox.attr('checked')){
				$checkbox.attr('checked', false);
				$(this).removeClass('tbody_select');
			}else{
				$checkbox.attr('checked', true);
				$(this).addClass('tbody_select');
			}
		}
	}).on('click', 'table[class="main_list"] td *:not(:checkbox, img):not(.ignore)', function(event){
		event.stopPropagation();
	}).on('click', 'table[class="main_list"] tr:gt(0) :checkbox', function(event){
		$(this).attr('checked', !$(this).attr('checked'));
	});
        $('.chkAll').click(function(){
        if($(this).attr('checked')){
            $(this).closest('table').find('input[rel="chk"]').attr('checked', true);
            $(this).closest('table').find('tr').addClass('tbody_select');
        }else{
            $(this).closest('table').find('input[rel="chk"]').attr('checked', false);
            $(this).closest('table').find('tr').removeClass('tbody_select');
        }
    });
        $('input[rel="chk"]').shiftClick();
        $('.main_list tbody tr:odd').addClass('tbody_base');
        $('a[rel="example_group"]').fancybox({
        'overlayShow'	    : true,
        'overlayOpacity'	: 0.5,
        'transitionIn'      : 'elastic',
	    'transitionOut'		: 'fade',
        'changeSpeed'       : 100,
        'speedIn'           : 500,
        'autoScale'			: false,
        'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
            return '
|  | 相片 ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? '   ' + title : '') + ' |  | 
';
        }
	});
        $('.fixed_height').fancybox({
    	'scrolling' : false,
    	'titleShow'	: false,
    	'width'		: 1024,
    	'height'    : $(document).height()-100,
    	'autoDimensions' :false
    });
        $('.webbrowse').fancybox({
		'width'				: '100%',
		'height'			: '100%',
		'autoScale'			: false,
        'speedIn'           : 200,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'fade',
		'type'				: 'iframe'
    });
    	$('.quick').fancybox({
        //'width'		: 1024,
        //'height'    : 495,
        //'autoDimensions' :false,
		'scrolling' : 'auto',
		'titleShow'	: false
        
	});
        $('.colorPicker').ColorPicker({
        onSubmit: function(hsb, hex, rgb, el) {
            $color_code = '#'+hex;
            $(el).val($color_code).css({'background-color':$color_code}).ColorPickerHide();
    	},
    	onBeforeShow: function () {
   		   $(this).ColorPickerSetColor($(this).val());
    	}
    })
    .bind('keyup', function(){
    	$(this).ColorPickerSetColor($(this).val()).css('background-color', $(this).val());
    });
        $('.datepicker').datepicker({dateFormat:'yy-mm-dd'});
        $(document).on('keydown', '.acceptNumber', function(e){
        return acceptNumberStr(e.keyCode);
    });
    
    $(document).on('mouseout', 'table[class="main_list"] tbody tr', function(event){
        $(this).find('td:eq(1)').mouseout(function(){
            $('table[class="main_list"] tbody').sortable({disabled:'disabled'});
        });
    });
        $('#btn_newmessage').click(function(){
        $cmd = 'new';
        $('input[name="cmd"]').val($cmd);
        submitForm('#form_add');
    });
    $('#btn_editmessage').click(function(){
        $cmd = 'edit';
        $msg = '確定儲存該筆資料?';
        $form_id = '#form_add';
        func_confirm($cmd, $msg, $form_id);
    });
    $('#edit_list').click(function(){
        $cmd = 'edit';
        $chk = $('input[rel="chk"]:checked').size();
        if($chk == 0){
            $status = 'fail';
            $msg = '請勾選要儲存的資料';
            $redirect = '';
            func_alert($status, $msg, $redirect);
        }else{
            $msg = '確定要儲存這 ' + $chk + ' 筆資料嗎?';
            $form_id = '#form_add';
            func_confirm($cmd, $msg, $form_id);
        }
    });
    $('#btn_delmessage').click(function(){
        $cmd = 'del';
        $msg = '一旦刪除後就無法回復!
您確定刪除該筆資料嗎?';
        $form_id = '#form_add';
        func_confirm($cmd, $msg, $form_id);
    });
    $('#del_list').click(function(){
        $cmd = 'del';
        $chk = $('input[rel="chk"]:checked').size();
        if($chk == 0){
            $status = 'fail';
            $msg = '請勾選要刪除的資料';
            $redirect = '';
            func_alert($status, $msg, $redirect);
        }else{
            $msg = '一旦刪除後就無法回復!
確定要刪除這 ' + $chk + ' 筆資料嗎?';
            $form_id = '#form_add';
            func_confirm($cmd, $msg, $form_id);
        }
    });
    $('#btn_htmlmessage').click(function(){
        $cmd = 'edit';
        $msg = '確定建立該筆HTML資料?';
        $form_id = '#form_html';
        $('input[name="html_link[]"]').val($(this).attr('data-html_link'));
        func_confirm($cmd, $msg, $form_id);
    });
    markCover();	$( '#sortable').sortable({        update: function(){
            markCover();
        }
    });
    
        $('#select_all').click(function(){
        if($(this).attr('checked')) $('.select_pic').attr('checked',true);
        else  $('.select_pic').attr('checked',false);
        
    });
});
function markCover(){
    $('.item').removeClass('cover').attr('title', '');
    $('.item').first().addClass('cover').attr('title', '封面');
};
function func_confirm($cmd, $msg, $form_id){
    $('input[name="cmd"]').val($cmd);
    $('#window_msg').html($msg);
    $('#func_window').dialog({
        draggable:false,
        resizable:false,
        closeOnEscape:false,
        //position:['',240],
        modal:true,
        title:'確認視窗',
        buttons: {
            '確認': function(){
                submitForm($form_id);
                $(this).dialog('close');
            },
            '取消': function() {
                $(this).dialog('close');
            }
        }
    }).find('img').attr('src', function(){return 'http://www.kaihung.com/tw/' + ($cmd=='edit'?'images/gw_dialog_notice.png':'images/gw_dialog_warning.png')});
    $sounds_url = 'http://www.kaihung.com/tw/' + ($cmd=='edit'?'gw_tool/sounds/notify':'gw_tool/sounds/warring');
    if(window.HTMLAudioElement){
        var snd = new Audio();
		if(snd.canPlayType('audio/mp3')){
			snd = new Audio($sounds_url+'.mp3');
		}else if(snd.canPlayType('audio/ogg')){
			snd = new Audio($sounds_url+'.ogg');
		}
		snd.play();
	}
}
function func_alert($status, $msg, $redirect){
   $('#window_msg').html($msg);
   $('#func_window').dialog({
        draggable:false,
        resizable:false,
        closeOnEscape:false,
        modal:true,
        title:'',
        width:function(){if($redirect=='./?act=setting&type=backup'){return '425';}else{return '';}},
        buttons: {
            '確認': function(){
                $(this).dialog('close');
                if($redirect == 'back'){
                    window.history.back();
                }else if($redirect != ''){
                    window.location.replace($redirect);
                }
            }
        }
    }).find('img').attr('src', function(){return 'http://www.kaihung.com/tw/' + ($status=='ok'?'images/gw_dialog_success.png':'images/gw_dialog_stop.png')});
    $sounds_url = 'http://www.kaihung.com/tw/' + ($status=='ok'?'gw_tool/sounds/notify':'gw_tool/sounds/warring');
    if(window.HTMLAudioElement){
        var snd = new Audio();
		if(snd.canPlayType('audio/mp3')){
			snd = new Audio($sounds_url+'.mp3');
		}else if(snd.canPlayType('audio/ogg')){
			snd = new Audio($sounds_url+'.ogg');
		}
		snd.play();
    }
}
function func_loading($msg){
    if($msg!=''){
        $('#loading_msg').html($msg);
    }
    $('#func_loading').dialog({
        draggable:false,
        resizable:false,
        closeOnEscape:false,
        //position:['',240],
        modal:true,
        title:''
    });
}
function func_success($msg){
    $('#func_success').dialog({
        height:80,width:200,
        draggable:false,
        resizable:false,
        closeOnEscape:false,
        //position:['',240],
        modal:false,
        title:'',
        create: function (event, ui) {
            $('div[role="dialog"] .ui-widget-header').hide();
        }
    });
}
function MovePrev(elementid){
    if ($(elementid).attr("type") !== 'submit'){
        var fields = $(elementid).parents('form:eq(0),body').find('button, input, textarea, select');
        var index = fields.index( elementid );
        if ( index > -1 && ( index - 1 ) < fields.length ) {
            fields.eq( index - 1 ).focus();
            fields.eq( index - 1 ).select();
        }
        $(elementid).blur();
        return false;
    }
}
function MoveNext(elementid){
    if ($(elementid).attr("type") !== 'submit'){
        var fields = $(elementid).parents('form:eq(0),body').find('button, input, textarea, select');
        var index = fields.index( elementid );
        if ( index > -1 && ( index + 1 ) < fields.length ) {
            fields.eq( index + 1 ).focus();
            fields.eq( index + 1 ).select();
        }
        $(elementid).blur();
        return false;
    }
}
function getLastDay($year, $month){
    $day = 0;
    switch($month){
        case '1':
        case '3':
        case '5':
        case '7':
        case '8':
        case '10':
        case '12':
            $day = 31;            break;
        case '4':
        case '6':
        case '9':
        case '11':
            $day = 30;            break;
        case '2':
            if($year%400==0){
                $day = 29;            }else if($year%4==0 && $year%100!=0){
                $day = 29;            }else{
                $day = 28;            }
            break;
    }
    return $day;
}
function addCommas($str, sValue) {
	if (! isNaN(sValue)) {
		sValue *= 1;
		sValue = sValue.toString();
		var sRegExp = new RegExp("(-?[0-9]+)([0-9]{3})");
		while(sRegExp.test(sValue)) {
			sValue = sValue.replace(sRegExp, '$1,$2');
		}
	}
	sValue = $str+ sValue;
	return sValue;
}
function cutCommas(sValue){
    sValue = sValue.toString() ;
    sValue = sValue.split(",");
    sValue = sValue.join("");
    return sValue;
}
function strReplace(search, replace, str) {
    var regex = new RegExp(search, "g");
    return str.replace(regex, replace);
}
function acceptNumberStr($code){
    switch(true){
        case ($code=='8'):              case ($code=='9'):              case ($code>='37'&&$code<='40'):            case ($code=='46'):             case ($code>='48'&&$code<='57'):            case ($code>='96'&&$code<='105'):           case ($code=='109'):           case ($code=='110'):           case ($code=='190'):               return true;
            break;
        default:
            return false;
            break;
    }
}