/*************************************************************************
 イベントAjax関連スクリプト
*************************************************************************/
var ajaxEvent = {
	baseURL:      '/event/search/event.php/',
	prefImageDir: '/event/search/images/pref/',
	formDomID:    'SORT_FORM',
	menuDomID:    'EVENT_MENU',
	replaceDomID: 'EVENT',
	uriDomID:     'PAGE_URI',
	
	cookieOptions: {expires:365, path:'/'},
	
	//-------------------------------------------------------------
	// イベント検索の初期化
	//-------------------------------------------------------------
	searchInit: function(){
		var menuObj = $('#' + this.menuDomID);
		if(!menuObj) return;
		
		// メニューの表示
		ajaxEvent.menu();
	},
	
	//-------------------------------------------------------------
	// AjaxRequest イベント検索メニュー
	//-------------------------------------------------------------
	menu: function(){
		var ajaxMethod = 'menu';
		
		$.ajax({
			type:		'get',
			url:		this.baseURL + ajaxMethod,
			cache:		false,
			success:	function(html, status){
				$('#' + ajaxEvent.menuDomID).html(html);
				
				var formObj = $('#' + this.formDomID);
				if(!formObj) return;
				
				// 初期値の設定
				ajaxEvent.setDefaultParams();
				ajaxEvent.changeArea(false);
				
				// イベントの割り当て
				$('#area').change(function() {
					ajaxEvent.changeArea(true);
					ajaxEvent.search();
				});
				$('#SORT_FORM .ajax_search').click(function() {
					ajaxEvent.search();
				});
				$('#' + this.uriDomID).click(function() {
					$(this).select();
				});
				
				// 初回実行
				ajaxEvent.search();
			}
		});
	},
	
	//-------------------------------------------------------------
	// エリア変更時の制御
	//-------------------------------------------------------------
	changeArea: function(prefClear){
		var area = $('#area').val();
		var pref = $("input:radio[@name='pref']:checked").val();
		
		// 表示制御
		$('.pref').hide();
		if(area > 1){ // 北海道エリアは１件なのでリスト表示しない
			$('#AREA' + area).show();
		}
		
		// 都道府県のクリア
		// エリア変更時は毎回
		if(prefClear){
			$("input:[name=pref]").attr("checked", false); // クリア
			$('#pref_all' + area).attr('checked', true);  // 全てをチェック
		}else{
			// 初回にエリアと県の対応が異なっている場合はクリア
			if(pref && $('#pref' + pref).closest('div').attr('id') != 'AREA' + area){
				$("input:[name=pref]").attr("checked", false);
				$('#pref_all' + area).attr('checked', true);
			}
			if(!pref){
				$('#pref_all' + area).attr('checked', true);
			}
		}
	},
	
	//-------------------------------------------------------------
	// AjaxRequest イベントをさがす
	//-------------------------------------------------------------
	search: function(page){
		var ajaxMethod = 'search';
		
		if(page){
			ajaxMethod += '/page:' +page+ '/';
		}
		ajaxEvent.makeParams(); // 保存用URL
		$.ajax({
			type:		'get',
			url:		this.baseURL + ajaxMethod,
			data:		$('#' + this.formDomID).serialize(),
			cache:		false,
			success:	function(html, status){
				$('#' + ajaxEvent.replaceDomID).html(html);
				// 都道府県 Cookie保存
				ajaxEvent.savePrefByRequest(this.data);
				
				// IE6用の領域調整
				if ($.browser.msie && $.browser.version == 6){
					var h = $('#container').height();
					$('#footer').css('top', h);
				}
				
				// 画面TOPへ
				window.scrollTo(0, 0);
			}
		});
	},
	
	//-------------------------------------------------------------
	// AjaxRequest ポケセン用イベント表示
	//-------------------------------------------------------------
	pokecen: function(pref){
		var ajaxMethod = 'pokecen';
		$.ajax({
			type:		'get',
			url:		this.baseURL + ajaxMethod + '/' + pref,
			cache:		false,
			success:	function(html, status){
				$('#' + ajaxEvent.replaceDomID).html(html);
			}
		});
	},
	
	//-------------------------------------------------------------
	// AjaxRequest TOP用のゲームのイベント情報
	//-------------------------------------------------------------
	topGame: function(area, pref){
		var ajaxMethod = 'game_top';
		$.ajax({
			type:		'get',
			url:		this.baseURL + ajaxMethod + '/' + area + '/' + pref,
			cache:		false,
			success:	function(html, status){
				$('#EVENT_GAME').html(html);
			}
		});
	},
	
	//-------------------------------------------------------------
	// AjaxRequest TOP用のカードゲームのイベント情報
	//-------------------------------------------------------------
	topCard: function(area, pref){
		var ajaxMethod = 'card_top';
		$.ajax({
			type:		'get',
			url:		this.baseURL + ajaxMethod + '/' + area + '/' + pref,
			cache:		false,
			success:	function(html, status){
				$('#EVENT_CARD').html(html);
			}
		});
	},
	
	//-------------------------------------------------------------
	// イベントTOP用の画面操作
	//-------------------------------------------------------------
	viewEventTop: function(area, pref){
		
		// パラメータ
		if(pref != undefined) {
			ajaxEvent.cookie('pref', pref);
		}else{
			pref = ajaxEvent.cookie('pref');
		}
		if(area != undefined) {
			ajaxEvent.cookie('area', area);
		}else{
			area = ajaxEvent.cookie('area');
		}
		if(!pref) pref = '';
		if(!area) area = '';
		
		// 初回アクセス判定
		eventSave = ajaxEvent.cookie('eventSave');
		if(!eventSave && !pref && !area){
			$('#AREA_ON').hide();
			$('#AREA_OFF').show();
			return;
		}else{
			$('#AREA_ON').show();
			$('#AREA_OFF').hide();
			
			// スマートフォン用のプルダウン値を変更
			var _pref = pref;
			var _area = area;
			if(!_pref) _pref = '0';
			if(!_area) _area = '0';
			$('#AREA_SELECT').val(_area + ',' + _pref);
		}
		
		ajaxEvent.topGame(area, pref);
		ajaxEvent.topCard(area, pref);
	},
	
	//-------------------------------------------------------------
	// GETパラメータ付きURLの生成
	//-------------------------------------------------------------
	makeParams: function(){
		var params = $('#' + this.formDomID).serialize();
		var href = window.location.href;
		if(href.indexOf('?') != -1){
			href = href.slice(0, href.indexOf('?'));
		}
		if(params == 'area='){
			params = '';
		}
		$('#' + this.uriDomID).val(href + '?' + params);
	},
	
	//-------------------------------------------------------------
	// GETパラメータの値を取得
	//-------------------------------------------------------------
	getParams: function(keyName){
		var hash;
		var href = window.location.href;
		if(href.indexOf('?') != -1){
			var hashes = href.slice(href.indexOf('?') + 1).split('&');
			for(var i = 0; i < hashes.length; i++) { 
				hash = hashes[i].split('=');
				if(hash[0] != '' && hash[0] == keyName && hash[1] != ''){
					return hash[1];
				}
			}
		}
		return '';
	},
	
	//-------------------------------------------------------------
	// GETパラメータからフォームの初期値をセット
	//-------------------------------------------------------------
	setDefaultParams: function(){
		var isGetParam = false;
		
		// GETパラメータ
		var hash;
		var href = window.location.href;
		if(href.indexOf('?') != -1){
			var hashes = href.slice(href.indexOf('?') + 1).split('&');
			for(var i = 0; i < hashes.length; i++) { 
				hash = hashes[i].split('=');
				if(hash[0] != '' && $('#'+ hash[0])){
					if(hash[0] == 'area'){
						isGetParam = true;
						$('#'+ hash[0]).val(hash[1]);
					
					}else if(hash[0] == 'pref'){
						isGetParam = true;
						$('#pref'+ hash[1]).attr({checked:'checked'});
					
					}else if(hash[0] == 'key'){
						$('#'+ hash[0]).val(hash[1]);
					
					}else{
						$('#'+ hash[0]).attr({checked:'checked'});
						$('#'+ hash[0]).val(1); // for IE6
					}
				}
			}
		}
		
		// GETパラメータが無い場合はクッキーから取得
		if(!isGetParam){
			// Cookieの都道府県を読み込み
			var area = ajaxEvent.cookie('area');
			var pref = ajaxEvent.cookie('pref');
			
			if(area) $('#area').val(area);
			if(pref) $('#pref'+pref).attr({checked:'checked'});
		}
	},
	
	//-------------------------------------------------------------
	// Cookie制御
	//-------------------------------------------------------------
	cookie: function(name, value){
		if (typeof value != 'undefined'){
			jQueryCookie('eventSave', true, ajaxEvent.cookieOptions);
		}
		return jQueryCookie(name, value, ajaxEvent.cookieOptions);
	},
	
	//-------------------------------------------------------------
	// リクエストURLなどから都道府県パラメータを取得
	//-------------------------------------------------------------
	savePrefByRequest: function(data, sep, eq){
		if (typeof sep == 'undefined') sep = '&';
		if (typeof eq  == 'undefined') eq  = '=';
		
		var pref = '';
		var area = '';
		var hash;
		var hashes = data.split(sep);
		for(var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split(eq);
			if(hash[0] == 'pref'){
				pref = hash[1];
			}
			if(hash[0] == 'area'){
				area = hash[1];
			}
		}
		ajaxEvent.cookie('pref', pref);
		ajaxEvent.cookie('area', area);
	},
	
	//-------------------------------------------------------------
	// バージョン
	//-------------------------------------------------------------
	version: '1.0'
};



/*************************************************************************
 cookie制御(jQuery.cookieを踏襲)
*************************************************************************/
function jQueryCookie(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};




