function $(obj) {
  return document.getElementById(obj);
}
function fCtrl() {
  this.inputList = new Array();
  this.addInput = function(value) {
    this.inputList.push(value);
  }
  // run through all required elements
  this.exec = function() {
    if (Act.skipCheck) {
        return true;
    }
    progress = true;
    var res = null;
    for(i=0;i<this.inputList.length;i++) {
      res = this.inputList[i].split('-');
      if (!this.validate(res[1],res[0])) {
        progress = false;
      }
    }
    if (!progress) {
        alert(FE.val('inputs.empty'));
    }
    return progress;
  }
  // validate those ones selected
  this.validate = function(dataType,obj) {
    // dependency on datatype
    ref = false;
    inp = $('input_'+obj);
    alt = $('alert_'+obj);

    if (!inp.disabled) {
        if (inp.hold) {
           empty = true;
        } else {
            switch (dataType) {
              case 'mail':
              empty = (inp.value ? false : true);
              if (!empty) {
                val = inp.value;
                empty = ((val.indexOf('.') > 0) && (val.indexOf('@') > 0) ? false : true);
              }
              break;
              case 'plain':
              empty = (inp.value ? false : true);
              break;
              case 'select':
              if (inp.value) {
                empty = (inp.options[inp.selectedIndex].value == 0 ? true : false);
              } else {
                empty = true;
              }
              break;
              case 'pass':
              val = inp.value;
              if (val && val == $('input_password').value) {
                  empty = false;
              } else {
                  empty = true;
              }

              break;
            }
        }
    }else {
        empty = false;
    }


    
    if (!ref) ref = inp;
    // unified
    if (empty) {
      ref.className = 'alert';
      return false;
    } else {
      ref.className = '';
      return true;
    }    
  }
  this.valRT = function(o,t) {
    if (o.value != '') {
        $('info_'+o.name).innerHTML = "<img class=\"ajaxIcon\" src=\"/data/admin/data/visual/ajax.gif\" alt=\"Kontrola...\">";
        switch(t) {
            case 'username':
                AJAX.init('act.find.match',{onComplete : function() {
                   if (AJAX.xml.responseText == 0) {
                     $('info_'+o.name).innerHTML = '';
                     o.hold = false;
                   } else {
                     $('info_'+o.name).innerHTML = '<small class="alert">Toto uživatelské jméno již existuje!</small>';
                     o.hold = true;
                   }
                   
                }},'table=users;ref=Username;val='+o.value);
            break;
        }     
    }

  }
  this.flush = function() {
    this.inputList = '';
  }
}
AEd = {
    on : false,
    add : function(n,v,push) {
        _v = FE.getArgs(v);
        if (_v.skip) {
            r = _v.skip.split(',');
            for(a=0;a<r.length;a++) {
                if (r[a] == _v.refId) {
                    return false;
                }
            }
        }

        if (!n.v) {
            n.title = "Kliknutím upravíte tento údaj";
            n.v = v;
            n.setAttribute('onclick', 'AEd.init(this,v)');               
            if (!n.innerHTML) {
                n.innerHTML = '(Prázdná hodnota)';  
                n.empty = true;
            } else {
                n.empty = false;
            }   
            if (push) {
                this.init(n,v);
            }         
        }

    },
    init : function(n,vl) {
        if (this.on) this.revert(b);
        this.on = true;

        p = n.parentNode;

        b = document.createElement('div');
        i = document.createElement('input');

        res = n.className.split(' ');
        for (a=0;a<res.length;a++) {
            item = res[a];
            i.className += ' '+item;
        }

        i.type = 'Text';
        i.v = vl;
        i.rev = n.innerHTML;
        if (!n.empty) {
            i.value = n.innerHTML;
        }
        b.appendChild(i);
        
        c = document.createElement('img');
        c.src = Base.vSrc+'icons/cancel.png';
        c.alt = c.title = 'Zrušit ';
        c.className = 'icon';
        c.setAttribute('onclick', 'AEd.revert(b,true)');
        b.appendChild(c);
        
        e = document.createElement('img');
        e.src = Base.vSrc+'icons/save.png';
        e.alt = e.title = 'Uložit';
        e.className = 'icon';
        e.setAttribute('onclick', 'AEd.save(b)');
        b.appendChild(e);        
        
        p.replaceChild(b,n);
        i.focus();
        i.select();
        
    },
    revert : function(b,t) {
        p = b.parentNode;
        i = b.getElementsByTagName('input');
        i = i[0];
        s = document.createElement('span');
        s.innerHTML = (t ? i.rev : i.value)
        v = i.v;
        s.className = i.className;
        this.add(s,v);       
        p.replaceChild(s,b);
        this.on = false;
        
    },
    save : function(b) {
        i = b.getElementsByTagName('input');
        i = i[0];
        AJAX.init('aed',{
            onComplete: function(r) {
                AEd.revert(b);
            }
        },'pushVal='+i.value+'&'+i.v);
    }
}
var Frm = {
    initSearch: function(e,o,i) {
        c = e.charCode || e.keyCode;
        if (c == 13 && o.value) {
            if (o.value.length < 2) {
                alert(FE.val('string.tooShort'));
            } else {
                Act.skipAct = true;
                AJAX.init('sub/product.add', {node: 'addInner'}, 'catId='+i+';srchText='+o.value, 'get');                
            }

        }
    }
}
var Dc = {
    add: function(o,v) {
        if (typeof(o.def) == "undefined") {
            o.def = o.value;
            o.onblur = function(){
                if (o.value == '') {
                    o.value = o.def;
                }
            }
            o.onfocus = function(){
                if (o.value == o.def) {
                    o.value = '';
                }
            } 
            o.onfocus();           
        }

    }
}
// jscolor
/**
 * jscolor, JavaScript Color Picker
 *
 * @version 1.3.1
 * @license GNU Lesser General Public License, http://www.gnu.org/copyleft/lesser.html
 * @author  Jan Odvarko, http://odvarko.cz
 * @created 2008-06-15
 * @updated 2010-01-23
 * @link    http://jscolor.com
 */


var jscolor = {

	dir : '/data/admin/data/visual/', // location of jscolor directory (leave empty to autodetect)
	bindClass : 'color', // class name
	binding : true, // automatic binding via <input class="...">
	preloading : true, // use image preloading?


	install : function() {
		jscolor.addEvent(window, 'load', jscolor.init);
	},


	init : function() {
		if(jscolor.binding) {
			jscolor.bind();
		}
		if(jscolor.preloading) {
			jscolor.preload();
		}
	},


	getDir : function() {
		if(!jscolor.dir) {
			var detected = jscolor.detectDir();
			jscolor.dir = detected!==false ? detected : 'jscolor/';
		}
		return jscolor.dir;
	},


	detectDir : function() {
		var base = location.href;

		var e = document.getElementsByTagName('base');
		for(var i=0; i<e.length; i+=1) {
			if(e[i].href) {base = e[i].href;}
		}

		var e = document.getElementsByTagName('script');
		for(var i=0; i<e.length; i+=1) {
			if(e[i].src && /(^|\/)jscolor\.js([?#].*)?$/i.test(e[i].src)) {
				var src = new jscolor.URI(e[i].src);
				var srcAbs = src.toAbsolute(base);
				srcAbs.path = srcAbs.path.replace(/[^\/]+$/, ''); // remove filename
				srcAbs.query = null;
				srcAbs.fragment = null;
				return srcAbs.toString();
			}
		}
		return false;
	},


	bind : function() {
		var matchClass = new RegExp('(^|\\s)('+jscolor.bindClass+')\\s*(\\{[^}]*\\})?', 'i');
		var e = document.getElementsByTagName('input');
		for(var i=0; i<e.length; i+=1) {
			var m;
			if(!e[i].color && e[i].className && (m = e[i].className.match(matchClass))) {
				var prop = {};
				if(m[3]) {
					try {
						eval('prop='+m[3]);
					} catch(eInvalidProp) {}
				}
				e[i].color = new jscolor.color(e[i], prop);
			}
		}
	},


	preload : function() {
		for(var fn in jscolor.imgRequire) {
			if(jscolor.imgRequire.hasOwnProperty(fn)) {
				jscolor.loadImage(fn);
			}
		}
	},


	images : {
		pad : [ 181, 101 ],
		sld : [ 16, 101 ],
		cross : [ 15, 15 ],
		arrow : [ 7, 11 ]
	},


	imgRequire : {},
	imgLoaded : {},


	requireImage : function(filename) {
		jscolor.imgRequire[filename] = true;
	},


	loadImage : function(filename) {
		if(!jscolor.imgLoaded[filename]) {
			jscolor.imgLoaded[filename] = new Image();
			jscolor.imgLoaded[filename].src = jscolor.getDir()+filename;
		}
	},


	fetchElement : function(mixed) {
		return typeof mixed === 'string' ? document.getElementById(mixed) : mixed;
	},


	addEvent : function(el, evnt, func) {
		if(el.addEventListener) {
			el.addEventListener(evnt, func, false);
		} else if(el.attachEvent) {
			el.attachEvent('on'+evnt, func);
		}
	},


	fireEvent : function(el, evnt) {
		if(!el) {
			return;
		}
		if(document.createEventObject) {
			var ev = document.createEventObject();
			el.fireEvent('on'+evnt, ev);
		} else if(document.createEvent) {
			var ev = document.createEvent('HTMLEvents');
			ev.initEvent(evnt, true, true);
			el.dispatchEvent(ev);
		} else if(el['on'+evnt]) { // alternatively use the traditional event model (IE5)
			el['on'+evnt]();
		}
	},


	getElementPos : function(e) {
		var e1=e, e2=e;
		var x=0, y=0;
		if(e1.offsetParent) {
			do {
				x += e1.offsetLeft;
				y += e1.offsetTop;
			} while(e1 = e1.offsetParent);
		}
		while((e2 = e2.parentNode) && e2.nodeName.toUpperCase() !== 'BODY') {
			x -= e2.scrollLeft;
			y -= e2.scrollTop;
		}
		return [x, y];
	},


	getElementSize : function(e) {
		return [e.offsetWidth, e.offsetHeight];
	},


	getMousePos : function(e) {
		if(!e) {e = window.event;}
		if(typeof e.pageX === 'number') {
			return [e.pageX, e.pageY];
		} else if(typeof e.clientX === 'number') {
			return [
				e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft,
				e.clientY + document.body.scrollTop + document.documentElement.scrollTop
			];
		}
	},


	getViewPos : function() {
		if(typeof window.pageYOffset === 'number') {
			return [window.pageXOffset, window.pageYOffset];
		} else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			return [document.body.scrollLeft, document.body.scrollTop];
		} else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			return [document.documentElement.scrollLeft, document.documentElement.scrollTop];
		} else {
			return [0, 0];
		}
	},


	getViewSize : function() {
		if(typeof window.innerWidth === 'number') {
			return [window.innerWidth, window.innerHeight];
		} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
			return [document.body.clientWidth, document.body.clientHeight];
		} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
			return [document.documentElement.clientWidth, document.documentElement.clientHeight];
		} else {
			return [0, 0];
		}
	},


	URI : function(uri) { // See RFC3986

		this.scheme = null;
		this.authority = null;
		this.path = '';
		this.query = null;
		this.fragment = null;

		this.parse = function(uri) {
			var m = uri.match(/^(([A-Za-z][0-9A-Za-z+.-]*)(:))?((\/\/)([^\/?#]*))?([^?#]*)((\?)([^#]*))?((#)(.*))?/);
			this.scheme = m[3] ? m[2] : null;
			this.authority = m[5] ? m[6] : null;
			this.path = m[7];
			this.query = m[9] ? m[10] : null;
			this.fragment = m[12] ? m[13] : null;
			return this;
		};

		this.toString = function() {
			var result = '';
			if(this.scheme !== null) {result = result + this.scheme + ':';}
			if(this.authority !== null) {result = result + '//' + this.authority;}
			if(this.path !== null) {result = result + this.path;}
			if(this.query !== null) {result = result + '?' + this.query;}
			if(this.fragment !== null) {result = result + '#' + this.fragment;}
			return result;
		};

		this.toAbsolute = function(base) {
			var base = new jscolor.URI(base);
			var r = this;
			var t = new jscolor.URI;

			if(base.scheme === null) {return false;}

			if(r.scheme !== null && r.scheme.toLowerCase() === base.scheme.toLowerCase()) {
				r.scheme = null;
			}

			if(r.scheme !== null) {
				t.scheme = r.scheme;
				t.authority = r.authority;
				t.path = removeDotSegments(r.path);
				t.query = r.query;
			} else {
				if(r.authority !== null) {
					t.authority = r.authority;
					t.path = removeDotSegments(r.path);
					t.query = r.query;
				} else {
					if(r.path === '') { // TODO: == or === ?
						t.path = base.path;
						if(r.query !== null) {
							t.query = r.query;
						} else {
							t.query = base.query;
						}
					} else {
						if(r.path.substr(0,1) === '/') {
							t.path = removeDotSegments(r.path);
						} else {
							if(base.authority !== null && base.path === '') { // TODO: == or === ?
								t.path = '/'+r.path;
							} else {
								t.path = base.path.replace(/[^\/]+$/,'')+r.path;
							}
							t.path = removeDotSegments(t.path);
						}
						t.query = r.query;
					}
					t.authority = base.authority;
				}
				t.scheme = base.scheme;
			}
			t.fragment = r.fragment;

			return t;
		};

		function removeDotSegments(path) {
			var out = '';
			while(path) {
				if(path.substr(0,3)==='../' || path.substr(0,2)==='./') {
					path = path.replace(/^\.+/,'').substr(1);
				} else if(path.substr(0,3)==='/./' || path==='/.') {
					path = '/'+path.substr(3);
				} else if(path.substr(0,4)==='/../' || path==='/..') {
					path = '/'+path.substr(4);
					out = out.replace(/\/?[^\/]*$/, '');
				} else if(path==='.' || path==='..') {
					path = '';
				} else {
					var rm = path.match(/^\/?[^\/]*/)[0];
					path = path.substr(rm.length);
					out = out + rm;
				}
			}
			return out;
		}

		if(uri) {
			this.parse(uri);
		}

	},


	/*
	 * Usage example:
	 * var myColor = new jscolor.color(myInputElement)
	 */

	color : function(target, prop) {


		this.required = true; // refuse empty values?
		this.adjust = true; // adjust value to uniform notation?
		this.hash = false; // prefix color with # symbol?
		this.caps = true; // uppercase?
		this.valueElement = target; // value holder
		this.styleElement = target; // where to reflect current color
		this.hsv = [0, 0, 1]; // read-only  0-6, 0-1, 0-1
		this.rgb = [1, 1, 1]; // read-only  0-1, 0-1, 0-1

		this.pickerOnfocus = true; // display picker on focus?
		this.pickerMode = 'HSV'; // HSV | HVS
		this.pickerPosition = 'bottom'; // left | right | top | bottom
		this.pickerFace = 10; // px
		this.pickerFaceColor = 'ThreeDFace'; // CSS color
		this.pickerBorder = 1; // px
		this.pickerBorderColor = 'ThreeDHighlight ThreeDShadow ThreeDShadow ThreeDHighlight'; // CSS color
		this.pickerInset = 1; // px
		this.pickerInsetColor = 'ThreeDShadow ThreeDHighlight ThreeDHighlight ThreeDShadow'; // CSS color
		this.pickerZIndex = 10000;


		for(var p in prop) {
			if(prop.hasOwnProperty(p)) {
				this[p] = prop[p];
			}
		}


		this.hidePicker = function() {
			if(isPickerOwner()) {
				removePicker();
			}
		};


		this.showPicker = function() {
			if(!isPickerOwner()) {
				var tp = jscolor.getElementPos(target); // target pos
				var ts = jscolor.getElementSize(target); // target size
				var vp = jscolor.getViewPos(); // view pos
				var vs = jscolor.getViewSize(); // view size
				var ps = [ // picker size
					2*this.pickerBorder + 4*this.pickerInset + 2*this.pickerFace + jscolor.images.pad[0] + 2*jscolor.images.arrow[0] + jscolor.images.sld[0],
					2*this.pickerBorder + 2*this.pickerInset + 2*this.pickerFace + jscolor.images.pad[1]
				];
				var a, b, c;
				switch(this.pickerPosition.toLowerCase()) {
					case 'left':a=1;b=0;c=-1;break;
					case 'right':a=1;b=0;c=1;break;
					case 'top':a=0;b=1;c=-1;break;
					default:a=0;b=1;c=1;break;
				}
				var l = (ts[b]+ps[b])/2;
				var pp = [ // picker pos
					-vp[a]+tp[a]+ps[a] > vs[a] ?
						(-vp[a]+tp[a]+ts[a]/2 > vs[a]/2 && tp[a]+ts[a]-ps[a] >= 0 ? tp[a]+ts[a]-ps[a] : tp[a]) :
						tp[a],
					-vp[b]+tp[b]+ts[b]+ps[b]-l+l*c > vs[b] ?
						(-vp[b]+tp[b]+ts[b]/2 > vs[b]/2 && tp[b]+ts[b]-l-l*c >= 0 ? tp[b]+ts[b]-l-l*c : tp[b]+ts[b]-l+l*c) :
						(tp[b]+ts[b]-l+l*c >= 0 ? tp[b]+ts[b]-l+l*c : tp[b]+ts[b]-l-l*c)
				];
				drawPicker(pp[a], pp[b]);
			}
		};


		this.importColor = function() {
			if(!valueElement) {
				this.exportColor();
			} else {
				if(!this.adjust) {
					if(!this.fromString(valueElement.value, leaveValue)) {
						styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
						styleElement.style.color = styleElement.jscStyle.color;
						this.exportColor(leaveValue | leaveStyle);
					}
				} else if(!this.required && /^\s*$/.test(valueElement.value)) {
					valueElement.value = '';
					styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
					styleElement.style.color = styleElement.jscStyle.color;
					this.exportColor(leaveValue | leaveStyle);

				} else if(this.fromString(valueElement.value)) {
					// OK
				} else {
					this.exportColor();
				}
			}
		};


		this.exportColor = function(flags) {
			if(!(flags & leaveValue) && valueElement) {
				var value = this.toString();
				if(this.caps) {value = value.toUpperCase();}
				if(this.hash) {value = '#'+value;}
				valueElement.value = value;
			}
			if(!(flags & leaveStyle) && styleElement) {
				styleElement.style.backgroundColor =
					'#'+this.toString();
				styleElement.style.color =
					0.213 * this.rgb[0] +
					0.715 * this.rgb[1] +
					0.072 * this.rgb[2]
					< 0.5 ? '#FFF' : '#000';
			}
			if(!(flags & leavePad) && isPickerOwner()) {
				redrawPad();
			}
			if(!(flags & leaveSld) && isPickerOwner()) {
				redrawSld();
			}
		};


		this.fromHSV = function(h, s, v, flags) { // null = don't change
			h<0 && (h=0) || h>6 && (h=6);
			s<0 && (s=0) || s>1 && (s=1);
			v<0 && (v=0) || v>1 && (v=1);
			this.rgb = HSV_RGB(
				h===null ? this.hsv[0] : (this.hsv[0]=h),
				s===null ? this.hsv[1] : (this.hsv[1]=s),
				v===null ? this.hsv[2] : (this.hsv[2]=v)
			);
			this.exportColor(flags);
		};


		this.fromRGB = function(r, g, b, flags) { // null = don't change
			r<0 && (r=0) || r>1 && (r=1);
			g<0 && (g=0) || g>1 && (g=1);
			b<0 && (b=0) || b>1 && (b=1);
			var hsv = RGB_HSV(
				r===null ? this.rgb[0] : (this.rgb[0]=r),
				g===null ? this.rgb[1] : (this.rgb[1]=g),
				b===null ? this.rgb[2] : (this.rgb[2]=b)
			);
			if(hsv[0] !== null) {
				this.hsv[0] = hsv[0];
			}
			if(hsv[2] !== 0) {
				this.hsv[1] = hsv[1];
			}
			this.hsv[2] = hsv[2];
			this.exportColor(flags);
		};


		this.fromString = function(hex, flags) {
			var m = hex.match(/^\W*([0-9A-F]{3}([0-9A-F]{3})?)\W*$/i);
			if(!m) {
				return false;
			} else {
				if(m[1].length === 6) { // 6-char notation
					this.fromRGB(
						parseInt(m[1].substr(0,2),16) / 255,
						parseInt(m[1].substr(2,2),16) / 255,
						parseInt(m[1].substr(4,2),16) / 255,
						flags
					);
				} else { // 3-char notation
					this.fromRGB(
						parseInt(m[1].charAt(0)+m[1].charAt(0),16) / 255,
						parseInt(m[1].charAt(1)+m[1].charAt(1),16) / 255,
						parseInt(m[1].charAt(2)+m[1].charAt(2),16) / 255,
						flags
					);
				}
				return true;
			}
		};


		this.toString = function() {
			return (
				(0x100 | Math.round(255*this.rgb[0])).toString(16).substr(1) +
				(0x100 | Math.round(255*this.rgb[1])).toString(16).substr(1) +
				(0x100 | Math.round(255*this.rgb[2])).toString(16).substr(1)
			);
		};


		function RGB_HSV(r, g, b) {
			var n = Math.min(Math.min(r,g),b);
			var v = Math.max(Math.max(r,g),b);
			var m = v - n;
			if(m === 0) {return [ null, 0, v ];}
			var h = r===n ? 3+(b-g)/m : (g===n ? 5+(r-b)/m : 1+(g-r)/m);
			return [ h===6?0:h, m/v, v ];
		}


		function HSV_RGB(h, s, v) {
			if(h === null) {return [ v, v, v ];}
			var i = Math.floor(h);
			var f = i%2 ? h-i : 1-(h-i);
			var m = v * (1 - s);
			var n = v * (1 - s*f);
			switch(i) {
				case 6:
				case 0:return [v,n,m];
				case 1:return [n,v,m];
				case 2:return [m,v,n];
				case 3:return [m,n,v];
				case 4:return [n,m,v];
				case 5:return [v,m,n];
			}
		}


		function removePicker() {
			delete jscolor.picker.owner;
			document.getElementsByTagName('body')[0].removeChild(jscolor.picker.boxB);
		}


		function drawPicker(x, y) {
			if(!jscolor.picker) {
				jscolor.picker = {
					box : document.createElement('div'),
					boxB : document.createElement('div'),
					pad : document.createElement('div'),
					padB : document.createElement('div'),
					padM : document.createElement('div'),
					sld : document.createElement('div'),
					sldB : document.createElement('div'),
					sldM : document.createElement('div')
				};
				for(var i=0,segSize=4; i<jscolor.images.sld[1]; i+=segSize) {
					var seg = document.createElement('div');
					seg.style.height = segSize+'px';
					seg.style.fontSize = '1px';
					seg.style.lineHeight = '0';
					jscolor.picker.sld.appendChild(seg);
				}
				jscolor.picker.sldB.appendChild(jscolor.picker.sld);
				jscolor.picker.box.appendChild(jscolor.picker.sldB);
				jscolor.picker.box.appendChild(jscolor.picker.sldM);
				jscolor.picker.padB.appendChild(jscolor.picker.pad);
				jscolor.picker.box.appendChild(jscolor.picker.padB);
				jscolor.picker.box.appendChild(jscolor.picker.padM);
				jscolor.picker.boxB.appendChild(jscolor.picker.box);
			}

			var p = jscolor.picker;

			// recompute controls positions
			posPad = [
				x+THIS.pickerBorder+THIS.pickerFace+THIS.pickerInset,
				y+THIS.pickerBorder+THIS.pickerFace+THIS.pickerInset ];
			posSld = [
				null,
				y+THIS.pickerBorder+THIS.pickerFace+THIS.pickerInset ];

			// controls interaction
			p.box.onmouseup =
			p.box.onmouseout = function() {target.focus();};
			p.box.onmousedown = function() {abortBlur=true;};
			p.box.onmousemove = function(e) {holdPad && setPad(e);holdSld && setSld(e);};
			p.padM.onmouseup =
			p.padM.onmouseout = function() {if(holdPad) {holdPad=false;jscolor.fireEvent(valueElement,'change');}};
			p.padM.onmousedown = function(e) {holdPad=true;setPad(e);};
			p.sldM.onmouseup =
			p.sldM.onmouseout = function() {if(holdSld) {holdSld=false;jscolor.fireEvent(valueElement,'change');}};
			p.sldM.onmousedown = function(e) {holdSld=true;setSld(e);};

			// picker
			p.box.style.width = 4*THIS.pickerInset + 2*THIS.pickerFace + jscolor.images.pad[0] + 2*jscolor.images.arrow[0] + jscolor.images.sld[0] + 'px';
			p.box.style.height = 2*THIS.pickerInset + 2*THIS.pickerFace + jscolor.images.pad[1] + 'px';

			// picker border
			p.boxB.style.position = 'absolute';
			p.boxB.style.clear = 'both';
			p.boxB.style.left = x+'px';
			p.boxB.style.top = y+'px';
			p.boxB.style.zIndex = THIS.pickerZIndex;
			p.boxB.style.border = THIS.pickerBorder+'px solid';
			p.boxB.style.borderColor = THIS.pickerBorderColor;
			p.boxB.style.background = THIS.pickerFaceColor;

			// pad image
			p.pad.style.width = jscolor.images.pad[0]+'px';
			p.pad.style.height = jscolor.images.pad[1]+'px';

			// pad border
			p.padB.style.position = 'absolute';
			p.padB.style.left = THIS.pickerFace+'px';
			p.padB.style.top = THIS.pickerFace+'px';
			p.padB.style.border = THIS.pickerInset+'px solid';
			p.padB.style.borderColor = THIS.pickerInsetColor;

			// pad mouse area
			p.padM.style.position = 'absolute';
			p.padM.style.left = '0';
			p.padM.style.top = '0';
			p.padM.style.width = THIS.pickerFace + 2*THIS.pickerInset + jscolor.images.pad[0] + jscolor.images.arrow[0] + 'px';
			p.padM.style.height = p.box.style.height;
			p.padM.style.cursor = 'crosshair';

			// slider image
			p.sld.style.overflow = 'hidden';
			p.sld.style.width = jscolor.images.sld[0]+'px';
			p.sld.style.height = jscolor.images.sld[1]+'px';

			// slider border
			p.sldB.style.position = 'absolute';
			p.sldB.style.right = THIS.pickerFace+'px';
			p.sldB.style.top = THIS.pickerFace+'px';
			p.sldB.style.border = THIS.pickerInset+'px solid';
			p.sldB.style.borderColor = THIS.pickerInsetColor;

			// slider mouse area
			p.sldM.style.position = 'absolute';
			p.sldM.style.right = '0';
			p.sldM.style.top = '0';
			p.sldM.style.width = jscolor.images.sld[0] + jscolor.images.arrow[0] + THIS.pickerFace + 2*THIS.pickerInset + 'px';
			p.sldM.style.height = p.box.style.height;
			try {
				p.sldM.style.cursor = 'pointer';
			} catch(eOldIE) {
				p.sldM.style.cursor = 'hand';
			}

			// load images in optimal order
			switch(modeID) {
				case 0:var padImg = 'hs.png';break;
				case 1:var padImg = 'hv.png';break;
			}
			p.padM.style.background = "url('"+jscolor.getDir()+"cross.gif') no-repeat";
			p.sldM.style.background = "url('"+jscolor.getDir()+"arrow.gif') no-repeat";
			p.pad.style.background = "url('"+jscolor.getDir()+padImg+"') 0 0 no-repeat";

			// place pointers
			redrawPad();
			redrawSld();

			jscolor.picker.owner = THIS;
			document.getElementsByTagName('body')[0].appendChild(p.boxB);
		}


		function redrawPad() {
			// redraw the pad pointer
			switch(modeID) {
				case 0:var yComponent = 1;break;
				case 1:var yComponent = 2;break;
			}
			var x = Math.round((THIS.hsv[0]/6) * (jscolor.images.pad[0]-1));
			var y = Math.round((1-THIS.hsv[yComponent]) * (jscolor.images.pad[1]-1));
			jscolor.picker.padM.style.backgroundPosition =
				(THIS.pickerFace+THIS.pickerInset+x - Math.floor(jscolor.images.cross[0]/2)) + 'px ' +
				(THIS.pickerFace+THIS.pickerInset+y - Math.floor(jscolor.images.cross[1]/2)) + 'px';

			// redraw the slider image
			var seg = jscolor.picker.sld.childNodes;

			switch(modeID) {
				case 0:
					var rgb = HSV_RGB(THIS.hsv[0], THIS.hsv[1], 1);
					for(var i=0; i<seg.length; i+=1) {
						seg[i].style.backgroundColor = 'rgb('+
							(rgb[0]*(1-i/seg.length)*100)+'%,'+
							(rgb[1]*(1-i/seg.length)*100)+'%,'+
							(rgb[2]*(1-i/seg.length)*100)+'%)';
					}
					break;
				case 1:
					var rgb, s, c = [ THIS.hsv[2], 0, 0 ];
					var i = Math.floor(THIS.hsv[0]);
					var f = i%2 ? THIS.hsv[0]-i : 1-(THIS.hsv[0]-i);
					switch(i) {
						case 6:
						case 0:rgb=[0,1,2];break;
						case 1:rgb=[1,0,2];break;
						case 2:rgb=[2,0,1];break;
						case 3:rgb=[2,1,0];break;
						case 4:rgb=[1,2,0];break;
						case 5:rgb=[0,2,1];break;
					}
					for(var i=0; i<seg.length; i+=1) {
						s = 1 - 1/(seg.length-1)*i;
						c[1] = c[0] * (1 - s*f);
						c[2] = c[0] * (1 - s);
						seg[i].style.backgroundColor = 'rgb('+
							(c[rgb[0]]*100)+'%,'+
							(c[rgb[1]]*100)+'%,'+
							(c[rgb[2]]*100)+'%)';
					}
					break;
			}
		}


		function redrawSld() {
			// redraw the slider pointer
			switch(modeID) {
				case 0:var yComponent = 2;break;
				case 1:var yComponent = 1;break;
			}
			var y = Math.round((1-THIS.hsv[yComponent]) * (jscolor.images.sld[1]-1));
			jscolor.picker.sldM.style.backgroundPosition =
				'0 ' + (THIS.pickerFace+THIS.pickerInset+y - Math.floor(jscolor.images.arrow[1]/2)) + 'px';
		}


		function isPickerOwner() {
			return jscolor.picker && jscolor.picker.owner === THIS;
		}


		function blurTarget() {
			if(valueElement === target) {
				THIS.importColor();
			}
			if(THIS.pickerOnfocus) {
				THIS.hidePicker();
			}
		}


		function blurValue() {
			if(valueElement !== target) {
				THIS.importColor();
			}
		}


		function setPad(e) {
			var posM = jscolor.getMousePos(e);
			var x = posM[0]-posPad[0];
			var y = posM[1]-posPad[1];
			switch(modeID) {
				case 0:THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)), 1 - y/(jscolor.images.pad[1]-1), null, leaveSld);break;
				case 1:THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)), null, 1 - y/(jscolor.images.pad[1]-1), leaveSld);break;
			}
		}


		function setSld(e) {
			var posM = jscolor.getMousePos(e);
			var y = posM[1]-posPad[1];
			switch(modeID) {
				case 0:THIS.fromHSV(null, null, 1 - y/(jscolor.images.sld[1]-1), leavePad);break;
				case 1:THIS.fromHSV(null, 1 - y/(jscolor.images.sld[1]-1), null, leavePad);break;
			}
		}


		var THIS = this;
		var modeID = this.pickerMode.toLowerCase()==='hvs' ? 1 : 0;
		var abortBlur = false;
		var
			valueElement = jscolor.fetchElement(this.valueElement),
			styleElement = jscolor.fetchElement(this.styleElement);
		var
			holdPad = false,
			holdSld = false;
		var
			posPad,
			posSld;
		var
			leaveValue = 1<<0,
			leaveStyle = 1<<1,
			leavePad = 1<<2,
			leaveSld = 1<<3;

		// target
		jscolor.addEvent(target, 'focus', function() {
			if(THIS.pickerOnfocus) {THIS.showPicker();}
		});
		jscolor.addEvent(target, 'blur', function() {
			if(!abortBlur) {
				window.setTimeout(function(){abortBlur || blurTarget();abortBlur=false;}, 0);
			} else {
				abortBlur = false;
			}
		});

		// valueElement
		if(valueElement) {
			var updateField = function() {
				THIS.fromString(valueElement.value, leaveValue);
			};
			jscolor.addEvent(valueElement, 'keyup', updateField);
			jscolor.addEvent(valueElement, 'input', updateField);
			jscolor.addEvent(valueElement, 'blur', blurValue);
			valueElement.setAttribute('autocomplete', 'off');
		}

		// styleElement
		if(styleElement) {
			styleElement.jscStyle = {
				backgroundColor : styleElement.style.backgroundColor,
				color : styleElement.style.color
			};
		}

		// require images
		switch(modeID) {
			case 0:jscolor.requireImage('hs.png');break;
			case 1:jscolor.requireImage('hv.png');break;
		}
		jscolor.requireImage('cross.gif');
		jscolor.requireImage('arrow.gif');

		this.importColor();
	}

};


jscolor.install();

/* file input */
function FIx(obj, id, unid) {
    // basic variables
    this.obj = obj;
    this.refId = id;
    this.unid = unid;
    this.imgTemp = null;
    this.inputs = null;
    // html elements
    this.uploadInput = null;
    // rezising related variables
    this.img;
    this.fixedWidth = 280;
    this.fixedHeight = 280;
    this.tempWidth = null;
    this.tempHeight = null;
    this.tempRatio = null;
    this.tempSrc = null;
    this.units;
    // dragging related variables
    this.dragStartId;
    this.tempStartElPos;
    this.dragTargetId;
    
    this.openDialog = function(id) {
        var sc = this;
        var edit = true;
        if (typeof(id) == 'undefined') {
            edit = false;
        }
        FE.Popup.show('file.process', 'unid='+this.unid+ (edit ? ';obj='+this.obj+';fileId='+id : ''), null, 1400, function(el) {
            //FE.Popup.autoRepos();
            var inps = el.getElementsByTagName('input');
            if (inps.length) {
                var item = null;
                for(i=0;i<inps.length;i++) {
                    item = inps[i];
                    if (item.type == 'file') {
                        sc.uploadInput = item;
                    }
                }                
            }

        });
    }
    
    this.openUpload = function() {
        var sc = this;
        if (this.uploadInput.onchange !== this.startUpload) {
            sc.uploadInput.onchange = function() {
                sc.startUpload();
            };
        }
        this.uploadInput.click();
    }
    
    this.startUpload = function() {
        var nd = document.getElementById('fileUploadCont');
        
        var inp = this.uploadInput;
        var h = nd.offsetHeight;
        
        
        var fname = this.fileName(inp.value);
        
        nd.innerHTML = '<div class="fileName" id="fileNameNode" style=""><strong>'+fname+'</strong></div><div class="fileLoader" id="fileLoaderNode"><img src="/data/shared/visual/loader.gif"><small> Probíhá nahrávání</small></div>';
        
        if (nd.offsetHeight <  h) {
            var diff = h - nd.offsetHeight;
            var tm = Math.floor(diff/2);
            $('fileNameNode').style.marginTop = tm+'px';
            var bm = Math.floor(diff/2);
            if ((tm + bm) != diff) {
                bm++;
            }
            $('fileLoaderNode').style.marginBottom = bm+'px';
        }     
        
        f = $('fileUploadForm');
        f.sc = this;
        f.action = '/data/admin/data/process/file.upload.inc.php?obj='+this.obj+'&refId='+this.refId;
        f.setAttribute('onsubmit', 'AIM.submit(this, {\'onComplete\' : this.sc.finishUpload})');

        
        $('fileUploadFormSubmit').click();
        return false;
    }
    
    this.finishUpload = function(r) {
        var sc = this.sc;
        var v = JSON.parse(r);
        if (v.error) {
            alert(v.error);
            sc.closeDialog();
        } else {
            sc.initFile(v);
        }
        FE.Popup.repos();
    }
        
    this.initFile = function(v) {
        this.imgTemp = v;
        var fname = this.fileName(v.file_name, true);
        var sc = this;
        
        //$('fileValuesIcon').src = this.matchIcon(fname[1]);
        $('fileValuesIcon').src = '/data/shared/visual/ftypes/jpg.png';
        
        $('fileValuesName').innerHTML = fname.join('.');
        $('fileValuesSize').innerHTML = this.fileSize(v.size);
        $('fileValuesAdded').innerHTML = this.fileDate(v.Added);
        
        var nd = $('fileUploadCont');
        var h = nd.offsetHeight;
        if (v.file_name.isImage()) {
            var src = v.path + v.file_name;
            
            var img = new Image();
            img.onload = function(){
                sc.initImageEditing(v, this);
            };
            img.src = src+'?rand='+(Math.random()*10000);       
                
        } else {
            
            nd.innerHTML = '<div class="fileLoader" id="fileLoaderNode">Náhled souboru není k dispozici.</div>';
            
            if (nd.offsetHeight <  h) {
                var diff = h - nd.offsetHeight;
                var tm = Math.floor(diff/2);
                $('fileLoaderNode').style.marginTop = tm+'px';
                var bm = Math.floor(diff/2);
                if ((tm + bm) != diff) {
                    bm++;
                }
                $('fileLoaderNode').style.marginBottom = bm+'px';
            }               
        }
        
    }
    
    this.initImageEditing = function(v, img) {
        this.dimensions = {
            percent: {
                w: 100,
                h: 100
            },
            pixels: {
                w: img.width,
                h: img.height
            }
        }
        // default value
        this.units = '%';
        var dir = v.path.split('/');
        dir = dir[dir.length-2];
        
        var sc = this;
        var nd = $('fileUploadCont');
        var h = nd.offsetHeight;
        this.tempSrc = '/data/user/vis.php?filepath='+dir + '/' + v.file_name+'&nocache=1&box=true';
        var src = this.tempSrc + '&width='+this.fixedWidth+'&height='+this.fixedHeight+'&rand='+(Math.random()*10000);
        nd.innerHTML = '<div style="background-image: url(\''+src+'\');width: '+this.fixedHeight+'px; height: '+this.fixedWidth+'px" id="imageEditingPreview"></div>';
        var prev = $('imageEditingPreview');
        

        var br = document.createElement('a');
        br.href = '/data/user/vis.php?filepath='+this.imgTemp.Rel+'/'+this.imgTemp.file_name;
        br.className = 'activeBorder';
        br.target = 'blank';
        br.id = 'imageEditingBorder';
        br.style.width = this.fixedWidth+'px';
        br.style.height = this.fixedHeight+'px';
        prev.appendChild(br);
        
        // same code as in the resizeImage function
        nd.style.height = this.fixedHeight+'px';
        prev.style.marginLeft = ((nd.offsetWidth - this.fixedWidth)/2)+'px';
        
        // set temp variables
        // change width and height when resizing occurs
        // do not change ratio!
        this.img = img;
        this.tempWidth = img.width;
        this.tempHeight = img.height;
        this.tempRatio = img.width / img.height;
        
        this.getInput('container').className = "";
        this.getInput('width').value = 100;
        this.getInput('width').onkeyup = sc.resizeImage;
        this.getInput('width').ref = this;
        this.getInput('height').value = 100;
        this.getInput('height').onkeyup = sc.resizeImage;
        this.getInput('height').ref = this;
        
        FE.Popup.update();
    }
    
    this.resizeImage = function(e) {
        // constrain proportions
        
        var sc = e.target.ref;   
        
        if (!e.target.value.isNumeric()) {
            e.target.value = 0;
            return false;
        }
        
        var r = sc.recalculate(e.target);        
        
        var w = r[0];
        var h = r[1];
        
        $('imageEditingPreview').style.color = '#000';
        
        var _w = sc.getInput('width').value;
        var _h = sc.getInput('height').value;        
        
        if (sc.units == '%') {          
            sc.dimensions.percent.w = _w;
            sc.dimensions.percent.h = _h;
            
            if (_w > 0 && _h > 0) {
                _w = (_w/100)*sc.fixedWidth;
                _h = (_h/100)*sc.fixedHeight;                
                
                $('imageEditingPreview').style.backgroundImage = 'url('+sc.tempSrc + '&width='+_w+'&height='+_h+'&rand='+(Math.random()*10000)+')';
                
                var padL = Math.round((sc.fixedWidth-_w)/2);
                var padT = Math.round((sc.fixedHeight-_h)/2);
                $('imageEditingPreview').style.backgroundPosition = padL+'px '+padT+'px';
            }
            
            
        } else if (sc.units == 'px') {
            sc.dimensions.pixels.w = _w;
            sc.dimensions.pixels.h = _h;
        }        
        $('imageEditingBorder').href = sc.tempSrc + '&width='+sc.dimensions.pixels.w+'&height='+sc.dimensions.pixels.h+'&ratio='+sc.dimensions.percent.w+'&rand='+(Math.random()*10000);
    }
    
    this.recalculate = function(obj, units) {
        if (typeof(units) != 'undefined') {
            if (units != this.units) {
                this.units = units;
                
                if (units == 'px') {
                    this.getInput('width').value = this.dimensions.pixels.w;
                    this.getInput('height').value = this.dimensions.pixels.h;
                } else if (units == '%') {
                    this.getInput('width').value = this.dimensions.percent.w;
                    this.getInput('height').value = this.dimensions.percent.h;                    
                }
            }
        }
        
        if (obj != null) {
            if (this.getInput('cp').value > 0) {
                if (obj == this.getInput('width')) { // && obj.value != this.tempWidth
                    if (this.units == 'px') {
                        this.getInput('height').value = Math.floor(obj.value / this.tempRatio);
                    } else if (this.units == '%') {
                        this.getInput('height').value = obj.value;
                    }
                    
                } else if (obj == this.getInput('height')) { // && obj.value != this.tempHeight
                    if (this.units == 'px') {
                        this.getInput('width').value = Math.floor(obj.value * this.tempRatio);
                    } else if (this.units == '%') {
                        this.getInput('width').value = obj.value;
                    }
                    
                }
            }               
        }    
        
        var w = this.getInput('width').value;
        var h = this.getInput('height').value;
        if (this.units == 'px') {
            return new Array(w, h);
        } else if (this.units == '%') {
            return new Array(
                Math.round(w*(this.img.width / 100)),
                Math.round(h*(this.img.height / 100))
            );
        }
    }
    
    this.addFiles = function(json) {
        var fc = $('files_'+this.unid);
        var item = null;
        for(i=0;i<json.length;i++) {
            item = json[i];
            
            var d = document.createElement('div');
            d.className = "item";
            d.id = this.unid+'_file_'+item.file_id;
            d.isDraggable = true;
            d.innerHTML += '<div class="edit small">'+this.addIcon('editLarge', this.unid+'.openDialog(\''+item.file_id+'\')', 'Upravit')+''+this.addIcon('moveLarge', 'onmousedown="'+this.unid+'.startDrag(\''+item.file_id+'\', this);return false;"', 'Přesunout')+''+this.addIcon('delLarge', this.unid+'.deleteFile(\''+item.file_id+'\')', 'Smazat')+'</div>';
            d.innerHTML += '<div class="iconDiv"><img id="'+this.unid+'_icon_'+item.file_id+'" class="fileIcon link" src="'+this.fileThumb(item, 64)+'" onclick="'+this.unid+'.openDialog(\''+item.file_id+'\')"></div><div class="fileAttrs"><div class="name"><div class="nameSelf" title="'+item.file_name+'">'+this.fileName(item.file_name, 0, 20)+'</div></div><div class="title small" id="'+this.unid+'_title_'+item.file_id+'">'+item.file_title.crop(50)+'</div><div class="size small"><span id="'+this.unid+'_size_'+item.file_id+'">'+this.fileSize(item.size)+'</span> | '+this.fileDate(item.Added)+'</div></div>';
            
            
            fc.appendChild(d);
            
            var srq = this.fileThumb(item);   
        }
    }
    
    this.startDrag = function(file_id, ref) {
        var sc = this;
        var divs = null;
        var cont = $('files_'+this.unid);
        divs = cont.getElementsByTagName('div');
        for(i=0;i<divs.length;i++) {
            if (divs[i].parentNode === cont && divs[i] !== $(this.unid+'_file_'+file_id)) {
                divs[i].sc = this;
                divs[i].onmouseover = function(e) {
                    sc.updateDrag(e.target);
                }
            }
        }
        this.dragStartId = file_id;
        this.dragStartElPos = ref.parentNode.parentNode.elPos();
        window.onmouseup = function(e) {
            sc.finishDrag(e.target);
        }
        return false;
    }
    
    this.updateDrag = function(obj) {
        if (typeof(obj.sc) == "undefined") {
            var html = document.body.parentNode;
            var srch = null;
            while (srch === null) {
                if (obj === html) {
                    srch = false;
                }
                if (typeof(obj.sc) != "undefined") {
                    srch = true;
                } else {
                    obj = obj.parentNode;
                }
            }
            
        }
        if (srch && typeof(obj.sc) != "undefined") {
            var sc = obj.sc;
            var cont = $('files_'+sc.unid);
            
            if (obj.parentNode === cont) {
                var tgt = $(sc.unid+'_file_'+sc.dragStartId);
                if (tgt.isBefore(obj)) {
                    tgt.parentNode.insertAfter(tgt, obj);
                } else {
                    tgt.parentNode.insertBefore(tgt, obj);
                }
                

                sc.dragTargetId = obj.id;
            }            
        }
        
    }
    
    this.finishDrag = function() {
        var src = $(this.unid+'_file_'+this.dragStartId);
        if (src.elPos() != this.dragStartElPos) {
            if (this.dragTargetId) {
                var el = $(this.dragTargetId).getElementByArgument('isDraggable', 1);
                window.onmouseup = function() {};
                if (el) {
                    var id = el.id.split('_file_').pop();
                    if (this.dragStartId != id) {
                        AJAX.init('file.sort', {onComplete: function(r) {
                        }}, 'srcId='+this.dragStartId+';tgtId='+id+';obj='+this.obj+';refId='+this.refId);
                    }
                }            
            }            
        }
        
        this.dragTargetId = null;
        var divs = null;
        var cont = $('files_'+this.unid);
        divs = cont.getElementsByTagName('div');
        for(i=0;i<divs.length;i++) {
            if (divs[i].parentNode === cont) {
                divs[i].onmouseover = function(){};
            }
        } 
       
    }
    
    this.deleteFile = function(id) {
        var sc = this;
        AJAX.init('file.delete', {onComplete: function(r){sc.hideFile(r);}}, 'refId='+this.refId+';obj='+this.obj+';fileId='+id);
    }

    this.hideFile = function(result) {
        var v = JSON.parse(result);
        if (typeof(v.success) != "undefined") {
            var fc = $('files_'+this.unid);
            fc.removeChild($(this.unid+'_file_'+v.file_id));
        } else if (v.error) {
            alert(v.error);
        }
    }
    
    this.closeDialog = function(save) {

        if (document.getElementById(this.unid+'_file_'+this.imgTemp.file_id) == null) {
            var arg = new Array(this.imgTemp);
            this.addFiles(arg);
        }

        if (typeof(save) != 'undefined') {
            // save changes
            var sc = this;
            var args = new Array('obj='+this.obj, 'fileId='+this.imgTemp.file_id);
            var f = $('fileUploadForm');
            var r = f.getValues();
            if (typeof(r.fileTitle) != 'undefined') {
                args.push('title='+r.fileTitle);
            }
            var d = this.dimensions;
            if (d.percent.w != 100 || d.percent.h != 100 || d.pixels.w != this.img.width || d.pixels.h != this.img.height) {
                args.push('width='+d.pixels.w);
                args.push('height='+d.pixels.h);
                args.push('oldWidth='+this.img.width);
                args.push('oldHeight='+this.img.height);
                args.push('percent='+d.percent.w);
            }
         
            
            var fid = this.unid+'_icon_'+this.imgTemp.file_id;
            var sid = this.unid+'_size_'+this.imgTemp.file_id;
            var res = null;
            AJAX.init('file.update', {onComplete: function(r){
                    if (r != '') {
                        var resp = JSON.parse(r);
                        if (typeof resp.error != 'undefined') {
                            alert(resp.error);
                        } else {
                            var val = $(fid).src;
                            if (val.indexOf('&rand=') != -1) {
                                res = val.split('&');
                                res.pop();
                                val = res.join('&');
                            }
                            val += '&rand='+(Math.random()*10000)+(Math.random()*100);
                            $(fid).src = val;

                            $(sid).innerHTML = sc.fileSize(resp.size);
                        }                        
                    }            
                }
            }, args.join(';'));
            
            $(this.unid+'_title_'+this.imgTemp.file_id).innerHTML = r.fileTitle.crop(50);
            
        }
        
        this.img = null;
        this.imgTemp = null;
        this.tempWidth = null;
        this.tempHeight = null;
        this.tempRatio = null;
        
        FE.Popup.hide();
    }
    
    this.fileThumb = function(item, dim) {
        if (!dim) {
            dim = 32;
        }
        
        var fn = this.fileName(item.file_name, true);
        var images = new Array('png', 'jpg', 'jpeg', 'gif');
        
        var isImage = false;
        for(b=0;b<images.length;b++) {
            if (images[b] == fn[1]) {
                isImage = true;
            }
        }
        
        
        var src = '';
        if (isImage) {
            src = '/data/user/vis.php?filepath='+item.Rel+'/'+item.file_name+'&width='+dim+'&height='+dim+'&box=true';
        } else {
            src = this.matchIcon(fn[1]);
        }
        return src;
    }
    
    this.addInputs = function() {
        var sc = this;
        var inputs = {};
        var item = null;
        if (document.getElementById('input_imageWidth') != null) {
            inputs.width = document.getElementById('input_imageWidth');
        }
        if (document.getElementById('input_imageHeight') != null) {
            inputs.height = document.getElementById('input_imageHeight');
        }
        if (document.getElementById('input_imageCP') != null) {
            inputs.cp = document.getElementById('input_imageCP');
        }        
        if (document.getElementById('imageControlsContainer') != null) {
            inputs.container = document.getElementById('imageControlsContainer');
        }
        var r = new Array();
        if (document.getElementById('unitsSelectorContainer')) {
            var children = document.getElementById('unitsSelectorContainer').childNodes;
            var i;
            for (i = 0; i < children.length; i++) {
                children[i].onclick = function() {
                    sc.recalculate(null, this.value);
                }
            }   
            inputs.units = r;
        }
        this.inputs = inputs;
    }
    
    this.getInput = function(name) {
        if (typeof(this.inputs[name]) != 'undefined') {
            return this.inputs[name];
        } else {
            return {};
        }
    }
    
    this.fileSize = function(num) {
        if (num > 0) {
            var sizes = new Array('', 'k', 'M', 'G');
            for(a=0;a<sizes.length;a++) {
                if (num < 1000 || typeof(sizes[a+1]) == "undefined") {
                    return (Math.round(num*10)/10) + ' '+sizes[a]+'B';
                }            
                if (num > 1000 && typeof(sizes[a+1]) != "undefined") {
                    num = num / 1000;
                }
            }            
        } else {
            return '0 B';
        }

    }
    
    this.fileName = function(str, split, limit) {
        var res = '';
        if (str.search('/') != -1) {
            res = str.split('/');
            str = res.pop();
        }
        if (str.search(/\\/) != -1) {
            res = str.split(/\\/);
            str = res.pop();
        }   
        res = str.split('.');
        var ext = res.pop().toLowerCase();
        var file = res.join('.');         

        if (split) {
            return new Array(file, ext);
        } else {
            if (limit > 0) {
                return file.crop(limit, true)+'.'+ext;
            } else {
                return file+'.'+ext;
            }
            
        }
        
    }  
    
    this.fileDate = function(date) {
        var res = date.split(' ');
        var dt = res[0].split('-');
        return dt[2]+'.'+dt[1]+'.'+dt[0]+' '+res[1];
    }
    
    this.matchIcon = function(ext) {
        var res = new Array('jsp','asp','php','txt','exe','tif','pdf','css','dat','swf','mp3','jpg','eps','fla','js','rar','mdb','png','psd','ppt','xls','flv','ogg','jar','inf','avi','pps','mpg','doc','7Z','sis','dmg','vob','zip','mp4','tmp','tar','gif','bmp','xml','ico','rtf','3gp','xpi','jad','gz');
        var ico = '';
        
        for(q=0;q<res.length;q++) {
            if (res[q] == ext) {
                ico = res[q];
            }
        }
        if (ico == '') {
            ico = 'na';
        }
        return '/data/shared/visual/ftypes/'+ico+'.png';
    }
    
    this.addIcon = function(ic, onclick, alt) {
        if (!alt) {
            alt = 'Popis obrázku není k dispozici';
        }
        if (onclick.indexOf('=') == -1) {
            onclick = 'onclick="'+onclick+'"';
        }
        return '<img class="icon" '+onclick+' src="/data/admin/data/visual/icons/'+ic+'.png" alt="'+alt+'">';
    }
    
}


function FI(c,m,r,t,i,l,lc,tp) {
    this.m = m;
    this.u = 0;
    this.c = c;
    this.a = false;
    this.at = false;
    this.r = r;
    if (t) {
        this.t = t;
        this.i = i;
    }
    this.l = l;
    this.lc = lc;
    this.tp = tp;
    this.addFileInput = function() {
        if (!this.a) {
            l = this.l || 'user_files';
            this.a = true;
            // create div (container)
            n = document.createElement('div');
            this.n = n;
            n.className = 'uploadBox intrude';
            $('uploadBoxes_'+this.c).appendChild(n);
            hl = document.createElement('h3');
            hl.innerHTML = FE.val('file.upload');
            n.appendChild(hl);
            // create form
            f = document.createElement('form');
            f.setAttribute('method', 'post');
            f.setAttribute('enctype','multipart/form-data');
            f.action = '/data/admin/data/process/fi.alter.inc.php?action=add&cd='+this.c+'&rel='+this.r+'&relType='+this.t+'&relId='+this.i+'&link='+l+'&linkCol='+this.lc+'&type='+this.tp;
            f.ref = this;

            n.appendChild(f);

            // create input (label)
            label = document.createElement('input');
            label.name = 'decoy_desc';
            label.type = 'text';
            label.value = FE.val('file.desc');
            label.className = 'decoy';

            //Act.addDecoy(label);
            f.appendChild(label);
            f.appendChild(document.createElement('br'));


            f.setAttribute('onsubmit', 'AIM.submit(this, {\'onComplete\' : this.ref.setOutput})');
            // create input (file)
            file = document.createElement('input');
            file.type = 'file';
            file.name = 'decoy_file';
            f.appendChild(file);
            f.appendChild(document.createElement('br'));
            s = document.createElement('input');
            s.type = 'submit';
            s.value = FE.val('file.upload.btn');
            f.appendChild(s);
            h = n.offsetHeight;
            n.style.marginTop = -(20+h)+'px';
            return this;
        } else {
            n = this.n;
            n.parentNode.removeChild(n);
            this.a = false;
        }
    }
    this.addAttachmentInput = function(tbl,c,id,col,type) {
        if (!this.at) {
            this.at = true;
            n = document.createElement('div');
            n.className = 'uploadBoxAtt intrude';
            n.id = 'attachment_'+this.c;
            this.atn = n;
            this.refId = id;
            this.refCol = col;
            $('uploadBoxes_'+this.c).appendChild(n);
            hl = document.createElement('h3');
            hl.innerHTML = FE.val('file.upload');
            n.appendChild(hl);
            // load div content
            AJAX.init('sub/attachment.add',{onComplete: function(r){
                $(n.id).innerHTML += r;
                h = n.offsetHeight;
                n.style.marginTop = -(20+h)+'px';
            }},'tbl='+tbl+';code='+c+';refCol='+col+';refId='+id+';type='+type);

        } else {
            n = this.atn;
            n.parentNode.removeChild(n);
            this.at = false;
        }
    }
    this.lim = function(str,lim) {
        add = '(...)';
        pos = add.length;
        if (str.length > (lim-pos)) {
            str = str.substr(0, lim-pos);
            str += '(...)';
        }
        return str;
    }
    this.sendAttachment = function(tbl,id) {
        i = $(id);
        val = i.options[i.selectedIndex].value;
        var obj = this;
        AJAX.init('fi.alter',{onComplete: function(r){
            obj.addAttachmentInput();
            if (r == 'error') {
                alert('Tuto přílohu nelze přiřadit!');
            } else {
                obj.setOutput(r,obj);
            }
        }},'tbl='+tbl+';id='+val+';action=add-attachment;refId='+this.refId+';refCol='+this.refCol);
        return false;
    }
    this.setOutput = function(r,obj) {
        if (r) {
            result = r;
        } else {
            result = this.ifr.contentWindow.document.body.innerHTML;
        }
        obj = obj || this.ref;
        if (result == 'error') {
            alert('Nahrání souboru se nepodařilo!');
        } else {
            r = result.split('^')
            obj.update(+1);
            obj.fBox({n: r[0], i: r[1], s: r[2], d: r[3], a: r[4], v: r[5], r: r[6], t: r[7]});
        }
        if (typeof(this.ifr) != "undefined") {
            this.ifr.parentNode.removeChild(this.ifr);
            n = this.ref.n;
            n.parentNode.removeChild(n);
            this.ref.a = false;
        }

    }
    //  n - file name, i - file id, s - file size [B], d - file desc, a - date added, v - editing values, t - rel table
    this.done = false;
    this.fBox = function(o) {

        r = Base.fLabel(o.n);
        e = r[0];
        n = r[1];
        t = document.createElement('div');
        t.rId = o.i;
        t.className = 'fBox';

        var imgs = new Array('jpg','jpeg','png','gif'); // ,'bmp','tif','tiff'
        if (imgs.search(e) != -1) {
            if (o.t == "user_files") {
                src = o.i+'.'+e;
            } else {
                src = o.n;
            }

            t.innerHTML = '<a class="fIcon floatL" rel="lightbox['+this.c+']" href="'+Base.uSrc+'vis.php?filepath='+o.r+'/'+src+'&box=true&width=1000&height=600"><img src="'+Base.uSrc+'vis.php?filepath='+o.r+'/'+src+'&width=72&height=72&box=true" alt="'+o.n+'"></a>';
            //  onerror="this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);FI_'+this.c+'.update(-1)"
        } else {
            src = o.i+'.'+e;
            t.innerHTML = '<a class="fIcon floatL" href="'+Base.uSrc+o.r+'/'+o.n+'"><img src="'+Base.vSrc+'ftypes/other.png" alt="'+o.n+'"></a>';
        }
        c = document.createElement('div');
        c.className = 'inner';
        this.done = true;
        v = '<div class="floatR">'+
            '<img src="'+Base.vSrc+'icons/delLarge.png" title="Smazat" alt="Smazat" class="floatR icon" onclick="FI_'+this.c+'.delF(this,\''+o.i+'\', \''+(o.t)+'\','+(this.c == 'Attachments' ? true : false)+')">'+ // this.l?'data_storage':'user_files'
            '<img src="'+Base.vSrc+'icons/moveLarge.png" title="Přesunout" alt="Přesunout" class="floatR icon" onmousedown="FI_'+this.c+'.sortF(this,\''+o.i+'\');return false">'+
            '</div>';
        v += '<div><strong title="'+n+'.'+e+'">'+this.lim(n,20)+'</strong>.'+e+'</div>';
        v += '<div class="desc"><span class="asEdit">'+o.d+'</span></div>';
        v += '<div><span class="comment">'+Base.cDate(o.a)+' - '+Base.fSize(o.s)+'</span></div>';
        c.innerHTML = v;
        t.appendChild(c);

        $('uploaded_'+this.c).appendChild(t);

        s = t.getElementsByTagName('span');
        s = s[0];

        AEd.add(s,o.v);
    }
    this.delF = function(ref,i,t,sp) {
        obj = this;
        AJAX.init('fi.alter',{
            onComplete: function(r) {
                div = ref.parentNode.parentNode.parentNode;
                div.parentNode.removeChild(div);
                obj.update(-1);
            }
        },'action=del;refId='+i+';tbl='+t+';objId='+this.i+';linkOnly='+(sp ? 1 : 0));
    }
    this.S = null;
    this.sortF = function() {
        if (this.S == null) {
            document.body.style.cursor = 'move';
            o = arguments[0];

            d = o.parentNode.parentNode.parentNode;
            m = d.parentNode;
            m.r = this;

            // get all main div children
            var c;
            c = m.getElementsByTagName('div');
            for(i=0;i<c.length;i++) {
                item = c[i];
                // if it is straightly related
                if (item.parentNode == m && item != d) {
                    item.onmouseover = function() {
                        if (this.parentNode.r.S) {
                            this.parentNode.r.S.focusOn = this;
                            this.setAttribute('focus', 'true');
                            this.title = "Přetáhnout sem";
                        }

                    }
                    item.onmouseout = function() {
                        if (this.parentNode.r.S) {
                            this.parentNode.r.S.focusOn = '';
                            this.setAttribute('focus', '');
                            this.title = "";
                        }
                    }
                }

            }

            this.S = {
                state: 'selecting',
                srcId: arguments[1],
                srcDiv: d,
                srcNode: o,
                focusOn: false
            }

            // add event listener for mouse up
            window.r = this;
            window.onmouseup = function() {
                if (this.r.S.focusOn && this.r.S.state == 'selecting') {
                    this.r.sortF();
                } else {
                    this.r.sFRev(d);
                    this.r.S = null
                }
            }
        } else {
            
            if (this.S.focusOn) {
                f = this.S.focusOn;
                if (f == this.S.srcDiv) {
                }

                this.S.tgtId = f.rId;
                this.S.tgtDiv = f;

                refI = 0;
                if (this.S.srcDiv.parentNode.id == 'uploaded_Attachments') {
                    refI = FI_Attachments.i;
                }



                fi = this;
                AJAX.init('fi.alter',{onComplete: function(r) {
                    fi.S.tgtDiv.parentNode.insertBefore(fi.S.srcDiv, fi.S.tgtDiv);
                    fi.S = null;
                }},'action=sort&refId='+refI+'&tbl='+(this.l?'data_storage':'user_files')+'&src='+this.S.srcId+'&tgt='+this.S.tgtId);
                this.sFRev(f);
            }
        }
        return false;
    }
    this.sFRev = function(d) {
        d.setAttribute('focus', '');
        window.onmouseup = null;
        document.body.style.cursor = 'inherit';
        m = d.parentNode;

        c = m.getElementsByTagName('div');
        for(i=0;i<c.length;i++) {
            item = c[i];
            // if it is straightly related
            if (item.parentNode == m) {
                item.onmouseover = null;
                item.onmouseout = null;
                item.title = '';
            }

        }
    }
    this.update = function(t) {
        if (typeof(t) == "undefined") t = 0;
        if ((this.u == 1 && t < 0) || !t && this.u == 0) {
            $('uploaded_'+this.c).innerHTML = '<div class="padBtm"><small>'+FE.val('file.noneUp')+'</small></div>';
        }
        if (this.u == 0 && t > 0) {
            $('uploaded_'+this.c).innerHTML = '';
        }
        this.u += t;

    }
}
/* forms aim */
AIM={frame:function(c){var n='f'+Math.floor(Math.random()*99999);var d=document.createElement('DIV');d.innerHTML='<iframe style="display: none" onclick="" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';document.body.appendChild(d);var i=document.getElementById(n);if(c&&typeof(c.onComplete)=='function'){f.onComplete=c.onComplete;}
return n;},form:function(f,name){f.setAttribute('target',name);},submit:function(f,c){AIM.form(f,AIM.frame(c));if(c&&typeof(c.onStart)=='function'){return c.onStart();}else{return true;}},loaded:function(id){var i=document.getElementById(id);if(i.contentDocument){var d=i.contentDocument;}else if(i.contentWindow){var d=i.contentWindow.document;}else{var d=window.frames[id].document;}
if(d.location.href=="about:blank"){return;}
if(typeof(f.onComplete)=='function'){f.ifr=i;f.onComplete(d.body.innerHTML);}}}

/* DBox*/
DBox = {
    offset: 100,
    active: false,
    // f - target file, t - target node, a - included arguments, s - specific variable, fn - included function
    set: function(f,t,a,s,fn) {
        if (!this.active) {
            this.active = true;
            this.fn = fn;
            this.s = s;
            this.a = a.split(';').join('&');

            n = document.createElement('div');
            tgt = $(t);
            tgt.className = '';
            tgt.parentNode.replaceChild(n,tgt);

            line = document.createElement('div');
            line.className = 'DBoxTopLine';
            n.appendChild(line);

            right = document.createElement('div');
            right.className = 'right';
            n.appendChild(right);
            add = document.createElement('input');
            add.type = 'submit';
            add.value = FE.val('add');
            add.className = 'light';
            add.style.margin = '0 0 5px 0';
            add.onclick = function() {
                Act.addProducts('addProduct',add);
                return false;
            };
            right.appendChild(add);

            n.appendChild(tgt);

            opt = document.createElement('div');
            opt.className = 'right';
            cl = document.createElement('input');
            cl.type = 'submit';
            cl.value = FE.val('close');
            cl.className = 'light';
            cl.style.margin = '5px 0 0 5px';
            cl.onclick = function() {
                DBox.revert();
            };
            add = document.createElement('input');
            add.type = 'submit';
            add.value = FE.val('add');
            add.className = 'light';
            add.style.margin = '5px 0 0 0';
            add.onclick = function() {
                Act.addProducts('addProduct',add);
                return false;
            };
            n.appendChild(opt);
            opt.appendChild(add);
            opt.appendChild(cl);

            this.t = n;

            this.draw();

            this.f = f;
            AJAX.init(f,{node: t},a);
        } else {
            // work on this
            if (this.t.firstChild.nextSibling.nextSibling.id == t) {
                this.revert();
            } else {
                alert('Nelze otevřít více dialogových oken najednou!');
            }

            return false;
        }

    },
    revert: function() {
        tgt = this.t.firstChild.nextSibling.nextSibling;
        tgt.className = 'hidden';
        tgt.innerHTML = '';
        this.t.parentNode.replaceChild(tgt,this.t);
        this.t = false;
        this.active = false;
    },
    // t - target node
    draw: function() {
        if (DBox.active) {
            if (typeof(window.innerHeight) != "undefined") {
                x = window.innerWidth;
                y = window.innerHeight;
            } else if (typeof(document.documentElement.clientHeight)) {
                x = document.documentElement.clientWidth;
                y = document.documentElement.clientHeight;
            } else if (typeof(document.body.clientHeight) != "undefined") {
                x = document.body.clientWidth;
                y = document.body.clientHeight;
            }
            w = x - this.offset;
            with (this.t) {
                className = 'DBox';
                style.top = ((this.offset) / 2) + window.pageYOffset + 'px';
                style.left = ((this.offset) / 2) + window.pageXOffset + 'px';
                style.width = (x - this.offset) + 'px';
                style.height = (y - this.offset) + 'px';
            }
            with (this.t.firstChild.nextSibling.nextSibling) {
                style.height = (y - this.offset - 66) + 'px';
                style.overflow = 'auto';
            }


            Base.addListener('resize',function() {
                DBox.draw();
            });
        }

    }
}
