/**
 * 
 */

/**
 * 条件セットボタンを押した際に
 * チェックしてある項目を取得し親窓に渡す
 * @param mode 
 */
function formSet(mode) {
	var chk = new Array();

	for(i=0;i<LIST.length;i++) {
		if(document.getElementsByName(mode + "[" + LIST[i] + "]").item(0).checked) {
//			chk[chk.length] = document.getElementById(mode + "[" + LIST[i] + "]").value;
			chk[chk.length] = document.getElementsByName(mode + "[" + LIST[i] + "]").item(0).value;
		}
	}

	window.parent.receive(mode, chk);
	window.parent.tb_remove();
}

/**
 * チェックボックスチェック時
 * の最大選択数の入力チェック
 * @param Checked チェックボックス自身
 */
function Check(Checked) {
	var oKflg = true;
	var count = 0 ;
	var maxChk = 5; 
	chkvalue = "";
	for(i=0;i<LIST.length;i++) {
//		chk = document.getElementById('special[' + LIST[i] + ']');
		chk = document.getElementsByName('special[' + LIST[i] + ']').item(0);
		if(chk.checked == true) {
			count++;
			if(count>maxChk) {
				alert("特徴は" + maxChk + "個まで選択できます。");
				Checked.checked = false;
				oKflg = false;
				break;
			}
		}
	}
}

function getParentsChecks(type) {
	for(i=0;i<LIST.length;i++) {
		var childNo = LIST[i];
		if(window.parent.document.getElementsByName(type + '[' + childNo + ']').item(0)){
			document.getElementsByName(type + "[" + childNo + "]").item(0).checked = true;
		}
	}
}

function checkAll(checkedElement){
	var divName = "checks_" + $(checkedElement).attr('id');
	$("#" + divName + " input[@type=checkbox]").attr('checked',checkedElement.checked);
}

function setSortMode(mode) {
	document.S02SearchForm.SM.value = mode;
	submission();
}

function changePage(pageNumber) {
	document.S02SearchForm.CP.value = pageNumber;
	submission();
}

function setFreeword() {
	changePage(1);
}

function receive(mode, chk) {
	doMode = mode;
	configs[mode]['renderer'](chk);
//	changePage(1);
}

function codeChangeCategory(chk) {
	if( typeof chk  == 'undefined' ){
		chk = [];
	}
	var categoryDisp = new Object();
	for(l in chk) {
		if(typeof chk[l] != 'function'){
			categoryDisp[l] = lists[doMode]['cat']['children'][chk[l]];
		}
	}
	writeTemplate(categoryDisp);
	hiddenForm(chk);
}

function codeChangeArea(chk) {
	if( typeof chk  == 'undefined' ){
		var chk = [];
	}
	var areaDisp = {};
	
	for(var l in chk) {
		if(typeof chk[l] != 'function'){
			var pCode = chk[l].substr(0, 3) + '000';
			if(typeof areaDisp[pCode] == 'undefined') {
				areaDisp[pCode] = new Object();
				areaDisp[pCode]['count'] = 0;
				areaDisp[pCode]['label'] = lists[doMode][pCode]['areaName'];
			}
			if(typeof areaDisp[pCode]['children'] == 'undefined') {
				areaDisp[pCode]['children'] = new Object();
			}
			areaDisp[pCode]['count']++;
			areaDisp[pCode]['children'][l] = lists[doMode][pCode]['children'][chk[l]];

		}

	}
	var cCount;
	for(var areaCode in lists[doMode]){
		if(typeof areaDisp[areaCode]  != 'undefined'){
			cCount = 0;
			for(var childrenCode in lists[doMode][areaCode].children){
				cCount++;
			}

			if(cCount ==  areaDisp[areaCode]['count']){
				areaDisp[areaCode]['children'] = ["すべてのエリア"];
			}
		}
	}

	writeTemplate(areaDisp);
	hiddenForm(chk);
	sidebarRefresh();
}

function codeChangeSpecial(chk) {
	if( typeof chk  == 'undefined' ){
		chk = [];
	}
	var specialDisp = new Object();
	for(l in chk) {
		if(typeof chk[l] != 'function'){
			pCode = chk[l].substr(0,1) + '000';
			specialDisp[l] = lists[doMode][pCode]['children'][chk[l]];
		}
	}
	writeTemplate(specialDisp);
	hiddenForm(chk);
}

function writeTemplate(disp) {
	element = configs[doMode]['element'];
	$('#' + element).setTemplate(templates[doMode]);
	$('#' + element).processTemplate(disp);
}

function hiddenForm(checked) {
	element = configs[doMode]['hiddenId'];
	$('#' + element).setTemplate(templates[element]);
	$('#' + element).processTemplate(checked);
	
}
  
function examination(jobId) {
	var loadingRectangle = new Rectangle();
	var uniqId = "sidebar";
	var lastUniqId = "sidebar";
	var $$ = $('#S02SearchForm');
	$.ajax({
		type: "POST",
		url: '/app/m/xml/a/AjaxJobExamination',
		data: {jobId:jobId},
		dataType: "xml",
		success: function (response) {
			if($(response).find("params").find("status").text()=="OK") {
				$("#exam_" + $(response).find("params").find("jobId").text()).attr("src",underExamImageSrc);
			} else if($(response).find("params").find("status").text() == "remove") {
				$("#exam_" + $(response).find("params").find("jobId").text()).attr("src", notUnderExamImageSrc);
			} else {
				alert($(response).find("params").find("error").text());
			}
		},
		beforeSend: function(xml) {
//			showLoadingImage(loadingRectangle, lastUniqId);
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			alert(resultTemplates['error']);
		}
    });
}

function submission() {
	if(isKeywordHint()) {
		$("#keyword").attr('value','');
	}
	var $$ = $('#S02SearchForm');
	var lastUniqId = "search_main";
	var loadingRectangle = new Rectangle($("#resultListHeader"));
	$.ajax({
		type: "POST",
		url: $$.attr('action'),
		data: $('input', $$),
		dataType: "xml",
		success: function(response) {
			var uniqId = $(response).find("response").attr('id');
			try {
//				alert(response);
				// process the data (runs the xml through httpData regardless of callback)
			} catch(e) {
				status = "parsererror";
				alert("parse error");
			}
			var statusArray = new Array();
			$(response).find("params").each(
				function() {
					statusArray[this.tagName] = $(this).text();
				}
			);

			$("#panlist").html(utf8to16(base64decode(($("bread",response).text()))));
//			$("#panlist").html($("bread",response).text()) ;

			$(".searchPageNavi").html($("pager",response).text());
			$("#status").setTemplate("<table BORDER>{#foreach $T as param}<tr><td>{$T.param.propName}</td><td>{$T.param.value}</td></tr>{#/foreach}</tbody></table>");
			if($("defaults",response).text().length > 0) {
				defaults = eval( "(" + $("defaults",response).text() + ");" );
				restore();
			}
			var currentSortMode = $("CSM",response).text();
			$(".sortModeChange").each(function(e) {
				var sm = this.id.replace(/sortModeChange_/,"");
				if(sm == currentSortMode) {
					$(this).html( $(this).text() );
				}else{
					$(this).html( '<a href="javascript:void(0);" onclick="javascript:setSortMode(' + sm + ');">' + $(this).text() + '</a>' );
				}
			});
			$("#sortPaySystem").html($("sortPaySystem", response).text());
			$("#status").processTemplate(statusArray);
			resultJobArray = [];
			$(response).find("jobData").each(
				function(index) {
					var tmpJob = {
						jobId : $(this).find("jobId").text(),
						manageNumber : $(this).find("manageNumber").text(),
						stationName1 : $(this).find("stationName1").text(),
						stationName2 : $(this).find("stationName2").text(),
						stationName3 : $(this).find("stationName3").text(),
						paySystem : $(this).find("paySystem").text(),
						pay : $(this).find("pay").text() != "" ? $(this).find("pay").text() + "円" : "",
						celebrationPrice : $(this).find("celebrationPrice").text(),
						jobTitle : $(this).find("jobTitle").text(),														
						jobDetail : $(this).find("jobDetail").text(),
						examination : $(this).find("examination").text(),
						produced : $(this).find("produced").text(),
						icon : $(this).find("icon").text()
					};
					resultJobArray.push(tmpJob);
				}
			);
			if(resultJobArray.length == 0) {
				$("#sortParent").hide();
				$("#result").setTemplate(resultTemplates['searchNone']);
			} else {
				$("#sortParent").show();
				$("#result").setTemplate(resultTemplates['search']);
			}
			$("#result").processTemplate(resultJobArray);
			$(".searchPageNavi").show();
			if(isEmptyKeyword()) {
				$("#keyword").attr('value',keywordHint);
				$("#keyword").addClass("keywordBlur");
			}
			return true;
		},
		beforeSend: function(xml) {
			$("#sortParent").hide();
			$(".searchPageNavi").hide();
			$("#result").setTemplate(resultTemplates['waiting']);
			$("#result").processTemplate([]);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			$("#sortParent").hide();
			$(".searchPageNavi").hide();
			$("#result").setTemplate(resultTemplates['error']);
			$("#result").processTemplate([]);
	    	if(isEmptyKeyword()) {
				$("#keyword").attr('value',keywordHint);
				$("#keyword").addClass("keywordBlur");
			}
		}
	});

    return true;
}

function restore() {
	doMode = "jZ";
	configs[doMode]['renderer'](defaults[doMode]);
	doMode = "CAT";
	configs[doMode]['renderer'](defaults[doMode]);
	doMode = "special";
	configs[doMode]['renderer'](defaults[doMode]);
	if(configs["keyword"] != undefined){
		$("#keyword").attr('value',configs["keyword"]);
	}
}

function isKeywordHint() {
	return $("#keyword").attr('value') == keywordHint;
}

function isEmptyKeyword() {
	return $("#keyword").attr('value') == '' || $("#keyword").attr('value') == undefined;
}

function removeLoadingImage(uniqId) {
	$(".li_" + uniqId).remove();
}

function Rectangle(element,y,width,height){
	if(element != null && y != null && width != null && height != null){
		this.x = element;
		this.y = y;
		this.width = width;
		this.height = height;
	}else if(element != null &&  $(element).text() != ""){
		//alert($(element).attr("id"));
		this.x =  $(element).offset().left;
		this.y =  $(element).offset().top;
		this.width = $(element).width();
		this.height = $(element).height();
	}else{
		this.x = 0;
		this.y = 0;
		this.width = $("body").width();
		this.height = $("body").height();
	}
}

Rectangle.prototype.toString = function(){
	//return  "{y:" + this.y + " , x:" + this.x + " , width:" + this.width + " , height" + this.height + "}";
	return  "{y:" + 100 + " , x:" + 100 + " , width:" + 100 + " , height" + 100 + "}";
}

Rectangle.prototype.getStyle = function(){
	return "text-align:center" + "; margin-top: " + this.y + "px; left:" + this.x + "px; top:" + this.y + "px; width:" + this.width + "px; height:" + this.height + "px;";
}

