var browser=navigator.userAgent.toLowerCase();
var isIE=((browser.indexOf("msie")!=-1) && (browser.indexOf("opera")==-1));
var isOpera = (/opera/i.test(navigator.userAgent));

function addSmile(name,intoID) {
	var into = document.getElementById(intoID);
	if(isIE){
		into.focus();
		document.selection.createRange().text=' '+name+' ';
	}
	else{
		var text=into;
		into.focus();
		text=text.value.substring(0, text.selectionStart)+' '+name+' '+text.value.substring(text.selectionEnd, text.value.length);
		into.value=text;
		if (isOpera) into.setSelectionRange(into.value.length,into.value.length);
	}
}


var debugSqlQueriesListStatus = 0;
function debugSqlQueriesListOperate(){
	var listItem = document.getElementById('debugSqlQueriesList');
	var opItem = document.getElementById('debugSqlQueriesListOperator');
	if (debugSqlQueriesListStatus == 0) {
		listItem.style.display = 'block';
		opItem.innerHTML ='hide list';
		debugSqlQueriesListStatus = 1;
	}
	else if (debugSqlQueriesListStatus == 1) {
		listItem.style.display = 'none';
		opItem.innerHTML ='show list';
		debugSqlQueriesListStatus = 0;
	}
}


function initCalendar(inputField, triggerField, dateFormat, options){
	if (!dateFormat) dateFormat = "%Y-%m-%d";
	if (!options) options = {};

	Calendar.setup($.extend({
      inputField  : 	inputField,
      ifFormat    :	dateFormat,
      button      : 	triggerField,
      singleClick : 	"true",
      firstDay  : 	1,
      weekNumbers : 	false,
      align : "br"
    }, options)
  );
}

function SetAllValue(sIdPrefix,mValue,sExcludeId,sElement,sObjType) {
	if(!sElement) sElement = "INPUT";

	var objs = document.getElementsByTagName(sElement);

	for(i=0;i<objs.length;i++){
		if(objs[i].id!=sExcludeId && objs[i].id.substr(0,sIdPrefix.length)==sIdPrefix) {
			if(!sObjType || objs[i].type==sObjType ) {
				if(objs[i].type=='checkbox') objs[i].checked = mValue;
				else objs[i].value = mValue;
				if(objs[i].onchange) objs[i].onchange();
			}
		}
	}
}


_$ = function(sId) {
	if (!sId) {
		return null;
	}
	var returnObj = document.getElementById(sId);
	if (!returnObj && document.all) {
		returnObj = document.all[sId];
	}
	return returnObj;
}

function CalculateWithdrawTotalAmount(feeType, feeValue, amount, feeMin, feeMax){

}


App =
{
    init: function()
    {

    },

    dialog: function(text)
    {
        var div = $('<div />');

        div.html(text).appendTo('body');

        div.dialog({
            title: 'Сообщение',
            height: 140,
            resizable: false
        });

        div.dialog('widget').delay(1000).fadeOut(400, function()
        {
            div.dialog('destroy').remove();
        });
    },

    existDialog: function(selector, options)
    {
        $(selector).dialog($.extend({
            hide: 'slow',
            modal: true,
            resizable: false,
            width: 530,
            dialogClass: 'sysDialog',
            close: function(event, ui) {
                $(this).remove();
            }
        }, options));
    },

    ajaxDialog: function(url, options)
    {
    	App.dialogHandlers.postAjaxLoaded = null;
    	var id = options && options.id ? options.id : "sysAjaxDialog_" + $time().toString().substr(5) + parseInt(Math.random() * (99999999 - 11111111) + 11111111);
        $('<div id="' + id + '"></div>').load(url, function(data) {
            App.existDialog(this, options);
            if (App.dialogHandlers.postAjaxLoaded) App.dialogHandlers.postAjaxLoaded.call(this);
        });
    },

    // обработчики для диалогов
    dialogHandlers: {postAjaxLoaded: null},

    showMessages: function(data)
    {
        if (!data || typeof(data.msg) == 'undefined' || !data.msg) return;

        for (var i=0; i<data.msg.length; i++) {
            alert(data.msg[i].text);
        }
    },

    // для добавления функций на странице
    // ex: App.local.someFunct: function(data) { }
    local: {},

    toIntArray : function (obj)
    {
    	var a = [];
    	for (var i in obj) a.push(parseInt(obj[i]));
    	return a;
    }
};

$(document).ready(App.init);

if (typeof jQuery.datepicker !== 'undefined') {
    jQuery.datepicker.setDefaults({
        closeText: 'Закрыть',
        prevText: '&#x3c;Пред',
        nextText: 'След&#x3e;',
        currentText: 'Сегодня',
        monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
        'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
        monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
        'Июл','Авг','Сен','Окт','Ноя','Дек'],
        dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
        dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
        dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
        firstDay: 1,
        isRTL: false
    });
}

$.postJSON = function(url, params, callback)
{
    $.post(url, params, function(data) {
    	callback = callback || function() {};
    	App.showMessages(data);
    	callback(data);
    }, "json");
};

$.ourGetJSON = function(url, params, callback)
{
    $.get(url, params, function(data) {
    	callback = callback || function() {};
    	App.showMessages(data);
    	callback(data);
    }, "json");
};

$.fn.reloadImg = function()
{
    var url = $(this).attr('src').toString();

	url = url.replace(/[?&]nocache=.*?(&|$)/g,"$1");
	if(url.indexOf("?")!=-1) url = url+"&";
	else url = url+"?";

	$(this).attr('src',url + "nocache=" + new Date());
}

$.fn.postForm = function(callback, params, serializeParams)
{
    formData = $(this).serializeArray();
    if (params) {
        for (idx in params) formData.push({"name": idx, "value": params[idx]});
    }

    if (serializeParams) {
        for (idx in serializeParams) formData.push(serializeParams[idx]);
    }

	$.postJSON($(this).attr('action'), formData, callback);
}

$.fn.htmlPostForm = function(container, callback, params, serializeParams)
{
    formData = $(this).serializeForm(params, serializeParams);

	$(container).load($(this).attr('action'), formData, function(data) {
    	callback = callback || function() {};
    	callback(data);
	});

	return false;
}

$.fn.serializeForm = function(params, serializeParams)
{
    formData = $(this).serializeArray();
    if (params) {
        for (idx in params) formData.push({"name": idx, "value": params[idx]});
    }

    if (serializeParams) {
        for (idx in serializeParams) formData.push(serializeParams[idx]);
    }

    return formData;
}

$.fn.serializeHash = function()
{
    var p = this.serializeArray(), result = {};
    for (var i=0; i<p.length; i++) {
        result[p[i].name] = p[i].value;
    }
    return result;
};





function getGets(name, full, sGets)
{
	var sGets = typeof sGets != "undefined" ? sGets : document.location.toString().split("#",2)[0].split("?",2)[1];
	if(typeof sGets == "undefined") sGets = '';

	if(name) {
		var aGets = sGets.split("&");
		for(var i=0; i<aGets.length; i++) {
			var aGet = aGets[i].split("=",2);
			if(aGet[0] == name) return full ? aGets[i] : aGet[1];
		}

		return '';
	}

	return sGets ? sGets : '';
}


function CloneChild()
{
    this._aChilds = {};
	this._aChildsNum = {};

	this.set = function(containerId)
	{
		this._aChilds[containerId] = $("#"+containerId).children().eq(0).clone();
		this._aChildsNum[containerId] = 1;
	}

	this.clone = function(containerId, count, maxChildren, emptyValue, actionObj)
	{
		var jContainer = $("#"+containerId);
		var jChildren = jContainer.children();
		var jChild = this._aChilds[containerId] ? this._aChilds[containerId] : jChildren.eq(0);
		var currChildrens = typeof this._aChildsNum[containerId] != "undefined" ? this._aChildsNum[containerId] : jChildren.length;

		for(var i=0; i<count && (!maxChildren || (currChildrens+i)<maxChildren); i++) {
			var jClone = jChild.clone().hide( );
			if(emptyValue) {
				jClone.val('');
				jClone.children('INPUT').val('');
			}
			if(typeof this._aChildsNum[containerId] != "undefined") this._aChildsNum[containerId]++;
			jContainer.append(jClone);
			jClone.fadeIn("slow");
		}

		if(actionObj && maxChildren && (currChildrens+i)>=maxChildren) $(actionObj).hide();

		return false;
	}
}

var cloneChild = new CloneChild();

