﻿function __doExecute2(strPanelName, aParams, strURL, strForm)
{
	try
	{
		var strThisForm = strForm;
	    var isFileFound = false;

		var nFileCount = 0

		//	iа need use form for make params list
		if (strForm != null && strForm != "")
		{
			if ($('form#' + strThisForm).attr("in_process") == "true")
			{
				alert("Data sending to server")
				return false;
			}

			//	find input type=file in form
			$('form#' + strForm + ' input:file').each(function(i)
			{
				isFileFound |= ($(this).val() != "");
				nFileCount++;
			});

			//	if no files - add to aParams all imput from form
			if (isFileFound == false)
			{
				//	inputs	
				$('form#' + strForm + ' input').each(function(i)
				{
					if ((this.type != 'radio' && this.type != 'checkbox') || this.checked)
					{
						if (this.type == 'checkbox')
						  aParams[this.name] = (aParams[this.name] != "" && aParams[this.name] != null ? (aParams[this.name] == "False" ? "" : aParams[this.name]) + "," : "") + this.value;
						else
						{
							if (this.name != "address_operation" || aParams["address_operation"] == null)
							  aParams[this.name] = this.value;
						}
					}
					else
					if (this.type == 'checkbox' && !this.checked)
					{
						if (aParams[this.name] == "" || aParams[this.name] == null) 
							aParams[this.name] = "False";
						else
							aParams[this.name] = (aParams[this.name] == "False" ? "" : aParams[this.name]) + ",";
					}
				});

				//	textareas
				$('form#' + strForm + ' textarea').each(function(i){
					  aParams[this.name] = this.value;
					});

				//	select
				$('form#' + strForm + ' select').each(function(i)
				{
					if (this.multiple != true)
	  				    aParams[this.name] = (aParams[this.name] != null ? aParams[this.name] + "," : "") + this.value;
					else
					{
						var strSelectName = this.name;
						aParams[strSelectName] = "";
						$('form#' + strForm + ' select[@name=' + this.name + '] option').each(function(i)
						{
							if ($(this).attr("selected"))
								aParams[strSelectName] += (aParams[strSelectName] != "" ? "," : "") + $(this).val();
						});
					}
				});

				try
				{
					if (tinyMCE != null)
					{
						$('textarea').each(function(i)
						{
							try
							{
								var oTinyMceEditor = tinyMCE.get(this.id);
								if (oTinyMceEditor != null)
									aParams[this.id] = oTinyMceEditor.getContent();
							}
							catch(e) {}
						});
					}
				}
				catch(e) {}
			}


			$('form#' + strForm).attr("in_process", "true");
		}

		var strThisPanelName = strPanelName.split('.')[0];
		$('#' + strThisPanelName).addClass("submited");

		aParams["__is_postback"] = "true";
		aParams["__is_postback_panel"] = strPanelName;

		//	if form has files for send to server use standard jquery ajax 
		if (isFileFound == false)
		{
			$('#AjaxResult').load(strURL, aParams, function()
			{
				ProccessResponse(strThisForm, strThisPanelName);
			});
		}
		else
		{
			//	send data to server use form tag and target iframe
			aParams["__is_postback_form"] = "true";
			FileUpload($('form#' + strThisForm), {url : strURL, form : strThisForm, panel : strThisPanelName, extraData : aParams, complete: UploadFileResponse });
		}
	}
	catch(e) {}
	
	return false;
}

function ProccessResponse(strForm, strPanelName)
{
	if (strForm != null && strForm != "")
		$('form#' + strForm).attr("in_process", "false");
	strForm = null;

	if (strPanelName != null)
		$('#' + strPanelName).removeClass("submited");

	$('#AjaxResult #Message').each(function(i)
	{
		//alert($(this).html());
	});

	var bIsCancelProccess = false;
	$('#AjaxResult #Redirect').each(function(i)
	{
		if (bIsCancelProccess == false)
			window.location.href = $(this).text();
		bIsCancelProccess = true;
	});

	if (bIsCancelProccess)
		return;

	$('#AjaxResult').children().each(function(i)
	{
		if (this.id != this.id.replace("_postback", ""))
		{
			$("#" + this.id.replace("_postback", "") + " > *").remove();
			$("#" + this.id + " > *").appendTo("#" + this.id.replace("_postback", ""));
		}
	});

	$("#AjaxResult").html("");
}

function UploadFileResponse(strResponseText, strForm, strPanelName)
{
	$('#AjaxResult').append(strResponseText);
	ProccessResponse(strForm, strPanelName);
}

function FileUpload(form, options) 
{
	var id = 'jqFormIO' + (new Date().getTime());
	var $io = $('<iframe id="' + id + '" name="' + id + '" src="about:blank" />');
	$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
	var io = $io[0];

	// take a breath so that pending repaints get some cpu time before the upload starts
	setTimeout(function() 
	{
		// make sure form attrs are set
        var t = $(form).attr('target')

		// update form attrs in IE friendly way
		$(form).attr('target', id);
		if ($(form).attr('method') != 'POST')
			$(form).attr('method', 'POST');
		if ($(form).attr('action') != options.url)
			$(form).attr('action', options.url);

        $(form).attr({encoding: 'multipart/form-data', enctype:  'multipart/form-data'});

        // add "extra" data to form if provided in options
        var extraInputs = [];
        try 
		{
            if (options.extraData)
                for (var n in options.extraData)
                    extraInputs.push($('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />').appendTo(form)[0]);

            // add iframe to doc and submit the form
            $io.appendTo('body');
            io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);

            form.submit();
        }
        finally 
		{
            // reset attrs and remove "extra" input elements
            t ? form.setAttribute('target', t) : $(form).removeAttr('target');
            $(extraInputs).remove();
        }
    }, 10);

    var nullCheckFlag = 0;
	var cbInvoked = 0;

    function cb() 
	{
        if (cbInvoked++) 
			return;

        io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

		var responseText = null;
        try 
		{
            // extract the server response from the iframe
            var doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;

            if ((doc.body == null || doc.body.innerHTML == '') && !nullCheckFlag) 
			{
                // in some browsers (cough, Opera 9.2.x) the iframe DOM is not always traversable when
                // the onload callback fires, so we give them a 2nd chance
                nullCheckFlag = 1;
                cbInvoked--;
                setTimeout(cb, 100);
                return;
            }

            responseText = doc.body ? doc.body.innerHTML : null;
        }
        catch(e) {}

        if (options.complete) 
			options.complete(responseText, options.form, options.panel);

        // clean up
        setTimeout(function() { $io.remove(); }, 100);
    };
};

function RegisterAjaxPostBackParameter(strName, strValue)
{
}

function RefreshPanel(strPanelName, nInterval, strURL)
{
	setTimeout("__doExecute('" + strPanelName + "', {}, '" + strURL + "');", nInterval * 1000);
}

function RefreshPanel2(strPanelName, nInterval, strURL, strParams)
{
	setTimeout("__doExecute2('" + strPanelName + "', " + strParams + ", '" + strURL + "');", nInterval * 1000);
}

SEPARATOR = "#2115b030-9506-46d1-bb22-f4cfff9eaa2c#";

function SetAutocomplite(strID, strUrl, nWidth, strRefreshOnChangePanel, strParentForm, strPageURL, bIsRefreshOnChange)
{
	setTimeout('$("#' + strID + '").blur()', 1);

	$("#" + strID).autocomplete(strUrl, {
		loadingClass: "loading",
		delay: 1000,
		minChars: 0,
		width: nWidth,
		scroll: true,
		scrollHeight: 200,
		highlightItem: true,
		//autoFill: true,
		selectFirst: true,
		matchSubset: true,
		mustMatch: true,
		cacheLength: 10,
		matchContains: true,
		multiple: false,
		multipleSeparator: SEPARATOR,

		highlight: function(value, term) { return value; },
		
		formatItem: function(data, i, n, value) {
			if ( typeof data[1] !== "undefined" )
				return data[1].split(SEPARATOR)[1];
			else 
				return "По Вашему запросу ничего не найдено!";
		},

		formatResult: function(data, value) {
			if ( typeof data[1] !== "undefined" )
				return data[1].split(SEPARATOR)[0].replace(/(^\s+)|(\s+$)/g, '');
			else 
				return "Не выбрано";
		}

	});

	$("#" + strID).attr("is_show", "false");

	$("#" + strID).result(function(event, data, formatted) 
	{
		var bIsNull = (data == null || data[0] == "0");
		var strNewValue = (!bIsNull ? data[0] : "");
		var strOldValue = $("#" + strID + "_id").attr("old_value");
		strOldValue = (strOldValue == null ? "" : strOldValue);

		$("#" + strID + "_id").val(strNewValue);
		$("#" + strID + "_id").attr("old_value", strNewValue);

		if (bIsNull)
			$(this).addClass("notset");
		else
			$(this).removeClass("notset");

		if (strNewValue != strOldValue && bIsRefreshOnChange && strRefreshOnChangePanel != "")
			__doExecute2(strRefreshOnChangePanel, {}, strPageURL, strParentForm);
	});

	$("#" + strID + "_button").click(function(event)
	{
		if (event.target.id == strID + "_button" && $("#" + strID).attr("is_show") == "false")
			setTimeout( 'OpenList("' + strID + '");', 300 );
	});

	$("#" + strID).blur(function()
	{
		setTimeout( 'HideList("' + strID + '");', 300 );
	});

	$("#" + strID).focus(function()
	{
		if ($(this).val().toLowerCase() == "не выбрано")
			$(this).val("");
	});

	$("#" + strID).keypress(function()
	{
		$(this).removeClass('notset');
	});
}

function OpenList(strID)
{
	$("#" + strID).focus();
	$("#" + strID).focus();
	$("#" + strID).click();
	$("#" + strID).attr("is_show", "true");
}

function HideList(strID)
{
	$("#" + strID).attr("is_show", "false");
}

function RefreshOnChange(oControl, strRefreshOnChangePanel, strParentForm, strPageURL)
{
	var strOldValue = $(oControl).attr("old_value");
	if (strOldValue != $(oControl).val() && strRefreshOnChangePanel != "")
		__doExecute2(strRefreshOnChangePanel, {__is_refresh: true, init_refresh_field: $(oControl).attr("name").substring(1) }, strPageURL, strParentForm);
}

function HideMessage(strID, nTimeOut)
{
	nTimeOut = (nTimeOut == null ? 10 : nTimeOut)
	
	$('#' + strID + 'Timer').html("&nbsp;<a href=# onclick='return HideMessage(\"" + strID + "\", 0);'><div style='display:inline;position:relative;top:-2px;vertical-align:top;background:url(/defs/images/message_close.gif);background-repeat: no-repeat; background-position: right 1px;'><span style='font-size:70%;text-decoration:underline;color:blue;padding-right:10px;'>(" + nTimeOut + ")</span></div></a>");

	if (nTimeOut > 0)
		window.setTimeout("HideMessage('" + strID + "', " + (nTimeOut - 1) + ")", 1000);
	else
		$('#' + strID).hide();

	return false;
}

function CheckMaxLength(oTextArea)
{
	var nMaxLenght = $(oTextArea).attr("max_length");
	var strCounterID = $(oTextArea).attr("id") + "_counter";
	var Value = $(oTextArea).val();
	var initLength = Math.max((Value ? (nMaxLenght - Value.length) : nMaxLenght),0);

	$("div#" + strCounterID + " span").css("color", "rgb("+(0.51*Value.length)+", 0, 0)");
	$("div#" + strCounterID + " span").html(initLength.toString());
   
	if (Value.length > nMaxLenght)
	{
		$(oTextArea).val(Value.substr(0, nMaxLenght));
		return false;
	}
}
