/* include jquery.form-2.43.js */
/*!
 * jQuery Form Plugin
 * version: 2.43 (12-MAR-2010)
 * @requires jQuery v1.3.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {

/*
	Usage Note:
	-----------
	Do not use both ajaxSubmit and ajaxForm on the same form.  These
	functions are intended to be exclusive.  Use ajaxSubmit if you want
	to bind your own submit handler to the form.  For example,

	$(document).ready(function() {
		$('#myForm').bind('submit', function() {
			$(this).ajaxSubmit({
				target: '#output'
			});
			return false; // <-- important!
		});
	});

	Use ajaxForm when you want the plugin to manage all the event binding
	for you.  For example,

	$(document).ready(function() {
		$('#myForm').ajaxForm({
			target: '#output'
		});
	});

	When using ajaxForm, the ajaxSubmit function will be invoked for you
	at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
	// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
	if (!this.length) {
		log('ajaxSubmit: skipping submit process - no element selected');
		return this;
	}

	if (typeof options == 'function')
		options = { success: options };

	var url = $.trim(this.attr('action'));
	if (url) {
		// clean url (don't include hash vaue)
		url = (url.match(/^([^#]+)/)||[])[1];
   	}
   	url = url || window.location.href || '';

	options = $.extend({
		url:  url,
		type: this.attr('method') || 'GET',
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
	}, options || {});

	// hook for manipulating the form data before it is extracted;
	// convenient for use with rich editors like tinyMCE or FCKEditor
	var veto = {};
	this.trigger('form-pre-serialize', [this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
		return this;
	}

	// provide opportunity to alter form data before it is serialized
	if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSerialize callback');
		return this;
	}

	var a = this.formToArray(options.semantic);
	if (options.data) {
		options.extraData = options.data;
		for (var n in options.data) {
		  if(options.data[n] instanceof Array) {
			for (var k in options.data[n])
			  a.push( { name: n, value: options.data[n][k] } );
		  }
		  else
			 a.push( { name: n, value: options.data[n] } );
		}
	}

	// give pre-submit callback an opportunity to abort the submit
	if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSubmit callback');
		return this;
	}

	// fire vetoable 'validate' event
	this.trigger('form-submit-validate', [a, this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
		return this;
	}

	var q = $.param(a);

	if (options.type.toUpperCase() == 'GET') {
		options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
		options.data = null;  // data is null for 'get'
	}
	else
		options.data = q; // data is the query string for 'post'

	var $form = this, callbacks = [];
	if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
	if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

	// perform a load on the target only if dataType is not provided
	if (!options.dataType && options.target) {
		var oldSuccess = options.success || function(){};
		callbacks.push(function(data) {
			var fn = options.replaceTarget ? 'replaceWith' : 'html';
			$(options.target)[fn](data).each(oldSuccess, arguments);
		});
	}
	else if (options.success)
		callbacks.push(options.success);

	options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
		for (var i=0, max=callbacks.length; i < max; i++)
			callbacks[i].apply(options, [data, status, xhr || $form, $form]);
	};

	// are there files to upload?
	var files = $('input:file', this).fieldValue();
	var found = false;
	for (var j=0; j < files.length; j++)
		if (files[j])
			found = true;

	var multipart = false;
//	var mp = 'multipart/form-data';
//	multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

	// options.iframe allows user to force iframe mode
	// 06-NOV-09: now defaulting to iframe mode if file input is detected
   if ((files.length && options.iframe !== false) || options.iframe || found || multipart) {
	   // hack to fix Safari hang (thanks to Tim Molendijk for this)
	   // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
	   if (options.closeKeepAlive)
		   $.get(options.closeKeepAlive, fileUpload);
	   else
		   fileUpload();
	   }
   else
	   $.ajax(options);

	// fire 'notify' event
	this.trigger('form-submit-notify', [this, options]);
	return this;


	// private function for handling file uploads (hat tip to YAHOO!)
	function fileUpload() {
		var form = $form[0];

		if ($(':input[name=submit]', form).length) {
			alert('Error: Form elements must not be named "submit".');
			return;
		}

		var opts = $.extend({}, $.ajaxSettings, options);
		var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

		var id = 'jqFormIO' + (new Date().getTime());
		var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ opts.iframeSrc +'" onload="(jQuery(this).data(\'form-plugin-onload\'))()" />');
		var io = $io[0];

		$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

		var xhr = { // mock object
			aborted: 0,
			responseText: null,
			responseXML: null,
			status: 0,
			statusText: 'n/a',
			getAllResponseHeaders: function() {},
			getResponseHeader: function() {},
			setRequestHeader: function() {},
			abort: function() {
				this.aborted = 1;
				$io.attr('src', opts.iframeSrc); // abort op in progress
			}
		};

		var g = opts.global;
		// trigger ajax global events so that activity/block indicators work like normal
		if (g && ! $.active++) $.event.trigger("ajaxStart");
		if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && $.active--;
			return;
		}
		if (xhr.aborted)
			return;

		var cbInvoked = false;
		var timedOut = 0;

		// add submitting element to data if we know it
		var sub = form.clk;
		if (sub) {
			var n = sub.name;
			if (n && !sub.disabled) {
				opts.extraData = opts.extraData || {};
				opts.extraData[n] = sub.value;
				if (sub.type == "image") {
					opts.extraData[n+'.x'] = form.clk_x;
					opts.extraData[n+'.y'] = form.clk_y;
				}
			}
		}

		// take a breath so that pending repaints get some cpu time before the upload starts
		function doSubmit() {
			// make sure form attrs are set
			var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST')
				form.setAttribute('method', 'POST');
			if (form.getAttribute('action') != opts.url)
				form.setAttribute('action', opts.url);

			// ie borks in some cases when setting encoding
			if (! opts.skipEncodingOverride) {
				$form.attr({
					encoding: 'multipart/form-data',
					enctype:  'multipart/form-data'
				});
			}

			// support timout
			if (opts.timeout)
				setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

			// add "extra" data to form if provided in options
			var extraInputs = [];
			try {
				if (opts.extraData)
					for (var n in opts.extraData)
						extraInputs.push(
							$('<input type="hidden" name="'+n+'" value="'+opts.extraData[n]+'" />')
								.appendTo(form)[0]);

				// add iframe to doc and submit the form
				$io.appendTo('body');
				$io.data('form-plugin-onload', cb);
				form.submit();
			}
			finally {
				// reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
				t ? form.setAttribute('target', t) : $form.removeAttr('target');
				$(extraInputs).remove();
			}
		};

		if (opts.forceSync)
			doSubmit();
		else
			setTimeout(doSubmit, 10); // this lets dom updates render
	
		var domCheckCount = 100;

		function cb() {
			if (cbInvoked) 
				return;

			var ok = true;
			try {
				if (timedOut) throw 'timeout';
				// extract the server response from the iframe
				var data, doc;

				doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
				
				var isXml = opts.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
				log('isXml='+isXml);
				if (!isXml && (doc.body == null || doc.body.innerHTML == '')) {
				 	if (--domCheckCount) {
						// in some browsers (Opera) the iframe DOM is not always traversable when
						// the onload callback fires, so we loop a bit to accommodate
				 		log('requeing onLoad callback, DOM not available');
						setTimeout(cb, 250);
						return;
					}
					log('Could not access iframe DOM after 100 tries.');
					return;
				}

				log('response detected');
				cbInvoked = true;
				xhr.responseText = doc.body ? doc.body.innerHTML : null;
				xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
				xhr.getResponseHeader = function(header){
					var headers = {'content-type': opts.dataType};
					return headers[header];
				};

				if (opts.dataType == 'json' || opts.dataType == 'script') {
					// see if user embedded response in textarea
					var ta = doc.getElementsByTagName('textarea')[0];
					if (ta)
						xhr.responseText = ta.value;
					else {
						// account for browsers injecting pre around json response
						var pre = doc.getElementsByTagName('pre')[0];
						if (pre)
							xhr.responseText = pre.innerHTML;
					}			  
				}
				else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
					xhr.responseXML = toXml(xhr.responseText);
				}
				data = $.httpData(xhr, opts.dataType);
			}
			catch(e){
				log('error caught:',e);
				ok = false;
				xhr.error = e;
				$.handleError(opts, xhr, 'error', e);
			}

			// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
			if (ok) {
				opts.success(data, 'success');
				if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
			}
			if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
			if (g && ! --$.active) $.event.trigger("ajaxStop");
			if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

			// clean up
			setTimeout(function() {
				$io.removeData('form-plugin-onload');
				$io.remove();
				xhr.responseXML = null;
			}, 100);
		};

		function toXml(s, doc) {
			if (window.ActiveXObject) {
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = 'false';
				doc.loadXML(s);
			}
			else
				doc = (new DOMParser()).parseFromString(s, 'text/xml');
			return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
		};
	};
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *	is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *	used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
	return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
		e.preventDefault();
		$(this).ajaxSubmit(options);
	}).bind('click.form-plugin', function(e) {
		var target = e.target;
		var $el = $(target);
		if (!($el.is(":submit,input:image"))) {
			// is this a child element of the submit el?  (ex: a span within a button)
			var t = $el.closest(':submit');
			if (t.length == 0)
				return;
			target = t[0];
		}
		var form = this;
		form.clk = target;
		if (target.type == 'image') {
			if (e.offsetX != undefined) {
				form.clk_x = e.offsetX;
				form.clk_y = e.offsetY;
			} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
				var offset = $el.offset();
				form.clk_x = e.pageX - offset.left;
				form.clk_y = e.pageY - offset.top;
			} else {
				form.clk_x = e.pageX - target.offsetLeft;
				form.clk_y = e.pageY - target.offsetTop;
			}
		}
		// clear form vars
		setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
	});
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
	return this.unbind('submit.form-plugin click.form-plugin');
};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
	var a = [];
	if (this.length == 0) return a;

	var form = this[0];
	var els = semantic ? form.getElementsByTagName('*') : form.elements;
	if (!els) return a;
	for(var i=0, max=els.length; i < max; i++) {
		var el = els[i];
		var n = el.name;
		if (!n) continue;

		if (semantic && form.clk && el.type == "image") {
			// handle image inputs on the fly when semantic == true
			if(!el.disabled && form.clk == el) {
				a.push({name: n, value: $(el).val()});
				a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
			continue;
		}

		var v = $.fieldValue(el, true);
		if (v && v.constructor == Array) {
			for(var j=0, jmax=v.length; j < jmax; j++)
				a.push({name: n, value: v[j]});
		}
		else if (v !== null && typeof v != 'undefined')
			a.push({name: n, value: v});
	}

	if (!semantic && form.clk) {
		// input type=='image' are not found in elements array! handle it here
		var $input = $(form.clk), input = $input[0], n = input.name;
		if (n && !input.disabled && input.type == 'image') {
			a.push({name: n, value: $input.val()});
			a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
		}
	}
	return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
	//hand off to jQuery.param for proper encoding
	return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
	var a = [];
	this.each(function() {
		var n = this.name;
		if (!n) return;
		var v = $.fieldValue(this, successful);
		if (v && v.constructor == Array) {
			for (var i=0,max=v.length; i < max; i++)
				a.push({name: n, value: v[i]});
		}
		else if (v !== null && typeof v != 'undefined')
			a.push({name: this.name, value: v});
	});
	//hand off to jQuery.param for proper encoding
	return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *	  <input name="A" type="text" />
 *	  <input name="A" type="text" />
 *	  <input name="B" type="checkbox" value="B1" />
 *	  <input name="B" type="checkbox" value="B2"/>
 *	  <input name="C" type="radio" value="C1" />
 *	  <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *	   array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
	for (var val=[], i=0, max=this.length; i < max; i++) {
		var el = this[i];
		var v = $.fieldValue(el, successful);
		if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
			continue;
		v.constructor == Array ? $.merge(val, v) : val.push(v);
	}
	return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
	var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	if (typeof successful == 'undefined') successful = true;

	if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1))
			return null;

	if (tag == 'select') {
		var index = el.selectedIndex;
		if (index < 0) return null;
		var a = [], ops = el.options;
		var one = (t == 'select-one');
		var max = (one ? index+1 : ops.length);
		for(var i=(one ? index : 0); i < max; i++) {
			var op = ops[i];
			if (op.selected) {
				var v = op.value;
				if (!v) // extra pain for IE...
					v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
				if (one) return v;
				a.push(v);
			}
		}
		return a;
	}
	return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
	return this.each(function() {
		$('input,select,textarea', this).clearFields();
	});
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
	return this.each(function() {
		var t = this.type, tag = this.tagName.toLowerCase();
		if (t == 'text' || t == 'password' || tag == 'textarea')
			this.value = '';
		else if (t == 'checkbox' || t == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
	return this.each(function() {
		// guard against an input with the name of 'reset'
		// note that IE reports the reset function as an 'object'
		if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
			this.reset();
	});
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
	if (b == undefined) b = true;
	return this.each(function() {
		this.disabled = !b;
	});
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
	if (select == undefined) select = true;
	return this.each(function() {
		var t = this.type;
		if (t == 'checkbox' || t == 'radio')
			this.checked = select;
		else if (this.tagName.toLowerCase() == 'option') {
			var $sel = $(this).parent('select');
			if (select && $sel[0] && $sel[0].type == 'select-one') {
				// deselect all other options
				$sel.find('option').selected(false);
			}
			this.selected = select;
		}
	});
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
	if ($.fn.ajaxSubmit.debug) {
		var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
		if (window.console && window.console.log)
			window.console.log(msg);
		else if (window.opera && window.opera.postError)
			window.opera.postError(msg);
	}
};

})(jQuery);

/* include ammo.js */
window.ammo = window.ammo || {};
(function(ammo) {
  var load_files = {};

  ammo.file_versions = ammo.file_versions || {};
  ammo.i18n_dictonary = ammo.i18n_dictonary || {};
  ammo.utils = {};

  ammo.i18n = function(message)
  {
    return ammo.i18n_dictonary[message] ? ammo.i18n_dictonary[message] : message;
  };
  
  ammo.dump = function(obj)
  {
    if(window.JSON && JSON.stringify)
      alert(JSON.stringify(obj));
    else
      alert(obj);
  };

  ammo.logError = function(e)
  {
    if(window.console)    
      window.console.error(e);
  };

  ammo.one = function(obj, name, func) {
    obj[name] = function() {
      obj[name] = null;
      obj[name] = func();
      return obj[name].apply(null, arguments);
    };
  };

  ammo.addVersion = function(src) {
    return ammo.file_versions[src] || src;
  };
   
  var __load = function(files, callback)
  {
    if(typeof(files) === 'string')
      files = [files];
    for(var i in files)
    {
      src = files[i];
      if(!src || load_files[src])
        continue;
      load_files[src] = true;
      callback(ammo.absPath(ammo.file_versions[src] || src));
    }
  };

  ammo.lazyMethod = function(options) {
    options = options || {};
    ammo.one(options.obj, options.name, function() {
      ammo.ajaxLoader().show();

      __load(options.css_files, function(url) {
        jQuery('<style>').attr('type', 'text/css').attr('media', 'all').html('@import url(\'' + url + '\');').appendTo('head');
      });

      __load(options.js_files, function(url) {
        jQuery.ajax({url: url, cache: true, type: 'GET', async: false, dataType: 'script', error: function() {throw 'Failed load js!';}});
      });

      ammo.ajaxLoader().hide();
      if(options.callback)
        return options.callback();
      if(options.get_object)
        return (function(obj) { return function() {return obj}; })(options.get_object());
      return options.obj[options.name];
    });
  }

  ammo.one(ammo, 'ajaxLoader', function() {

    var ajax_loader = jQuery('<div class="-ammo-ajax-loader" style="display:none;">'+ammo.i18n('Загрузка')+'...</div>').appendTo('body');
    return function() {
      return ajax_loader; 
    };
  });

  ammo.modalWindow = {
    message: function(message) { 
      alert(message); 
    },

    confirm: function(message, callback_yes, callback_no) {
      if(confirm(message))
        if(typeof(callback_yes) == 'function')
          callback_yes();
      else
        if(typeof(callback_no) == 'function')
          callback_no();
    }
  };
  
  ammo.baseErrorAjaxSend = function() {
    ammo.modalWindow.message(ammo.i18n('Не удалось отправить запрос.'));
  };

  ammo.absPath = function(url)
  {
    return url;
  };

  ammo.ajax = function(options) 
  {
    options.type = options.type || 'POST';
    options.data = options.data || {};
    options.data.is_ajax = 1;
    options.dataType = options.dataType || 'json'; 
    options.url = ammo.absPath(options.url || '');
    options.error = options.error || function() { ammo.baseErrorAjaxSend();};
    if(typeof(options.async) == 'undefined')
      options.async = false;
    (function(complete) {
      options.complete = function() 
      {
        ammo.ajaxLoader().hide(); 
        if(typeof(complete) == 'function')
          complete();
      }
    })(options.complete);
    (function(beforeSend) {
      options.beforeSend = function() 
      {
        ammo.ajaxLoader().show(); 
        if(typeof(beforeSend) == 'function')
          beforeSend();
      }
    })(options.beforeSend);
    return options;
  };
})(window.ammo);

/* include main.js */
window.myjs = window.myjs || {};
(function() {

  var private_vars = {
      rexp: {
        act: new RegExp('^action:'),
        act_type: new RegExp('^[^:]+'),
        act_replace: new RegExp('^[^:]+:'),
        hash: new RegExp('^#'),
        strip_slash: new RegExp('^\\/+'),
        is_abs_path: new RegExp('^(https?|\\/)'),
        is_external_path: new RegExp('^(https?)')
      }
    };

  myjs.vars = {current_app_class: ''};
  myjs.server_vars = myjs.server_vars || {};

  myjs.ajax = function(options)
  {
    (function(success) {
      options.success= function(data)
      {
        if(data.error)
          return ammo.modalWindow.message(data.error);
        if(data.message)
          ammo.modalWindow.message(data.message);
        if(typeof(success) == 'function')
          success.apply(null, arguments);
        if(data.js_callback)
          eval(data.js_callback.join(';'));
        myjs.onloadContent(options.is_new_page);
        if(options.is_new_page)
        {
          if(data.page_title)
            document.title = data.page_title;
          if(data.page_shared_link)
            myjs.server_vars.page_shared_link = data.page_shared_link;
        }
      }
    })(options.success);
    if(options.cache == false)
    {
      if(!options.url.match(private_vars.rexp.is_external_path))
      {
        options.cache = true; 
        var offset_path = '/' + myjs.server_vars.offset_path;
        if(options.url.substr(0, offset_path.length) == offset_path)
          options.url = options.url.substr(offset_path.length, options.url.length);
        options.url =  '_t/' + (new Date()).getTime() + '/' + options.url;
      }
    }
    return ammo.ajax(options);
  };

  var
    hash_actions = {'goo': function(hash) {myjs.goo(hash);}};

  myjs.hashAction = function(hash, options)
  {
    var rhash = hash;
    if(!hash.match(private_vars.rexp.act))
      return false;
    hash = hash.replace(private_vars.rexp.act, '');
    var action = hash.match(private_vars.rexp.act_type);
    if(action && hash_actions[action.join('')])
      hash_actions[action.join('')](hash.replace(private_vars.rexp.act_replace, ''), options);
    return false;
  };

  myjs.clickHashLink = function(link)
  {
    link = jQuery(link);
    var hash = link.attr('href').replace(private_vars.rexp.hash, '');
    myjs.history().push(hash);
    return false;
  };

  myjs.clickAjaxLink = function(link)
  {
    myjs.ajaxGoo($(link).attr('href'));
    return false;
  };
  myjs.a = myjs.clickAjaxLink;

  myjs.ajaxGoo = function(url, params)
  {
    if(params)
    {
      var items = new Array();
      for(var name in params)
        items.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
      url += '?' + items.join('&');
    }

    if($.browser.msie)
    {
      if(url.substr(0, myjs.server_vars.base_path.length) == myjs.server_vars.base_path)
        url = url.substr(myjs.server_vars.base_path.length);
    }
    myjs.history().push('action:goo:'+url);
  };

  myjs.content = function()
  {
    if(!myjs.vars.content)
      myjs.vars.content = $('#-js-main-col-content');
    return myjs.vars.content;
  };

  var showSlotsResponse = function(data)
  {
    myjs.vars.scroll_to = true;
    if(data.slots)
    {
      myjs.content().html(data.slots.content);
      if(data.slots.js_ready)
        eval(data.slots.js_ready);
    }
    else
      myjs.content().html(data.html);
  };

  myjs.goo = function(url)
  {
    $.ajax(myjs.ajax({
      async: true,
      url: url,
      type: 'GET',
      cache: false,
      success: showSlotsResponse,
      is_new_page: true
    }));
  }

  myjs.ajaxFormLoadContent = function(form)
  {
    form = $(form);
    $(form).ajaxForm(myjs.ajax({
      url: '',
      beforeSubmit: function(data)
      {
        var 
          i,
          params = {};
        for(i in data)
          params[data[i].name] = data[i].value;
        delete params['is_ajax'];
        myjs.ajaxGoo(form.attr('action'), params);
        return false;
      }
    }));
    return form;
  };

  myjs.rawAbsPath = function(url)
  {
    return window.myjs.server_vars.base_path + url.replace(private_vars.rexp.strip_slash, '');
  };

  myjs.loadHtml = function(url, el)
  {
    $.ajax(myjs.ajax({
      type: 'GET',
      cache: false,
      url: url,
      async: true,
      success: function(data)
      {
        $(el).html(data.html);
      }
    }));
  };

  var
    head_app_menu = false,
    scrollTop = function() {return document.documentElement.scrollTop || document.body.scrollTop; };

  myjs.onloadContent = function(newpage)
  {
    if(myjs.vars.scroll_to)
    {
      myjs.vars.scroll_to = false;
      if(scrollTop() > 100)
        window.scrollTo(0, 100);
    }

    if(newpage)
    {
      head_app_menu = head_app_menu || $('#-js-head-app-menu').eq(0);
      var current_app_class = myjs.vars.current_app_class;
      if(current_app_class)
      {
        myjs.vars.current_app_class = false;
        current_app_class = current_app_class.replace(/_application$/, '');
        $('li', head_app_menu).removeClass('active').each(function() {
          var el = $(this);
          if(el.attr('class') == current_app_class)
            el.addClass('active');
        });
      }
      else
        $('li', head_app_menu).removeClass('active');
    }
  }

  myjs.bindDatepicker = function(options) {
    options = options || {};
    options.dateFormat = options.dateFormat || 'dd.mm.yy';
    return function()
    {
      myjs.ui(this).datepicker(options).datepicker('show');
    };
  };

  myjs.bindSelectPeriod = function(form, minDate)
  {
    var
      form = $(form),
      datep = myjs.bindDatepicker({maxDate: '+0m', minDate: (minDate ? minDate : false)}),
      bday = form.find('#bday').one('click', datep),
      eday = form.find('#eday').one('click', datep);
    form.ajaxForm({
      beforeSubmit: function()
      {
        myjs.ajaxGoo(form.attr('action'), {eday: eday.val(), bday: bday.val()});
        return false;  
      }
    }).find('#-js-submit').click(function() { form.submit(); });
  };

  myjs.buildHttpQuery = function(params)
  {
    var 
      query = new Array(),
      i;
    for(i in params)
      query.push(encodeURIComponent(i) + '=' + encodeURIComponent(params[i]));
    return query.join('&');
  }

  myjs.openPopup = function(url, windowWidth, windowHeight, name)
  {
    var centerWidth = (window.screen.width - windowWidth) / 2, centerHeight = (window.screen.height - windowHeight) / 2;
    var newWindow = window.open(url, name,
                            'resizable=0' +
                            ',toolbar=0' + 
                            ',location=0' +  
                            ',scrollbars=1' +
                            ',width=' + windowWidth +
                            ',height=' + windowHeight +
                            ',left=' + centerWidth +
                            ',top=' + centerHeight);
    if(newWindow)
      newWindow.focus();
  }

  // change ammo
  ammo.absPath = function(url)
  {
    return url.match(private_vars.rexp.is_abs_path) ? url : myjs.rawAbsPath(url);
  };

  myjs.main = function() {
    if(myjs.server_vars.member.is_logged_in)
    {
      $('#wrapper').removeClass('is_guest').addClass('is_user');
      if(myjs.server_vars.member.is_admin)
        $('#wrapper').addClass('is_admin');
    }
    else
      $('#wrapper').removeClass('is_user').addClass('is_guest');
  };
})();

(function() {
  var search_form, search_input, manager = {}, default_query = ammo.i18n("поиск приложений");

  manager.init = function()
  {
    search_form = $('#-js-search-form');
    search_input = search_form.find('#search_query');
    search_input.val(default_query);
    search_input.focus(function(){
      if(search_input.val() == default_query)
        search_input.val("");
    }).blur(function(){
      if(search_input.val() == "")
        search_input.val(default_query);
    });
    if(!$.browser.msie)
      search_form.submit(function() {
        if(search_input.val().length)
          manager.search(search_input.val());
        return false;
      });
  };

  manager.search = function(query)
  {
    myjs.ajaxGoo('search', {q: query});
  };

  myjs.search = function() { return manager; };
})();

(function() {
  var manager = {};

  manager.init = function()
  {
    $.historyInit(function(hash) {
      if(!hash.length)
        myjs.goo(window.location.pathname + (window.location.search.length ? "?" + window.location.search : ""));
      else
        myjs.hashAction(hash.replace('|', '?'));
    });
  };

  manager.push = function(hash)
  {
    $.historyLoad(hash.replace('?', '|'));
  };

  myjs.history = function() { return manager;};
})(myjs);

ammo.lazyMethod({obj: myjs, name: 'login', js_files: ['js/login.js']});
ammo.lazyMethod({obj: myjs, name: 'feedback', js_files: ['js/feedback.js']});
ammo.lazyMethod({obj: myjs, name: 'stats', js_files: ['js/stats.js']});
ammo.lazyMethod({obj: myjs, name: 'favorite', js_files: ['js/favorite.js']});
ammo.lazyMethod({obj: myjs, name: 'comparisons', js_files: ['js/comparisons.js']});
ammo.lazyMethod({obj: myjs, name: 'events', js_files: ['js/events.js']});
ammo.lazyMethod({obj: myjs, name: 'developers', js_files: ['js/developers.js']});
ammo.lazyMethod({obj: myjs, name: 'app_events', js_files: ['js/app_events.js']});
ammo.lazyMethod({obj: myjs, name: 'ui', js_files: 'js/ui/js/jquery-ui-1.8.5.custom.min.js', callback: function() {return window.jQuery}});
ammo.lazyMethod({obj: myjs, name: 'blog', js_files: ['js/blog.js']});
ammo.lazyMethod({obj: myjs, name: 'admin', js_files: ['js/admin.js']});
ammo.lazyMethod({obj: myjs, name: 'calendar', css_files: ['shared/calendar/js/calendar-win2k-1.css'],  js_files: ['shared/calendar/js/calendar.js', 'shared/calendar/js/lang/calendar-ru.js', 'shared/calendar/js/calendar-setup.js'], get_object: function() { return window.Calendar;}});

ammo.one(myjs, 'social', function() {
  var manager = {};

  var like_iframe = '<iframe frameborder="0" scrolling="no" allowtransparency="true" style="border: medium none ; overflow: hidden; width: 450px; height: 21px;" src="http://www.facebook.com/plugins/like.php?href={url}&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;font&amp;colorscheme=light&amp;height=21"></iframe>';

  var settings = 
  {
    vk: {url: new String('http://vkontakte.ru/share.php?url={url}&title={title}&noparse=true'), height: 270, popup: true}, // TODo image=<http://logo?>
    fb: {url: new String('http://www.facebook.com/sharer.php?u={url}&t={title}'), height: 270, popup: true},
    yandex: {url: new String('http://zakladki.yandex.ru/newlink.xml?url={url}&name={title}')},
    google: {url: new String('http://www.google.com/bookmarks/mark?op=add&bkmk={url}&title={title}')},
    twitter: {url: new String('http://twitter.com/home?status={title}%20{url}')},
    bobrdobr: {url: new String('http://bobrdobr.ru/addext.html?url={url}&title={title}')},
    memori: {url: new String('http://memori.ru/link/?sm=1&u_data[url]={url}&u_data[name]={title}')},
    buzz: {url: new String('http://www.google.com/buzz/post?url={url}&message={title}'), width: 750, height: 415, popup: true}, // TODO &imageurl=<Дополнительный URL изображения>
    digg: {url: new String('http://digg.com/submit?url={url}&title={title}')}
  };

  var widget = {};
  (function(widget) {
    is_show = false;
    widget.wrap = $('#-js-social-select-share');

    var toggle = function(show)
    {
      is_show = show;
      widget.wrap.toggle(is_show).parent().toggleClass('z_indexed', is_show);
    };

    widget.hide = function()
    {
      toggle(false);
    };

    widget.show = function()
    {
      toggle(true);
    };

    widget.isShow = function() {
      return is_show;
    };
  })(widget);


  manager.clickShare = function()
  {
    if(!widget.isShow())
    {
      var 
        title = encodeURIComponent(document.title),
        raw_url = myjs.server_vars.page_shared_link,
        share_url = encodeURIComponent(raw_url); 
        widget.wrap.find('#-js-social-primary').eq(0).attr('href', raw_url);
  
      var popup = function(el, options)
      { 
        el.attr('href', options.url.replace('{url}', share_url).replace('{title}', title));
        if(options.popup)
        {
          el.click(function() {
            myjs.openPopup(this.href, options.width || 600,  options.height || 500);
            return false;
          });
        }
      };

      for(var i in settings)
        popup(widget.wrap.find('#-js-slink-'+i).eq(0), settings[i]);

      //widget.wrap.find('#-js-like-wrapper').eq(0).html(like_iframe.replace('{url}', share_url));
      widget.show();
    }
    else
    {
      widget.hide();
    };
  };
  
  return function() { return manager};
});

(function(myjs) {

  var
    manager = {},
    map = {
      line: {base_path: ammo.absPath('_/0/lib/amline/'), swf: 'amline.swf'},
      column: {base_path: ammo.absPath('_/0/lib/amcolumn/'), swf: 'amcolumn.swf'}
    },
    flash_params = {'wmode': 'transparent'},
    set_titles = {};

  window.amChartInited = function(chart_id)
  {
    var id = chart_id.replace(/-/g, '_');
    if(set_titles[id])
    {
      document.getElementById(chart_id).setParam('labels.label[0].text', set_titles[id]);
      delete set_titles[id];
    }
  }

  manager.render = function(options) {
    var
      vars = {
        'path': map[options.type].base_path,
        'chart_data': options.data,
        'preloader_color': '#999999',
        'chart_id': options.id
      };

    if(options.settings)
      vars.chart_settings = options.settings;
    else
      vars.settings_file = ammo.absPath(ammo.addVersion(options.settings_file));

    if($.browser.msie)
    {
      if(vars.chart_settings)
        vars.chart_settings = encodeURIComponent(vars.chart_settings);
      if(vars.chart_data)
        vars.chart_data = encodeURIComponent(vars.chart_data);
    }

    if(options.link)
      set_titles[options.id.replace(/-/g, '_')] = options.link;

    swfobject.embedSWF(
      map[options.type].base_path + map[options.type].swf,
      options.id,
      options.width || Math.max(648, Math.min(740, myjs.content().width() - 10)),
      options.height || "350",
      "8",
      false,
      vars,
      flash_params
    );
  };

  myjs.charts = function() { return manager; };
})(myjs);

(function(myjs) {
  var
    t = function() {return (new Date).getTime(); },
    cache = {};

  manager = {};
  manager.add = function(name, value, ttl) {
    cache[name] = {v: value, t: t(), ttl: ttl*1000 || -1};
  };

  manager.get = function(name)
  {
    if(cache[name])
      if(cache[name].ttl < 0 || (t() - cache[name].t < cache[name].ttl))
        return cache[name].v;
      else
        delete cache[name];
    return false;
  };

  myjs.cache = function() { return manager; };
})(myjs);

/// Desing
(function(myjs) {
  myjs.toogleMenu = function(link) {
    $(link).parent().toggleClass('active_block');
    return false;
  };
})(myjs);

$(document).ready(function()
{
  myjs.search().init();
  myjs.history().init();
});

/* include stats.js */
(function() {
  var manager = {};

  manager.prepare = function(data)
  {
    if(myjs.server_vars.member.is_logged_in)
      myjs.favorite().bindLinks(data.id, myjs.content(), data.is_in_favorite);
    var item, i;
    for(i in data.charts)
    {
      item = data.charts[i];
      item.id = "-js-chart-app-" + i + '-' + data.id;
      myjs.charts().render(item);
    };
  };

  manager.prepareSum = function(data)
  {
    var item, i;
    for(i in data)
    {
      item = data[i];
      item.id = '-js-chart-sum-'+i;
      myjs.charts().render(item);
    }
  }

  manager.prepareTopPage = function()
  {
    var options = {maxDate: '+0m'};
    if(!myjs.server_vars.member.is_admin)
      options.minDate = '-2m';
    myjs.ajaxFormLoadContent($('#-js-select-top-period').find('form')).find('#day').one('click', myjs.bindDatepicker(options));
  };

  manager.showAddAppForm = function()
  {
    $.ajax(myjs.ajax({
      url: 'stats/ajax_add_new_app_form',
      data: {s: 1},
      success: function(data)
      {
        var dialog = myjs.ui(data.html).dialog({
          modal: true,
          width: 450,
          height: 320
        });
        dialog.find('#add_app_form').eq(0).ajaxForm(myjs.ajax({
          url: 'stats/ajax_add_new_app',
          success: function(data) {
            if(data.app_url)
            {
              dialog.dialog('close');
              myjs.ajaxGoo(data.app_url);
            }
            else
              ammo.baseErrorAjaxSend();
          }
        }));
        dialog.find('#-js-submit').eq(0).removeAttr('disabled');
      }
    }));
  };

  manager.appPage = function(id, charts, minDate)
  {
    myjs.stats().prepare(charts);
    myjs.bindSelectPeriod(myjs.content().find('#-js-select-app-period-'+id).eq(0), minDate);
  };

  manager.loadMoreForDevelop = function(link, develop_id, app_class, offset)
  {
    var table_id = '#-js-develop-apps-'+app_class;
    $.ajax(myjs.ajax({
      url: 'developers/ajax_more_apps',
      type: 'GET',
      data: {id: develop_id, app_class: app_class, offset: offset},
      success: function(data)
      {
        if(data && data.slots)
        {
          $(table_id).append(data.slots.list);
          $(link).after(data.slots.more_link).remove();
        }
      }
    }));  
  };


  myjs.stats = function() { return manager; };
})();


/* include blog.js */
(function(myjs) {
  var manager = {};

  manager.mainPage = function() {
    myjs.goo("blog/main_page");
  };

  manager.initPostPage = function(message_id)
  {
    manager.ajaxCommentForm(message_id);
    manager.showCommentActionsLinks($('#-js-blog-comments-'+message_id));
  };

  manager.showCommentActionsLinks = function(comments)
  {
    if(myjs.server_vars.member.is_logged_in)
      comments.find('a.js-owner-'+myjs.server_vars.member.id).show();
  }

  manager.ajaxCommentForm = function(message_id)
  {
    var form = $('#-js-blog-comment-form-'+message_id);
    form.ajaxForm(myjs.ajax({
      url: 'member_comment/ajax_save_comment',
      data: {is_create: 1, commented_id: message_id},
      success: function(data) {
        if(data.html)
          manager.showCommentActionsLinks($('#-js-blog-comments-'+message_id).append(data.html));
        form.find('#content').val('');
      }
    }));
  };

  manager.clickDeleteComment = function(id)
  {
    ammo.modalWindow.confirm(ammo.i18n("Удалить комментарий?"), function() {
      $.ajax(myjs.ajax({
        url: "member_comment/ajax_delete_comment",
        data: {id: id},
        success: function() 
        {
          $("#-js-blog-comment-" + id).remove();
        }
      }));
    });
  };

  myjs.blog = function() {return manager;};
})(window.myjs);

/* include favorite.js */
(function(myjs) {
  var manager = {};

  var setVisibleLinks = function(div, is_in)
  {
    div.find('#-js-add').css('display', (!is_in ? 'block' : 'none'));
    div.find('#-js-remove').css('display', (is_in ? 'block' : 'none'));
  };

  var clickLink = function(id, div, is_add) {
    jQuery.ajax(myjs.ajax({
      url: 'member_app/ajax_' + (is_add ? 'add' : 'remove') + '_favorite',
      data: {id: id},
      success: function(data) {
        if(data.success)
          setVisibleLinks(div, is_add);
        if(is_add && !$('#-js-fav-menu-'+id).length)
          $('#-js-mmenu-favorite-list').append(data.html);         
        else
          $('#-js-fav-menu-'+id).remove();
      }
    })); 
  };

  manager.clickAdd = function(link, id)
  {
    clickLink(id, $(link).parent(), true);
  };
  
  manager.clickRemove = function(link, id)
  {
    clickLink(id, $(link).parent(), false);
  };
  
  manager.bindLinks = function(id, div, is_in) 
  {
    div.find('#-js-add').click(function() {clickLink(id, div, true);});    
    div.find('#-js-remove').click(function() {clickLink(id, div, false);});    
    setVisibleLinks(div, is_in);
  };

  myjs.favorite = function() { return manager; };
})(window.myjs);


/* include app_events.js */
(function(myjs) {
  var manager = {};

  manager.clickShowList = function(el, link)
  {
    $(el).toggle();
    $(link).parent().toggleClass("z_indexed");
    return false;
  }

  var editForm = function(is_create, link, id, app_id)
  {
    $.ajax(myjs.ajax({
      url: 'member_app/ajax_app_event_form',
      data: {is_create: 0+is_create, id: (id ? id : -1), app_id: app_id},
      success: function(data)
      {
        var dialog = myjs.ui(data.html).dialog({
          width: 390,
          height: 230,
          close: function() {$(this).remove();}
        });
        dialog.find('#item_form').eq(0).ajaxForm(myjs.ajax({
          url: 'member_app/ajax_save_app_event',
          success: function(data) {
            dialog.remove();
            if(is_create)
              $(link).parent().find('ul').eq(0).prepend($('<li>').html(data.html));
            else
              $(link).parent().html(data.html);
          }
        })).find('input#date').one('click', myjs.bindDatepicker());
        dialog.find('#-js-submit').eq(0).removeAttr('disabled');

        dialog.find('#-js-publish').eq(0).click(function() {
          ammo.modalWindow.confirm(ammo.i18n('Опубликованные события видят все пользователи. Опубликовать событие?'), function() {
            var form = dialog.find('#item_form').eq(0);
            form.find('#act_publish').val(1);
            form.submit();
          });
        }).removeAttr('disabled');
      }
    }));
  };


  manager.clickCreate = function(app_id, link)
  {
    editForm(true, link, false, app_id); 
  };

  manager.clickEdit = function(link, id)
  {
    editForm(false, link, id); 
  };

  manager.clickDelete = function(link, id)
  {
    ammo.modalWindow.confirm(ammo.i18n('Удалить событие?'), function() {
      $.ajax(myjs.ajax({
        url: 'member_app/ajax_remove_app_event',
        data: {id: id},
        success: function(data) {
          $(link).parent().remove();
        }
      }));
    });
  };

  myjs.app_events = function() { return manager; };
})(window.myjs);

/* include events.js */
(function(myjs) {
  var manager = {};

  var editForm = function(is_create, id)
  {
    $.ajax(myjs.ajax({
      url: 'events/ajax_edit_form',
      data: {is_create: 0+is_create, id: id},
      success: function(data) {
        if(!data.html)
          return;
        var dialog = myjs.ui(data.html).dialog({
          close: function() {$(this).remove();},
          width: 450,
          height: 220
        });
        var form = dialog.find('#item_form').eq(0);
        form.ajaxForm(myjs.ajax({
          url: 'events/ajax_save',
          data: {is_create: 0+is_create, id: id},
          success: function(data)
          {
            dialog.dialog('close');
            if(data.html)
            {
              if(is_create)
                $('#-js-events-list').prepend(data.html);
              else
                $('#-js-event-'+id).replaceWith(data.html);
            }
          }
        }));
        form.find('#-js-submit').removeAttr('disabled');
      }
    }));
  };

  manager.clickAdd = function()
  {
    editForm(true);
  };
  
  manager.clickEdit = function(id)
  {
    editForm(false, id);
  };

  manager.clickDelete = function(id)
  {
    ammo.modalWindow.confirm(ammo.i18n("Удалить событие?"), function() {
      $.ajax(myjs.ajax({
        url: "events/ajax_delete",
        data: {id: id},
        success: function() 
        {
          $("#-js-event-" + id).remove();
        }
      }));
    });
  };

  myjs.events = function() { return manager; };
})(window.myjs);

/* include developers.js */
(function(myjs) {
  var manager = {};

  manager.profile = function(id, charts_options, min_date)
  {
    var
      item;
    for(var i in charts_options)
    {
      item = charts_options[i];
      item.id = "-js-char-developer-" + i + '-' + id;
      myjs.charts().render(item);
    };
    myjs.bindSelectPeriod(myjs.content().find('#-js-select-developer-period-'+id).eq(0), min_date);
  };

  manager.changeForApp = function(app_id)
  {
    $.ajax(myjs.ajax({
      url: 'member_app/ajax_add_developer_to_app_form',
      data: {id: app_id},
      success: function(data) {
        if(!data.html)
          return;
        var dialog = myjs.ui(data.html).dialog({
          close: function() {$(this).remove();},
          modal: true,
          width: 320,
          height: 180
        });
        var form = dialog.find('#item_form').eq(0);
        form.ajaxForm(myjs.ajax({
          url: 'member_app/ajax_add_developer_to_app',
          success: function(data)
          {
            dialog.dialog('close');
            myjs.ajaxGoo(data.goo);
          }
        }));
        form.find('#-js-submit').removeAttr('disabled');
      }
    }));
  };

  manager.deleteApp = function(app_id, developer_id)
  {
    ammo.modalWindow.confirm(ammo.i18n('Удалить автора из списка?'), function() {
      $.ajax(myjs.ajax({
        url: 'member_app/ajax_delete_developer_for_app',
        data: {app_id: app_id, developer_id: developer_id},
        success: function(data) {
          myjs.ajaxGoo(data.goo);
        }
      }));
    });
  };

  myjs.developers = function() { return manager; };
})(myjs);

/* include comparisons.js */
(function(myjs) {
  var manager = {};

  var editForm = function(is_create, link, id, in_menu, app_id) {
    $.ajax(myjs.ajax({
      url: 'member_app/ajax_comparison_form',
      data: {is_create: 0+is_create, id: (id ? id : -1)},
      success: function(data)
      {
        var dialog = myjs.ui(data.html).dialog({
          modal: true,
          width: 390,
          height: 230
        });
        dialog.find('#comparisons_form').eq(0).ajaxForm(myjs.ajax({
          url: 'member_app/ajax_save_comparison',
          data: {app_id: app_id},
          success: function(data) {
            dialog.dialog('close');
            if(!in_menu)
              if(is_create)
                $(link).parent().find('ul').eq(0).append($('<li>').html(data.html));
              else
                $(link).parent().html(data.html);
            if(data.menu)
              if(is_create)
                $('#-js-mmenu-comparsions-list').append(data.menu);
              else
                $('#-js-comparison-menu-'+id).replaceWith(data.menu);
          }
        }));
        dialog.find('#-js-submit').eq(0).removeAttr('disabled');
      }
    }));

  };

  manager.clickEdit = function(link, id, in_menu, app_id)
  {
    editForm(false, link, id, in_menu, app_id);
  };

  manager.clickCreate = function(link, in_menu, app_id)
  {
    editForm(true, link, false, in_menu, app_id);
  };

  manager.clickDelete = function(id)
  {
    ammo.modalWindow.confirm(ammo.i18n('Удалить список сравнения?'), function() {
      $.ajax(myjs.ajax({
        url: 'member_app/ajax_remove_comparison',
        data: {id: id},
        success: function(data) {
          var a, c = 0;
          while((a = $('#-js-comparison-menu-'+id)) && a.length && 3 > ++c)
            a.remove();
        }
      }));
    });
  }

  var mapl = {plus: 'images/icon/checkbox.png', minus: 'images/icon/checkbox_checked.png'};
  manager.clickCheckbox = function(link, app_id, id)
  {
    link = $(link);
    var
      img = link.find('img').eq(0),
      is_add = img.attr('src').substr(img.attr('src').length - mapl.plus.length) == mapl.plus; // i hate ie
    $.ajax(myjs.ajax({
      url: 'member_app/ajax_change_comparison',
      data: {id: id, app_id: app_id, is_add: 0+is_add},
      success: function(data) {
        img.attr('src', is_add ? mapl.minus : mapl.plus);
      },
      async: true
    }));
  };

  manager.clickShowList = function(el, link, app_id)
  {
    var 
      wrap = $(link).parent(),
      el = $(el);
    if(wrap.hasClass('z_indexed'))
    {
      el.hide();
      wrap.removeClass('z_indexed');
    }
    else
    {
      $.ajax(myjs.ajax({
        url: 'member_app/ajax_comparison_list_for_app',
        data: {app_id: app_id},
        success: function(data) {
          wrap.addClass('z_indexed');
          el.html(data.html).show();
        }
      }));
    }
    return false;
  };

  manager.clickRemoveApp = function(id, app_id)
  {
    ammo.modalWindow.confirm(ammo.i18n('Удалить приложение из списка?'), function() {
      jQuery.ajax(myjs.ajax({
        url: 'member_app/ajax_change_comparison',
        data: {id: id, app_id: app_id, is_add: 0},
        success: function(data) {
          myjs.goo('stats/comparison/'+id);
        }
      }));
    });
  };

  manager.comparsion = function(id, charts_options, minDate)
  {
    var
      item;
    for(var i in charts_options)
    {
      item = charts_options[i];
      item.id = "-js-char-comparisons-" + i + '-' + id;
      myjs.charts().render(item);
    };

    myjs.bindSelectPeriod(myjs.content().find('#-js-select-comparison-period-'+id).eq(0), minDate);
  };

  myjs.comparisons = function() { return manager; };
})(window.myjs);

/* include jquery.history.js */
/*
 * jQuery history plugin
 * 
 * sample page: http://www.mikage.to/jquery/jquery_history.html
 *
 * Copyright (c) 2006-2009 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */

jQuery.extend({
	historyCurrentHash: undefined,
	historyCallback: undefined,
	historyIframeSrc: undefined,
	historyNeedIframe: jQuery.browser.msie && (jQuery.browser.version < 8 || document.documentMode < 8),
  historyIsSafary: jQuery.browser.safari && !(window.navigator && navigator.userAgent && (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)),
	
	historyInit: function(callback, src){
		jQuery.historyCallback = callback;
		if (src) jQuery.historyIframeSrc = src;
		var current_hash = location.hash.replace(/\?.*$/, '');
		
		jQuery.historyCurrentHash = current_hash;
		if (jQuery.historyNeedIframe) {
			// To stop the callback firing twice during initilization if no hash present
			if (jQuery.historyCurrentHash == '') {
				jQuery.historyCurrentHash = '#';
			}
		
			// add hidden iframe for IE
			jQuery("body").prepend('<iframe id="jQuery_history" style="display: none;"'+
				' src="javascript:false;"></iframe>'
			);
			var ihistory = jQuery("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = current_hash;
		}
		else if (jQuery.historyIsSafary) {
			// etablish back/forward stacks
			jQuery.historyBackStack = [];
			jQuery.historyBackStack.length = history.length;
			jQuery.historyForwardStack = [];
			jQuery.lastHistoryLength = history.length;
			
			jQuery.isFirst = true;
		}
		if(current_hash)
			jQuery.historyCallback(current_hash.replace(/^#/, ''));
		setInterval(jQuery.historyCheck, 100);
	},
	
	historyAddHistory: function(hash) {
		// This makes the looping function do something
		jQuery.historyBackStack.push(hash);
		
		jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this.isFirst = true;
	},
	
	historyCheck: function(){
		if (jQuery.historyNeedIframe) {
			// On IE, check for location.hash of iframe
			var ihistory = jQuery("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash.replace(/\?.*$/, '');
			if(current_hash != jQuery.historyCurrentHash) {
			
				location.hash = current_hash;
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
				
			}
		} else if (jQuery.historyIsSafary) {
			if(jQuery.lastHistoryLength == history.length && jQuery.historyBackStack.length > jQuery.lastHistoryLength) {
				jQuery.historyBackStack.shift();
			}
			if (!jQuery.dontCheck) {
				var historyDelta = history.length - jQuery.historyBackStack.length;
				jQuery.lastHistoryLength = history.length;
				
				if (historyDelta) { // back or forward button has been pushed
					jQuery.isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
					}
					var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
					if (cachedHash != undefined) {
						jQuery.historyCurrentHash = location.hash.replace(/\?.*$/, '');
						jQuery.historyCallback(cachedHash);
					}
				} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (location.hash) {
						var current_hash = location.hash;
						jQuery.historyCallback(location.hash.replace(/^#/, ''));
					} else {
						var current_hash = '';
						jQuery.historyCallback('');
					}
					jQuery.isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash.replace(/\?.*$/, '');
			if(current_hash != jQuery.historyCurrentHash) {
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
			}
		}
	},
	historyLoad: function(hash){
		var newhash;
		hash = decodeURIComponent(hash.replace(/\?.*$/, ''));
		
		if (jQuery.historyIsSafary) {
			newhash = hash;
		}
		else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		jQuery.historyCurrentHash = newhash;
		
		if (jQuery.historyNeedIframe) {
			var ihistory = jQuery("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			jQuery.lastHistoryLength = history.length;
			jQuery.historyCallback(hash);
		}
		else if (jQuery.historyIsSafary) {
			jQuery.dontCheck = true;
			// Manually keep track of the history values for Safari
			this.historyAddHistory(hash);
			
			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {jQuery.dontCheck = false;};
			window.setTimeout(fn, 200);
			jQuery.historyCallback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  jQuery.historyCallback(hash);
		}
	}
});
