/* Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};
 
  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;
   
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
   
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
           
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
           
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);       
            this._super = tmp;
           
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
   
    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
   
    // Populate our constructed prototype object
    Class.prototype = prototype;
   
    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;
   
    return Class;
  };
})();


//zasadniczna biblioteka


/*
 *  config:{
 * 	destEl
 * }
 * 
 */
Ex1 = {};

Ex1.Response = {};
Ex1.Response.STATUS_SESS_EXPIRED = 		 "session";
Ex1.Response.STATUS_EXCEPTION =          "exception";
Ex1.Response.STATUS_VALIDATION_ERROR =   "validation";
Ex1.Response.STATUS_ERROR =              "error";
Ex1.Response.STATUS_OK =                 "ok";

Ex1.formatNumber =  function(v, format) {
            if (!format) {
                return v;
            }
            var comma = ',',
                dec   = '.',
                i18n  = false,
                neg   = v < 0;

            v = Math.abs(v);
            if (format.substr(format.length - 2) == '/i') {
                format = format.substr(0, format.length - 2);
                i18n   = true;
                comma  = '.';
                dec    = ',';
            }

            var hasComma = format.indexOf(comma) != -1,
                psplit   = (i18n ? format.replace(/[^\d\,]/g, '') : format.replace(/[^\d\.]/g, '')).split(dec);

            if (1 < psplit.length) {
                v = v.toFixed(psplit[1].length);
            } else if(2 < psplit.length) {
                throw ('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
            } else {
                v = v.toFixed(0);
            }

            var fnum = v.toString();

            psplit = fnum.split('.');

            if (hasComma) {
                var cnum = psplit[0], 
                    parr = [], 
                    j    = cnum.length, 
                    m    = Math.floor(j / 3),
                    n    = cnum.length % 3 || 3,
                    i;

                for (i = 0; i < j; i += n) {
                    if (i != 0) {
                        n = 3;
                    }
                    
                    parr[parr.length] = cnum.substr(i, n);
                    m -= 1;
                }
                fnum = parr.join(comma);
                if (psplit[1]) {
                    fnum += dec + psplit[1];
                }
            } else {
                if (psplit[1]) {
                    fnum = psplit[0] + dec + psplit[1];
                }
            }

            return (neg ? '-' : '') + format.replace(/[\d,?\.?]+/, fnum);
}

Ex1.formatPrice = function (val){
	return Ex1.formatNumber(val,'0.00');
}
Ex1.logout = function(){
	window.location.href = siteUrl+'wyloguj.html';
}
Ex1.blockLink = function(elem){
	var link = $(elem).attr('href');
	if(link == '#'){ return false;}
	$(elem).attr('href','#');
	window.location.href = link;
}

Ex1.ContentLoader = function (config){
	
	this.config = config;
	
	this.parseResponse = function(rawResp){
		var response = $.parseJSON(rawResp);
		if(response){
			if( response.type == Ex1.ContentLoader.STATUS_SESS_EXPIRED ){
				Ex1.logout();
				return;
			}
			if( response.success ){
				if( response.type == Ex1.ContentLoader.STATUS_OK ){
					if( response.data ) $( this.config.destEl ).html(response.data.content);
				}
			}
		}
	}
	
	this.load = function(urlToLoad,params,config){
		if(!params) params = {};
		if(!config) config = {};
		params.ajax = 1;
		
		var scopeObj = this;
		this.showLoadingAnimation();
		return $.ajax({
	      url: urlToLoad,
	      type: "POST",
	      data: (params),
	      //dataType:'script',
	      success: function(resp){
	      	if (resp == '') {
	      		$( scopeObj.config.destEl ).html('Nie można załadować zawartości. ');
	      	}
	      	scopeObj.parseResponse(resp);
	      	scopeObj.hideLoadingAnimation();
	      	if(config.callback){
	      		if(config.scope)
	      			config.callback.call(config.scope,resp);
	      		else
	      			config.callback(resp);
	      	}
	      },
	      error:function(jqXHR, textStatus, errorThrown){
	      	scopeObj.hideLoadingAnimation();
	      },
	      complete:function(){
	      	scopeObj.hideLoadingAnimation();
	      }

	   	});
	}
	
	this.showLoadingAnimation = function(){
		var h = $(this.config.destEl).height();
		$(this.config.destEl).css('position','relative');
		
		var size = '';
		if( this.config.maskMaxHeight || this.config.maskMaxWidth ){
			if( this.config.maskMaxHeight ) size += 'height: '+this.config.maskMaxHeight+'px;';
			if( this.config.maskMaxWidth ) size += 'width: '+this.config.maskMaxWidth+'px;';
		}
		
		if( $(this.config.destEl).css('display') == 'block' ){
			var mask = $('<div class="loading-mask"><img src="'+Ex1.Images.LOADING+'"/></div>');
		}else{
			var mask = $('<div class="loading-mask" style="display:inline;"><img src="'+Ex1.Images.LOADING+'"  style="'+size+'"/></div>');
		}
			
		mask.css({
			background: '#222222',
			border: 'solid 2px black',
			opacity:0.6,
			padding: '10px 0',
			margin:'-2px 0 0 -2px',
			width:'100%'
		});
		
		if(this.config.transparentMask){
			mask.css({background: 'none',border:'none'});	
		}
		
		if( h ){
			mask.css({
				position:'absolute',
				top:0,
				left:0
			});
		}
		
		$('img',mask).css('opacity',1);
		
		if( !$('.loading-mask',this.config.destEl)[0] ){
			$(this.config.destEl).append(mask);
			if( h ){ 
				mask.height(h);
				$('img',mask).css('margin-top',(h/2-16)+'px' );
			}
		}
		
		
	}
	this.hideLoadingAnimation = function(){
		$('.loading-mask', this.config.destEl).remove();
	}

}

// PanelAjax do obsługi proxy po stronie serwera
Ex1.Ajax = function(config){
	
	$.ajax({
		url: config.url,
		data: config.data,
		type:'POST',
		success: function(resp){
			if(!config.scope) config.scope = this;
			
			if( config.success ){
				config.success.call( config.scope, resp );
			}
		},
		failure: function(resp){
			if(!config.scope) config.scope = this;
			
			if( config.failure ){
				config.failure.call( config.scope, resp );
			}
		}
	});
};

// PanelAjax do obsługi proxy po stronie serwera
Ex1.PanelAjax = function(_url,_params,_success, _scope){
	var PROXYURL = Ex1.SITE_TO_PANEL_PROXY_URL;
	var _data = _params;
	
	_data.URI = _url;
		
	return $.ajax({
		url: PROXYURL,
		data: _data,
		type:'POST',
		success: _success,
		success: function(resp){
			if(!_scope) _scope = this;
			
			if( _success ){
				_success.call( _scope, resp );
			}
		},
		failure: function(resp){
			if(!_scope) _scope = this;
			
			if( _failure ){
				_failure.call( _scope, resp );
			}
		}
	});
};

//Ex1.Ajax = Ex1.PanelAjax;


Ex1.AjaxForm = Class.extend({
	/*
	 * config:{
	 * 	el,
	 *  validationUrl,
	 *  url,
	 *  beforeSubmit: - przed wyslaniem form, gdy zwraca true to submit sie wykona
	 *  submitComplete: - handler gdy zaladowano zwrot
	 *  sessionExpired: - gdy wygasnie sesja
	 * }
	 */
	classes:{
		ITEM:'form-item',
		LABEL: 'form-item-label',
		VAL_ERR_TEXT:'validation-error-text',
		VAL_ERR_ITEM:'validation-error'
	},
	init:function(config){
		this.config = {
			proxy:false
		};
		$.extend(this.config, config);
		this.listeners = {
			beforeSubmit: config.beforeSubmit,
			submitComplete: config.submitComplete,
			submitFail: config.submitFail,
			sessionExpired: config.sessionExpired
		};
		this.scope = config.scope || this;
		
		this.form = $(this.config.el);
		this.action = this.form.attr('action');
		
		this.mask = new Ex1.LoadMask({el: this.config.el});
		var self = this;
		$(this.config.el).resize(function(){
			self.mask.resize();
		});
		
		this.form.bind('submit',{scope:this},this.onSubmit);
	},
	getField: function( name ){
		if( name )
			return this.form.find('[name="'+name+'"]')[0];
		return null;
	},
	setField: function(name,val){
		var field = this.getField(name);
		if( !field )  this.form.append('<input type="hidden" name="'+name+'" value="'+val+'"/>');
		else $(field).val(val);
	},
	validate: function(){
		
	},
	getParams: function(){
		
		var data = {};
		var params = this.form.serializeArray();
		for( idx in  params){
			data[params[idx].name] = params[idx].value;
		} 
		return data;
	},
	
	onSubmit: function(e){
		if( e.data.scope.listeners.beforeSubmit == undefined 
			|| e.data.scope.listeners.beforeSubmit.call(e.data.scope.scope)
		){
			e.data.scope.submit();
		}
		e.stopPropagation();
		return false;
	},
	
	submit: function(){
		this.mask.show();
		
		if( !this.config.proxy ){
			Ex1.Ajax({
				url: this.action,
				data: this.getParams(),
				success: this.onSuccess,
				scope: this
			});
		}else{
			Ex1.PanelAjax(this.config.url,this.getParams(),this.onSuccess,this);	
		}
		return false;
	},
	
	onSuccess: function(response){
		this.mask.hide();
		var obj = $.parseJSON(response);
		this.handleFieldsErrors(obj.verrors);
		
		if( obj.success == false && obj.type == Ex1.Response.STATUS_SESS_EXPIRED ){
			if( se = this.listeners.sessionExpired ){
				se.call(this.scope,obj);
			}
			return;	
		}
		
		if( this.listeners.submitComplete ){
			this.listeners.submitComplete.call(this.scope, obj);
			if( obj.data && obj.data.id ){
				this.setField('id',obj.data.id);
			}
		}
	},
	
	handleFieldsErrors: function(errors){
		this.clearAllInvalidMessages();
		if( errors ){
			for( field in errors){
				this.markInvalidField(field,errors[field]);
			}
		}
	},
	
	markInvalidField: function (fieldName, msg ){
		var field = this.getField(fieldName);
		
		if( !field ){
		  if(console) console.log('Pole ' + fieldName + ' nie istnieje');
		}
		
		var formItem = $(field).parent('.'+this.classes.ITEM);
		var label = formItem.find('.'+this.classes.LABEL);
		
		formItem.addClass(this.classes.VAL_ERR_ITEM);
		formItem.append( $('<span class="'+this.classes.VAL_ERR_TEXT+'">'+msg+'</span>') );
	},
	clearAllInvalidMessages:function(){
		this.form.find('.'+this.classes.ITEM).removeClass(this.classes.VAL_ERR_ITEM);
		this.form.find('span.'+this.classes.VAL_ERR_TEXT).remove();
	},
	clearInvalidMessage:function(fieldName){
		var field = this.getField(fieldName);
		if(!field) return;
		
		var formItem = $(field).parent('.'+this.classes.ITEM);
		formItem.removeClass(this.classes.VAL_ERR_ITEM);
		formItem.find('span.'+this.classes.VAL_ERR_TEXT).remove();
	},
	
	clear:function(){
		for( k in this.getParams() ){
			this.getField(k).value = '';
			$( this.getField(k) ).change();
		}
	}
	
	
	
});


Ex1.LoadMask = Class.extend({
	visible:false,
	init: function(config){
		Ex1.LoadMask.count++;
		this.count = Ex1.LoadMask.count;
		this.el = $(config.el);
		this.config = {};
		$.extend(this.config,config);
		
		var self = this;
		
		this.el.resize(function(){
			self.resize();
		});
	},
	resize:function(){
		if( this.visible ){
			this.hide();
			this.show();
		}
	},
	show:function(){
		var h = $(this.el).height();
		$(this.el).css('position','relative');
		
		var size = '';
		if( this.config.maskMaxHeight || this.config.maskMaxWidth ){
			if( this.config.maskMaxHeight ) size += 'height: '+this.config.maskMaxHeight+'px;';
			if( this.config.maskMaxWidth ) size += 'width: '+this.config.maskMaxWidth+'px;';
		}
		
		if( $(this.el).css('display') == 'block' ){
			var mask = $('<div id="load_mask_'+this.count+'" class="loading-mask"><img src="'+Ex1.LoadMask.LOADINGIMG+'"/></div>');
		}else{
			var mask = $('<div id="load_mask_'+this.count+'" class="loading-mask" style="display:inline;"><img src="'+Ex1.LoadMask.LOADINGIMG+'"  style="'+size+'"/></div>');
		}
			
		mask.css({
			background: '#aaaaaa',
			border: 'solid 2px black',
			'border-radius': '10px',
			opacity: 0.6,
			padding: '0',
			margin: '-2px 0 0 -2px',
			width: '100%',
			'text-align': 'center',
			'z-index':9999
		});
		
		if(this.config.transparentMask ){
			mask.css({background: 'none',border:'none'});
		}
		if( h ){
			mask.css({
				position:'absolute',
				top:0,
				left:0
			});
		}
		
		$('img',mask).css('opacity',1);
		
		if( !$('#load_mask_'+this.count,this.el)[0] ){
			$(this.el).append(mask);
			if( h ){ 
				mask.height(h);
				$('img',mask).css('margin-top',(h/2-16)+'px' );
			}
		}
		this.visible = true;		
	},
	hide:function(){
		$('.loading-mask', this.el).remove();
		this.visible = false;
	}
});
Ex1.LoadMask.LOADINGIMG = Ex1.JSPATH + 'resources/img/large-loading.gif';
Ex1.LoadMask.count = 0;


Ex1.Message = new (Class.extend({
	el:null,
	init:function(){
		this.el = $('<div>');
		$('body').append(this.el);
	},
	show:function(title,message){
		this.el.html(message);
		this.el.dialog( {title: title,modal:true} );
	}
}))();

Ex1.Dialog = Class.extend({
	dialog:null,
	form:null, // gdy zaladowano kontent 
	init:function(config){
		this.config = {
			title: '',
			width: 300,
			height: 100,
			modal: true,
			autoOpen:false,
			form: false
		}
		this.scope = this;
		if(config.scope)
			this.scope = config.scope;
		
		$.extend(this.config,this.config,config);
		
		this.el = $('<div>');
		
		$('body').append(this.el);
		
		
		this.dialog = $(this.el).dialog({
			title: this.config.title,
			minWidth: this.config.width,
			minHeight:this.config.height,
			modal: this.config.modal,
			autoOpen: this.config.autoOpen,
			buttons: this.config.buttons
		});
		this.mask = new Ex1.LoadMask({el: this.el});
	},
	open:function(){
		this.dialog.dialog('open');
		if( this.config.load ){
			this.loadContent(this.config.load);
		}
	},
	close:function(){
		this.dialog.dialog('close');
	},
	destroy:function(){
		this.dialog.dialog('destroy');
		this.el.remove();
	},
	getContentEl:function(){
		return this.el;
	},
	loadContent:function(_url){
		this.mask.show();
		Ex1.Ajax({url:_url,success:this.contentLoaded,scope:this });
	},
	contentLoaded:function(resp){
		this.getContentEl().html(resp);
		this.createForm();
		this.mask.hide();
	},
	createForm:function(){
		if( this.config.form ){
			this.form = new Ex1.AjaxForm({
				el: this.el.find('form')[0],
				beforeSubmit: function(){ 
					if( this.config.beforeSubmit ) return this.config.beforeSubmit.call(this.scope);
					return true;
				},
				submitComplete:function(json){
					if(this.config.submitComplete){
						this.config.submitComplete.call(this,json);
					}
				},
				sessionExpired:function(json){
					if(this.config.sessionExpired){
						this.config.sessionExpired.call(this,json);
					}
				},
				scope:this
			});
		}
	}
});



Ex1.Images = {};

Ex1.VPS = {};
/*
 * elId - HTML table element ID
 * prevId - DIV element ID for upgrade preview
 */
Ex1.VPS.UpgradesTable = function(elId,prevId){
	this.elId = elId;
	this.prevId = prevId;
	
	// upgrade preview loader
	this.ldr = new Ex1.ContentLoader({destEl:this.prevId} );

	var utbl = this;
	
	$(this.elId+' tr').bind('click',function(){
		var upID = $('td span',this).html();
		if( upID ){
			$(this).parent().find('tr').removeClass('selected');
			utbl.ldr.load( Ex1.VPS.UPGRADE_PREVIEW_URL, {id: upID } ,{callback:function(){
				$(this).addClass('selected');
			},scope:this});
		}
		
	}).addClass('selectable');
	
	
}


Ex1.VPS.MiniStatus = function(destContainer){
	this.power = null;
	this.tools = null;
	
	this.destEl = destContainer;
	
	this.ldr = new Ex1.ContentLoader({destEl:this.destEl} );
	this.count = 0;
	
	this.getStats = function(params){
		if( this.count == 0 )
			this.loadHtml(params);
		else
			this.loadJson(params);
	},
	
	this.loadHtml = function(params){
		this.vpsId = params.vpsId;
		this.ldr.load( Ex1.VPS.VM_STATUS_URL, {vps_id: params.vpsId } ,{
			callback: function(){
				if( this.power ){
					$('#vps_poweroff').removeClass('x-hidden');
					$('#vps_restart').removeClass('x-hidden');
				}else{
					$('#vps_poweron').removeClass('x-hidden');
				} 
				this.setPBProc(window.pbProc);
				this.setPBRam(window.pbRam);
				this.setPBNet(window.pbNet);
				this.count++;
				
				this.startTimer();
			},
			scope:this
		});
	},
	this.loadJson = function(params){
		this.vpsId = params.vpsId;
		var self = this;
		
		$.ajax({
	      url: Ex1.VPS.VM_STATUS_URL,
	      type: "POST",
	      data: {json:true, vps_id: params.vpsId },
	      dataType:'script',
	      success: function(resp){
	      	var obj = $.parseJSON(resp);
	      	
	      	if( obj.data.content ){
				$(self.destEl).html(obj.data.content);
				self.count = 0;
				$('#vps_poweron').addClass('x-hidden');
				$('#vps_poweroff').addClass('x-hidden');
				$('#vps_restart').addClass('x-hidden');	 
				return;
			}
	      	
	      	self.pbProc.updateProgress(obj.data.proc, obj.data.proc_text, true);
	      	self.pbRam.updateProgress(obj.data.ram, obj.data.ram_text, true);
	      	self.pbNet.updateProgress(obj.data.net, obj.data.net_text, true);
	      	
	      	$(self.destEl).find('.proc .value').html(obj.data.proc_mhz);
	      	$(self.destEl).find('.ram .value').html(obj.data.ram_mb);
	      	$(self.destEl).find('.net .value').html(obj.data.net_kbps);

			self.power = obj.data.power;	      	
	      	if( obj.data.power){
	      		$('#power').html('<span class="available">włączony</span>');
	      		$('#vps_poweroff').removeClass('x-hidden');
				$('#vps_restart').removeClass('x-hidden');
				$('#vps_poweron').addClass('x-hidden');
	      	}else{
	      		$('#power').html('<span class="unavailable">wyłączony</span>');
				$('#vps_poweron').removeClass('x-hidden');
				$('#vps_poweroff').addClass('x-hidden');
				$('#vps_restart').addClass('x-hidden');	      		
	      	}
	      	
	      	if( obj.data.tools){
	      		$('#tools').html('<span class="available">zainstalowane</span>');
	      	}else{
	      		$('#tools').html('<span class="unavailable">brak</span>');
	      	}
	      	
	      	if( obj.data.uptime){
	      		$('#uptime').html(obj.data.uptime);
	      	}else{
	      		$('#uptime').html('n/d');
	      	}
	      	
	      	this.startTimer();
	      }
	   	});		
	},
	this.setPBProc = function(pb){this.pbProc = pb;},
	this.setPBRam = function(pb){this.pbRam = pb;},
	this.setPBNet = function(pb){this.pbNet = pb;},
	
	mst = this;
	this.startTimer = function(){
		this.timer = setTimeout(function(){
			if( mst.vpsId ){
				if( !mst.power ){
					mst.count = 0
				}
				mst.getStats({vpsId:mst.vpsId});
			}
		},10000);	
	}	
	
}


Ex1.VPS.PromotionsLoader = function(formId,promotionsBox,config){
	this.config = config;
	this.form = $(formId);
	this.destEl = $(promotionsBox);
	
	this.ldr = new Ex1.ContentLoader({destEl:this.destEl,transparentMask:true} );
	
	this.loadPromotions = function(soId){
		if( !soId )
			soId = $('select[name="so"]',this.form).val();
			
		if( this.XHR ){
			if( this.XHR.readyState != 4 )
				this.XHR.abort();
		}
			
		this.XHR = this.ldr.load( Ex1.VPS.PROMOTIONS_LOAD_URL, { so: soId },{
			scope:this,
			callback:function(resp){
				if(this.config.loaded){
					this.config.loaded.call(this.config.scope,resp);
				}
			}
		});
	}

	
	var pl = this;
	$('select[name="so"]',this.form).change(function(){
		pl.loadPromotions();
	});
}

Ex1.VPS.CodeChecker = function( inputId,statusIconId ){
	this.inputId = inputId;
	this.statusIconId = statusIconId;
	
	
	var cc = this;
	
	this.ldr = new Ex1.ContentLoader({destEl:this.status,transparentMask:true,maskMaxHeight:18,maskMaxWidth:18} );
	
	this.checkCode = function(c,v){
		this.status.removeClass('code-error');
		this.status.removeClass('code-ok');
		
		this.ldr.load( Ex1.SITE_TO_PANEL_PROXY_URL, {URI: Ex1.VPS.CODE_CHECK_URL, code: c,value:v},{
			scope:this,
			callback:function(resp){
				var data = $.parseJSON(resp);
				if(data.success){
					cc.status.removeClass('code-error');
					cc.status.addClass('code-ok');
					this.status.html('');
				}else{
					cc.status.removeClass('code-ok');
					cc.status.addClass('code-error');
					cc.status.html(data.msg);
				}
				if( this.checkCallback )
					this.checkCallback.call(this.checkCallbackScope,resp);
			}
		} );
	}
	
	this.init = function(checkCallback,scope){
		this.checkCallbackScope = scope;
		this.checkCallback = checkCallback;
		this.input = $(inputId);
		this.status = $(statusIconId);
		this.input.change(function(){
			if( cc.input.val() )
				cc.checkCode( cc.input.val() );
		});
	}
	
	this.init();	
}


Ex1.VPS.Options = Class.extend({
	optionIdx: null,
	
	init: function(config){
		this.config = config;
		this.optionIdx = 0;
		
		this.setOptions(config.options);
		
		
		if( this.config.fieldName ){
			$(this.config.el).append('<input type="hidden" name="'+this.config.fieldName+'" />');
			this.input = $('input',this.config.el);
		}else{
			alert('Nie podano nazwy parametru');
		}
	},
	setOptions: function(opts){
		this.options = new Array();
		for( var o in opts ){
			this.options.push( opts[o] );
		}
	},
	
	setValue: function(id){
		if( this.input ){
			this.input.val(id);
		}
	},
	getValue:function(){
		if( this.input ){
			return this.input.val();
		}
	},
	getOptionId: function(){
		return this.options[this.optionIdx].id;
	},
	getPrice: function(){
		return this.options[this.optionIdx].price;
	},
	getName: function(){
		return this.options[this.optionIdx].name;
	},
	getOptionIdxById:function(id){
		for(o in this.options){
			if(this.options[o].id==id) return o;
		}
		return undefined;
	},
	setOptionById:function(id){
		
	}
});

/*
 * 
 *
 * function change(OptionsSlider os ){
 * 	
 * }
 */

Ex1.VPS.OptionsSlider = Ex1.VPS.Options.extend({
	init: function(config){
		this._super.call(this,config);
		this.callbackScope = this;
		if( config.scope ) this.callbackScope = config.scope;
		
		var OS = this;
		$(this.config.el).append('<div class="slider">');
		
		this.slider = $('.slider',this.config.el ).slider({
			animate:true,
			min: 0,
			max: this.options.length-1,
			
			change: function( event, ui ) { OS.updateValues(event, ui);	},
			slide: function( event, ui ) { OS.updateValues(event, ui);	}
			
		});
		
		this.handle = $('.ui-slider-handle',this.config.el );
		this.setText( this.options[ this.getOptionIdx() ] );
		
		this.setValue( this.getOptionId() );
		
	},
	
	updateValues:function(event,ui){
		this.optionIdx = ui.value;
		this.setText(this.options[ui.value]);
		this.setValue(this.getOptionId() );	
		if( this.config.change ){
			this.config.change.call(this.callbackScope,this,event);
		}		
	},
	
	setText: function(option){
		var texts = option.name.split(' ');
		var text = texts.join('<br/>');
		this.handle.html( text );
	},
	
	getOptionIdx: function(){
		this.optionIdx = this.slider.slider('value');
		return this.optionIdx;
	},
	
	setOptionById: function(id){
		this.optionsIdx = this.getOptionIdxById(id);
		this.slider.slider('value',this.optionsIdx);
	}
});

Ex1.VPS.OptionsSelect = Ex1.VPS.Options.extend({
	listVisible:false,
	listInitiated:false,
	height:null,
	width:null,
	x:null,
	y:null,
	
	
	init: function(config){
		this._super(config);
		
		$(this.config.el).append('<div class="ex1-select-main"><span class="selected-text"/><div class="ex1-select-handler"/></div>');
		this.main = $('.ex1-select-main', this.config.el );
		this.x = this.main.offset().left;
		this.y = this.main.offset().top;
		
		
		
		this.handler = $('.ex1-select-handler', this.config.el );
		this.handler.bind('click',{scope:this},this.toggleList );
		this.main.bind('click',{scope:this},this.toggleList );
		
		$('body').bind('click',{scope:this},this.hideList);
		
		this.list = $('<div class="ex1-select-list"></div>');
		this.listContent = $('<div class="ex1-select-list-content" />');
		
		$(this.config.el).append(this.list);
		this.list.append(this.listContent);
		
		if( config.value ){
			this.setOptionById( config.value );
		}else{
			this.setOption(0);
		}
		
		
		var e = new jQuery.Event("click");
		e.data = {};
		e.data.scope = this;
		e.data.scope = this;
		
		if( this.input){
			var self;
			self = this;
			this.input.bind('change', {scope:this}, function(e){
				e.data.scope.onInputChange();
			});
		}
		
	},
	onInputChange:function(){
		this.setOptionById( this.input.val() );
	},
	updateSelectedText:function(optIdx){
		this.main.find('.selected-text').html( this.getName() );
	},
	setOption:function(idx,event){
		this.optionIdx = idx;
		this.updateSelectedText(idx);
		this.setValue( this.getOptionId() );
		if( this.config.change ){
			this.config.change(this,event);
		}
	},
	
	setOptionById:function(id){
		if( id ){
			this.setOption(  this.getOptionIdxById(id)  );
		}else{
			this.setOption(0);
		}
			
	},
	updateItems:function(){
		this.listContent.html('');
		var i=0;
		for( o in this.options ){
			
			var text = this.options[o].name;
			var item = $('<div class="ex1-select-list-item">'+text+'</div>').hover(function(){
				$(this).addClass('ex1-select-list-item-highlited');
			},function(){
				$(this).removeClass('ex1-select-list-item-highlited');
			}).bind('click',{scope:this,idx:i},function(event){
				event.data.scope.setOption(event.data.idx,event);
				event.data.scope.hideList(event);
			});
			this.listContent.append(item)
			i++;
		}
	},
	initList:function(){
		this.height = this.main.height();
		this.width = this.main.width();
		
		this.list.width(this.width-4);
		this.list.show();
		$(this.list).position({
			of: this.main,
			my: 'center top',
			at: 'center center',
			offset: '1 0'
		});
		
		
		this.list.hide();
		this.updateItems();
	},
	showList:function(event,speed){
		var thisObj = event.data.scope;
		if(speed = undefined) speed = 300;
		
		if( !thisObj.listInitiated ){
			thisObj.initList();
			thisObj.initList();			
			thisObj.listInitiated = true;
		}
		//thisObj.list.stop(true);
		if(thisObj.list.queue().length) return false;
		thisObj.list.slideDown(speed);
		thisObj.listVisible = true;
		event.stopPropagation();
		thisObj.incrementZIndex();
		if( Ex1.VPS.OptionsSelect.currentShowed ){
			var e = new jQuery.Event();
			e.data = {};
			e.data.scope = Ex1.VPS.OptionsSelect.currentShowed;
			Ex1.VPS.OptionsSelect.currentShowed.hideList(e);
		}
		Ex1.VPS.OptionsSelect.currentShowed = this;		
	},
	hideList:function(event,speed){
		if(speed == undefined) speed = 300;
		
		thisObj = event.data.scope;
		//thisObj.list.stop(true);
		if( thisObj.list.queue().length ) return false;
		thisObj.list.slideUp(speed);
		thisObj.listVisible = false;
		thisObj.decrementZIndex();
		
		if( Ex1.VPS.OptionsSelect.currentShowed == this  || 
			event.currentTarget == $('body')[0]
		){
			Ex1.VPS.OptionsSelect.currentShowed = null;
		}
	},
	toggleList:function(event,speed){
		thisObj = event.data.scope;
		if( thisObj.listVisible ){
			thisObj.hideList(event,speed);
		}else{
			thisObj.showList(event,speed);
		}
	},
	incrementZIndex:function(){
		this.main.css('z-index',1010 );
		this.list.css('z-index',1009 );
	},
	decrementZIndex:function(){
		this.main.css('z-index',1000 );
		this.list.css('z-index',999 );
	}
	
});

/*
 * Przyjmuje opcje ktorych jest tylko 2 możliwosci (w przypadku wiekszej liczy wezmie 2 piersze)
 */
Ex1.VPS.OptionsSingleCheck = Ex1.VPS.Options.extend({
	checked:false,
	
	init: function(config){
		this._super(config);
		this.content = $(this.config.el);
		
		var item = $('<div class="'+Ex1.VPS.OptionsRadioChecks.ItemClass+'"></div>').bind('click',{scope:this},function(event){
				event.data.scope.setOption(!event.data.scope.checked,event);
			});
		this.checkBox = item;
		this.content.append(item)
		this.setOption(0);
	},
	setOption:function(checked,event){
		this.checked = checked;
		if( checked ){
			this.checkBox.addClass(Ex1.VPS.OptionsRadioChecks.CheckedItemClass);
			this.optionIdx = 1;
		}else{
			this.checkBox.removeClass(Ex1.VPS.OptionsRadioChecks.CheckedItemClass);
			this.optionIdx = 0;
		}
		this.setValue( this.getOptionId() );
		if( this.config.change ){
			this.config.change(this,event);
		}
	},
	setOptionById:function(id){
		if( id ){
			 var idx = this.getOptionIdxById(id) ;
			 var checked = this.options[idx].value*1;
			 this.setOption( checked );
		}
			
	}
	
});

Ex1.VPS.OptionsRadioChecks = Ex1.VPS.Options.extend({
	init: function(config){
		this._super(config);
		this.content = $(this.config.el);
		this.updateItems();
		this.setOption(0);
	},
	updateItems:function(){
		this.content.find('.'+Ex1.VPS.OptionsRadioChecks.ItemClass).remove();
		var i=0;
		for( o in this.options ){
			var text = this.options[o].name;
			var item = $('<div class="'+Ex1.VPS.OptionsRadioChecks.ItemClass+'">'+text+'</div>').bind('click',{scope:this,idx:i},function(event){
				event.data.scope.setOption(event.data.idx,event);
			});
			this.content.append(item)
			i++;
		}		
	},
	setOption:function(idx,event){
		this.optionIdx = idx;
		
		this.content.find('.'+Ex1.VPS.OptionsRadioChecks.CheckedItemClass).removeClass(Ex1.VPS.OptionsRadioChecks.CheckedItemClass);
		this.content.find('.'+Ex1.VPS.OptionsRadioChecks.ItemClass).eq(idx).addClass(Ex1.VPS.OptionsRadioChecks.CheckedItemClass);
		
		this.setValue( this.getOptionId() );
		
		//this.updateSelectedText(idx);
		//this.setValue( this.getOptionId() );
		if( this.config.change ){
			this.config.change(this,event);
		}
			
	},
	setOptionById:function(id){
		if( id ){
			this.setOption(  this.getOptionIdxById(id)  );
		}
			
	}
});
Ex1.VPS.OptionsRadioChecks.ItemClass = 'radio-item';
Ex1.VPS.OptionsRadioChecks.CheckedItemClass = 'radio-item-checked';

Ex1.VPS.Configurator = function(config){
	this.config = config;
	this.allParamsShown = false;
	this.preconfigs = null;
	this.rabatValue = 0;
	this.requirementsURL = '/vps/checkRequirements';
	this.requirementsOK = true;
	this.mask = null;  // warstwa blokujaca elementy
	
	var thisC = this;
	this.init = function(config){
		this.systemFamily = ''; //[windows,linux,bsd,iso];
		this.panel = '';
		
		$('#vps-configurator-systems .item', this.config.el).click(this.systemClick);
		$('#vps-configurator-panels .item', this.config.el).click(this.panelsClick);
		
		this.initShowAllButton();
		
		this.options = [
			this.procSlider  = new Ex1.VPS.OptionsSlider( {el: $('#processorSlider'), fieldName:'processor', options: this.config.allOptions.processor,change:this.optionChange }),
			this.ramSlider = new Ex1.VPS.OptionsSlider( {el: $('#ramSlider'), fieldName:'ram', options: this.config.allOptions.ram,change:this.optionChange  }),
			this.diskSlider = new Ex1.VPS.OptionsSlider( {el: $('#diskSlider'), fieldName:'disk_space', options: this.config.allOptions.disk_space,change:this.optionChange  }),
			this.soSelect = new Ex1.VPS.OptionsSelect( {el: $('#systemSelect'), fieldName:'so', options: this.config.allOptions.so, change:this.optionChange,value:77 }),
			new Ex1.VPS.OptionsSelect( {el: $('#transferSelect'), fieldName:'transfer', options: this.config.allOptions.transfer, change:this.optionChange }),
			new Ex1.VPS.OptionsRadioChecks({el: $('#supportRadio'), fieldName:'support', options: this.config.allOptions.support, change:this.optionChange }),
			new Ex1.VPS.OptionsRadioChecks({el: $('#interfacesRadio'), fieldName:'extra_interface', options: this.config.allOptions.extra_interface, change:this.optionChange }),
			new Ex1.VPS.OptionsRadioChecks({el: $('#ipsRadio'), fieldName:'ips', options: this.config.allOptions.ips, change:this.optionChange }),
			new Ex1.VPS.OptionsSingleCheck({el: $('#snapshotsCheck'), fieldName:'snapshots', options: this.config.allOptions.snapshots, change:this.optionChange })
		];
		
		for(v in this.config.allOptions.vtech){
			 $('<input type="hidden" name="vtech" value="'+this.config.allOptions.vtech[v].id+'" />').appendTo($(this.config.el).find('form')) ;
			break;
		}
		
		
		
		thisC.preconfigs = [];
		thisC.preconfigs.push( {id:0, name: 'Własna konfiguracja' } );
		this.loadPreconfigs();
		
		this.preconfigsSelect = new Ex1.VPS.OptionsSelect( {el: $('#preconfigSelect'),fieldName:'preconfig',options: [
				{id:0, name:'Własna konfiguracja'}
			],
			change:this.preconfigChange 
		});
		if( sf = this.config.sysFamily ){
			this.simulateSystemClick(sf);
		}else{
			this.simulateSystemClick('linux');
		}
		
		this.calcPrice();
		this.promotionsLoader = new  Ex1.VPS.PromotionsLoader('#vps-configurator-view form','#promotions',{
			scope:this,
			loaded: function(resp){
				this.codeChecker.init(this.setRabat,this);
				
				var codes = window.location.search.match(/VR[0-9]{8}/) ;
				if(codes && codes[0] ){
					$('#codeRadio').attr('checked','checked');
					$('#specialCode').val(codes[0]);
					
					this.codeChecker.checkCode(codes[0]);
				}
			}
		});
		this.promotionsLoader.loadPromotions();
		this.codeChecker = new Ex1.VPS.CodeChecker('#specialCode','#specialCodeStatus');
		
		if(this.config.selected){
			for( field in this.config.selected ){
				this.getField(field).setOptionById( this.config.selected[field] );	
			}
		}
		
		this.mask = new Ex1.LoadMask({el:this.config.el});
		
		this.initiaded = true;
	},
	
	this.checkRequirements = function(){
		if( this.initiaded ){
			if( this.checkingR ) this.checkingR.abort();
			
			this.requirementsOK = false;
			this.mask.show();
			this.checkingR = Ex1.PanelAjax(
				this.requirementsURL,
				{
					so: this.soSelect.getValue(),
	                disk_space: this.diskSlider.getValue(),
	                processor: this.procSlider.getValue(),
	                ram: this.ramSlider.getValue()
				},
				function(resp){
					this.mask.hide();
					if( resp == '' ){
						this.requirementsOK = false;
						return false;
					}
					
					resp = $.parseJSON(resp);
	                if(resp && !(resp.ram || resp.processor || resp.disk_space)  ){
	                	this.requirementsOK = true;
	                	this.doSubmit();
	                }else{
	                	this.requirementsOK = false;
						this.showRequirementsErrors(resp);
	                }
	            },
	            this
			);
		}
	},
	this.showRequirementsErrors = function(errors){
		var text = "Wybrane parametry VPSa nie spełniaja wymagań systemu operacyjnego. <br/>";
		
		for( e in errors ){
			text += errors[e] + "<br/>";
		}
		Ex1.Message.show('Niespełnione wymagania',text);
	},
	this.checkRequirementsErrors = function(){
		if( !this.requirementsOK ){
			Ex1.Message.show('Sprawdzanie wymagań','Wymagania nie zostały spełnione lub są jeszcze sprawdzane na serwerze.');
			return false;
		}else{
			return true;	
		}
	},
	
	this.setRabat = function(resp){
		var obj = $.parseJSON(resp);
		if( obj.data && obj.data.rabat_value ){
			this.rabatValue = obj.data.rabat_value;
		}else{
			this.rabatValue = 0;
		}
		this.calcPrice();
	},
	this.loadPreconfigs = function(){
		thisC = this;
		Ex1.PanelAjax('vps/getPreconfigs',{},function(resp){
			thisC.preconfigs = [];
			thisC.preconfigs.push( {id:0, name:'Własna konfiguracja'} );
			var data = $.parseJSON(resp);
			for( d in data){
				thisC.preconfigs.push(data[d]);
			}
			thisC.preconfigsSelect.setOptions(thisC.preconfigs);
			thisC.preconfigsSelect.updateItems();
			
		});
	};
	this.getField = function(name){
		for( vo in this.options ){
			if(this.options[vo].config.fieldName == name ){
				return this.options[vo];
			}
		}
	},
	this.getSystemSelect = function(){
		return this.getField('so');
		for( vo in this.options ){
			if(this.options[vo].config.fieldName == 'so' ){
				return this.options[vo];
			}
		}
	};
	this.initShowAllButton = function(){
		thisC.allParamsShown = false;
		$('#allOptionsButton').toggle(function(){
			if( thisC.allParamsShown == false){
				$('#allParams').slideDown(300,function(){
					thisC.allParamsShown = true; 
				});
				$(this).addClass('hideall');
				//$(this).attr('src',$(this).attr('src').replace('vps_all_options_button','vps_all_options_hide_button') );
			}
		},function(){
			if( thisC.allParamsShown == true){
				$('#allParams').slideUp(300,function(){
					thisC.allParamsShown = false; 
				});
				$(this).removeClass('hideall');
				//$(this).attr('src',$(this).attr('src').replace('vps_all_options_hide_button','vps_all_options_button') );
			}
		}).hover(function(){
			$(this).toggleClass('pokazmouseon');
		});
	};
	this.optionChange = function(slider, e){
		thisC.calcPrice();
		
		switch(slider.config.fieldName){
			case 'so': 
				thisC.selectSystemOnTop(slider);
				thisC.selectPanelOnTop(slider);
				if(thisC.promotionsLoader){
					thisC.promotionsLoader.loadPromotions(
						thisC.getSystemSelect().getOptionId() 
					);
				}
				$('#'+slider.config.fieldName+'Val').html( slider.getName() );
				
				var src = $('#vps-configurator-system #logo_oferty img').attr('src');
				
				patt = /logo[a-z0-9_]+.png/
				file2 = 'logo_'+thisC.getSystemFamily()+'_1.png';
				src = src.replace(patt,file2);

				$('#vps-configurator-system #logo_oferty img').attr('src',src );
				//thisC.checkRequirements();
			break;
			case 'processor':
			case 'ram':
			case 'disk_space':
				//thisC.checkRequirements();
			case 'transfer':
			case 'ips':
			case 'extra_interface':
				$('#'+slider.config.fieldName+'Val').html( slider.getName() );
			break;
			
		}
		
		if(e && e.originalEvent && thisC.preconfigsSelect ){
			if(thisC.preconfigsSelect.optionIdx != 0)
				thisC.preconfigsSelect.setOption(0);
		}
	};
	this.preconfigChange = function(option){
		var currPreconf = thisC.preconfigs[option.optionIdx];
		
		thisC.getSystemSelect().setOptions( thisC.getSystemFilteredOptions('') );
		thisC.getSystemSelect().updateItems();
		
		for(o in thisC.options){
			var key = thisC.options[o].config.fieldName;
			if( currPreconf[key] ){
				thisC.options[o].setOptionById( currPreconf[key] );
			}
		}	
	}
	this.calcPrice = function(){
		var sum = 0;
		for(o in this.options){
			sum += this.options[o].getPrice()*1;
		}
		
		if( this.rabatValue > 0){
			sum = sum * (1-this.rabatValue);
		}
		
		sum = Ex1.formatPrice(sum);
		sum += 'zł';
		if( this.rabatValue ){
			sum += '<br/> <span class="rabat_info">rabat '+this.rabatValue*100 + '%</span>';
		}
		
		$('#price').html( sum );
	}
	
	
	this.clearSystemFamilyChecks = function(){
		$('#vps-configurator-systems .item', this.config.el).removeClass('checked');
		$('#vps-configurator-systems .item img', this.config.el).each(function(){
			$(this).attr('src', $(this).attr('src').replace('1.png','0.png') );
		});
		this.systemFamily = '';
	};
	this.simulateSystemClick = function(key){
		this.systemClick.call(
			$('#vps-configurator-systems .item input[value="'+key+'"]' ).parents('.item')
		);
	};
	
	this.systemClick = function(){
		// this - klikniety element (div)
		
		thisC.checkSystemBox.call(this);
		
		var soOpt = thisC.getSystemSelect();
		var options = thisC.getSystemFilteredOptions( thisC.getSystemFamily() );
		soOpt.setOptions(options);
		soOpt.updateItems();
		soOpt.setOption(0);
		
		if( thisC.systemFamily != 'linux' ){
			thisC.clearPanelChecks();
		}else{
			soOpt.setOptionById(77);
		}
		
		if( thisC.systemFamily == 'windows' ){
			soOpt.setOptionById(39);
		}

		if( thisC.systemFamily == 'iso'){
			thisC.setISOInSummary(true);
		}else{
			thisC.setISOInSummary(false);
		}
		
	};
	this.checkSystemBox = function(){
		thisC.clearSystemFamilyChecks();
		$(this).addClass('checked');
		thisC.systemFamily = $('input',$(this)).val();
		
		var src = $(this).find('img').attr('src');
		src = src.replace('0.png','1.png');
		$(this).find('img').attr('src',src);
	};
	this.selectSystemOnTop = function(option){
		var sysName = option.getName().toLowerCase();
		var key = '';
		if( sysName.search('windows') != -1 ){
			key = 'windows';
		}else if(sysName.search('bsd') != -1){
			key = 'bsd';
		}else if(sysName.search('iso') != -1){
			key = 'iso';
		}else{ //linux
			key = 'linux';
		}
		
		this.checkSystemBox.call( $('#vps-configurator-systems .item input[value="'+key+'"]' ).parents('.item') );
		this.systemFamily = key;
	};
	this.selectPanelOnTop = function(option){
		this.clearPanelChecks();
		var sysName = option.getName().toLowerCase();
		var key = '';
		if( sysName.search('directadmin') != -1 ){
			key = 'directadmin';
		}else if(sysName.search('cpanel') != -1){
			key = 'cpanel';
		}else if(sysName.search('ispcp') != -1){
			key = 'isp';
		}
		
		if( key ){
			this.checkPanelBox.call( $('#vps-configurator-panels .item input[value="'+key+'"]' ).parents('.item') );
		}
	};
	
	this.getSystemFilteredOptions = function(key){
		var optionsIn = this.config.allOptions.so;
		var optionsOut = {};
		for( o in optionsIn ){
			switch( key ){
				case '':  //wszystkie opcje
					optionsOut[o] = optionsIn[o];
					break;
				case 'directadmin':
				case 'cpanel':
				case 'isp':
				
				case 'windows':
				case 'bsd':
				case 'iso':
				 	if( optionsIn[o].name.toLowerCase().search(key) != -1 ){
				 		optionsOut[o] = optionsIn[o];
				 	}
					break;	
				default:
					if( key =='linux' && optionsIn[o].name.toLowerCase().search('windows')== -1 &&
						optionsIn[o].name.toLowerCase().search('bsd')== -1 &&
						optionsIn[o].name.toLowerCase().search('iso')== -1 )
					{						
				 		optionsOut[o] = optionsIn[o];
					}
			}
		}
		return optionsOut;
	}
	
	this.clearPanelChecks = function(){
		$('#vps-configurator-panels .item', this.config.el).removeClass('checked');
		this.panel = '';
		this.setPanelInSummary(this.panel);
	};
	
	this.panelsClick = function(){
		// this - klikniety element (div)
		thisC.checkPanelBox.call(this);
		
		var soOpt = thisC.getSystemSelect();
		var key = thisC.panel;
		if(!key) key = thisC.systemFamily;
		var options = thisC.getSystemFilteredOptions( key );
		soOpt.setOptions(options);
		soOpt.updateItems();
		
		if( thisC.panel == 'directadmin' ){
			soOpt.setOptionById(84);
		}else{
			soOpt.setOption(0);
		}
		
		if( thisC.panel == ''){
			soOpt.setOptionById(77);
		}
			
	};
	this.checkPanelBox = function(){
		if( $(this).hasClass('checked') ){
			thisC.clearPanelChecks();
			thisC.panel = '';
		}else{
			thisC.clearPanelChecks();
			$(this).addClass('checked');
			thisC.panel = $('input',$(this)).val(); 
		}
		thisC.setPanelInSummary(thisC.panel);
		thisC.setISOInSummary(false);
	};
	this.setPanelInSummary = function(key){
		switch(key){
			case 'directadmin': 
				$('#panelVal').html('Panel Direct Admin PL');
				$('#panelCheckImg').attr('src',$('#panelCheckImg').attr('src').replace('_off','_on') );
				break;
			case 'cpanel': 
				$('#panelVal').html('Panel - cPanel');
				$('#panelCheckImg').attr('src',$('#panelCheckImg').attr('src').replace('_off','_on') );				
			break;
			case 'isp': 
				$('#panelVal').html('Panel - ispCP Omega');
				$('#panelCheckImg').attr('src',$('#panelCheckImg').attr('src').replace('_off','_on') );
			break;
			default:
				$('#panelVal').html('Panel - brak');
				$('#panelCheckImg').attr('src',$('#panelCheckImg').attr('src').replace('_on','_off') );			
		}
	};
	this.setISOInSummary = function(val){
		if(val){
			$('#isoCheckImg').attr('src',$('#isoCheckImg').attr('src').replace('_off','_on') );
		}else{
			$('#isoCheckImg').attr('src',$('#isoCheckImg').attr('src').replace('_on','_off') );
		}
	}
	this.getSystemFamily = function(){
		return this.systemFamily;
	};
	
	this.submit = function(){
		this.checkRequirements();
	}
	this.doSubmit = function(){
		if( !this.checkRequirementsErrors() ) return false;
		
		if( $(this.config.el).find('input[name="policy"]' ).attr('checked') ){
			$(this.config.el).find('form').submit();
		}else{
			Ex1.Message.show('Regulamin','Akceptacja regulaminu jest wymagana');
		}
	}
	
	this.init();
};

Ex1.VPS.MiniConfigurator = Class.extend({
	init:function(config){
		this.el = $(config.el);
		this.systemFamily = 'linux';
		this.cfg = {
			minWinPrice: 19
		}
		$.extend(this.cfg,config);
		
		this.basePrice = 4; //19-(4(processor)+7(ram)+4(dysk) )
		
		this.initSystems();
		
		this.options = [
			new Ex1.VPS.OptionsSlider( {el: $('#processorSlider'), fieldName:'processor', options: this.cfg.allOptions.processor,change:this.optionChange,scope:this }),
			new Ex1.VPS.OptionsSlider( {el: $('#ramSlider'), fieldName:'ram', options: this.cfg.allOptions.ram,change:this.optionChange,scope:this  }),
			new Ex1.VPS.OptionsSlider( {el: $('#diskSlider'), fieldName:'disk_space', options: this.cfg.allOptions.disk_space,change:this.optionChange,scope:this  })
		];		
        this.calcPrice();
	},
	initSystems:function(){
		var self = this;
		
		$(this.el).find('#vps-configurator-systems .mainitemos').click(function(){
			self.clearChecks();
			
			$(this).addClass('mainichecked').addClass('checked');
			self.systemFamily = $(this).find('input').attr('checked','checked').val();
			
			var src = $(this).find('img').attr('src');
			src = src.replace('0.png','1.png');
			$(this).find('img').attr('src',src);
			
			
			self.calcPrice();
		});
	},
	clearChecks:function(){
		$(this.el).find('#vps-configurator-systems .mainitemos').removeClass('mainichecked').removeClass('checked');
		$(this.el).find('#vps-configurator-systems .mainitemos input').attr('checked','');
		
		$('#vps-configurator-systems .mainitemos img', this.el).each(function(){
			$(this).attr('src', $(this).attr('src').replace('1.png','0.png') );
		});
		
	},
	updatePrice:function(val){
		$( '#miniVpsPrice').html(val+' zł');
	},
	optionChange:function(slider,e){
		this.calcPrice();
	},
    calcPrice:function(){
        var sum = this.basePrice*1;
        
        if( this.systemFamily == 'windows') sum += this.cfg.minWinPrice;
        
        for(var o in this.options){
            sum += this.options[o].getPrice()*1;
        }
        this.updatePrice(sum);
    },
    submit:function(){
    	this.el.find('form')[0].submit();
    }
        
});

Ex1.Contact = {};
Ex1.Contact.Form = Class.extend({
	init: function(config){
		this.config = {
			action: 'panel/sendContact'
		};
		$.extend(this.config,config);
		var self = this;
		
		this.form = new Ex1.AjaxForm({el: this.config.el,url: this.config.action,proxy:true,
			submitComplete:function(resp){
				this.onSendComplete(resp);
			},
			scope: this
		});
		
	},
	onSendComplete: function(resp){
		if( this.config.onResponse ){
			this.config.onResponse.call(this,resp);
		}
		if(resp.success){
			alert(resp.msg);
			this.form.clear();
		}
	}

	
});




//constants definitions
Ex1.SITE_TO_PANEL_PROXY_URL = siteUrl+'/index.php/tools/required/panel_proxy';
Ex1.PANEL_BASE = 'http://panel.exone.pl/';
Ex1.ContentLoader.STATUS_SESS_EXPIRED = 		 "session";
Ex1.ContentLoader.STATUS_EXCEPTION =          "exception";
Ex1.ContentLoader.STATUS_VALIDATION_ERROR =   "validation";
Ex1.ContentLoader.STATUS_ERROR =              "error";
Ex1.ContentLoader.STATUS_NOTICE =             "notice";
Ex1.ContentLoader.STATUS_OK =                 "ok";
Ex1.ContentLoader.STATUS_HELP =               "help";
Ex1.Images.LOADING = Ex1.PANEL_BASE + '/images/large-loading.gif';
Ex1.VPS.UPGRADE_PREVIEW_URL = siteUrl + 'podgladUpgradu.html';
Ex1.VPS.VM_STATUS_URL = siteUrl + 'vps/vmStatus';
Ex1.VPS.PROMOTIONS_LOAD_URL = '/serwery/vps/kalkulator/getPromotions';
Ex1.VPS.CODE_CHECK_URL = '/vps/checkCode';
