		
	$.reget = function(){
		document.location = document.location;
		return false;
	};

	$.reload = function(){
		document.location.reload();
		return false;
	};
		
	$.sessionCheck = function(dataAJAX){
	    if ((dataAJAX.indexOf('<html') >= 0) || (dataAJAX.indexOf('<HTML') >= 0)) {			 					
			$.reget();
		}		
	};
	
	$.evalResponse = function(textJSON){
		$.sessionCheck(textJSON);
		var response;		
		try{eval("response = " + textJSON);}catch(e){}
		return (response || {});
	};
	
	Security = {
		SERVER_NAME: "",
		HEAD_SERVER_NAME: "",
		login: function(){
		    var login = $("#login").val();		
		    var password = $("#password").val();
		    var $panel = $('#user-panel');
		    var maskText = 'Авторизация...';
		    $panel.mask(maskText);
			$.ajax({
				url: '/tbm-web/logintbm?m=AJAXLOGIN',
				data: { j_username: login, j_password: password, "x": 1 },
				success: function(data){
					$panel.unmask();
					var response = eval(data);
					if(response.isOk === '0'){
						alert(response.error);
					}
					else if(response.isOk === '1'){
						$panel.mask(maskText);
						$.ajax({
						    url: '/tbm-web/j_security_check',
						    data: {j_username: login, j_password: password},
							success: function(data){
								$.ajax({
									url: 'http://' + Security.SERVER_NAME + '/tbm-web/site/act/session_helper',
									success: function(data){
										$.reget();
									}
								});
							},
							error: function(xhr){
								$panel.unmask();
							}													
						});
					}
					else {
						alert('Неизветсная ошибка');
					}
				},
				error: function(xhr){
					$panel.unmask();
				}
			});				    
		},
		
		logout: function(){
			$.getJSON("http://" + Security.SERVER_NAME + "/tbm-web/site/act/SESSION_HELPER?fn=logout&callback=?", 
		    	function(data) {
		    		if(data.status == 'ok!')
		    			$.reget();
				}
			);
		},
				
		enter:  function(e){
	 		var keycode;
	 		if (window.event)
	 			keycode = window.event.keyCode;
	 		else if (e)
	 			keycode = e.which;
	 		else
	 			return true;
	 		if (keycode == 13)
	 		{
	 			Security.login();
	 			return false;
	 		}
	 		else
	 			return true;
	 	}
	};
	
	
	Cart = {
		timers: [],
		from: 0,
		orderby: "",
		recalcSum: function(field){
			var kodtov = field.name.substring(5);
			var sumfield =  document.getElementById('sum'+kodtov);
			var cenafield =  document.getElementById('cena'+kodtov);
			sumfield.innerHTML = Math.round(field.value * cenafield.value * 100) / 100				
			jQuery("#" + field.id).addClass("dirty");
			clearTimeout(Cart.timers[field.id]);
			if(!isNumber(field.value)){
				return;
			}
			var count = parseInt(field.value);
			Cart.timers[field.id] = 
				setTimeout(
					function()
					{
					var data = "kodtov=" + kodtov;
					data += "&kol=" + count; 
			
				 	jQuery.ajax({
						type: "POST",
						url: "/tbm-web/cart?action=SETCOUNT",
						cache: false,
						data: data,
						success: function(data){
							try{
								eval("var response=" + data);
								jQuery("#order" + data.id).removeClass("dirty");
							}catch(e){								
								window.location.reload();
							}
						},
						error: function(xhr){
						}
					});		
					}, 
					500
				);
		},
	
		clear: function(){
		
		},
					
		stepCount: function(fieldname, step){
			var field = document.getElementById(fieldname);
			field.value = parseInt(field.value) + step;
			if (field.value < 0) field.value = 0;
			Cart.recalcSum(field);
		},
		
		del: function(kodtov){
			var data = "kodtov=" + kodtov + "&kol=0" + "&catalogId=" + Security.CATALOG_ID;
			
			$.getJSON("http://" + Security.HEAD_SERVER_NAME + "/tbm-web/site/act/CART_JS?fn=setcount&callback=?&" + data, 
	    			function(data) {
	    				if(data.empty)
							jQuery("#main_cart").attr("src",Cart.emptySrc);
						$.reget();		    			
					}
			);							
		},
		
		setCount: function(kodTov, count){
		
			var data = "kodtov=" + kodtov + "&kol=" + count + "&inCart=true" + "&catalogId=" + Security.CATALOG_ID;
	    			
	    	$.getJSON("http://" + Security.HEAD_SERVER_NAME + 
    				"/tbm-web/site/act/CART_JS?fn=setcount&callback=?&" + data, 
	    			function(data) {
	    				Cart.apply(data);
					}
			);	
		
		},
						
		send: function(o){
			var ref = "http://" + Security.HEAD_SERVER_NAME + "/tbm-web/myzk?m=CREATEFROMCART";
			if(o){
				if(o.shifrFir)				
					ref += "&shifrfir=" + o.shifrFir;
				if(o.zkSource)
					ref += "&zkSource=" + o.zkSource;
			}
			ref += "&href=%27" + encodeURIComponent(document.location.href) + "%27";			
			document.location = ref;
			window.focus();
		},
						
		src: "/tbm-web/images/cart.gif",
			
		emptySrc: "/tbm-web/images/cart_empty.gif",
			
		apply: function(data){
			jQuery("#cart-total").html(data.total);		
			var src = Cart.src;
			if(data.empty)
				jQuery("#main_cart").attr("src",Cart.emptySrc);
			else
				jQuery("#main_cart").attr("src",Cart.src);
			if(data.count == 0)
				src = Cart.emptySrc;
			var button = jQuery("#cart_img_" + data.id);
			button.attr("src", src);
			jQuery("#cart_count_" + data.id).html(data.count);
			if(data.sum)
				jQuery("#sum-cur-" + data.id).html(data.sum);			
			if(data.sumRUR)
				jQuery("#sum-ru-" + data.id).html(data.sumRUR);								
			if(data.totalSum)
				jQuery("#totalSum").html(data.totalSum);
			    jQuery(".total-sum").html(data.totalSum);
		},
			
		init: function(a){
			if(a)
			for(var i = 0; i < a.length; i++){
				$("#spinner_input_" + a[i].kodTov).val(a[i].count);
				$("#cart_count_" + a[i].kodTov).html(a[i].count);					
				$("#cart_img_" + a[i].kodTov).attr("src", Cart.src);
			}
		}			
		
	};
	
	
	Location = function() {
		
		this.location =  "" + document.location;
		
		this.removeParam = function(key){
			if(this.location == null)
				return;
			var reg = new RegExp("([&|?]" + key + "=)([^&|^#]*)(.*)", "g");
			this.location = this.location.replace(reg, "$1$3");
			if(this.location.indexOf('&') == 0)
				this.location = this.location.substr(1, this.location.length); 
			
			return this;
		};
		
		this.removeAnchor = function(){
			if(this.location != null)
				this.location = this.location.split("#")[0];
				
			return this;				
		};
		
		this.setParam = function(key, value){
			var reg = new RegExp("([&|?]" + key + "=)([^&|^#]*)(.*)", "g");
			if(reg.test(this.location))
				this.location = this.location.replace(reg, "$1" + value + "$3");
			else{
				this.location = this.location.split("#");
				var pref = this.location[0].indexOf('?') == -1 ? "?" : "&";
								
				this.location[0] += pref + key + "=" + value;
												
				if(this.location.length > 1)
					this.location = (this.location[0] + "#" + this.location[1]);
				else
					this.location = this.location[0];					
			}
			
			return this;						
		};
		
		this.go = function(){
			document.location = this.location;
		};
			
	}
		
	LocationUtil = {
	
		location: "" + document.location,
		
		removeParam: function(str, key){
			var s = "" + str;
			var reg = new RegExp("([&|?]" + key + "=)([^&|^#]*)(.*)", "g");
			return s.replace(reg, "$3");
		},
		
		removeAnchor: function(str){
			if(str != null)
				return ("" + str).split("#")[0]
			return null;
		},
		
		setParam: function(str, key, value){
			var s = "" + str;
			var reg = new RegExp("([&|?]" + key + "=)([^&|^#]*)(.*)", "g");
			if(reg.test(s))
				return s.replace(reg, "$1" + value + "$3");
			else{
				s = s.split("#");
				var pref = s[0].indexOf('?') == -1 ? "?" : "&";
				s[0] += pref + key + "=" + value;
				if(s.length > 1)
					s[0] += "#" + s[1];
				return s[0];
			}				
		}
	};
	
   	Cookie = { 
   	   	
    	get: function(key) {
			var reg = new RegExp("[^;]*(" + key + "=)([^;]+)(.*)");						
			if (reg.test(document.cookie))
				return decodeURIComponent(RegExp["$2"]);								
			return false;			    				    	
		},
		
		set: function(key, value, days, path, domain, secure) {
			if (!key || !value) 
				return false;
				
			var d = new Date();
			d.setDate(d.getDate() + (days ? days : 0));	
									
			var c = key + '=' + encodeURIComponent(value);	
			c += '; expires=' + d.toGMTString();
			if (path)    c += '; path=' + path;
			else c += '; path=' + "/";
			if (domain)  c += '; domain=' + domain;
			if (secure)  c += '; secure';	
			document.cookie = c;
							
			return true;
		},
		setConfig: function(key, value){				
			var cookie = Cookie.get(Cookie.configKey);
			var item = key + ":" + value;
			var itemsArray = [];
			try{
				itemsArray = cookie.split(";");
			}catch(e){}	
			var isSet = false;
			var i;
			for(i = 0; i < itemsArray.length; i++)
				if(itemsArray[i].indexOf(key + ":") == 0){
					itemsArray[i] = item;
					isSet = true;
					break;
				}
			if(!isSet)
				itemsArray[itemsArray.length] = item;
			Cookie.set(Cookie.configKey, itemsArray.join(";"), 1000);
		},
		addToBuff: function(id, key, max, days){
	    	if(id);
	    		else return;
	    
			var ids = Cookie.get(key);
			ids = $.trim(ids); 	
			var idsArray = [];		
			if(ids != null && ids != "")
				idsArray = ids.split(",");
		
			var isSet = false;
			var i;
			for(i = 0; i < idsArray.length; i++)
				if(idsArray[i] == id){
					isSet = true;
					break;
			}
			var item = id;
								
			if(!isSet){
				if(idsArray.length > max - 1)
					idsArray = idsArray.splice(0, max - 1);

				if(idsArray.length > 0)
					item = id + ",";			
					 
				ids = item + idsArray.join(",");
			}
			Cookie.set(key, ids, days);	
		}
   	};
   	
   	
   	var loc = new Location();
	
	Table = {
		id: function(id){
			loc.location = "?id=" + id
			loc.go(); 
		},
		order: function(order){
			var loc = new Location();
			loc
			.removeParam("page")
			.setParam("order", order)
			.go();
		},
		page: function(page){
			loc
			.setParam("page", page)
			.go();
		}
	};
	
	Util = {
		limitImageSize: function (o, limit)  {
					var img = new Image();					
					img.src = o.src;
					var horiz = img.width > img.height
					var sum = img.width + img.height;
					var max = img.width > img.height ? img.width : img.height;
					var size = {}; 
					if(max == 0 || min == 0)
						return size;
					var min = sum - max;
					var factor = (min / max);					
					if(max > limit){
					    size.height = limit * (horiz ? factor : 1);
					    size.width = limit * (!horiz ? factor : 1);
						o.style.height = size.height + 'px';
						o.style.width = size.width + 'px';					
					}
					return size;
		},
		limitImageSizeBoth: function (o, limitX, limitY)  {
			var img = new Image();
			img.src = o.src;
			var horiz = img.width > img.height
			var width = img.width;
			var height = img.height;
			var factor = 1;
			if(width > limitX){
			  factor = (limitX / width);
			  width *= factor;
			  height *= factor; 		
			}			
			if(height > limitY){
			  factor = (limitY / height);
			  width *= factor;
			  height *= factor; 					
			}
			o.style.height = height + 'px';
			o.style.width = width + 'px';
	  }		
	};
			
	function saveInCart(){			
		$("[id^='cart_container_']").show();
		$("table").filter("[id^='spinner_table_']").each(
			function(){
				if($(this).is(":hidden") == false){
					var id = $(this).attr("id");
					var kodtov = id.substr("spinner_table_".length, id.length);
					var value = $("#spinner_input_" + kodtov).val();							
					$(this).hide();
																																																											
			    	var data = "kodtov=" + kodtov + "&kol=" + value + "&inCart=true" + "&catalogId=" + Security.CATALOG_ID;
			    			
			    	$.getJSON("http://" + Security.HEAD_SERVER_NAME + 
		    				"/tbm-web/site/act/CART_JS?fn=setcount&callback=?&" + data, 
			    			function(data) {
			    				Cart.apply(data);
							}
					);																						
	    			
				}
			}
		);			
	};	
	
	
