var Main = {
	is_debug: true,
	showDebug: function(msg){
		if(this.is_debug == true){
			alert(msg);
		}
	},
	apply: function(o, c, defaults){
	    if(defaults){
	        Main.apply(o, defaults);
	    }
	    if(o && c && typeof c == 'object'){
	        for(var p in c){
	            o[p] = c[p];
	        }
	    }
	    return o;
	},
	_mask_remover: function(el) {
    	if(el.mask_element_exist){
	    		el.mask_element_exist = null;
	    		el.mask_element.remove();
    	}
    },

	_loadMask: function(el, load){
		if(Prototype.Browser.IEVersion == 6){
			return false;
		}
		this.mask_prefix = "";
		if(typeof el != "object"){
			el = $(el);
		}
		if(!el){
			Main.showAlert("FATAL - Element not found");
		}

		if(load){
			if(!el.mask_element_exist)	{
				var element_loader=new Element("div");
				el.mask_element = element_loader;
				el.mask_element_exist = true;

				var h = el.getHeight();
				var w = el.getWidth();
		        element_loader.setStyle({
		                'height':h+"px",
		                'width':w+"px",
		                'text-align':'center',
		                'background':'#EEEEEE',
		                'position'    :'absolute',
		                'top'        :'0px',
		                'left'        :'0px',
		                'filter'    :'alpha(opacity=10)',
		                '-moz-opacity':'0.5',
		                'opacity'    :'0.5',
		                'z-index'	: '1000'
		        });
		        h = h/2;
		        element_loader.update('<img style="margin: 0 auto; display: block; margin-top:'+(h)+'px;" src="images/blue-loading.gif" alt="Load..." />');
		        el.insert(element_loader);
			}
		} else {
			setTimeout(this._mask_remover.bind(this, el), 100);
		}
	},
	showAlert: function(msg, title, handler, scope, width, height){
		alert(msg);
		return true;
		if(typeof msg == "undefined"){
			var msg = "Hello World!";
		}
		if(typeof title == "undefined"){
			var title = "Message";
		}
		var _width = 350;
		if(width){
			_width = width;
		}
		var _height = 140;
		if(height){
			_height = height;
		}
		var alert_win = new UI.Window({
	    		shadow:true,
	    		width: _width,
	    	//	draggable: false,
	    		height: _height
	    });
	    var html = '<div class="alert_content_container">'+msg+'</div><div class="alert_buttons_container"><input type="button" class="s_btn" value="    Close    " onclick="Main.CloseAlertWin(this);" id="alert_btn_close"  /></div>';
	    alert_win.setContent(html);
	    alert_win.setHeader(title);
	     alert_win.setZIndexWithShadow(3000);
	    alert_win.center().show();
	    alert_win.activate();
		//if (handler) {
			 alert_win._CloseHandler = handler;
			 alert_win._CloseScope = scope;
		//}

		this.btn();
		if($("alert_btn_close")){
			$("alert_btn_close").focus();
		}
	},

	CloseAlertWin: function(el){
		var w = UI.defaultWM.getWindow(el);
		if (typeof w._CloseHandler == 'function') {
			if (w._CloseScope) {
				w._CloseHandler.apply(w._CloseScope);
			} else {
				w._CloseHandler();
			}
		}
		w.destroy();
	},

	showConfirm: function(msg, title, okAction, scope, handler, btns){
		if(typeof msg == "undefined"){
			var msg = "Hello World!";
		}
		if(typeof title == "undefined"){
			var title = "Confirm";
		}
		var buttons = {
			ok: '    Ok    ',
			cancel: '    Cancel    '
		};
		if (btns) {
			Main.apply(buttons, btns);
		};

			var confirm_win = new UI.Window({
	    		shadow:true,
	    		width: 450,
	    		draggable: true,
	    		height: 160
		    });
		    var html = '<div class="alert_content_container">'+msg+'</div><div class="conf_buttons_container">'+
		    '<input type="button" class="s_btn" value="' + buttons.ok + '" onclick="Main.CloseConfirmWin(true, this);" /><input type="button" class="s_btn" value="' + buttons.cancel + '" onclick="Main.CloseConfirmWin(false, this);" /></div>';
		    confirm_win.setContent(html);
		    confirm_win.setHeader(title);
		    confirm_win.setZIndexWithShadow(3000);
		    confirm_win.center().show();
		    confirm_win.activate();

	//TODO change
		    confirm_win._OkHandler = okAction;
		    confirm_win._CloseHandler = handler;
			confirm_win._CloseScope = scope;

			this.btn();
	},

	 CloseConfirmWin: function(btn, el){
		var w = UI.defaultWM.getWindow(el);
		var f = null;
		if (btn && w._OkHandler) {
			f = w._OkHandler;
		} else if (w._CloseHandler){
			f = w._CloseHandler;
		}
		if (typeof f == 'function') {
			if (w._CloseScope) {
				f.apply(w._CloseScope);
			} else {
				f();
			}
		}
		w.close();
	},

	getWinLeftPosition: function(shift){
		if(typeof shift == 'undefined'){
			shift = 0;
		}
		return  document.body.getWidth() - shift;
	},

	rList: [],

	onReady: function(fn, scope) {
		if (scope) {
			this.rList.push(fn.bind(scope));
		} else {
			this.rList.push(fn);
		};
	},
	_onPLoad: function() {
		for(var i=0; i<this.rList.length; i++) {
			this.rList[i]();
		}
	},
	// ----- Search Box Functionality ----------------
	addListenerToSearch: function(id){
		this.search_box_id = id;
		this.search_box = $(id);
		this.search_value_not_set = true;
		if(this.search_box){
			this.search_box_value = this.search_box.value;
			this.search_box.observe("click", function(){
					this.search_box.value = "";
					this.search_value_not_set = true;
			}.bind(this));
			this.search_box.observe("blur",	 function(){
				if(this.search_box.value == ""){
					this.search_box.value = this.search_box_value;
					this.search_value_not_set = true;
				}else{
					this.search_value_not_set = false;
				}
			}.bind(this));
		}
	},
	request: function(url, params){

		if(!url || url == ""){
			Main.showAlert("FATAL - URL not found");
			return false;
		}

		function _onRequestComplete(jsonObj, response){
			if (jsonObj) {
				var msg_text = null;
				if (jsonObj.messages) {
					var m = jsonObj.messages;
					if (m instanceof Array) {
						msg_text = m.join("<br />");
					}
				}

					if (jsonObj.is_error) {
							_internalOnFail(jsonObj, response);
					} else {
							_internalOnSuccess(jsonObj, response);
					}
			} else if(response){
				_internalOnSuccess(false, response);
			}else{
				var req_fail = "This request has failed.  Please try later.";
				Main.showAlert(req_fail, "Error",
					_internalOnFail( jsonObj, response)
				);
			}
		}

			function _internalOnSuccess(result, response) {
				if (!params ||  !params['onSuccess']) return false;
				var f = params['onSuccess'] ? params['onSuccess'] : null;
				if (f && typeof f == 'function') {
					if (params['scope']) {
						f.apply(params['scope'], arguments);
					} else {
						f(result, response);
					}
				}
			};

		function _internalOnFail(result, response) {
			if (!params || !params['onFail']) return false;
			var f = params['onFail'] ? params['onFail'] : null;
			if (f && typeof f == 'function') {
				if (params['fscope']) {
					f.apply(params['fscope'], arguments);
				} else {
					f(result, response);
				}
			}
		};

		var p = (params && params.parameters) ? params.parameters : null;
		var requestData = new Ajax.Request(url,{
		method: 'post',
		parameters: p,
			onComplete: function(transport, json) {
				if(transport.responseText == "LOGOUT"){
					document.location = "logout.php";
				}
				var js = false;
				if(json && json.is_json == true){
					eval("js=" + transport.responseText)
				}
				_onRequestComplete(js, transport.responseText);
			}
		})
	},
	btn: function(){
		var m_btns = document.getElementsByClassName('m_btn');
		for(var i=0; i < m_btns.length; i++){
			m_btns[i].observe("mouseover", function(ev){
				ev.target.className = "m_btn-over";
			});
			m_btns[i].observe("mouseout", function(ev){
				ev.target.className = "m_btn";
			});
		}
		var s_btns = document.getElementsByClassName('s_btn');
		for(var i=0; i < s_btns.length; i++){
			s_btns[i].observe("mouseover", function(ev){
				ev.target.className = "s_btn-over";
			});
			s_btns[i].observe("mouseout", function(ev){
				ev.target.className = "s_btn";
			});
		}
		var l_btns = document.getElementsByClassName('l_btn');
		for(var i=0; i < l_btns.length; i++){
			l_btns[i].observe("mouseover", function(ev){
				ev.target.className = "l_btn-over";
			});
			l_btns[i].observe("mouseout", function(ev){
				ev.target.className = "l_btn";
			});
		}

	},
	chache_states: {},
	onChangeCountry: function(c_selector, state_selector_id, mask_el) {
		var country_id = c_selector.value;

		var state_selector = $(state_selector_id);
		if(country_id == -1){
			var newOpt = new Option("Any","-1");
			state_selector.add(newOpt, null);
			return false;
		}
		if (state_selector) {
			if (this.chache_states && this.chache_states[country_id]) {
				this.updateStateSelector(state_selector, this.chache_states[country_id]);
			} else {
				this.current_state_selector = state_selector;
				this.current_mask_el = mask_el ? mask_el : null;
				if (this.current_mask_el) {
					Main._loadMask(this.current_mask_el, true);
				}
				Main.request("ajax_getstates_list.php", {
					parameters: {country_id: country_id},
					onSuccess: function(json, response){
						var list = null;
						if (json && json['country_id'] > 0) {
							if (json['data']) {
								list = json['data'];
							}
							this.chache_states[json['country_id']] = list;
						}
						this.updateStateSelector(this.current_state_selector, list);
						if (this.current_mask_el) {
							Main._loadMask(this.current_mask_el, false);
						}
					},
					scope: this
				});
			}
		}
	},

	updateStateSelector: function(selector, list) {
		if (!selector) return null;
		var l = [];
		if (list) {
			for(var i in list) {
				l.push({v: i, t: list[i]});
			}
		}

		if (l.length == 0) {
			selector.disabled = true;
			return true;
		}

		while(selector.options.length > 0) {
			selector.remove(0);
		}
		for(var i=0; i<l.length; i++) {
			var newOpt = new Option(l[i].t, l[i].v);
			try {
    			selector.add(newOpt, null);
  			}
			catch(ex) {
				selector.add(newOpt); // IE only
			}
		}
		selector.selectedIndex = 0;
	}
};

Main.ajaxForm = function(config) {

	Main.apply(this, config);

	this.init();
};

Main.ajaxForm.prototype = {

	form: null,

	with_multiselect: false,

	multi_select_name: 'f[categories]',

	inputErrorClass: 'field-invalid',

	invalidClass: '',

	divErrorClass: 'error',

	listeners: null,

	mask_element: null,

	alert_title: "Information",

	init: function() {
		var f = $(this.form);
		if (!f) {
			Main.showDebug('FATAL - FORM element not found!!');
			return false;
		}
		if(!this.mask_element){
				this.mask_element = this.form;
		}

		f.onsubmit = this._onSubmit.bind(this);
		this.form = f;
	},
	_onSubmit: function() {
		Main._loadMask(this.mask_element, true);
		if(this.with_multiselect == false){
			Main.request(this.form.action,{
				parameters: this.form.serialize(true),
				onSuccess: function(json){
					this._onRequestComplete(json);
				},
				onFail: function(json){
					this._onRequestComplete(json);
				},
				scope: this,
				fscope: this
			})
		}else{
				var url 	= this.form.action;
				var data = this.form.serialize(true);
				var categories = null;
				data[this.multi_select_name]._each(function(item){
					if(categories == null){
						categories = item;
					}else{
						categories += ","+item;
					}

				}.bind(this));
				data[this.multi_select_name] = categories;
				Main.request(url,{
					parameters: data,
					onSuccess: function(json){
						this._onRequestComplete(json);
					},
					onFail: function(json){
						this._onRequestComplete(json);
					},
					scope: this,
					fscope: this
				})
		}
		return false;
	},
	_onRequestComplete: function(jsonObj) {
		if (jsonObj) {
			var msg_text = null;
			if (jsonObj.messages) {
				var m = jsonObj.messages;
				if (m instanceof Array) {
					msg_text = m.join("<br />");
				} else if (jsonObj.is_error) {
					this._setupErrors(m);
				} else {
					this.resetErrors();
				}
			}
			if (msg_text) {
				if (jsonObj.is_error) {
					Main.showAlert(msg_text, "Error",
						this._internalOnFail.bind(this, jsonObj)
					);
				} else {
					this.resetErrors();
					Main.showAlert(msg_text, this.alert_title,
						this._internalOnSuccess.bind(this, jsonObj)
					);
				}
			} else {
				if (jsonObj.is_error) {
					this._internalOnFail(jsonObj);
				} else {
					this._internalOnSuccess(jsonObj);
				}
			}
		} else {
			var req_fail = "Request is fail. Please, try later.";
			Main.showAlert(req_fail, "Error",
				this._internalOnFail.bind(this, jsonObj)
			);
		}

		Main._loadMask(this.mask_element, false);
	},

	_internalOnSuccess: function(result) {
		if (!this.listeners) return false;
		var f = this.listeners['onSuccess'] ? this.listeners['onSuccess'] : null;
		if (f && typeof f == 'function') {
			if (this.listeners['scope']) {
				f.apply(this.listeners['scope'], arguments);
			} else {
				f(result);
			}
		}
	},

	_internalOnFail: function(result) {
		if (!this.listeners) return false;
		var f = this.listeners['onFail'] ? this.listeners['onFail'] : null;
		if (f && typeof f == 'function') {
			if (this.listeners['scope']) {
				f.apply(this.listeners['scope'], arguments);
			} else {
				f(result);
			}
		}
	},

	_setFieldState: function(field, is_valid, mes) {
		if (!is_valid) {
			if (!field.error_div) {
				var p = field.parentNode;
				var d = document.createElement("div");
				d.className = this.divErrorClass;
				p.appendChild(d);
				field.error_div = d;
			} else {
				field.error_div.style.display = '';
			}
			field.error_div.innerHTML = mes;
			if(!field.is_invalid){
				field.begining_class = field.className;
				field.className += " "+this.inputErrorClass+this.invalidClass;
				field.is_invalid = true;
			}
		} else if(field.is_invalid) {
				field.is_invalid = false;
				field.error_div.style.display = 'none';
				field.className = field.begining_class;
		}
	},
	_getFieldsMap: function() {
		if (!this.fieldsMap) {
			var m = this.form.elements;
			var map = {};
			for(var i=0; i<m.length; i++) {
				if (m[i].tagName == 'FIELDSET' || m[i].type == "hidden" || m[i].type == "button" || m[i].type == "submit" || m[i].type == "image" || m[i].type == "radio") {
					continue;
				}
				var data_key = this.getFieldDataKey(m[i]);
				if (data_key) {
					if (map[data_key]) {
						Main.showDebug('already_set' + data_key);
					} else {
						map[data_key] = m[i];
						var error_div_id = m[i].getAttribute("error_div_id");
						if (error_div_id) {
							var error_div = document.getElementById(error_div_id);
							if (error_div) {
								m[i].error_div = error_div;
							}
						}
						//m[i].onfocus = this._setFieldState.bind(this, m[i], true);
					}
				} else {
					Main.showDebug('Cant get ' + m[i].name + m[i].type);
				}
			}
			this.fieldsMap = map;
		}

		return this.fieldsMap;
	},

	getFieldDataKey: function(field) {
		var res = field.getAttribute("_dataIndex");
		if (!res) {
			res = field.name.replace(/(?:.*\[)(.*)(?:\])/, "$1");
		}
		return res;
	},

	resetErrors: function() {
		this._setupErrors({});
	},

	reset: function() {
		this.form.reset();
		this._setupErrors({});
	},

	_setupErrors: function(mesages){
		var m = this._getFieldsMap();
		for(var name in m) {
			if (mesages[name]) {
				this._setFieldState(m[name], false, mesages[name]);
			} else {
				this._setFieldState(m[name], true);
			}
		}
	},
	submit: function() {
		this._onSubmit();
	}
};

// Produced By Aleksey Prozhoga

Main.starboxWidget = function(config){
	Main.apply(this, config);
	this.init();
}
Main.starboxWidget.prototype = {
	container: null,
    countStars: 5,
    classStar: "star",
    classStarLeft_i: "star star-left-i",
    classStarRight_i: "star star-right-i",
    classStarLeft: "star star-left",
    classStarRight: "star star-right",
    classPointer: "pointer",
    duration: 40,   // in miliseconds
    count_rated: 0,
    url: null,
    parameters: null,
    rate: null,

	init: function(){
		if(!this.url){
			Main.showDebug('FATAL - URL not found!!');
		}
		if(!this.parameters){
			Main.showDebug('FATAL - Parameters not found!!');
		}
		this.c = $(this.container);
		if (!this.c) {
			Main.showDebug('FATAL - Starbox container not found!!');
			return false;
		}
		if(!this.rate && this.rate != "hide"){
			this.c.observe("mouseout", this.mouseOut.bind(this));

			// Show initial stars

			for(var i = 0; i < this.countStars*2; i++){
				var div = document.createElement("div");
				this["star_"+i] = $(div);
				if(i % 2 == 0){
					div.className = this.classPointer+" "+this.classStarLeft_i;
				}else{
					div.className = this.classPointer+" "+this.classStarRight_i;
				}
				div.position = i;
				this["star_"+i].observe("mouseover", this.mouseOver.bind(this));
				this["star_"+i].observe("click", this._onRate.bind(this));
				this.c.appendChild(div);
			}
		}else if(this.rate != "hide"){
			for(var i = 0; i < this.countStars*2; i++){
				var div = document.createElement("div");
				if(i <= (this.rate)*2-1){
					if(i % 2 == 0){
						div.className = this.classStarLeft;
					}else{
						div.className = this.classStarRight;
					}
				}else{
					if(i % 2 == 0){
						div.className = this.classStarLeft_i;
					}else{
						div.className = this.classStarRight_i;
					}
				}
				this.c.appendChild(div);

			}
		}
	},
	mouseOver: function(el){
		clearTimeout(this.mouse_out_timeout);
		if(el.target.className == this.classStarLeft_i){
			el.target.className = this.classPointer+" "+this.classStarLeft;
		}else if(el.target.className == this.classStarRight_i){
			el.target.className = this.classPointer+" "+this.classStarRight;
		}
		for(var i = 0; i <= el.target.position; i++){
			if(i % 2 == 0){
				this["star_"+i].className =  this.classPointer+" "+this.classStarLeft;
			}else{
				this["star_"+i].className =  this.classPointer+" "+this.classStarRight;
			}
		}
		for(var i = this.countStars*2-1; i >el.target.position; i-- ){
			if(i % 2 == 0){
				this["star_"+i].className =  this.classPointer+" "+this.classStarLeft_i;
			}else{
				this["star_"+i].className =  this.classPointer+" "+this.classStarRight_i;
			}
		}
	},
	mouseOut: function(el){
		this.mouse_out_timeout = setTimeout(this.resetStars.bind(this), 500);
		this.currentStar = this.countStars*2-1;
	},
	resetStars: function(){

			if(this.currentStar % 2 == 0){
				this["star_"+this.currentStar].className = this.classPointer+" "+this.classStarLeft_i;
			}else{
				this["star_"+this.currentStar].className = this.classPointer+" "+this.classStarRight_i;
			}
			this.currentStar--;
			if(this.currentStar >= 0){
				 this.mouse_out_timeout = setTimeout(this.resetStars.bind(this), this.duration);
			}
	},
	_onRate: function(el){
		this.parameters["f[rate]"] = el.target.position;
		this.currentStar = el.target.position;
		this._removeListeners();
			Main.request(this.url,{
			parameters: this.parameters,
				onSuccess: function(json, r) {
					if(json.is_error == false){
						if($(this.average_rate_box) && json.rate){
							$(this.average_rate_box).innerHTML = json.rate;
							this.count_rated_box = $(this.count_rated_box);
							if(this.count_rated_box){
								this.count_rated_box.update((this.count_rated+1));
							}
						}
						Main.showAlert(json.messages[0], "Message");
					}else{
						Main.showAlert(json.messages[0], "Error");
					}
				},
				scope: this
			})
	},
	_removeListeners: function(){
		this.c.stopObserving();
		for(var i = 0; i < this.countStars*2; i++){
			this["star_"+i].stopObserving();
				if(i <= this.currentStar){
					if(i % 2 == 0){
						this["star_"+i].className = this.classStarLeft;
					}else{
						this["star_"+i].className = this.classStarRight;
					}
				}else{
					if(i % 2 == 0){
						this["star_"+i].className = this.classStarLeft_i;
					}else{
						this["star_"+i].className = this.classStarRight_i;
					}
				}
		}
	}
};

Main.colorBoxWidget = function(conf){
	Main.apply(this, conf);
	this.init();
}

Main.colorBoxWidget.prototype = {
	colors: Array('000000', '993300', '333300', '003300', '003366', '000080', '333399', '333333',
							'800000', 'FF6600', '808000', '008000', '008080', '0000FF', '666699', '808080',
							'FF0000', 'FF9900', '99CC00', '339966', '33CCCC', '3366FF', '800080', '969696',
							'FF00FF', 'FFCC00', 'FFFF00', '00FF00', '00FFFF', '00CCFF', '993366', 'C0C0C0',
							'FF99CC', 'FFCC99', 'FFFF99', 'CCFFCC', 'CCFFFF', '99CCFF', 'CC99FF', 'FFFFFF'),
	container:	null,
	selected_color_input_id: null,
	count_cols: 8,
	object_name: null,
	reset_link: "reset_link",
	init_color: null,
	init: function(){
		var c = $(this.container);
		if(!c){
			Main.showAlert("FATAL - Color Box container not found!");
			return false;
		}
		this.input = $(this.selected_color_input_id);
		this.reset_link = $(this.reset_link);
		if(this.reset_link){
			this.reset_link.observe("click", this.resetColor.bind(this));
			this.reset_link.hide();

		}
		this.input.readOnly = true;
		var box_content = "";
		var count_in_row = 0;
		var _new_row = true;
		var _init_selected_color_id = "";
		for (var i = 0; i < this.colors.length; i++){
			if(this.count_cols <= count_in_row){
				box_content += '<div class="clear"></div>';
				count_in_row = 0;
			}
			if(this.init_color && this.colors[i] == this.init_color){
				_init_selected_color_id = 'id="selected_color_id"';
			}
			box_content += '<div class="color_box_cell" _color="'+this.colors[i]+'" '+_init_selected_color_id+' onclick="'+this.object_name+'.setColor(\''+this.colors[i]+'\', this);" style="background-color: #'+this.colors[i]+';"></div>';

			count_in_row++;
		}
		c.update(box_content);

		if(this.init_color){
			function r(){
				this.setColor(this.init_color, $("selected_color_id"));
			};
			setTimeout(r.bind(this), 500);
		}

	},
	setColor: function(color, el){
		if(this.selected_el){
			this.selected_el.className = "color_box_cell";
		}
		this.selected_el = el;
		if(el.className){
			el.className = "color_box_cell-selected"	;
		}
		this.input.setStyle({
			"border": "1px solid  #c1c1c1",
			"background": "#"+color,
			"color":"#"+color
		});
		this.input.setValue(color);
		if(this.reset_link){
			this.reset_link.show();
		}
	},
	resetColor: function(){
		this.input.setValue("");
		if(this.selected_el){
			this.selected_el.className = "color_box_cell";
		}
		this.input.setStyle({
			"border": "1px solid #c1c1c1",
			"background": "#ffffff"
		});
		if(this.reset_link){
			this.reset_link.hide();
		}
	}
}



// *************************** Prototype  GRID **************************
/*
  		Example of use :

  	 	 var config = {
			url : "ajax_search_users.php",
			content_container: "search_users_box",
			mask_element: "mask_container",
			limit: public_num_rows,
			template: new Template('<div class="f_l userbox">' +
				'<a href="profile.php?user_id=#{user_id}"><div class="shadow"><div class="shadow_inner"><img src="#{picture}" alt="#{username}" /></div></div></a></div>')
		};
		new Main.grid(config);
 */


Main.grid = function (config) {
	Main.apply(this, config);
	this.init();
}

Main.grid.prototype = {
	limit: 10, // Count records on the one page is displaying
	mask_element: null, // Default mask element applyed to general content container. If set "none" then mask does not applyed
	url: null, //REQUIRED
	params: {}, // Additional parameters for AJAX REQUEST
	pager_container: null,
	content_container: null, //REQUIRED:  ID of content container
	template: null, // Required Prototype Template. Example new Template("<img src='#{picture}' alt="#{name}" />");
	no_records: "No Records to Display.",
	init_page: 0,
	init: function(){
		if(!this.url){
			Main.showDebug("FATAL - Url undefined!");
			return false;
		}
		this.params["limit"] = this.limit;

		this.content_container = $(this.content_container);

		if(!this.content_container){
			Main.showDebug("FATAL -  Content container undefined!");
			return false;
		}
		this.pager_container = $(this.pager_container);
		if(!this.template || typeof this.template != "object"){
			Main.showDebug("FATAL -  Template for Records not defined.<br> <a class='pointer' target='_blank' href='http://prototypejs.org/api/template'>See Doc</a>");
			return false;
		}
		this._loadGrid(this.init_page);
	},
	_loadGrid: function(page){

		this._mask(true);

		this.start = page*this.limit;
		this.page = page;
		this.params["start"] = this.start;

		Main.request(this.url, {
			parameters: this.params,
			onSuccess: function(json, response){
				if(!json){
					eval("json = " + response);
				}
				var records = "";
				if(json.total > 0){
					records = this._getAllRecords(json.data);
				} else {
					records = this.no_records;
				}
				this.content_container.update(records);
				if(this.pager_container){
					this.pager_container.update(this._getPager(json));
				} else {
					if(!this._internalPagerContainer){
						this._internalPagerContainer = new Element("div", {"class": "f_r"});
					}
					this.content_container.insert(this._internalPagerContainer);
					var dd =this._getPager(json);
					this._internalPagerContainer.update(dd);
				}
				this._mask(false);
			},
			scope: this
		});
	},
	_getAllRecords: function(data){
			var content = '';
			data.each(function(item){
					content += this.template.evaluate(item);
			}.bind(this))
			content += '<div class="clear"></div>';
			return content;
	},
	_getPager: function(d){
				var content = new Element("div");
				if(d.total > this.limit){
						var count_pages = Math.round(0.4+(d.total / this.limit));
						var a = {};
						if (this.start != 0){

								a = this._createPagerLinkWithListener(0, "<< Первая");
								content.insert(a);

							    a = this._createPagerLinkWithListener((parseInt(this.page)-1), "< Предыдущая");
								content.insert(a);

						}
						for(var i = 0 ; i <count_pages; i++){
							if(this.page == i){
								content.insert(new Element('span', {"class": "active pager_link"}).update((i+1)));
							}else{
							    a = this._createPagerLinkWithListener(i, (i+1));
								content.insert(a);
							}
				 		}
				 	    if(this.page < (count_pages-1)){
						    a = this._createPagerLinkWithListener((parseInt(this.page)+1), "Следующая >");
							content.insert(a);

						    a = this._createPagerLinkWithListener((parseInt(count_pages)-1), "Последняя >>");
							content.insert(a);
				 	    }
				}
			return content;
	},
	_mask: function (show){
		if(this.mask_element != "none"){
			if(!this._ismask){
				this._ismask = this.mask_element;
			}
			if(this._ismask == null){
				this.mask_element = this.content_container;
			} else {
				this.mask_element = $(this.mask_element);
			}
			if(this.mask_element){
				Main._loadMask(this.mask_element, show);
			}
		}
	},
	_createPagerLinkWithListener: function(param, name){
			var a = new Element("a", {"class": "pointer pager_link"});
			a.update(name);
			a.observe("click", this._loadGrid.bind(this, [parseInt(param)]));
			return a;
	}
}