/**
 * S02検索用JS
 */

/**
 * 条件セットボタンを押した際に
 * チェックしてある項目を取得し親窓に渡す
 * @param mode 
 */
function formSet(mode) {
	var chk = new Array();
	for (var i = 0; i < LIST.length; i++){
		if (document.getElementsByName(mode + "[" + LIST[i] + "]").item(0).checked) {
			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.getElementsByName('special[' + LIST[i] + ']').item(0);
      if(chk.checked == true){
          count++;
          if(count>maxChk){
              alert("特徴は" + maxChk + "個まで選択できます。");
              Checked.checked = false;
              oKflg = false;
              break;
          }   
      }else{
			//console.log('none');
	  }
   }
}

function getParentsChecks(type){
    for (i=0;i<LIST.length;i++){
        var childNo = LIST[i];
        if(window.parent.document.getElementById(type + '[' + childNo + ']')){
            document.getElementById(type + "[" + childNo + "]").checked = true;
        }
    }
}

function checkAll(checkedElement){
	var divName = "checks_" + $(checkedElement).attr('id');
	$("#" + divName + " input[@type=checkbox]").attr('checked',checkedElement.checked);
}

/**
 * チェックオール++
 * @since 2008-10-21
 */
function checkLabelAll (e) {
	var a = "checks_" + $(e).attr('id'),
		b = $("#" + a + " input[@type=checkbox]");
	$.each(b, function(key, value){
		if ($(e).attr("checked")) {
			$(this).attr("checked", true);
			if ($("#jZ\\[" + String($(this).attr("id")).substring(2) + "\\]")) { 
				toggleHidden("jZ", "", String($(this).attr("id")).substring(2));
			}
		} else {
			$(this).attr("checked", false);
			if ($("#jZ\\[" + String($(this).attr("id")).substring(2) + "\\]")) {
				toggleHidden("jZ", "", String($(this).attr("id")).substring(2));
			}
		}
	});
}

//-- #604 Edit by Motohashi (IWS) 2008/11/18 Start
/**
 * チェックオール++
 * @since 2008-10-21
 */
function checkCatLabelAll (e) {
	var a = "checks_" + $(e).attr('id'),
		b = $("#" + a + " input[@type=checkbox]");
	$.each(b, function(key, value){
		if ($(e).attr("checked")) {
			$(this).attr("checked", true);
			if ($("#OCC\\[" + String($(this).attr("id")).substr(2) + "\\]")) { 
				toggleHidden("OCC", "", String($(this).attr("id")).substr(2));
			}
		} else {
			$(this).attr("checked", false);
			if ($("#OCC\\[" + String($(this).attr("id")).substr(2) + "\\]")) {
				toggleHidden("OCC", "", String($(this).attr("id")).substr(2));
			}
		}
	});
}
//-- #604 Edit by Motohashi (IWS) 2008/11/18 End

/**
 * jqueryオブジェクトの中身をダンプする関数
 */
$.dump = function ($obj) {
	var r = [];
	if ($.browser.msie) {
		for (var i = 0; i < $obj.length; i++) {
			r.push('[' + i + '] ');
			r.push($obj[i].outerHTML.replace(/^[\r\n\t]+/, ''));
			r.push("\n");
		}
	} else {
		for (var i = 0; i < $obj.length; i++) {
			r.push('[' + i + '] '
				+ '<' + $obj[i].nodeName.toLowerCase());
			for (var j = 0; j < $obj[i].attributes.length; j++) {
				r.push(' ' + $obj[i].attributes[j].nodeName + '="' 
					+ $obj[i].attributes[j].nodeValue + '"');
			}
			r.push('>' + $obj[i].innerHTML);
			r.push('<\/' + $obj[i].nodeName.toLowerCase() + '>');
			r.push("\n");
		}
	}
	alert(r.join(''));
}

/**
 * 対象の id をもつ hidden ノードを追加または削除
 *
 * @param String category name e.g. "jZ"
 * @param String category value
 * @param Number category number
 * @since  2008/10/03
 */
function toggleHidden (a, b, c) {
	var id = getCatId(a, c),
		s = '<input type=hidden id="' + a + '[' + id + ']" name="' + a + '[' + id + ']" value="' + id + '">',
		e = $("#" + configs[a]['hiddenId']);

	if ( $("#" + a.charAt(0).toLowerCase() + "_" + c).attr("checked") ) { 
		e.append(s);
	} else {
		e.children().remove("#" + a + "\\[" + id + "\\]");
	}
}

/**
 * 対象のカテゴリ(CAT/jZ/special)から id を取得
 *
 * @param String category name e.g. "jZ"
 * @param String category value
 * @return String category id
 */
function getCatId (a, b) {
/*
	var r, c = /cat/i.test(a) ? "cat" : 
				/jz/i.test(a) ? b.substr(0, 3) : b.charAt(0) + '00';
*/
//-- #604 Edit by Motohashi (IWS) 2008/11/19 Start
	var r, c = /cat/i.test(a) ? b.substr(0, 2) : 
				/occ/i.test(a) ? b.substr(0, 2) : 
				/jz/i.test(a) ? b.substr(0, 3) : b.charAt(0) + '00';
//-- #604 Edit by Motohashi (IWS) 2008/11/19 End
	if (typeof lists[a][c].children != "undefined") {
		$.each(lists[a][c].children, function(key, value){
			if (key == b) {
				r = key;
			}
		});
	}
	return r;
}


	function setSortMode(mode) {
		document.S02SearchForm.SM.value = mode;
		submission($.actionName);
	}

	function changePage(pageNumber) {
		document.S02SearchForm.CP.value = pageNumber;
		submission($.actionName);
	}

	function changePage2(pageNumber, tm) {
		document.S02SearchForm.CP.value = pageNumber;
		document.S02SearchForm.TM.value = tm;
		submission($.actionName);
	}

	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();
//-- #604 Edit by Motohashi (IWS) 2008/11/18 Start
		var categoryDisp = {};
//-- #604 Edit by Motohashi (IWS) 2008/11/18 End
		for(l in chk) {
			if(typeof chk[l] != 'function'){
//				//categoryDisp[l] = lists[doMode]['cat']['children'][chk[l]];
//				categoryDisp[chk[l]] = lists[doMode]['cat']['children'][chk[l]];
//-- #604 Edit by Motohashi (IWS) 2008/11/18 Start
				var pCode = chk[l].substr(0,2);
				if(typeof categoryDisp[pCode] == 'undefined') {
					categoryDisp[pCode] = new Object();
					categoryDisp[pCode]['count'] = 0;
					categoryDisp[pCode]['label'] = lists[doMode][pCode]['catName'];
				}
				if(typeof categoryDisp[pCode]['children'] == 'undefined') {
					categoryDisp[pCode]['children'] = new Object();
				}
				categoryDisp[pCode]['count']++;
				categoryDisp[pCode]['children'][chk[l]] = lists[doMode][pCode]['children'][chk[l]];
//-- #604 Edit by Motohashi (IWS) 2008/11/18 End
			}
		}
		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);
				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]];
				areaDisp[pCode]['children'][chk[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) + '00';
				//specialDisp[l] = lists[doMode][pCode]['children'][chk[l]];
				specialDisp[chk[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);
//-- Add by Motohashi 2008/07/02 Start
                            } else if ($(response).find("params").find("status").text() == "remove") {
                            	$("#exam_" + $(response).find("params").find("jobId").text()).attr("src", notUnderExamImageSrc);
//-- Add by Motohashi 2008/07/02 End
                            }else{
                            	alert($(response).find("params").find("error").text());
                            }
				        },
				        beforeSend: function (xml){
				        	//showLoadingImage(loadingRectangle, lastUniqId);
				        },
						error: function (XMLHttpRequest, textStatus, errorThrown) {
						alert(resultTemplates['error']);
						}
	    	}
	    );
	}


	function submission($actionName){
		$.actionName = $actionName;
		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();
				           		}
				           );

							//### add 2008-10-09 miyamoto 検索結果数を取得・表示
				           try {
				           	$("#jobTotal").html($("total", response).text());
				           }catch(e){}

							//ぱんくず
							try{
								$("#panlist").html(
									utf8to16(base64decode(($("bread",response).text()))).
										replace(/top/i, "アパレルワークス")
								);
							}catch(e){}

				           	$("#sortPaySystem").html($("sortPaySystem", 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}"+
								"</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="setSortMode(' + sm + ');">' + $(this).text() + 
										'</a>'
									);
								}
							});
							$("#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(),
										jobPrefName : $(this).find("jobPrefName").text(),
										jobAreaName : $(this).find("jobAreaName").text(),
										jobZoneName : $(this).find("jobZoneName").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(),
										//#2008-10-09 add LOGO#
										logo : $(this).find("logo").text(),
										//#2008-10-09 add CLIENT_NAME#
										clientName : $(this).find("clientName").text(),
										clientId : $(this).find("clientId").text(),
										//#2008-10-10 add SPECIAL#164
										special : $.trim(String($(this).find("special").text())).split(/\s+/),
										//#2008-10-10 add EMPOLY#916
										empoly : $.trim(String($(this).find("empoly").text())).split(/\s+/),
										actionNameS02 : ($actionName == "S02")
									};

									//#2008-10-10 add SPECIAL#164 Begin
									if (tmpJob.special) {
										var t = [];
										$.each(tmpJob.special, function(key, value){
											if (String($.trim(value)).length) {
												t.push(value);
											}
										});
										tmpJob.special = t;
									}
									//#2008-10-10 add SPECIAL#164 End
									//#2008-10-10 add EMPOLY#916 Begin
									if (tmpJob.empoly) {
										var t = [];
										$.each(tmpJob.empoly, function(key, value){
											if (String($.trim(value)).length) {
												t.push(value);
											}
										});
										tmpJob.empoly = t;
									}
									//#2008-10-10 add EMPOLY#916 End
									resultJobArray.push(tmpJob);
				           		}
				           );
							if(resultJobArray.length == 0){
								$("#sortParent").hide();
								//#2008-10-14 add jobTotalBox#
								$("#jobTotalBox").hide();
								$("#result").setTemplate(resultTemplates['searchNone']);
							}else{
								$("#sortParent").show();
								//#2008-10-14 add jobTotalBox#
								$("#jobTotalBox").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();
							//#2008-10-14 add jobTotalBox#
							$("#jobTotalBox").hide();
							$("#result").setTemplate(resultTemplates['waiting']);
							$("#result").processTemplate([]);
				        },
						error: function (XMLHttpRequest, textStatus, errorThrown) {
						  	$("#sortParent").hide();
							$(".searchPageNavi").hide();
							//#2008-10-14 add jobTotalBox#
							$("#jobTotalBox").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]);
//-- #604 Edit by Motohashi (IWS) 2008/11/19 Start
			doMode = "OCC";
			configs[doMode]['renderer'](defaults[doMode]);
//-- #604 Edit by Motohashi (IWS) 2008/11/19 End
			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() != ""){
			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;";
	}
