var query_params = $H(location.search.parseQuery());//クエリの取得
var cookie_manager = new CookieManager();
var target_tags = ['div', 'span', 'a', 'b', 'li', 'ul', 'ol', 'image', 'h1', 'h2', 'h3', 'h4', 'H5'];
if (typeof window.swf_file_name != 'undefined') {
	if(query_params.get('clr')!= null){
			swf_file_name = query_params.get('clr')+'_'+swf_file_name;
	}else if (cookie_manager.getCookie('color')!= null){
			swf_file_name = cookie_manager.getCookie('color')+'_'+swf_file_name;
	}
}

//ロード終了時の呼出

var start = function() {
		//cookie オンオフ判定
		cookie_manager.setCookie('is_cookie_on', 'on');
		if(cookie_manager.getCookie('is_cookie_on')=='on'){
				$A(document.getElementsByClassName('error-cookie')).each(function(element){element.hide();});
				//if($('error-cookie')!=null){$('error-cookie').hide();}
		}
		cookie_manager.setCookie('is_cookie_on', '');
		
		var cr = new CMS('../common/data/data.csv', 'country_select.html');
		/*if(query_params.get('series') == null && cookie_manager.getCookie('series') == null){alert('エラー：シリーズが指定されていません。');}*/
		cr.show_country_applications('codeexample', '../software/software_inc.html');
		cr.show_only_country_colors('codeexample');
		//cr.list_countries_for_series($('country_select'));

/******************************************デバッグ用***************************************************/
/*
		//クッキー消去用。
		var HrefWatcher = Class.create();
	
		HrefWatcher.prototype = {
			initialize: function(href) {
				this.href = $(href);
				
				this.href.onclick = 
			  	this.showMessage.bindAsEventListener(this);
				
	  	},

	   	showMessage: function(evt) {
				cookie_manager.clearCookie('color');
				cookie_manager.clearCookie('series');
				cookie_manager.clearCookie('country');
				alert("cookie delete");
	   	}
		};
		
		var watcher = new HrefWatcher('destroy_cookie');
		//クッキー表示用
		$('cookie_inspect').innerHTML += 'color='+cookie_manager.getCookie('color')+'<br />';
		$('cookie_inspect').innerHTML += 'series='+cookie_manager.getCookie('series')+'<br />';
		$('cookie_inspect').innerHTML += 'country='+cookie_manager.getCookie('country')+'<br />';
		$('cookie_inspect').innerHTML += 'model='+cookie_manager.getCookie('model')+'<br />';
*/
/******************************************デバッグ用***************************************************/

}

Event.observe(window, 'load', start, false);





//CMSクラス


var CMS = Class.create();

CMS.prototype = {
	initialize: function(csv_url, redirect_url) {
		this.master_csv = new MasterCSV(csv_url);
		this.init(redirect_url);
	},
	init: function(redirect_url) {
		//1．ＧＥＴもしくは＃（ページ内リンク）で国が指定されている　→　クッキーに国をセット
		//2．クッキーに国があるならばロード
		//3．クッキーにもＧＥＴもしくは＃にも国が指定されていない　→　リダイレクト（リダイレクト先も引数で指定したほうがよい感じでしょうか？）
		//4．シリーズが指定されている　→　クッキーにシリーズをセット
		//5．クッキーにシリーズがあるならばロード
		//6．クッキーにも引数にもシリーズがないなら、エラー
		//7．色が指定　→　クッキーに覚えさせる＆書き換え
		//8．色がnull　→　クッキーにあればロード＆書き換え
			
		if(query_params.get('cty') != null) {
			cookie_manager.setCookie('country', query_params.get('cty'));
		}
		
		if(query_params.get('clr') != null) {
			cookie_manager.setCookie('color', query_params.get('clr'));
		}
		/*
		if(query_params.get('model') != null) {
			cookie_manager.setCookie('model', query_params.get('model'));
		}
		*/
		if(query_params.get('country') == null && cookie_manager.getCookie('country') == null && location.pathname.indexOf(redirect_url) == -1 && query_params.get('cty') == null) {
			location.href = redirect_url;//test時はコメントアウト
		}
		
		
		//画像及びflashにprefix付ける
		if(cookie_manager.getCookie('color') != null){
			//var img_elements = $A(document.getElementsByTagName('img'));
			var img_elements = $A(document.getElementsByClassName('change_by_color'));
			img_elements.each(function(img_element){img_element.setAttribute('src', img_element.getAttribute('src').gsub(/([^/]+?)(\.[a-zA-Z]+)$/, this.get_color_code()+'_#{1}#{2}'))}.bind(this));
		}
		
		target_tags.each(function(target_tag){
			var elements = $A(document.getElementsByTagName(target_tag));
			elements.each(function(element){
				if(element.getAttribute('color_code')==null){element.setAttribute('color_code', this.get_color_code());}
			}.bind(this));
		}.bind(this));
		

	},
	get_series_code: function() {
		return series;
	},
	get_country_code: function() {
		return cookie_manager.getCookie('country');
	},
	get_color_code: function() {
		return cookie_manager.getCookie('color');
	},
	get_model_code: function() {
		return cookie_manager.getCookie('model');
	},
/*
	parse_csv: function(url) {
		return new MasterCSV(url);
	},
*/
	show_only_country_colors: function(element_id) {
		var color_codes = this.master_csv.find_rows_by_country_and_series(this.get_country_code(), this.get_series_code()).collect(function(row){return row.get('color_codes');});
		$A(document.getElementsByClassName('show_only_country', $(element_id))).select(function(element){
				return element.getAttribute('color_code') != null && !color_codes.flatten().uniq().include(element.getAttribute('color_code'));
																																					 }).each(function(element){element.hide()});
	},
show_country_applications: function(element_id, template_url) {
		var application_codes = this.master_csv.find_rows_by_country_and_series(this.get_country_code(), this.get_series_code()).collect(function(row){return row.get('application_codes');});
		new Ajax.Request(template_url, {
			method: "get",
			asynchronous : false,
			onSuccess : function(httpObj) {
				$(element_id).innerHTML = httpObj.responseText;
				//divの子ノードから、class=”show_only_country”の要素をすべて取り出し,アプリケーションコード内に無いものをhide()する。
				$A(document.getElementsByClassName('show_only_country', $(element_id))).select(function(element){
								//return  element.getAttribute('application_code') != null && !application_codes.flatten().uniq().include(element.getAttribute('application_code'));
								return  element.getAttribute('application_code') != null && !$w(element.getAttribute('application_code')).any(function(element_application_code){return application_codes.flatten().uniq().include(element_application_code);});
																						 }).each(function(element){element.hide()});
				//divの子ノードから、class=”show_only_model”の要素をすべて取り出し,全てのモデルに対応しているか、どのモデルにも対応していないならhide()する。
				$A(document.getElementsByClassName('show_only_model', $(element_id))).select(function(element){
								return  element.getAttribute('application_code') != null && (!application_codes.flatten().uniq().include(element.getAttribute('application_code')) || application_codes.all(function(application_code){return application_code.include(element.getAttribute('application_code'))}));
																						 }).each(function(element){element.hide()});
			
			}
		});
	},
	list_countries_for_series: function(element_id) {
		var rows = this.master_csv.find_rows_by_series(this.get_series_code());
		rows.each(function(row){
			var op = new Element('option', {value:row.get('country')}).update(row.get('country_name'));
			$(element_id).insert(op);
		});

	}
	
};

//MasterCSVクラス

var MasterCSV = Class.create();

MasterCSV.prototype = {
	initialize: function(url) {
		this.rows = new Array();
		new Ajax.Request(url, {
			method: "get",
			asynchronous : false,
			onSuccess : this.lines2rows.bind(this)
		});
	},
	lines2rows: function(httpObj) {
		this.text = httpObj.responseText;
		var lines = $A(this.text.strip().replace(/\r\n/ig, "\n").split("\n"));
		var rows = this.rows;
		lines.each(function(line) {
			var p = line.split(',');
			var row= new Object();
			row.country = p[0];
			row.country_name = p[1];
			row.series = p[2];
			row.series_name = p[3]
			
			//model追加
			row.model = p[4]
			row.model_name = p[5]
			
			row.application_codes = p[6].split('+');
			row.color_codes = p[7].split('+');
			rows.push($H(row));
		});
	},
	find_rows_by_country_and_series: function(country, series) {
		var result = this.rows.select(function(row) {return (row.get('country') == country && row.get('series') == series);});
		if(result.size() == 0){/*alert('指定された国名とシリーズ名に一致するデータがありません。');return null;*/}
		return result;
	},
	find_row_by_country_and_series_and_model: function(country, series, model) {
		var result = this.rows.select(function(row) {return (row.get('country') == country && row.get('series') == series && row.get('model') == model);});
		if(result.size() == 0){/*alert('指定された国名とシリーズ名とモデル名に一致するデータがありません。');return null;*/}
		return result.first();
	},
	find_rows_by_series: function(series) {
		var result = this.rows.select(function(row) {return (row.get('series') == series);});
		if(result.size() == 0){/*alert('指定されたシリーズ名に一致するデータがありません。');return null;*/}
		return result;
	}
	
};