function showError(msg) {
	alert("Warning: " + msg);
}

function removeRow(tabId, tr) {
	var tab = $("#" + tabId);
	if ($(tr).find(".__remove").attr("disabled"))
		return; // do nothing (the page is in readonly mode)

	// test if tr is last row (add button should be preserved)
	var lastRowIndex = tab.find("tr:last-child td:eq(2)").text();
	if (lastRowIndex == 1) {
		if (!tab.find("input,select").eq(0).attr("disabled")) {
			if (!window.confirm("Are you sure?")) return;
			tab.find(":input").not(tab.find("button.addButton")).attr("disabled", true);
			tab.find(":input").not("button").val("");
			tab.find("input:checkbox").attr("checked", false);
		}
		doFieldColoring();
		return;
	}

	if (!window.confirm("Are you sure?")) return;
	var thisRowIndex = $(tr).find("td:eq(2)").text();
	if (thisRowIndex == lastRowIndex) {
		var but = $(tr).find(":button:first").clone(true);
		var trs = tab.find("tbody tr");
		trs.eq(trs.size() - 2).find("td:first-child").append(but);
	}

	$(tr).remove();

	// reorder indices
	tab.find("tr").each(function(i) {
		$(this).find("td:eq(2)").html(i);
	});
	doFieldColoring();
}

function addNewRow(add, tabId, postExec) {
	var tab = $("#" + tabId);
	var lastRow = tab.find("tbody tr:last-child");
	var newRowNum = parseInt(lastRow.find("td:eq(2)").text()) + 1;
	var inp = lastRow.find(":input").not(":button").eq(0);
	var newRow;
	if (newRowNum == 2 && inp.attr("disabled")) { // first row is inserted
		lastRow.find(":input").attr("disabled", false);
		if ($.browser.msie) {
			setTimeout(function() { // prevent IE crash
				lastRow.find(":input").not(":hidden,:button").eq(0).focus();
			}, 10);
		} else {
			// alert(lastRow.find(":input").not().eq(1).parent().html());
			lastRow.find(":input").not(":hidden,:button").eq(0).focus();
		}
		newRow = lastRow;
	} else {
		// clone a new row and clear it
		newRow = lastRow.clone(true);
		newRow.find("td:eq(2)").html(newRowNum);

		var file = newRow.find(":input[@type=file]").eq(0);
		if (file.size() > 0)
			file.attr('name', file.attr('name').replace('[1]', '['+newRowNum+']'));

		newRow.find(":text,textarea").val("");
		newRow.find("input:checked").removeAttr("checked");
	
		if ($.browser.msie) { // IE bug if last row's checkbox was checked
			newRow.find(":checkbox").removeAttr("$events").removeAttr("$handle");
		}

		lastRow.after(newRow);

		if ($.browser.msie) {
			setTimeout(function() { // prevent IE crash
				newRow.find(":input").not(":hidden,:button").eq(0).focus();
	    		$(add).remove();
			}, 10);
		} else {
			newRow.find(":input").not(":hidden,:button").eq(0).focus();
	   	$(add).remove();
		}
	}
	doFieldColoring();
	if (postExec) postExec.call(this, newRow);
}

function doFieldColoring() {
	if($.browser.msie) {
		$("input,textarea").not(":button,:checkbox,[type=reset],[type=radio]").bind("focus", function() {
			$(this).addClass("focusedInput");
		}).bind("blur", function() {
			$(this).removeClass("focusedInput");
		});
	}
	$(":input").each(function() {
		$(this).removeClass("readonlyInput").removeClass("disabledInput");
	});
	$(":input[readonly]").each(function() {
		$(this).addClass("readonlyInput");
	});
	$(":input[disabled]").each(function() {
		$(this).addClass("disabledInput");
	});
}

function onBoniadReady() {
	doFieldColoring();
	if ($("form").get(0)) installFormValidator($("form").get(0));
	installButtonListener();
}

function installButtonListener() {
	$(":button[@dispatch]").bind("click", function() {
		var t = $(this);
		if (t.attr("dispatch")) {
			$("#dispatch").val($(this).attr("dispatch"));
			if (t.attr("precond") && !eval(t.attr("precond"))) return false;
			var frm = $("#dispatch")[0].form;
			if (frm["onSubmitHandler"] && !frm["onSubmitHandler"].call(this)) return false;
			frm.submit();
		}
	});
	$("div.search :text,div.search select").bind("keypress", function(e) {
		if (e.which == 13) // enter
			$(this).parents("div.search:first").find(":button.search").trigger("click");
	});
}

function openMaximizedWindow(url) {
	var adjustHeight = 50;
	var adjustWidth = 10;
	var height = screen.availHeight - adjustHeight;
	var width = screen.availWidth - adjustWidth;        
	var winProps = "height=" + height + ",width=" + width + ",left=0,top=0,scrollbars=yes,resizable=yes";        
	var theWin = window.open(url, "WinName", winProps);
	theWin.focus();
	return theWin;
}

function fetchCodingInfo(ev, th) {
	var k = ev.keyCode ? ev.keyCode : ev.charCode;
	if (k == 13 || k == 9) {
		var res = doFetchCodingInfo(th);
		return (k == 9 && res);
	}
	return true;
}

function doFetchCodingInfo(th) {
	var codeRegex = /^\d{4,5}$/g; // matches 4 or 5 digits
	if (!codeRegex.test(th.value)) {
		alert("لطفاً يك عدد 4 يا 5 رقمي وارد نماييد.");
		return false;
	}

	var CODING_URL = "ajaxServlet?action=fetchCoding";
	var xml = $.ajax({
		type: "GET",
		url: CODING_URL,
		data: "code=" + th.value,
		async: false,
		dataType: "xml",
		error: function(err) {
			alert("Data fetch error: " + err);
		}
	}).responseXML;

	var x = $(xml.documentElement);
	if (!x.attr("type")) return;
	var tp = x.attr("type");
	var pc = x.attr("percent");
	var id = x.attr("id");

	var inps = $(th).parent().parent().find(":input");
	var itp = inps.eq(1);
	var iid = inps.eq(2);
	var ipc = inps.eq(3);

	if (tp) {
		itp.val(tp); // type
		iid.val(id); // hidden input
		ipc.val(pc); // percent
		return true;
	} else {
		itp.val(""); // type
		ipc.val(""); // percent
		iid.val(""); // hidden input
		alert("كد وارد شده يافت نشد.");
		return false;
	}
}

function ajaxGet(act, param) {
     return  baseAjaxGet(act, param)[0];
}

function baseAjaxGet(act, param) {
	var CODING_URL = "ajaxServlet?action=" + act;
	var xml = $.ajax({
		type: "GET",
		url: CODING_URL,
		data: param,
		async: false,
		dataType: "xml",
		error: function(err) { alert("خطا در اتصال به سرور: " + err); }
	}).responseXML;
	var x = xml.documentElement;
	if (!x) { alert("امکات ارتباط با سرور وجود ندارد!"); return null; }
	var list = new Array();
	var items = $(x).find("item").each(function(i) {
		var attrs = this.attributes;
		var o = new Object();
		for (var j = 0; j < attrs.length; j++) {
			o[attrs[j].name] = attrs[j].value;
		}
	    list.push(o);
	});
	
	/*
	for(var j = 0 ; var < items.length ; j++){
	 var attrs = items[j].attributes;
	 for (var i = 0; i < attrs.length; i++) {
		o[attrs[i].name] = attrs[i].value;
		list.push(o);
	 }
	}
	*/
	return list;
}
function saveTag(ev) {
	var k = ev.keyCode ? ev.keyCode : ev.charCode;
	if (k == 13 || ev.type == "click") {
		doSaveTag(ev);
	}
}
function doSaveTag() {
	var success = true;
	$(".__num").each(function () {
		if (isNaN(this.value)) { alert("لطفاً براي موارد شماره صفحه و شماره برگه عدد وارد نماييد."); success = false; return false; }
	});
	if ($("#tagEssence").find("option:eq(0)").attr("selected") && $("#confirm").val() != 't') {
		alert("لطفاً ماهيت سند را مشخص نماييد.");
		return;
	}

	if (!success) return;

	var im = $("#imageName").val();
	var pn = $("#tagPageNum").val();
	var sn = $("#tagSheetNum").val();
	var te = $("#tagEssence").val();
	var cc = $("#comCode").val();
	var cf = $("#confirm").val();
	var SAVE_TAG_URL = "ajaxServlet?action=saveTag";
	var xml = $.ajax({
		type: "POST",
		url: SAVE_TAG_URL,
		data: {imageName: im, sheetNum: sn, pageNum: pn, essence: te, comCode: cc, confirm: cf},
		async: false,
		dataType: "xml",
		error: function(err) {
			alert("خطا در اتصال به سرور " + err);
			success = false;
		}
	}).responseXML;
	var x = $(xml.documentElement);
	if (!success || x.attr("success") != "1")
		if (x.attr("success") == "2")
			alert("پس از تأييد امكان تأييد مجدد وجود ندارد");
		else if (x.attr("success") == "3")
			alert("پس از تأييد امكان ثبت وجود ندارد");
		else
			alert("بروز خطا در ذخيره سازي!");
	else { // succeeded
		if ($("#confirm").val() != 't')
			$("#" + $("#thumbId").val()).addClass("taggedImage");
	}
}

function fetchTag(imageName) {
	var FETCH_TAG_URL = "ajaxServlet?action=fetchTag";
	var success = true;
	var cc = $("#comCode").val();
	var xml = $.ajax({
		type: "GET",
		url: FETCH_TAG_URL,
		data: {"imageName": imageName, "comCode": cc},
		async: false,
		dataType: "xml",
		error: function(err) {
			alert("خطا در اتصال به سرور " + err);
			success = false;
		}
	}).responseXML;
	if (success) {
		var x = $(xml.documentElement);
		var im = x.attr("imageName");
		var pn = x.attr("pageNum");
		var sn = x.attr("sheetNum");
		var tc = x.attr("essence");
		var cf = x.attr("confirm");
		// tagEssence
		if (im) {
			$('#imageName').val(im);
			$("#tagPageNum").val(pn);
			$("#tagSheetNum").val(sn);
			$("#confirm").val(cf);
			$("#tagEssence").find("option[value=" + tc + "]").attr("selected", true);
		} else {
			$('#imageName').val(imageName);
			$('#tagEssence').find("option:first").attr("selected", true);
			$("#confirm").val('f');
			$("#tagPageNum").val("1");
			$("#tagSheetNum").val("1");
		}
	}
}

function installFormValidator(formObj) {
	var onSubmitHandler = function() {
		return doFormValidation(formObj);
	};
	// $(formExpr).submit(onSubmitHandler);
	// $(formExpr).bind("submit", formExpr);
	formObj["onSubmitHandler"] = onSubmitHandler;
}

function doFormValidation(thisForm) {
	var msg = [];
	var inpObj;
	$(thisForm).find(":input").each(function() {
		var th = $(this);
		if (inpObj || th.attr("disabled")) return;
		if (!th.attr("class") || th.attr("class").indexOf("_v_") <= -1) return true;
		var cl = th.attr("class").split(/\s+/);
		cli = cl.findStartWith("_v_"); // finds index of those items in the array starting with _v_
		if (!cli) return true; 
		$(cli).each(function() {
			var fobj = VALIDATOR[cl[this].substr(3)];
			if (!fobj) return;
			if (!fobj[1].test(th.val())) {
				msg.push(fobj[0]);
				inpObj = th;
			}
		});
	});
	if (inpObj) {
		if (inpObj.attr("type") && inpObj.attr("type").equalsIgnoreCase("hidden")) {
			msg.push(inpObj.attr("title"));
			alert(msg.convertToString("\n"));
		} else {
			alert(msg.convertToString("\n"));
			inpObj.focus();
		}
		return false;
	}
	return true;
}

function validateComCode() {
	var dateRegex = /^\d{10}$/;
	if (!dateRegex.test($("#comCode").val())) {
		alert('كد كامپيوتري بايد يك عدد 10 رقمي باشد');
		return false;
	}
	return true;
}

/** toggles all checkboxes with name='selection'. obj is the controlling select-all checkbox */
function toggleAll(obj) {
	$(obj).parents("table:first").find(":checkbox[name='selection']").attr("checked", obj.checked);
}   

function checkForSelection(obj) {
	if ($(obj).find("input:checked[name='selection']").size() < 1) {
		alert("حداقل یک سطر را انتخاب نمایید.");
		return false;
	}
	return true;
}

function openPopupCenter(url, popWidth, popHeight) {
	var documentBody = document.body;
	if (top)
		documentBody = top.document.body;
	var leftPos = (documentBody.clientWidth - popWidth) / 2, topPos = (documentBody.clientHeight - popHeight) / 2;
	return window.open(url, 'popup', 'width=' + popWidth + ',height=' + popHeight + ',top=' + topPos + ',left=' + leftPos);
}

function fetchCity() {
	var pc = $('#geoPosPvc').val();
	if (isEmpty(pc)) {
		_fillCity(new Array());
	} else {
		var resList = baseAjaxGet('fetchCity',{province: pc});
		if ( resList.length > 0) {
			_fillCity(resList);
		}else{
		 _fillCity(new Array());
		}
	}
}
	
function _fillCity(resList) {
    // $("#geoPosCity").empty();
    var options = "";
    if($("#geoPosCity").attr("nullable") == "true" || resList.length <= 0){
		options +=  "<option value=''>- - - - - - - - - - - -</option>\n";
    }
    for(var i = 0 ; i < resList.length ; i++){
		var map = resList[i];
		options += "<option value= '"+map['id']+"'>" +map['name']+ "</option>\n";
    }
	$("#geoPosCity").html(options);
}

function fetchRegion(){
var sc = $('#systemCoding').val();
	if (isEmpty(sc)) {
		_fillRegion(new Array());
	} else {
		var resList = baseAjaxGet('fetchRegion',{systemCoding: sc});
		if ( resList.length > 0) {
			_fillRegion(resList);
		}else{
		 _fillRegion(new Array());
		}
	}
}
function _fillRegion(resList){
    var options = "";
    if($("#regionCoding").attr("nullable") == "true" || resList.length <= 0){
		options +=  "<option value=''>- - - - - - - - - - - -</option>\n";
    }
    for(var i = 0 ; i < resList.length ; i++){
		var map = resList[i];
		options += "<option value= '"+map['id']+"'>" +map['name']+ "</option>\n";
    }
	$("#regionCoding").html(options);
}

function check4selection(par) {
	if($(par ? par : document).find(':checked[@name=selection]').size() <= 0) {
		alert('حداقل یک سطر را انتخاب نمایید.'); return false;
	} else {
		return true;
	}
}

function check4singleSelection(par) {
	if($(par ? par : document).find(':checked[@name=selection]').size() != 1) {
		alert('فقط یک سطر را انتخاب نمایید.'); return false;
	} else {
		return true;
	}
}

function checkRange(inp) {
	var tr = $(inp).parents('tr:first');
	var percent = parseInt($(inp).val());
	var min = parseInt(tr.find('input[@name=minPercent]').val());
	var max = parseInt(tr.find('input[@name=maxPercent]').val());
	if (percent > max || percent < min) {
		alert('مقدار درصد باید بین ' + min + ' تا ' + max + ' باشد.');
		$(inp).val(min);
	}
}
